@staix/agent-research 0.3.0 → 0.4.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 (44) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/README.md +93 -22
  3. package/package.json +4 -1
  4. package/src/cli-output.ts +446 -0
  5. package/src/cli.ts +208 -66
  6. package/src/commands-table.ts +213 -93
  7. package/src/commands.ts +86 -17
  8. package/src/exp/artifacts.ts +20 -2
  9. package/src/exp/attempts.ts +26 -9
  10. package/src/exp/calibrate.ts +125 -0
  11. package/src/exp/executor.ts +130 -21
  12. package/src/exp/final.ts +12 -3
  13. package/src/exp/idea-report.ts +97 -0
  14. package/src/exp/ideas.ts +90 -6
  15. package/src/exp/investigate.ts +25 -22
  16. package/src/exp/metrics.ts +3 -5
  17. package/src/exp/protocol.ts +28 -3
  18. package/src/exp/reuse-admission.ts +3 -1
  19. package/src/exp/reuse-runtime.ts +5 -1
  20. package/src/exp/screen.ts +83 -0
  21. package/src/exp/selection.ts +110 -4
  22. package/src/exp/snapshot.ts +28 -8
  23. package/src/exp/stages.ts +3 -1
  24. package/src/harness/transitions.ts +37 -5
  25. package/src/manifest.ts +13 -5
  26. package/src/mcp-tools.ts +67 -14
  27. package/src/memory/archive.ts +8 -3
  28. package/src/paper/build.ts +39 -25
  29. package/src/paper/check.ts +46 -15
  30. package/src/paper/dependencies.ts +47 -0
  31. package/src/paper/document.ts +19 -0
  32. package/src/paper/figures.ts +152 -0
  33. package/src/paper/hygiene.ts +16 -5
  34. package/src/paper/plan.ts +71 -29
  35. package/src/paper/point-evidence.ts +27 -12
  36. package/src/paper/render.ts +113 -0
  37. package/src/paper/renderer.ts +128 -0
  38. package/src/paper/review.ts +41 -5
  39. package/src/plan/definition.ts +6 -1
  40. package/src/playbook.ts +21 -11
  41. package/src/provenance.ts +4 -3
  42. package/src/study-export.ts +7 -4
  43. package/src/study.ts +9 -4
  44. package/src/ui/plugin.ts +3 -1
@@ -6,13 +6,14 @@ import { join } from "node:path";
6
6
  import { assertWritable, commit, openStudy, plain, readLedger, readTextBounded, requireExperiment, sha256, type Actor, type LedgerEvent } from "../study.ts";
7
7
  import { listAttempts, type Attempt, type AttemptStatus } from "./attempts.ts";
8
8
  import { protocolHash, readProtocol } from "./protocol.ts";
9
- import { readSelection, selectionHash } from "./selection.ts";
9
+ import { evaluateSelectionConstraints, observedMetric, readSelection, sampleMean, selectionHash, type ConstraintResult } from "./selection.ts";
10
+ import { readBoundCalibration } from "./calibrate.ts";
10
11
 
11
12
  export const INVESTIGATE_BYTES = 1_048_576;
12
- export type NoWinner = "no-baseline" | "baseline-seeds" | "no-candidate" | "below-margin" | "tie";
13
+ export type NoWinner = "no-baseline" | "baseline-seeds" | "no-candidate" | "below-margin" | "tie" | "constraints";
13
14
  type Exclusion = "other-protocol" | "before-selection" | "missing-start-event" | "undeclared-seed" | "later-success" | "reserved-seed";
14
15
  export interface Sample { seed: number; attempt: string; value: number }
