@lelouchhe/agent-evals 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -7,8 +7,9 @@ import { judgeChecker } from "./checkers/judge/index.js";
7
7
  import { mockChecker } from "./checkers/mock/index.js";
8
8
  import { shellChecker } from "./checkers/shell/index.js";
9
9
  import { traceChecker } from "./checkers/trace/index.js";
10
- import { loadCase, loadCases } from "./engine/authoring.js";
10
+ import { loadCases } from "./engine/authoring.js";
11
11
  import { ConfigError, errorMessage } from "./engine/config.js";
12
+ import { createEnvSource } from "./engine/env-source.js";
12
13
  import { addChecker, addRunner, createRegistry, loadTrustedImplementations } from "./engine/registry.js";
13
14
  import { executeEvaluation, prepareEvaluation } from "./engine/run.js";
14
15
  import { formatMatrix, formatReport } from "./engine/report.js";
@@ -23,18 +24,21 @@ const USAGE = `Usage: agent-evals <command> <config.yml> [options]
23
24
 
24
25
  Commands:
25
26
  run <config.yml> Execute the selected case, or every case when --case is omitted
26
- view <config.yml> Show the resolved case, its field origins and its placement
27
+ view <config.yml> Show the selected case, or every case when --case is omitted
27
28
  report <results-dir>... Print a session report from retained run records
28
29
  config <agent.yml> Query ACP configuration values without prompting
29
30
  login <agent.yml> Run the declared native command and save login files
30
31
 
31
32
  Options:
32
- --case <name> Named case to select (required by view for files with cases)
33
- --reps <n> Repeat each selected case n times, serially (default: 1)
33
+ --case <name> Named case to select (omitting selects every case in a cases document)
34
+ --reps <n> Repeat each selected case n times (default: 1)
35
+ --jobs <n> Maximum concurrent runs (default: 1)
36
+ --retain <mode> Retain workspace and home (excluding login): none, on-failure, all (default: none)
34
37
  --results-dir <path> Where run records are written (default: .agent-evals)
35
38
  --extension-dir <path> Trusted extension root, one implementation per subdirectory (repeatable)
36
39
  --files With view: list every placed and excluded path
37
40
  --matrix With report: one table of checks by case instead of the session report
41
+ --version, -V Show version
38
42
  --help Show this help
39
43
 
40
44
  Configuration errors exit with code 2 before any run resource is created.
@@ -54,16 +58,25 @@ async function main(argv) {
54
58
  process.stdout.write(USAGE);
55
59
  return 0;
56
60
  }
61
+ if (error instanceof VersionRequested) {
62
+ const pkg = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
63
+ process.stdout.write(`${pkg.version ?? "unknown"}\n`);
64
+ return 0;
65
+ }
57
66
  process.stderr.write(`error: ${errorMessage(error)}\n\n${USAGE}`);
58
67
  return 2;
59
68
  }
60
69
  try {
61
70
  if (options.command === "view") {
62
- const resolved = await loadCase(options.configPath, {
71
+ const cases = await loadCases(options.configPath, {
63
72
  ...(options.caseName === undefined ? {} : { caseName: options.caseName }),
64
73
  });
65
- const placement = await describePlacement(resolved);
66
- process.stdout.write(formatResolvedCase(resolved, { placement, files: options.showFiles }));
74
+ const rendered = [];
75
+ for (const resolved of cases) {
76
+ const placement = await describePlacement(resolved);
77
+ rendered.push(formatResolvedCase(resolved, { placement, files: options.showFiles }));
78
+ }
79
+ process.stdout.write(rendered.join("\n"));
67
80
  return 0;
68
81
  }
69
82
  if (options.command === "report") {
@@ -126,10 +139,18 @@ async function runCommand(options) {
126
139
  });
127
140
  await loadTrustedImplementations(registry, { extensionDirs: options.extensionDirs });
128
141
  const resultsDir = options.resultsDir ?? resolve(".agent-evals");
142
+ const envSource = createEnvSource(process.cwd(), abort.signal);
129
143
  const prepared = [];
130
144
  for (let rep = 0; rep < options.reps; rep += 1) {
131
145
  for (const entry of cases) {
132
- prepared.push(await prepareEvaluation({ case: entry, registry, resultsDir, signal: abort.signal }));
146
+ prepared.push(await prepareEvaluation({
147
+ case: entry,
148
+ registry,
149
+ resultsDir,
150
+ retain: options.retain,
151
+ signal: abort.signal,
152
+ envSource,
153
+ }));
133
154
  }
134
155
  }
135
156
  // One repetition of one case keeps the single-run output; so does an ordinary document.
@@ -139,15 +160,58 @@ async function runCommand(options) {
139
160
  process.stdout.write(`\n${formatReport([record])}`);
140
161
  return exitCode(record);
141
162
  }
142
- const records = [];
143
- for (const entry of prepared) {
144
- // Cancellation stops the rest; an error or a failed check does not.
145
- if (abort.signal.aborted)
146
- break;
147
- records.push(await executeEvaluation(entry));
163
+ const slots = new Array(prepared.length);
164
+ const pending = prepared.map((_, index) => index);
165
+ const inFlightKeys = new Set();
166
+ let firstError;
167
+ let active = 0;
168
+ // Event-driven bounded pool: runs sharing a `concurrencyKey` (e.g., persistent ACP login.dir)
169
+ // serialize while unrelated runs execute concurrently up to `options.jobs`. If any worker
170
+ // rejects unexpectedly, abort and wait for all active workers to drain before exiting.
171
+ await new Promise((resolvePool) => {
172
+ const schedule = () => {
173
+ while (active < options.jobs && !abort.signal.aborted && firstError === undefined) {
174
+ const pos = pending.findIndex((index) => prepared[index].registered.concurrencyKeys.every((key) => !inFlightKeys.has(key)));
175
+ if (pos === -1)
176
+ break;
177
+ const [index] = pending.splice(pos, 1);
178
+ const entry = prepared[index];
179
+ const keys = entry.registered.concurrencyKeys;
180
+ for (const key of keys)
181
+ inFlightKeys.add(key);
182
+ active += 1;
183
+ void executeEvaluation(entry)
184
+ .then((record) => {
185
+ slots[index] = record;
186
+ }, (caught) => {
187
+ firstError ??= caught;
188
+ abort.abort();
189
+ })
190
+ .finally(() => {
191
+ for (const key of keys)
192
+ inFlightKeys.delete(key);
193
+ active -= 1;
194
+ schedule();
195
+ if (active === 0 && (pending.length === 0 || abort.signal.aborted || firstError !== undefined)) {
196
+ resolvePool();
197
+ }
198
+ });
199
+ }
200
+ if (active === 0) {
201
+ resolvePool();
202
+ }
203
+ };
204
+ schedule();
205
+ });
206
+ if (firstError !== undefined) {
207
+ throw firstError;
148
208
  }
209
+ const records = [];
149
210
  const casesPerRep = cases.length;
150
- for (const [index, record] of records.entries()) {
211
+ for (const [index, record] of slots.entries()) {
212
+ if (record === undefined)
213
+ continue;
214
+ records.push(record);
151
215
  const repLabel = options.reps === 1 ? "" : `rep ${Math.floor(index / casesPerRep) + 1}/${options.reps} `;
152
216
  printCaseLine(record, resultsDir, repLabel);
153
217
  }
@@ -182,6 +246,9 @@ function parseArguments(argv) {
182
246
  files: { type: "boolean" },
183
247
  matrix: { type: "boolean" },
184
248
  reps: { type: "string" },
249
+ jobs: { type: "string" },
250
+ retain: { type: "string" },
251
+ version: { type: "boolean", short: "V" },
185
252
  help: { type: "boolean", short: "h" },
186
253
  },
187
254
  });
@@ -193,6 +260,9 @@ function parseArguments(argv) {
193
260
  if (values.help === true) {
194
261
  throw new HelpRequested();
195
262
  }
263
+ if (values.version === true) {
264
+ throw new VersionRequested();
265
+ }
196
266
  const [command, rawConfigPath, ...unexpected] = positionals;
197
267
  if (command !== "run" && command !== "view" && command !== "report" && command !== "config" && command !== "login") {
198
268
  throw new ConfigError(command === undefined ? "a command is required" : `unknown command: ${command}`);
@@ -207,13 +277,19 @@ function parseArguments(argv) {
207
277
  (values.case !== undefined ||
208
278
  values["results-dir"] !== undefined ||
209
279
  values["extension-dir"] !== undefined ||
210
- values.reps !== undefined)) {
280
+ values.reps !== undefined ||
281
+ values.jobs !== undefined ||
282
+ values.retain !== undefined)) {
211
283
  throw new ConfigError(`${command} accepts only an agent configuration file, not case or run options`);
212
284
  }
213
285
  const extensionDirs = (values["extension-dir"] ?? []).map((directory) => resolve(directory));
214
286
  if (command === "view" &&
215
- (values["results-dir"] !== undefined || extensionDirs.length > 0 || values.reps !== undefined)) {
216
- throw new ConfigError("view does not accept --results-dir, --extension-dir or --reps");
287
+ (values["results-dir"] !== undefined ||
288
+ extensionDirs.length > 0 ||
289
+ values.reps !== undefined ||
290
+ values.jobs !== undefined ||
291
+ values.retain !== undefined)) {
292
+ throw new ConfigError("view does not accept --results-dir, --extension-dir, --reps, --jobs or --retain");
217
293
  }
218
294
  if (command !== "view" && values.files === true) {
219
295
  throw new ConfigError("--files applies only to view");
@@ -225,10 +301,14 @@ function parseArguments(argv) {
225
301
  (values.case !== undefined ||
226
302
  values["results-dir"] !== undefined ||
227
303
  values["extension-dir"] !== undefined ||
228
- values.reps !== undefined)) {
304
+ values.reps !== undefined ||
305
+ values.jobs !== undefined ||
306
+ values.retain !== undefined)) {
229
307
  throw new ConfigError("report accepts only results directories");
230
308
  }
231
- const reps = values.reps === undefined ? 1 : expectReps(values.reps);
309
+ const reps = values.reps === undefined ? 1 : expectPositiveInt(values.reps, "--reps");
310
+ const jobs = values.jobs === undefined ? 1 : expectPositiveInt(values.jobs, "--jobs");
311
+ const retain = values.retain === undefined ? "none" : expectRetain(values.retain);
232
312
  return {
233
313
  command,
234
314
  configPath: resolve(rawConfigPath),
@@ -238,17 +318,25 @@ function parseArguments(argv) {
238
318
  showFiles: values.files === true,
239
319
  matrix: values.matrix === true,
240
320
  reps,
321
+ jobs,
322
+ retain,
241
323
  extraPaths: unexpected.map((path) => resolve(path)),
242
324
  };
243
325
  }
244
- /** A repetition count is a positive integer written in decimal that a loop can count to. */
245
- function expectReps(value) {
326
+ /** A count flag is a positive integer written in decimal that a loop can count to. */
327
+ function expectPositiveInt(value, flag) {
246
328
  const count = Number(value);
247
329
  if (!/^[0-9]+$/.test(value) || !Number.isSafeInteger(count) || count < 1) {
248
- throw new ConfigError(`--reps must be a positive integer, got ${JSON.stringify(value)}`);
330
+ throw new ConfigError(`${flag} must be a positive integer, got ${JSON.stringify(value)}`);
249
331
  }
250
332
  return count;
251
333
  }
334
+ function expectRetain(value) {
335
+ if (value !== "none" && value !== "on-failure" && value !== "all") {
336
+ throw new ConfigError(`--retain must be "none", "on-failure", or "all", got ${JSON.stringify(value)}`);
337
+ }
338
+ return value;
339
+ }
252
340
  /**
253
341
  * Read every retained run record under the given paths. A path may be a results directory (walked
254
342
  * recursively), a single run directory or a `result.json` file.
@@ -295,16 +383,18 @@ async function findResultFiles(path) {
295
383
  if (info.isFile()) {
296
384
  return [path];
297
385
  }
386
+ const entries = await readdir(path, { withFileTypes: true });
387
+ // A directory with `result.json` is a single run record; do not recurse into its subdirectories.
388
+ if (entries.some((entry) => !entry.isDirectory() && entry.name === "result.json")) {
389
+ return [join(path, "result.json")];
390
+ }
298
391
  const found = [];
299
- for (const entry of await readdir(path, { withFileTypes: true })) {
300
- const child = join(path, entry.name);
301
- if (entry.isDirectory()) {
302
- for (const file of await findResultFiles(child))
392
+ for (const entry of entries) {
393
+ // Never descend into retained artifact trees, even for an incomplete run with no `result.json`.
394
+ if (entry.isDirectory() && entry.name !== "artifacts") {
395
+ for (const file of await findResultFiles(join(path, entry.name)))
303
396
  found.push(file);
304
397
  }
305
- else if (entry.name === "result.json") {
306
- found.push(child);
307
- }
308
398
  }
309
399
  return found.sort();
310
400
  }
@@ -318,6 +408,12 @@ function printRecord(record, resultsDir) {
318
408
  if (record.error !== undefined) {
319
409
  lines.push(` error: ${record.error}`);
320
410
  }
411
+ if (record.artifacts?.status === "retained" && record.artifacts.path !== undefined) {
412
+ lines.push(` artifacts: ${join(resultsDir, record.runId, record.artifacts.path)}`);
413
+ }
414
+ else if (record.artifacts?.status === "failed") {
415
+ lines.push(` artifacts: failed — ${record.artifacts.error ?? "unknown error"}`);
416
+ }
321
417
  lines.push(` results: ${join(resultsDir, record.runId, "result.json")}`);
322
418
  process.stdout.write(lines.join("\n") + "\n");
323
419
  }
@@ -337,7 +433,10 @@ function exitCode(record) {
337
433
  /** One summary line per executed case: name, status and the retained result record. */
338
434
  function printCaseLine(record, resultsDir, prefix = "") {
339
435
  const name = record.case.name ?? record.case.path;
340
- process.stdout.write(`${prefix}${name}: ${runOutcome(record)} ${join(resultsDir, record.runId, "result.json")}\n`);
436
+ const retainNote = record.artifacts?.status === "failed"
437
+ ? ` (artifacts retention failed: ${record.artifacts.error ?? "unknown error"})`
438
+ : "";
439
+ process.stdout.write(`${prefix}${name}: ${runOutcome(record)} ${join(resultsDir, record.runId, "result.json")}${retainNote}\n`);
341
440
  }
342
441
  /** Zero only when every case passed, 1 for failed checks, 2 for anything that could not be judged. */
343
442
  function aggregateExit(records) {
@@ -348,5 +447,7 @@ function aggregateExit(records) {
348
447
  }
349
448
  class HelpRequested extends Error {
350
449
  }
450
+ class VersionRequested extends Error {
451
+ }
351
452
  const code = await main(process.argv.slice(2));
352
453
  process.exitCode = code;
@@ -3,7 +3,7 @@ import { dirname, resolve } from "node:path";
3
3
  import { parseImplementationParams } from "./params.js";
4
4
  import { checkPlaceholders, substituteValues } from "./values.js";
5
5
  import { isAlias, isMap, isNode, isScalar, isSeq, parseDocument } from "yaml";
6
- import { CASES_KEY, CASE_FIELD_KEYS, ConfigError, errorMessage, expectCaseConfig, } from "./config.js";
6
+ import { CASES_KEY, CASE_FIELDS, CASE_FIELD_KEYS, ConfigError, errorMessage, expectCaseConfig, } from "./config.js";
7
7
  /**
8
8
  * Resolve one YAML authoring document to a single case.
9
9
  *
@@ -44,27 +44,30 @@ async function readCaseDocument(path) {
44
44
  common.push(field);
45
45
  }
46
46
  const cases = casesField === undefined ? undefined : parseCases(casesField, file, text);
47
- return { file, common, ...(cases === undefined ? {} : { cases }) };
47
+ return { file, text, common, ...(cases === undefined ? {} : { cases }) };
48
48
  }
49
49
  function buildCase(document, selected) {
50
- const { file, common } = document;
51
- if (selected !== undefined) {
52
- const commonKeys = new Set(common.map((field) => field.key));
53
- const shared = selected.fields.filter((field) => commonKeys.has(field.key)).map((field) => field.key);
54
- if (shared.length > 0) {
55
- throw new ConfigError(`case "${selected.name}" in ${file} repeats top-level field${shared.length === 1 ? "" : "s"} from the common part: ${shared.join(", ")}; common and selected fields must be disjoint`);
56
- }
57
- }
50
+ const { file, text, common } = document;
58
51
  const final = {};
59
52
  const origins = {};
60
53
  for (const field of common) {
54
+ const type = fieldType(field.key);
61
55
  final[field.key] = fieldValue(field);
62
- origins[field.key] = { file, line: field.line, kind: "common" };
56
+ origins[field.key] = extractFieldOrigin(type, field, { file, line: field.line, kind: "common" }, text);
63
57
  }
64
58
  if (selected !== undefined) {
65
59
  for (const field of selected.fields) {
66
- final[field.key] = fieldValue(field);
67
- origins[field.key] = { file, line: field.line, kind: "case", caseName: selected.name };
60
+ const type = fieldType(field.key);
61
+ const nextValue = fieldValue(field);
62
+ const nextOrigin = extractFieldOrigin(type, field, { file, line: field.line, kind: "case", caseName: selected.name }, text);
63
+ if (Object.hasOwn(final, field.key)) {
64
+ final[field.key] = composeFieldValue(type, final[field.key], nextValue);
65
+ origins[field.key] = composeFieldOrigin(type, origins[field.key], nextOrigin);
66
+ }
67
+ else {
68
+ final[field.key] = nextValue;
69
+ origins[field.key] = nextOrigin;
70
+ }
68
71
  }
69
72
  }
70
73
  const label = selected === undefined ? `case configuration ${file}` : `case "${selected.name}"`;
@@ -81,6 +84,98 @@ function buildCase(document, selected) {
81
84
  origins,
82
85
  };
83
86
  }
87
+ function fieldType(key) {
88
+ return CASE_FIELDS[key];
89
+ }
90
+ function composeFieldValue(type, commonValue, caseValue) {
91
+ if (typeof type !== "string") {
92
+ if (!isPlainRecord(commonValue) || !isPlainRecord(caseValue)) {
93
+ return isPlainRecord(commonValue) ? caseValue : commonValue;
94
+ }
95
+ const merged = {};
96
+ for (const [entryKey, value] of Object.entries(commonValue)) {
97
+ defineOwn(merged, entryKey, value);
98
+ }
99
+ for (const [entryKey, caseEntry] of Object.entries(caseValue)) {
100
+ defineOwn(merged, entryKey, Object.hasOwn(merged, entryKey) ? composeFieldValue(type.child, merged[entryKey], caseEntry) : caseEntry);
101
+ }
102
+ return merged;
103
+ }
104
+ switch (type) {
105
+ case "value":
106
+ return caseValue;
107
+ case "list":
108
+ if (!Array.isArray(commonValue) || !Array.isArray(caseValue)) {
109
+ return Array.isArray(commonValue) ? caseValue : commonValue;
110
+ }
111
+ return [...commonValue, ...caseValue];
112
+ }
113
+ }
114
+ function extractFieldOrigin(type, field, base, text) {
115
+ if (typeof type !== "string") {
116
+ if (!isMap(field.node))
117
+ return base;
118
+ const entries = {};
119
+ for (const pair of field.node.items) {
120
+ if (!isScalar(pair.key) || typeof pair.key.value !== "string")
121
+ continue;
122
+ const entryBase = {
123
+ ...base,
124
+ line: isNode(pair.key) ? lineAt(pair.key, text) : base.line,
125
+ };
126
+ defineOwn(entries, pair.key.value, extractFieldOrigin(type.child, { node: pair.value }, entryBase, text));
127
+ }
128
+ return { kind: "map", base, entries };
129
+ }
130
+ switch (type) {
131
+ case "value":
132
+ return base;
133
+ case "list": {
134
+ if (!isSeq(field.node))
135
+ return base;
136
+ const items = field.node.items.map((item) => ({
137
+ ...base,
138
+ line: isNode(item) ? lineAt(item, text) : base.line,
139
+ }));
140
+ return { kind: "list", base, items };
141
+ }
142
+ }
143
+ }
144
+ function composeFieldOrigin(type, common, next) {
145
+ if (typeof type !== "string") {
146
+ if (common.kind === "map" && next.kind === "map") {
147
+ const entries = {};
148
+ for (const [entryKey, entryOrigin] of Object.entries(common.entries)) {
149
+ defineOwn(entries, entryKey, entryOrigin);
150
+ }
151
+ for (const [entryKey, entryOrigin] of Object.entries(next.entries)) {
152
+ defineOwn(entries, entryKey, Object.hasOwn(entries, entryKey)
153
+ ? composeFieldOrigin(type.child, entries[entryKey], entryOrigin)
154
+ : entryOrigin);
155
+ }
156
+ return { kind: "map", base: common.base, entries };
157
+ }
158
+ return next;
159
+ }
160
+ switch (type) {
161
+ case "value":
162
+ if ((common.kind === "common" || common.kind === "case") && (next.kind === "common" || next.kind === "case")) {
163
+ return { ...next, overrides: common };
164
+ }
165
+ return next;
166
+ case "list":
167
+ if (common.kind === "list" && next.kind === "list") {
168
+ return { kind: "list", base: common.base, items: [...common.items, ...next.items] };
169
+ }
170
+ return next;
171
+ }
172
+ }
173
+ function defineOwn(target, key, value) {
174
+ Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });
175
+ }
176
+ function isPlainRecord(value) {
177
+ return typeof value === "object" && value !== null && !Array.isArray(value);
178
+ }
84
179
  /** Load a standalone implementation object using the same YAML and placeholder rules as cases. */
85
180
  export async function loadImplementationParameters(path, schema, source) {
86
181
  const { file, fields } = await readMapping(path);
@@ -78,16 +78,39 @@ export type ShellMocks = Readonly<Record<string, ShellMock>>;
78
78
  export interface MocksConfig {
79
79
  readonly shell: ShellMocks;
80
80
  }
81
- /** Where one final top-level case field was declared. Nested values share this origin. */
82
- export type FieldOrigin = {
81
+ /**
82
+ * Structural YAML type of a top-level case field, which determines how common and case declarations compose:
83
+ * - `"value"`: scalar or atomic object; a case replaces the common default as a whole.
84
+ * - `"list"`: sequence; a case appends its items after the common items.
85
+ * - `{ kind: "map", child }`: mapping; keys merge recursively using `child` (when `child` is `"value"`,
86
+ * a repeated key in the case replaces the common value).
87
+ */
88
+ export type FieldType = "value" | "list" | {
89
+ readonly kind: "map";
90
+ readonly child: FieldType;
91
+ };
92
+ /** Where a single declaration originated in a YAML document, plus the declaration it overrode if any. */
93
+ export type SourceOrigin = {
83
94
  readonly file: string;
84
95
  readonly line: number;
85
96
  readonly kind: "common";
97
+ readonly overrides?: SourceOrigin;
86
98
  } | {
87
99
  readonly file: string;
88
100
  readonly line: number;
89
101
  readonly kind: "case";
90
102
  readonly caseName: string;
103
+ readonly overrides?: SourceOrigin;
104
+ };
105
+ /** Origin annotation mirroring `FieldType`: a leaf origin, list items, or recursive map entries. */
106
+ export type FieldOrigin = SourceOrigin | {
107
+ readonly kind: "list";
108
+ readonly base: SourceOrigin;
109
+ readonly items: readonly SourceOrigin[];
110
+ } | {
111
+ readonly kind: "map";
112
+ readonly base: SourceOrigin;
113
+ readonly entries: Readonly<Record<string, FieldOrigin>>;
91
114
  };
92
115
  /** Basic environment-variable name grammar used by placeholders and declared variables. */
93
116
  export declare const ENV_NAME_PATTERN: RegExp;
@@ -101,6 +124,12 @@ export interface ResolvedCase {
101
124
  /** One annotation per final top-level field in `config`. */
102
125
  readonly origins: Readonly<Record<string, FieldOrigin>>;
103
126
  }
127
+ /**
128
+ * Single source of truth for case fields and their structural types.
129
+ * Naming convention: plural names (`files`, `checks`, `mocks`) are collections (`list` / `map`);
130
+ * singular names (`input`, `runner`, `fixture`, `timeoutMs`, `expect`) are atomic `value`s.
131
+ */
132
+ export declare const CASE_FIELDS: Readonly<Record<keyof CaseConfig, FieldType>>;
104
133
  /** Top-level fields allowed in a complete resolved case. */
105
134
  export declare const CASE_FIELD_KEYS: ReadonlySet<string>;
106
135
  /** The document-level authoring control for named cases. */
@@ -9,17 +9,23 @@ export class ConfigError extends Error {
9
9
  }
10
10
  /** Basic environment-variable name grammar used by placeholders and declared variables. */
11
11
  export const ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
12
+ /**
13
+ * Single source of truth for case fields and their structural types.
14
+ * Naming convention: plural names (`files`, `checks`, `mocks`) are collections (`list` / `map`);
15
+ * singular names (`input`, `runner`, `fixture`, `timeoutMs`, `expect`) are atomic `value`s.
16
+ */
17
+ export const CASE_FIELDS = {
18
+ input: "value",
19
+ fixture: "value",
20
+ files: { kind: "map", child: "value" },
21
+ timeoutMs: "value",
22
+ mocks: { kind: "map", child: { kind: "map", child: "value" } },
23
+ expect: "value",
24
+ checks: "list",
25
+ runner: "value",
26
+ };
12
27
  /** Top-level fields allowed in a complete resolved case. */
13
- export const CASE_FIELD_KEYS = new Set([
14
- "input",
15
- "fixture",
16
- "files",
17
- "timeoutMs",
18
- "mocks",
19
- "expect",
20
- "checks",
21
- "runner",
22
- ]);
28
+ export const CASE_FIELD_KEYS = new Set(Object.keys(CASE_FIELDS));
23
29
  /** The document-level authoring control for named cases. */
24
30
  export const CASES_KEY = "cases";
25
31
  const MOCK_KEYS = new Set(["shell"]);
@@ -1,4 +1,5 @@
1
1
  import { type ResolvedCase } from "./config.js";
2
+ import { fileIdentity } from "./workspace.js";
2
3
  /**
3
4
  * Place the case's workspace `files` entries into the prepared workspace. Entries are
4
5
  * combined in an otherwise empty staging directory first, so an entry can
@@ -51,11 +52,7 @@ export declare function copyPlacement(stagingDir: string, targetDir: string, opt
51
52
  readonly protect?: PlacementProtection;
52
53
  readonly signal?: AbortSignal;
53
54
  }): Promise<void>;
54
- /** The identity a filesystem uses for one file, independent of the spelling that reached it. */
55
- export declare function fileIdentity(info: {
56
- readonly dev: bigint;
57
- readonly ino: bigint;
58
- }): string;
55
+ export { fileIdentity };
59
56
  /**
60
57
  * Validate a checker's check-time `files`: workspace destinations and authoring sources, with
61
58
  * the same rules as `case.files` destinations plus a non-root destination. Throws `ConfigError`
@@ -3,7 +3,7 @@ import { tmpdir } from "node:os";
3
3
  import { dirname, join, relative, resolve, sep } from "node:path";
4
4
  import { ConfigError, errorMessage, expectRelativePath, expectWorkspaceDestination, resolveAuthoringAsset, workspaceTargetPath, } from "./config.js";
5
5
  import { IgnoreTree, isIgnored } from "./ignore.js";
6
- import { isMissing } from "./workspace.js";
6
+ import { fileIdentity, isMissing } from "./workspace.js";
7
7
  /**
8
8
  * Place the case's workspace `files` entries into the prepared workspace. Entries are
9
9
  * combined in an otherwise empty staging directory first, so an entry can
@@ -91,10 +91,7 @@ export async function placedPaths(entries, authoringDir, label, signal) {
91
91
  export async function copyPlacement(stagingDir, targetDir, options) {
92
92
  await copyInto(stagingDir, targetDir, ".", options.label, options.overwrite, options.signal, { tree: new IgnoreTree(), root: stagingDir, segments: [] }, options.protect === undefined ? undefined : new ProtectedPaths(options.protect));
93
93
  }
94
- /** The identity a filesystem uses for one file, independent of the spelling that reached it. */
95
- export function fileIdentity(info) {
96
- return `${info.dev}:${info.ino}`;
97
- }
94
+ export { fileIdentity };
98
95
  /** Target-relative files a placement may never create or replace. */
99
96
  class ProtectedPaths {
100
97
  #paths;
@@ -12,5 +12,7 @@ export declare const patternListSchema: z.ZodPipe<z.ZodUnknown, z.ZodTransform<r
12
12
  export declare const nonEmptyTrimmedString: z.ZodString;
13
13
  /** Shared schema rule for check targets relative to the evaluated workspace. */
14
14
  export declare const runRelativePathSchema: z.ZodString;
15
+ /** A workspace path, or `~/…` for a file or directory inside the run HOME. `~/` alone names HOME itself. */
16
+ export declare const runFilePathSchema: z.ZodString;
15
17
  /** Parse raw declared parameters exactly once with the implementation's Zod schema. */
16
18
  export declare function parseImplementationParams<P>(schema: ZodType<P>, raw: ImplementationParams, label: string): Promise<P>;
@@ -1,3 +1,4 @@
1
+ import { posix } from "node:path";
1
2
  import { z } from "zod";
2
3
  import { ConfigError, parsePatternScalar, } from "./config.js";
3
4
  /**
@@ -67,6 +68,15 @@ export const runRelativePathSchema = z
67
68
  .refine((value) => !value.startsWith("/") && !value.split(/[\\/]+/).includes(".."), {
68
69
  message: "must be relative to the run workspace without '..' segments",
69
70
  });
71
+ /** A workspace path, or `~/…` for a file or directory inside the run HOME. `~/` alone names HOME itself. */
72
+ export const runFilePathSchema = runRelativePathSchema.superRefine((value, context) => {
73
+ if (value.startsWith("~/")) {
74
+ const inner = posix.normalize(value.slice(2)).replace(/\/+$/u, "");
75
+ if (inner === "" || inner === ".") {
76
+ context.addIssue({ code: "custom", message: "must name a file or directory inside HOME, not HOME itself" });
77
+ }
78
+ }
79
+ });
70
80
  /** Parse raw declared parameters exactly once with the implementation's Zod schema. */
71
81
  export async function parseImplementationParams(schema, raw, label) {
72
82
  const result = await schema.safeParseAsync(raw);
@@ -112,6 +112,8 @@ export interface Runner {
112
112
  readonly prepareHome?: (context: RunnerContext) => Promise<readonly string[]>;
113
113
  /** HOME-relative login files a case may never place over; independent of `prepareHome`. */
114
114
  readonly homeFiles?: readonly string[];
115
+ /** Shared mutable host resource key (e.g., persistent login dir); runs with the same key serialize. */
116
+ readonly concurrencyKey?: string;
115
117
  readonly run: (context: RunnerContext) => Promise<RunnerOutcome>;
116
118
  /** Stop the harness and its owned processes. Must be idempotent. */
117
119
  readonly stop: () => Promise<void>;
@@ -166,6 +168,11 @@ export interface RegisteredRunnerDefinition {
166
168
  /** Declared by the definition when the runner gives the run a HOME. */
167
169
  readonly home?: boolean;
168
170
  }
171
+ /** HOME-relative paths and file identities belonging to runner login state, never exposed to checks. */
172
+ export interface HomeProtection {
173
+ readonly paths: readonly string[];
174
+ readonly identities: readonly string[];
175
+ }
169
176
  export interface CheckerContext {
170
177
  /** Prepared workspace root; its identity is verified for every operation. */
171
178
  readonly workspace: RunRoot;
@@ -175,6 +182,8 @@ export interface CheckerContext {
175
182
  readonly home: RunRoot;
176
183
  /** What the case placed in HOME, outside the evaluated agent's writable area. */
177
184
  readonly homeBaseline: RunRoot;
185
+ /** Runner login files in HOME that checks must not expose. */
186
+ readonly protectedHome?: HomeProtection;
178
187
  readonly runRootDir: string;
179
188
  readonly input: string;
180
189
  /** The runner's trace, when it records one. */