15
- export interface CommitResult {
16
+ export interface CommitResult extends Omit<ConstraintResult, "reason"> {
16
17
  commit: string; idea?: string; attempts: Record<AttemptStatus, string[]>; perSeed: Sample[];
17
18
  pairedSeeds: number[]; pairs: { seed: number; attempt: string; baselineAttempt: string; value: number; baselineValue: number }[];
18
19
  mean: number | null; baselineMean: number | null; delta: number | null; eligible: boolean; reason: string;
@@ -23,6 +24,7 @@ export interface InvestigateResult {
23
24
  baseline: CommitResult; candidates: CommitResult[];
24
25
  totals: { attempts: number; byStatus: Record<AttemptStatus, number>; countedSuccesses: number; excluded: number };
25
26
  excluded: { id: string; commit: string; seed: number; status: AttemptStatus; reasons: Exclusion[] }[];
27
+ calibration?: { recommendedMinDelta: number; minDelta: number; belowNoise: boolean };
26
28
  winner: { commit: string; idea?: string; attempts: string[]; mean: number; delta: number } | null; reason?: NoWinner;
27
29
  }
28
30
  const recover = "; inspect ares attempt show and restore the last valid study inputs before ares investigate show";
@@ -32,21 +34,11 @@ function canonical(raw: unknown): string {
32
34
  if (plain(raw)) return `{${Object.keys(raw).sort().map(k => `${JSON.stringify(k)}:${canonical(raw[k])}`).join(",")}}`;
33
35
  return JSON.stringify(raw) ?? "null";
34
36
  }
35
- function mean(values: number[]): number | null {
36
- if (!values.length) return null;
37
- const total = values.reduce((sum, value) => sum + value, 0);
38
- if (Number.isFinite(total)) return total / values.length;
39
- const scale = Math.max(...values.map(Math.abs));
40
- if (!scale) return 0;
41
- // Normalize before summing so finite evaluator values never overflow their mean.
42
- return Math.max(-1, Math.min(1, values.reduce((sum, v) => sum + v / scale / values.length, 0))) * scale;
43
- }
44
37
  export function metricValue(attempt: Attempt, metric: InvestigateResult["metric"]): number {
45
38
  if (!Array.isArray(attempt.metrics)) bad(`attempt ${attempt.id}: primary metrics missing`);
46
- const values = attempt.metrics.filter(m => m?.name === metric.name);
47
- const value = values[0];
48
- if (values.length !== 1 || !value || value.unit !== metric.unit || value.provenance !== "ares-observed" || typeof value.value !== "number" || !Number.isFinite(value.value)) bad(`attempt ${attempt.id}: primary metric missing, duplicate, non-finite or unvalidated`);
49
- return value.value;
39
+ const value = observedMetric(attempt, metric);
40
+ if (value === undefined) bad(`attempt ${attempt.id}: primary metric missing, duplicate, non-finite or unvalidated`);
41
+ return value;
50
42
  }
51
43
  export interface PairedSamples {
52
44
  pairedSeeds: number[]; pairs: { seed: number; attempt: string; referenceAttempt: string; value: number; referenceValue: number }[];
@@ -58,7 +50,7 @@ export function pairSamples(samples: Sample[], reference: Sample[], direction: "
58
50
  const base = reference.find(b => b.seed === sample.seed);
59
51
  return base ? [{ seed: sample.seed, attempt: sample.attempt, referenceAttempt: base.attempt, value: sample.value, referenceValue: base.value }] : [];
60
52
  });
61
- const candidateMean = mean(pairs.map(p => p.value)), referenceMean = mean(pairs.map(p => p.referenceValue));
53
+ const candidateMean = sampleMean(pairs.map(p => p.value)), referenceMean = sampleMean(pairs.map(p => p.referenceValue));
62
54
  const delta = candidateMean === null || referenceMean === null ? null : direction === "max" ? candidateMean - referenceMean : referenceMean - candidateMean;
63
55
  if (delta !== null && !Number.isFinite(delta)) bad(`commit ${commit}: primary metric delta overflows; rescale the metric's unit in a new protocol and rerun attempts`);
64
56
  return { pairedSeeds: pairs.map(p => p.seed), pairs, mean: candidateMean, referenceMean, delta };
@@ -66,7 +58,9 @@ export function pairSamples(samples: Sample[], reference: Sample[], direction: "
66
58
  function empty(commit: string): CommitResult {
67
59
  return { commit, attempts: { running: [], succeeded: [], failed: [], cancelled: [], unknown: [] }, perSeed: [], pairedSeeds: [], pairs: [], mean: null, baselineMean: null, delta: null, eligible: false, reason: "no-counted-success" };
68
60
  }
69
- function inputs(dirArg: string) {
61
+ export type InvestigationInputs = ReturnType<typeof inputs>;
62
+ /** Shared by investigate and the read-only idea report so both see the same pairs. */
63
+ export function inputs(dirArg: string) {
70
64
  const { dir, study } = openStudy(dirArg); requireExperiment(study);
71
65
  const protocol = readProtocol(dir);
72
66
  if (!protocol) throw new Error("investigate: protocol missing; run ares protocol before selecting an investigation rule");
@@ -82,7 +76,7 @@ function inputs(dirArg: string) {
82
76
  const reserved = readFinalSeeds(dir, protocol)?.seeds ?? [], reservedSha = finalSeedsHash(dir, protocol);
83
77
  return { dir, protocol, rule, ruleSha, events, cutoff, hash, metric, attempts, reserved, reservedSha };
84
78
  }
85
- function calculate(input: ReturnType<typeof inputs>): InvestigateResult {
79
+ export function calculate(input: InvestigationInputs): InvestigateResult {
86
80
  const { rule, ruleSha, events, cutoff, hash, metric, attempts, protocol, reserved, reservedSha } = input;
87
81
  const ideas = foldIdeas(events), owners = new Map<string, string>();
88
82
  // The journal enforces exactly one idea owner for any associated commit.
@@ -118,16 +112,24 @@ function calculate(input: ReturnType<typeof inputs>): InvestigateResult {
118
112
  for (const row of rows.values()) { const idea = owners.get(row.commit); if (idea !== undefined) row.idea = idea; }
119
113
  const baseline = rows.get(rule.baseline.commit)!;
120
114
  for (const row of rows.values()) row.perSeed.sort((a, b) => a.seed - b.seed);
121
- baseline.mean = mean(baseline.perSeed.map(s => s.value)); baseline.baselineMean = baseline.mean;
115
+ baseline.mean = sampleMean(baseline.perSeed.map(s => s.value)); baseline.baselineMean = baseline.mean;
122
116
  baseline.pairedSeeds = baseline.perSeed.map(s => s.seed); baseline.delta = baseline.mean === null ? null : 0;
123
117
  baseline.eligible = baseline.perSeed.length >= rule.minSeeds;
124
118
  baseline.reason = !baseline.perSeed.length ? "no-baseline" : baseline.eligible ? "baseline" : "baseline-seeds";
119
+ const attemptsById = new Map(attempts.map(attempt => [attempt.id, attempt]));
125
120
  const candidates = [...rows.values()].filter(row => row !== baseline).sort((a, b) => a.commit.localeCompare(b.commit));
126
121
  for (const row of candidates) {
127
122
  const paired = pairSamples(row.perSeed, baseline.perSeed, metric.direction, row.commit);
128
123
  row.pairedSeeds = paired.pairedSeeds; row.mean = paired.mean; row.baselineMean = paired.referenceMean; row.delta = paired.delta;
129
124
  row.pairs = paired.pairs.map(p => ({ seed: p.seed, attempt: p.attempt, baselineAttempt: p.referenceAttempt, value: p.value, baselineValue: p.referenceValue }));
130
125
  row.reason = !baseline.perSeed.length ? "no-baseline" : !baseline.eligible ? "baseline-seeds" : !row.perSeed.length ? "no-counted-success" : row.pairs.length < rule.minSeeds ? "candidate-seeds" : row.delta! <= 0 || row.delta! < rule.minDelta ? "below-margin" : "eligible";
126
+ if (baseline.eligible && paired.pairs.length >= rule.minSeeds && paired.delta !== null && rule.v === 2 && (rule.guards?.length || rule.cost)) {
127
+ const { reason, ...details } = evaluateSelectionConstraints(rule, protocol, paired.pairs.map(pair => ({
128
+ attempt: attemptsById.get(pair.attempt)!, baseline: attemptsById.get(pair.referenceAttempt)!,
129
+ })), paired.delta);
130
+ Object.assign(row, details);
131
+ if (reason) row.reason = reason;
132
+ }
131
133
  row.eligible = row.reason === "eligible";
132
134
  }
133
135
  const eligible = candidates.filter(row => row.eligible).sort((a, b) => b.delta! - a.delta!);
@@ -135,14 +137,15 @@ function calculate(input: ReturnType<typeof inputs>): InvestigateResult {
135
137
  if (!baseline.perSeed.length) reason = "no-baseline";
136
138
  else if (!baseline.eligible) reason = "baseline-seeds";
137
139
  else if (!candidates.some(row => row.pairedSeeds.length >= rule.minSeeds)) reason = "no-candidate";
138
- else if (!eligible.length) reason = "below-margin";
140
+ else if (!eligible.length) reason = candidates.some(row => /^(?:guard[-:]|cost-)/.test(row.reason)) ? "constraints" : "below-margin";
139
141
  else if (eligible.length > 1 && eligible[0]!.delta === eligible[1]!.delta) reason = "tie";
140
142
  else { const row = eligible[0]!; winner = { commit: row.commit, ...(row.idea !== undefined ? { idea: row.idea } : {}), attempts: row.pairs.map(p => p.attempt), mean: row.mean!, delta: row.delta! }; }
143
+ const calibration = rule.v === 2 ? readBoundCalibration(input.dir, rule, protocol) : undefined;
141
144
  const result: InvestigateResult = {
142
145
  v: 1, run: rule.run, ruleSha256: ruleSha, protocolHash: hash,
143
146
  inputsSha256: sha256(canonical({ ruleSha, protocolHash: hash, ...(reservedSha !== undefined ? { finalSeedsSha256: reservedSha } : {}), cutoff, ideas: sha256(canonical(ideas)), attempts: ordered.map(a => ({ record: sha256(canonical(a)), start: starts.get(a.id)?.index ?? null })) })),
144
147
  metric, baseline, candidates, totals: { attempts: attempts.length, byStatus, countedSuccesses: [...rows.values()].reduce((n, r) => n + r.perSeed.length, 0), excluded: excluded.length }, excluded,
145
- winner, ...(reason ? { reason } : {}),
148
+ winner, ...(reason ? { reason } : {}), ...(calibration === undefined ? {} : { calibration }),
146
149
  };
147
150
  assertWritable(JSON.stringify(result, null, 2) + "\n", INVESTIGATE_BYTES, "investigate result; archive this study and use a new bounded run");
148
151
  return result;
@@ -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 }); }
@@ -8,8 +8,11 @@ import { commit, openStudy, plain, readBytesBounded, readJsonFile, readTextBound
8
8
 
9
9
  export interface Limits { cpus: number; memoryMb: number; pidsLimit: number; wallSeconds: number; gpus: number }
10
10
  export interface ProtocolInput { path?: string; sha256: string; mount: { candidate?: string; evaluator?: string } }
11
+ /** Deterministic only: exact evaluator-only input copies and declared literals, never a model decision. */
12
+ export interface ProtocolScreen { evaluatorInputs?: true; literals?: string[] }
11
13
  export interface Protocol {
12
14
  v: 1; method: string; inputs?: Record<string, ProtocolInput>;
15
+ screen?: ProtocolScreen;
13
16
  candidate: { image: string; command: string[]; env?: Record<string, string> };
14
17
  evaluator: { image: string; command: string[] };
15
18
  metrics: { name: string; unit: string; direction: "max" | "min" }[];
@@ -23,7 +26,8 @@ export function validateProtocolDefinition(raw: unknown): ProtocolDefinition {
23
26
  return validateProtocol(raw);
24
27
  }
25
28
  export const METRIC_LIMIT = 100;
26
- export const PROTOCOL_BYTES = 65_536, TASK_FILES = 500, TASK_BYTES = 64 * 1024 * 1024;
29
+ export const SCREEN_LITERALS = 64, SCREEN_LITERAL_MIN_BYTES = 8, SCREEN_LITERAL_BYTES = 200;
30
+ export const PROTOCOL_BYTES = 65_536, TASK_FILES = 500, TASK_BYTES = 64 * 1024 * 1024, TASK_DIRECTORIES = 1000;
27
31
  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
32
  function object(raw: unknown, keys: string[], what: string): Record<string, unknown> {
29
33
  if (!plain(raw)) throw new Error(`${what}: object required; set ${what} to a JSON object`);
@@ -95,12 +99,32 @@ function protocolInputs(raw: unknown, stored: boolean): Record<string, ProtocolI
95
99
  }
96
100
  return Object.fromEntries(result);
97
101
  }
102
+ /** A declared screen is closed and deterministic: no warning mode, no inferred material. */
103
+ function screenField(raw: unknown): ProtocolScreen {
104
+ const value = object(raw, ["evaluatorInputs", "literals"], "protocol.screen"), result: ProtocolScreen = {};
105
+ if (value.evaluatorInputs !== undefined) {
106
+ if (value.evaluatorInputs !== true) throw new Error("protocol.screen.evaluatorInputs: true or omitted required; the screen has no warning mode, so omit the field instead of disabling it");
107
+ result.evaluatorInputs = true;
108
+ }
109
+ if (value.literals !== undefined) {
110
+ const literals = array(value.literals, "protocol.screen.literals", SCREEN_LITERALS).map((item, index) => {
111
+ const text = literal(item, `protocol.screen.literals[${index}]`, SCREEN_LITERAL_BYTES), bytes = Buffer.byteLength(text);
112
+ if (bytes < SCREEN_LITERAL_MIN_BYTES) throw new Error(`protocol.screen.literals[${index}]: at least ${SCREEN_LITERAL_MIN_BYTES} UTF-8 bytes required; declare a longer fixed string`);
113
+ if (bytes > SCREEN_LITERAL_BYTES) throw new Error(`protocol.screen.literals[${index}]: at most ${SCREEN_LITERAL_BYTES} UTF-8 bytes allowed; shorten that fixed string`);
114
+ return text;
115
+ });
116
+ if (new Set(literals).size !== literals.length) throw new Error("protocol.screen.literals: duplicate string; declare each fixed string once");
117
+ result.literals = literals;
118
+ }
119
+ if (!Object.keys(result).length) throw new Error("protocol.screen: empty screen; declare evaluatorInputs, a literals list, or omit protocol.screen");
120
+ return result;
121
+ }
98
122
  /** Public configuration always requires executor-local locators for declared inputs. */
99
123
  export function validateProtocol(raw: unknown): Protocol { return protocolShape(raw, false); }
100
124
  /** Frozen attempt records carry identities only, never executor-host locators. */
101
125
  export function validateStoredProtocol(raw: unknown): Protocol { return protocolShape(raw, true); }
102
126
  function protocolShape(raw: unknown, stored: boolean): Protocol {
103
- const p = object(raw, ["v", "method", "candidate", "evaluator", "metrics", "seeds", "limits", "network", "budget", "inputs"], "protocol");
127
+ const p = object(raw, ["v", "method", "candidate", "evaluator", "metrics", "seeds", "limits", "network", "budget", "inputs", "screen"], "protocol");
104
128
  if (p.v !== 1) throw new Error("protocol.v: unsupported version; this executor supports v1 only; use a compatible ares release for stage protocols, keeping the original definition unchanged");
105
129
  if (p.network !== "none") throw new Error('protocol.network: network access is unsupported; set protocol.network to "none"');
106
130
  const limitsRaw = object(p.limits, Object.keys(LIMIT_BOUNDS), "protocol.limits");
@@ -120,6 +144,7 @@ function protocolShape(raw: unknown, stored: boolean): Protocol {
120
144
  maxGpuHours: number(budget.maxGpuHours, "budget.maxGpuHours", 0, 64_000_000, false),
121
145
  } };
122
146
  if (p.inputs !== undefined) protocol.inputs = protocolInputs(p.inputs, stored);
147
+ if (p.screen !== undefined) protocol.screen = screenField(p.screen);
123
148
  if (Buffer.byteLength(JSON.stringify(protocol, null, 2) + "\n") > PROTOCOL_BYTES) throw new Error(`protocol: too large; reduce the formatted protocol to at most ${PROTOCOL_BYTES} bytes`);
124
149
  return protocol;
125
150
  }
@@ -172,7 +197,7 @@ export function taskTreeHash(dir: string): string {
172
197
  if (stat.isSymbolicLink()) throw new Error(`${label}: symlink refused; replace it with a regular file or directory inside task/`);
173
198
  if (!relative && !stat.isDirectory()) throw new Error("task/: directory required; replace task with a directory containing task.md and evaluator/");
174
199
  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`);
200
+ 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
201
  const directory = opendirSync(path);
177
202
  try {
178
203
  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;
@@ -0,0 +1,83 @@
1
+ import { hashExecutorInputBlobs, spawnRunner, type Executor, type ProcessRunner, type ProcessResult } from "./executor.ts";
2
+ import { canonical, type ProtocolInput, type ProtocolScreen } from "./protocol.ts";
3
+ import { sha256 } from "../study.ts";
4
+
5
+ export interface ScreenHit { rule: string; path: string; line?: number }
6
+ export interface ScreenSummary { rules: string[]; sha256: string }
7
+ /** Directory inputs are screened file by file; above this count the screen refuses instead of vouching partially. */
8
+ export const SCREEN_FILES = 20_000, SCREEN_OUTPUT_BYTES = 1_048_576, SCREEN_HITS = 16;
9
+
10
+ function passed(result: ProcessResult): boolean { return result.exitCode === 0 && !result.timedOut && !result.truncated; }
11
+ function git(repo: string, args: string[], runner: ProcessRunner): Promise<ProcessResult> {
12
+ return runner({ command: "git", args: ["-C", repo, ...args], timeoutMs: 300_000, maxOutputBytes: SCREEN_OUTPUT_BYTES });
13
+ }
14
+ function gitFailure(step: string): Error {
15
+ return new Error(`attempt screen: Git ${step} failed; check --repo and that --commit names an existing commit, then retry ares attempt run`);
16
+ }
17
+ /** Object ids only: the commit's file bytes are never read on this host. */
18
+ async function treeBlobs(repo: string, commit: string, runner: ProcessRunner): Promise<Map<string, string[]>> {
19
+ const format = await git(repo, ["rev-parse", "--show-object-format"], runner);
20
+ if (!passed(format)) throw gitFailure("object format");
21
+ // A sha-256 repository issues 64-hex blob ids, so an input's sha-1 blob id could never match.
22
+ if (format.stdout.trim() !== "sha1") throw new Error("attempt screen: evaluator inputs cannot be compared in a repository whose object format is not sha-1; screen the declared literals only, or use a sha-1 candidate repository");
23
+ const listing = await git(repo, ["ls-tree", "-r", "-z", "--full-tree", commit], runner);
24
+ if (listing.truncated) throw new Error(`attempt screen: candidate commit lists more files than the screen reads (${SCREEN_OUTPUT_BYTES} bytes of git ls-tree); screen the declared literals only, or screen a smaller commit`);
25
+ if (!passed(listing)) throw gitFailure("tree listing");
26
+ const blobs = new Map<string, string[]>();
27
+ for (const entry of listing.stdout.split("\0")) {
28
+ const tab = entry.indexOf("\t");
29
+ if (tab < 0) continue;
30
+ const [, type, oid] = entry.slice(0, tab).split(" ");
31
+ if (type !== "blob" || oid === undefined || !/^[a-f0-9]{40}$/.test(oid)) continue;
32
+ const paths = blobs.get(oid) ?? [];
33
+ paths.push(entry.slice(tab + 1)); blobs.set(oid, paths);
34
+ }
35
+ return blobs;
36
+ }
37
+ /** Verbatim search only: every hit is a fixed string, so transformed material passes unguarded. */
38
+ async function literalPaths(repo: string, commit: string, value: string, runner: ProcessRunner): Promise<string[]> {
39
+ const result = await git(repo, ["grep", "--no-color", "-a", "-F", "-l", "-z", "-e", value, commit, "--"], runner);
40
+ if (result.exitCode === 1 && !result.truncated && !result.timedOut) return [];
41
+ if (!passed(result)) throw gitFailure("literal search");
42
+ const prefix = `${commit}:`;
43
+ return result.stdout.split("\0").filter(Boolean).map(entry => entry.startsWith(prefix) ? entry.slice(prefix.length) : entry).sort();
44
+ }
45
+ async function literalLine(repo: string, commit: string, path: string, value: string, runner: ProcessRunner): Promise<number | undefined> {
46
+ const result = await git(repo, ["grep", "--no-color", "-a", "-F", "-n", "-z", "-e", value, commit, "--", path], runner);
47
+ if (!passed(result)) return undefined;
48
+ // With -z git terminates both the tree-qualified name and the line number with NUL: name\0line\0text.
49
+ const nul = result.stdout.indexOf("\0");
50
+ if (nul < 0 || result.stdout.slice(0, nul) !== `${commit}:${path}`) return undefined;
51
+ const line = /^(\p{Nd}+)\u0000/u.exec(result.stdout.slice(nul + 1))?.[1];
52
+ return line === undefined ? undefined : Number(line);
53
+ }
54
+ /** Runs before the executor is asked to execute anything: no attempt record and no budget exist yet. */
55
+ export async function screenCandidate(repo: string, commit: string, screen: ProtocolScreen, inputs: Record<string, ProtocolInput>, executor: Executor, runner: ProcessRunner = spawnRunner): Promise<{ hits: ScreenHit[]; summary: ScreenSummary }> {
56
+ const hits: ScreenHit[] = [], rules: string[] = [];
57
+ if (screen.evaluatorInputs) {
58
+ rules.push("evaluatorInputs");
59
+ const tree = await treeBlobs(repo, commit, runner);
60
+ for (const [name, input] of Object.entries(inputs)) {
61
+ // Only an evaluator-only mount is invisible to the candidate at run time, so only that leak matters.
62
+ if (!input.mount.evaluator || input.mount.candidate) continue;
63
+ if (input.path === undefined) throw new Error(`attempt screen: evaluator input ${name} has no executor locator; restore its path in design/protocol.json before attempt run`);
64
+ let blobs: { blobs: string[] };
65
+ try { blobs = await hashExecutorInputBlobs(executor, input.path, SCREEN_FILES, runner); }
66
+ catch (error) { throw new Error(`attempt screen: evaluator input ${name}: ${error instanceof Error ? error.message : "blob list could not be read"}`); }
67
+ for (const blob of blobs.blobs) {
68
+ for (const path of tree.get(blob) ?? []) if (hits.length < SCREEN_HITS) hits.push({ rule: `evaluator-input:${name}`, path });
69
+ }
70
+ }
71
+ }
72
+ if (screen.literals) {
73
+ rules.push("literals");
74
+ for (const [index, value] of screen.literals.entries()) {
75
+ for (const path of await literalPaths(repo, commit, value, runner)) {
76
+ if (hits.length >= SCREEN_HITS) break;
77
+ const line = await literalLine(repo, commit, path, value, runner);
78
+ hits.push({ rule: `literal:${index}`, path, ...(line === undefined ? {} : { line }) });
79
+ }
80
+ }
81
+ }
82
+ return { hits, summary: { rules, sha256: sha256(canonical({ commit, screen })) } };
83
+ }
@@ -2,16 +2,60 @@ import { existsSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { boundedText, commit, onlyKeys, openStudy, plain, readTextBounded, requireExperiment, sha256, type Actor } from "../study.ts";
4
4
  import type { ProtocolDefinition as Protocol } from "./protocol.ts";
5
+ import type { Attempt } from "./attempts.ts";
6
+ import { readBoundCalibration } from "./calibrate.ts";
5
7
 
6
- export interface Selection { v: 1; run: string; metric: string; baseline: { commit: string }; minSeeds: number; minDelta: number }
8
+ interface SelectionFields { run: string; metric: string; baseline: { commit: string }; minSeeds: number; minDelta: number }
9
+ interface Guard { metric: string; maxRegression: number }
10
+ interface CostRule { metric: string; free: number; perUnit: number }
11
+ export type Selection = SelectionFields & (
12
+ { v: 1 } | { v: 2; guards?: Guard[]; cost?: CostRule; calibration?: { sha256: string } }
13
+ );
14
+ const V1_FIELDS = ["v", "run", "metric", "baseline", "minSeeds", "minDelta"];
15
+ const V2_FIELDS = [...V1_FIELDS, "guards", "cost", "calibration"];
16
+
17
+ function nonnegative(value: unknown, field: string): number {
18
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new Error(`${field}: finite number >= 0 required`);
19
+ return value;
20
+ }
21
+
22
+ function v2Fields(raw: Record<string, unknown>, protocol: Protocol, primary: string) {
23
+ const fields: Pick<Extract<Selection, { v: 2 }>, "guards" | "cost" | "calibration"> = {};
24
+ if (Object.hasOwn(raw, "guards")) {
25
+ if (!Array.isArray(raw.guards) || raw.guards.length > 8) throw new Error("selection.guards: array of at most eight guards required");
26
+ const seen = new Set<string>([primary]);
27
+ fields.guards = raw.guards.map(guard => {
28
+ if (!plain(guard)) throw new Error("selection.guards: each guard must be an object");
29
+ onlyKeys(guard, ["metric", "maxRegression"], "selection.guard");
30
+ const metric = boundedText(guard.metric, "selection.guard.metric", 128);
31
+ if (seen.has(metric) || !protocol.metrics.some(m => m.name === metric)) throw new Error("selection.guard.metric: select a distinct declared metric other than the primary");
32
+ seen.add(metric);
33
+ return { metric, maxRegression: nonnegative(guard.maxRegression, "selection.guard.maxRegression") };
34
+ });
35
+ }
36
+ if (Object.hasOwn(raw, "cost")) {
37
+ if (!plain(raw.cost)) throw new Error("selection.cost: object required");
38
+ onlyKeys(raw.cost, ["metric", "free", "perUnit"], "selection.cost");
39
+ const metric = boundedText(raw.cost.metric, "selection.cost.metric", 128);
40
+ if (!protocol.metrics.some(m => m.name === metric && m.direction === "min")) throw new Error("selection.cost.metric: select a declared min metric");
41
+ fields.cost = { metric, free: nonnegative(raw.cost.free, "selection.cost.free"), perUnit: nonnegative(raw.cost.perUnit, "selection.cost.perUnit") };
42
+ }
43
+ if (Object.hasOwn(raw, "calibration")) {
44
+ if (!plain(raw.calibration)) throw new Error("selection.calibration: object required");
45
+ onlyKeys(raw.calibration, ["sha256"], "selection.calibration");
46
+ if (typeof raw.calibration.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(raw.calibration.sha256)) throw new Error("selection.calibration.sha256: lowercase SHA-256 required");
47
+ fields.calibration = { sha256: raw.calibration.sha256 };
48
+ }
49
+ return fields;
50
+ }
7
51
  export const SELECTION_BYTES = 65_536;
8
52
  const compatible = "use an ares version that supports this selection, keeping design/selection.json unchanged";
9
53
  export function selectionPath(dir: string): string { return join(dir, "design", "selection.json"); }
10
54
  export function validateSelection(raw: unknown, protocol: Protocol): Selection {
11
55
  try {
12
56
  if (!plain(raw)) throw new Error("selection: JSON object required");
13
- if (raw.v !== 1) throw new Error(`selection.v: unsupported version; ${compatible}`);
14
- onlyKeys(raw, ["v", "run", "metric", "baseline", "minSeeds", "minDelta"], "selection");
57
+ if (raw.v !== 1 && raw.v !== 2) throw new Error(`selection.v: unsupported version; ${compatible}`);
58
+ onlyKeys(raw, raw.v === 1 ? V1_FIELDS : V2_FIELDS, "selection");
15
59
  if (typeof raw.run !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(raw.run)) throw new Error("selection.run: use 1..64 letters, digits, underscores or hyphens, starting with a letter or digit");
16
60
  if (["ablate", "final", "posthoc"].includes(raw.run)) throw new Error(`selection.run: ${raw.run} is a reserved phase run; choose another run such as investigate`);
17
61
  const metric = boundedText(raw.metric, "selection.metric", 128);
@@ -21,7 +65,8 @@ export function validateSelection(raw: unknown, protocol: Protocol): Selection {
21
65
  if (typeof raw.baseline.commit !== "string" || !/^[a-fA-F0-9]{40}$/.test(raw.baseline.commit)) throw new Error("selection.baseline.commit: full 40-hex commit required");
22
66
  if (!Number.isSafeInteger(raw.minSeeds) || (raw.minSeeds as number) < 1 || (raw.minSeeds as number) > protocol.seeds.length) throw new Error(`selection.minSeeds: integer in 1..${protocol.seeds.length} required (declared protocol seed count)`);
23
67
  if (typeof raw.minDelta !== "number" || !Number.isFinite(raw.minDelta) || raw.minDelta < 0) throw new Error("selection.minDelta: finite number >= 0 required in the metric's unit");
24
- return { v: 1, run: raw.run, metric, baseline: { commit: raw.baseline.commit.toLowerCase() }, minSeeds: raw.minSeeds as number, minDelta: raw.minDelta };
68
+ const fields = { run: raw.run, metric, baseline: { commit: raw.baseline.commit.toLowerCase() }, minSeeds: raw.minSeeds as number, minDelta: raw.minDelta };
69
+ return raw.v === 1 ? { v: 1, ...fields } : { v: 2, ...fields, ...v2Fields(raw, protocol, metric) };
25
70
  } catch (error) {
26
71
  const message = error instanceof Error ? error.message : "selection: invalid rule";
27
72
  throw new Error(message.includes(compatible) ? message : `${message}; correct the rule and run ares selection <dir> --file PATH again`);
@@ -47,7 +92,68 @@ export function selectionHash(dir: string, protocol: Protocol): string | undefin
47
92
  export function setSelection(dir: string, raw: unknown, protocol: Protocol, actor: Actor) {
48
93
  requireExperiment(openStudy(dir).study);
49
94
  const selection = validateSelection(raw, protocol), previous = record(dir, protocol);
95
+ if (selection.v === 2 && selection.calibration) readBoundCalibration(dir, selection, protocol);
50
96
  const text = JSON.stringify(selection, null, 2) + "\n", hash = sha256(text), changed = previous?.text !== text;
51
97
  if (changed) commit(dir, [[selectionPath(dir), text, SELECTION_BYTES]], [{ actor, type: "selection.set", data: { sha256: hash, run: selection.run, metric: selection.metric } }]);
52
98
  return { selection, sha256: hash, changed };
53
99
  }
100
+
101
+ export function observedMetric(attempt: Attempt, metric: Protocol["metrics"][number]): number | undefined {
102
+ const values = Array.isArray(attempt.metrics) ? attempt.metrics.filter(m => m?.name === metric.name) : [];
103
+ const measurement = values[0];
104
+ return values.length === 1 && measurement?.unit === metric.unit && measurement.provenance === "ares-observed"
105
+ && typeof measurement.value === "number" && Number.isFinite(measurement.value) ? measurement.value : undefined;
106
+ }
107
+
108
+ export function sampleMean(values: number[]): number | null {
109
+ if (!values.length) return null;
110
+ const total = values.reduce((sum, value) => sum + value, 0);
111
+ if (Number.isFinite(total)) return total / values.length;
112
+ const scale = Math.max(...values.map(Math.abs));
113
+ if (!scale) return 0;
114
+ return Math.max(-1, Math.min(1, values.reduce((sum, value) => sum + value / scale / values.length, 0))) * scale;
115
+ }
116
+
117
+ export interface SelectionPair { attempt: Attempt; baseline: Attempt }
118
+ export interface ConstraintResult {
119
+ guardDeltas?: Record<string, number | null>;
120
+ cost?: { growth: number; allowedGrowth: number };
121
+ reason?: string;
122
+ }
123
+
124
+ /** Both phases apply the same independent rules to their actual paired attempts. */
125
+ export function evaluateSelectionConstraints(
126
+ rule: Selection, protocol: Protocol, pairs: readonly SelectionPair[], delta: number,
127
+ ): ConstraintResult {
128
+ if (rule.v === 1 || !pairs.length) return {};
129
+ const result: ConstraintResult = {};
130
+ const values = (name: string) => {
131
+ const metric = protocol.metrics.find(entry => entry.name === name)!;
132
+ const candidate = pairs.map(pair => observedMetric(pair.attempt, metric));
133
+ const baseline = pairs.map(pair => observedMetric(pair.baseline, metric));
134
+ return { metric, candidate, baseline };
135
+ };
136
+ const complete = (sample: (number | undefined)[]): sample is number[] => sample.every(value => value !== undefined);
137
+ for (const guard of rule.guards ?? []) {
138
+ const { metric, candidate, baseline } = values(guard.metric);
139
+ const measured = complete(candidate) && complete(baseline);
140
+ const difference = measured ? sampleMean(candidate)! - sampleMean(baseline)! : null;
141
+ const adjusted = difference === null ? null : metric.direction === "max" ? difference : -difference;
142
+ if (adjusted !== null && !Number.isFinite(adjusted)) throw new Error(`selection guard ${guard.metric}: delta overflows; rescale the metric in a new protocol and rerun attempts`);
143
+ (result.guardDeltas ??= Object.create(null) as Record<string, number | null>)[guard.metric] = adjusted;
144
+ if (adjusted === null) result.reason ??= `guard-missing:${guard.metric}`;
145
+ else if (adjusted < -guard.maxRegression) result.reason ??= `guard:${guard.metric}`;
146
+ }
147
+ if (rule.cost) {
148
+ const { candidate, baseline } = values(rule.cost.metric);
149
+ const base = complete(baseline) ? sampleMean(baseline) : null;
150
+ if (base !== null && base <= 0) throw new Error(`selection cost ${rule.cost.metric}: baseline mean must be positive; correct the cost metric and rerun the baseline attempts`);
151
+ if (base === null || !complete(candidate)) { result.reason ??= "cost-missing"; return result; }
152
+ const average = sampleMean(candidate)!;
153
+ const growth = (average - base) / base, allowedGrowth = rule.cost.free + rule.cost.perUnit * delta;
154
+ if (!Number.isFinite(growth) || !Number.isFinite(allowedGrowth)) throw new Error(`selection cost ${rule.cost.metric}: cost rule overflows; rescale the metrics or revise the rule and rerun investigation`);
155
+ result.cost = { growth, allowedGrowth };
156
+ if (growth > 0 && growth > allowedGrowth) result.reason ??= "cost-rule";
157
+ }
158
+ return result;
159
+ }
@@ -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/exp/stages.ts CHANGED
@@ -96,10 +96,12 @@ function candidateStages(raw: unknown, common: Protocol): CandidateStage[] {
96
96
 
97
97
  /** Pure preflight: no study writes, process calls, mounts or artifact availability claims. */
98
98
  export function validateStageProtocol(raw: unknown): ProtocolV2 {
99
- const p = object(raw, ["v", "method", "candidate", "evaluator", "metrics", "seeds", "limits", "network", "budget"], "protocol");
99
+ const p = object(raw, ["v", "method", "candidate", "evaluator", "metrics", "seeds", "limits", "network", "budget", "screen"], "protocol");
100
100
  if (p.v !== 2) throw new Error("protocol.v: unsupported stage version; use a compatible ares release, keeping the original definition unchanged");
101
101
  // Validate common fields with the authoritative v1 validator; no common bound is multiplied.
102
102
  const common = validateProtocol({ ...p, v: 1, candidate: PLACEHOLDER_EXECUTION });
103
+ // A stage protocol declares no protocol-level inputs, so no evaluator-only mount exists to compare.
104
+ if (common.screen?.evaluatorInputs) throw new Error("protocol.screen.evaluatorInputs: stage protocols declare no protocol inputs; screen the declared literals only");
103
105
  const { v: _v, candidate: _candidate, inputs: _inputs, ...base } = common;
104
106
  const result: ProtocolV2 = { ...base, v: 2, candidate: { stages: candidateStages(p.candidate, common) } };
105
107
  if (Buffer.byteLength(JSON.stringify(result, null, 2) + "\n") > PROTOCOL_BYTES) throw new Error(`protocol: too large; reduce the formatted protocol to at most ${PROTOCOL_BYTES} bytes`);