@ancha-labs/cli 0.4.19 → 0.4.20

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/lib/ancha.mjs CHANGED
@@ -187097,13 +187097,13 @@ async function stageProject(sourceRoot, selections2, destination, options4 = {})
187097
187097
  async function sourceStat(path7) {
187098
187098
  const rootNow = await lstat(source);
187099
187099
  if (!sameFile(sourceIdentity, rootNow) || rootNow.isSymbolicLink()) throw invalid29("project directory changed while staging");
187100
- const stat19 = await lstat(path7).catch(() => {
187100
+ const stat20 = await lstat(path7).catch(() => {
187101
187101
  throw invalid29(`selected source is missing or changed: ${relative3(source, path7) || "."}`);
187102
187102
  });
187103
- if (stat19.isSymbolicLink() || await realpath2(path7) !== path7 || !within(source, path7)) {
187103
+ if (stat20.isSymbolicLink() || await realpath2(path7) !== path7 || !within(source, path7)) {
187104
187104
  throw invalid29(`symlinks are not allowed: ${relative3(source, path7) || "."}`);
187105
187105
  }
187106
- return stat19;
187106
+ return stat20;
187107
187107
  }
187108
187108
  for (const selection of selected2) await sourceStat(resolve9(source, selection));
187109
187109
  const requestedDestination = resolve9(destination);
@@ -187134,8 +187134,8 @@ async function stageProject(sourceRoot, selections2, destination, options4 = {})
187134
187134
  } catch (error65) {
187135
187135
  if (error65.code !== "EEXIST") throw error65;
187136
187136
  }
187137
- const stat19 = await lstat(current);
187138
- if (!stat19.isDirectory() || stat19.isSymbolicLink() || await realpath2(current) !== current) throw invalid29("staging destination contains a link or changed directory");
187137
+ const stat20 = await lstat(current);
187138
+ if (!stat20.isDirectory() || stat20.isSymbolicLink() || await realpath2(current) !== current) throw invalid29("staging destination contains a link or changed directory");
187139
187139
  }
187140
187140
  }
187141
187141
  let files2 = 0;
@@ -187144,9 +187144,9 @@ async function stageProject(sourceRoot, selections2, destination, options4 = {})
187144
187144
  let directories2 = 0;
187145
187145
  async function copy(path7) {
187146
187146
  if (visited.has(path7)) return;
187147
- const stat19 = await sourceStat(path7);
187147
+ const stat20 = await sourceStat(path7);
187148
187148
  visited.add(path7);
187149
- if (stat19.isDirectory()) {
187149
+ if (stat20.isDirectory()) {
187150
187150
  if (++directories2 > MAX_DIRECTORIES) throw invalid29(`source exceeds ${MAX_DIRECTORIES} directories`);
187151
187151
  const entries4 = await readdir2(path7);
187152
187152
  if (path7 !== source && entries4.includes("scene.yaml")) return;
@@ -187157,14 +187157,14 @@ async function stageProject(sourceRoot, selections2, destination, options4 = {})
187157
187157
  }
187158
187158
  if (excludedPaths.has(path7)) return;
187159
187159
  const name5 = relative3(source, path7);
187160
- if (!stat19.isFile()) throw invalid29(`only regular files are supported: ${name5}`);
187161
- if (stat19.nlink !== 1) throw invalid29(`hard-linked source files are not allowed: ${name5}`);
187160
+ if (!stat20.isFile()) throw invalid29(`only regular files are supported: ${name5}`);
187161
+ if (stat20.nlink !== 1) throw invalid29(`hard-linked source files are not allowed: ${name5}`);
187162
187162
  if (files2 + 1 > MAX_FILES) throw invalid29(`source exceeds ${MAX_FILES} files`);
187163
- if (bytes3 + stat19.size > MAX_BYTES) throw invalid29(`source exceeds 512 MiB while adding ${name5} (${(stat19.size / 1024 / 1024).toFixed(1)} MiB; ${(bytes3 / 1024 / 1024).toFixed(1)} MiB already selected). Narrow the selected project files or move large assets into the runtime image`);
187163
+ if (bytes3 + stat20.size > MAX_BYTES) throw invalid29(`source exceeds 512 MiB while adding ${name5} (${(stat20.size / 1024 / 1024).toFixed(1)} MiB; ${(bytes3 / 1024 / 1024).toFixed(1)} MiB already selected). Narrow the selected project files or move large assets into the runtime image`);
187164
187164
  const input4 = await open2(path7, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
187165
187165
  try {
187166
187166
  const opened = await input4.stat();
187167
- if (!sameFile(stat19, opened) || !opened.isFile() || opened.nlink !== 1 || opened.size !== stat19.size) throw invalid29(`source changed while opening: ${name5}`);
187167
+ if (!sameFile(stat20, opened) || !opened.isFile() || opened.nlink !== 1 || opened.size !== stat20.size) throw invalid29(`source changed while opening: ${name5}`);
187168
187168
  await sourceStat(path7);
187169
187169
  const outputPath = join4(target5, name5);
187170
187170
  await destinationDirectory(dirname4(outputPath));
@@ -187177,14 +187177,14 @@ async function stageProject(sourceRoot, selections2, destination, options4 = {})
187177
187177
  const { bytesRead } = await input4.read(buffer, 0, buffer.length, null);
187178
187178
  if (bytesRead === 0) break;
187179
187179
  copied += bytesRead;
187180
- if (copied > stat19.size || bytes3 + copied > MAX_BYTES) throw invalid29(`source grew while staging: ${name5}`);
187180
+ if (copied > stat20.size || bytes3 + copied > MAX_BYTES) throw invalid29(`source grew while staging: ${name5}`);
187181
187181
  let written = 0;
187182
187182
  while (written < bytesRead) written += (await output2.write(buffer, written, bytesRead - written, null)).bytesWritten;
187183
187183
  }
187184
187184
  const after = await input4.stat();
187185
187185
  const namedAfter = await sourceStat(path7);
187186
- if (copied !== stat19.size || !sameFile(stat19, namedAfter) || after.nlink !== 1 || after.size !== stat19.size || after.mtimeMs !== stat19.mtimeMs || after.ctimeMs !== stat19.ctimeMs) throw invalid29(`source changed while staging: ${name5}`);
187187
- await output2.chmod(stat19.mode & 73 ? 365 : 292);
187186
+ if (copied !== stat20.size || !sameFile(stat20, namedAfter) || after.nlink !== 1 || after.size !== stat20.size || after.mtimeMs !== stat20.mtimeMs || after.ctimeMs !== stat20.ctimeMs) throw invalid29(`source changed while staging: ${name5}`);
187187
+ await output2.chmod(stat20.mode & 73 ? 365 : 292);
187188
187188
  files2 += 1;
187189
187189
  bytes3 += copied;
187190
187190
  } finally {
@@ -188004,8 +188004,8 @@ function attemptDescriptor() {
188004
188004
  let fd;
188005
188005
  try {
188006
188006
  fd = openSync(path7, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
188007
- const stat19 = fstatSync(fd);
188008
- if (!stat19.isFile() || stat19.size > 4 * 1024 * 1024 || stat19.mode & 63 || runtime2 === "fly-vm" && stat19.uid !== 0) invalid30();
188007
+ const stat20 = fstatSync(fd);
188008
+ if (!stat20.isFile() || stat20.size > 4 * 1024 * 1024 || stat20.mode & 63 || runtime2 === "fly-vm" && stat20.uid !== 0) invalid30();
188009
188009
  const parsed4 = descriptorSchema.safeParse(JSON.parse(readFileSync2(fd, "utf8")));
188010
188010
  if (!parsed4.success) invalid30();
188011
188011
  const value5 = parsed4.data;
@@ -216180,113 +216180,22 @@ var init_trial = __esm({
216180
216180
  }
216181
216181
  });
216182
216182
 
216183
- // backend/src/runner/run-state.ts
216184
- import { randomBytes as randomBytes5 } from "node:crypto";
216185
- import { mkdir as mkdir9, readFile as readFile4, rename as rename2, stat as stat2, writeFile as writeFile7 } from "node:fs/promises";
216186
- import { join as join14 } from "node:path";
216187
- function validateRunId(runId2) {
216188
- if (runId2.length > 128 || !/^run_[A-Za-z0-9_-]+$/.test(runId2)) throw new AnchaError("USAGE", "invalid run id", { hint: "use the run id returned by run" });
216189
- }
216190
- async function reserveRun(outDir, totalTrials) {
216191
- if (!Number.isSafeInteger(totalTrials) || totalTrials < 1) throw new AnchaError("USAGE", "total trials must be a positive safe integer");
216192
- await mkdir9(join14(outDir, ".status"), { recursive: true });
216193
- for (; ; ) {
216194
- const now11 = (/* @__PURE__ */ new Date()).toISOString();
216195
- const runId2 = `run_${now11.slice(0, 19).replace(/[-:]/g, "").replace("T", "-")}_${randomBytes5(8).toString("hex")}`;
216196
- if (await stat2(join14(outDir, runId2)).then(() => true, () => false)) continue;
216197
- const state3 = { version: 1, runId: runId2, state: "starting", pid: process.pid, startedAt: now11, updatedAt: now11, completedTrials: 0, totalTrials };
216198
- try {
216199
- await writeFile7(pathOf4(outDir, runId2), JSON.stringify(state3), { flag: "wx", mode: 384 });
216200
- return state3;
216201
- } catch (error65) {
216202
- if (error65.code !== "EEXIST") throw error65;
216203
- }
216204
- }
216205
- }
216206
- async function saveRunState(outDir, state3) {
216207
- validateRunId(state3.runId);
216208
- const path7 = pathOf4(outDir, state3.runId);
216209
- const tmp = `${path7}.${process.pid}.${randomBytes5(6).toString("hex")}.tmp`;
216210
- await writeFile7(tmp, JSON.stringify(state3), { mode: 384 });
216211
- await rename2(tmp, path7);
216212
- }
216213
- async function readRunState(outDir, runId2) {
216214
- validateRunId(runId2);
216215
- let value5;
216216
- try {
216217
- value5 = JSON.parse(await readFile4(pathOf4(outDir, runId2), "utf8"));
216218
- } catch (error65) {
216219
- if (error65.code === "ENOENT") throw new AnchaError("USAGE", `unknown run ${JSON.stringify(runId2)}`, { hint: `see ${outDir}` });
216220
- throw new AnchaError("INTERNAL", "cannot read run status", { cause: error65 });
216221
- }
216222
- const state3 = value5;
216223
- if (state3 === null || typeof state3 !== "object" || state3.version !== 1 || state3.runId !== runId2 || !["starting", "running", "finished", "failed", "interrupted"].includes(state3.state) || !Number.isSafeInteger(state3.pid) || state3.pid <= 0 || !Number.isSafeInteger(state3.completedTrials) || !Number.isSafeInteger(state3.totalTrials) || state3.completedTrials < 0 || state3.totalTrials < state3.completedTrials || !Number.isFinite(Date.parse(state3.updatedAt)) || !Number.isFinite(Date.parse(state3.startedAt)) || terminal(state3) && (!Number.isInteger(state3.exitCode) || state3.exitCode < 0 || state3.exitCode > 4) || state3.error !== void 0 && (state3.error === null || !isErrorCode(state3.error.code) || typeof state3.error.message !== "string") || state3.upload !== void 0 && (typeof state3.upload !== "object" || state3.upload === null || ("error" in state3.upload ? !isErrorCode(state3.upload.error?.code) || typeof state3.upload.error.message !== "string" : typeof state3.upload.url !== "string"))) {
216224
- throw new AnchaError("INTERNAL", "invalid run status");
216225
- }
216226
- if (!terminal(state3)) {
216227
- let alive4 = true;
216228
- try {
216229
- process.kill(state3.pid, 0);
216230
- } catch (error65) {
216231
- alive4 = error65.code !== "ESRCH";
216232
- }
216233
- if (!alive4 || Date.now() - Date.parse(state3.updatedAt) > 15e3) {
216234
- return { ...state3, state: "failed", exitCode: 3, error: { code: "INTERNAL", message: alive4 ? "run worker heartbeat expired; completion is unknown" : "run worker exited without a terminal status" } };
216235
- }
216236
- }
216237
- return state3;
216238
- }
216239
- function stateWriter(outDir, initial) {
216240
- let state3 = initial;
216241
- let pending = Promise.resolve();
216242
- let failure6;
216243
- const update3 = (patch) => {
216244
- state3 = { ...state3, ...patch, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
216245
- const snapshot = state3;
216246
- const publication = pending.then(() => saveRunState(outDir, snapshot));
216247
- pending = publication.catch((error65) => {
216248
- failure6 ??= error65;
216249
- });
216250
- return publication;
216251
- };
216252
- const backgroundUpdate = (patch) => {
216253
- void update3(patch).catch(() => {
216254
- });
216255
- };
216256
- const timer = setInterval(() => {
216257
- backgroundUpdate({});
216258
- }, 1e3);
216259
- timer.unref();
216260
- return {
216261
- update: update3,
216262
- trialFinished() {
216263
- backgroundUpdate({ completedTrials: state3.completedTrials + 1 });
216264
- },
216265
- async finish(patch) {
216266
- clearInterval(timer);
216267
- await update3(patch);
216268
- if (failure6 !== void 0) throw failure6;
216269
- }
216270
- };
216271
- }
216272
- var terminal, pathOf4;
216273
- var init_run_state = __esm({
216274
- "backend/src/runner/run-state.ts"() {
216183
+ // backend/src/harness-issues.ts
216184
+ var init_harness_issues2 = __esm({
216185
+ "backend/src/harness-issues.ts"() {
216275
216186
  "use strict";
216276
216187
  init_src();
216277
- terminal = (state3) => ["finished", "failed", "interrupted"].includes(state3.state);
216278
- pathOf4 = (outDir, runId2) => join14(outDir, ".status", `${runId2}.json`);
216279
216188
  }
216280
216189
  });
216281
216190
 
216282
216191
  // backend/src/scenes.ts
216283
- import { access as access3, readFile as readFile5 } from "node:fs/promises";
216284
- import { basename as basename4, dirname as dirname6, join as join15, relative as relative5, resolve as resolve12 } from "node:path";
216192
+ import { access as access3, readFile as readFile4 } from "node:fs/promises";
216193
+ import { basename as basename4, dirname as dirname6, join as join14, relative as relative5, resolve as resolve12 } from "node:path";
216285
216194
  import { createHash as createHash56 } from "node:crypto";
216286
216195
  async function checkWorldFile(cwd, path7) {
216287
216196
  let text29;
216288
216197
  try {
216289
- text29 = await readFile5(resolve12(cwd, path7), "utf8");
216198
+ text29 = await readFile4(resolve12(cwd, path7), "utf8");
216290
216199
  } catch (e) {
216291
216200
  return { path: path7, bytes: 0, counts: {}, warnings: [], problems: [e.code === "ENOENT" ? "no such file" : e.message] };
216292
216201
  }
@@ -216294,15 +216203,15 @@ async function checkWorldFile(cwd, path7) {
216294
216203
  }
216295
216204
  async function isWorldFile(cwd, path7) {
216296
216205
  try {
216297
- const doc = parseSceneYaml(await readFile5(resolve12(cwd, path7), "utf8"));
216206
+ const doc = parseSceneYaml(await readFile4(resolve12(cwd, path7), "utf8"));
216298
216207
  return typeof doc === "object" && doc !== null && doc.version === 2 && !isTestFile(doc);
216299
216208
  } catch {
216300
216209
  return false;
216301
216210
  }
216302
216211
  }
216303
216212
  async function worldFile(cwd, test3, id14) {
216304
- const beside2 = basename4(dirname6(test3)) === "tests" ? [join15(dirname6(test3), "..", "worlds", `${id14}.yaml`)] : [];
216305
- const candidates = [.../* @__PURE__ */ new Set([...beside2, join15(cwd, "ancha", "worlds", `${id14}.yaml`)])];
216213
+ const beside2 = basename4(dirname6(test3)) === "tests" ? [join14(dirname6(test3), "..", "worlds", `${id14}.yaml`)] : [];
216214
+ const candidates = [.../* @__PURE__ */ new Set([...beside2, join14(cwd, "ancha", "worlds", `${id14}.yaml`)])];
216306
216215
  for (const candidate of candidates) if (await access3(candidate).then(() => true, () => false)) return candidate;
216307
216216
  throw new AnchaError("SCENE_INVALID", `world ${id14} not found: no ${candidates.map((path7) => relative5(cwd, path7)).join(" or ")}`, {
216308
216217
  hint: `put the world at ancha/worlds/${id14}.yaml, or generate one: ancha world gen "<the company and the scenario>" --id ${id14}`
@@ -216310,12 +216219,12 @@ async function worldFile(cwd, test3, id14) {
216310
216219
  }
216311
216220
  async function loadWorldFile(cwd, ref22) {
216312
216221
  const exists7 = (path8) => access3(path8).then(() => true, () => false);
216313
- const path7 = /\.ya?ml$/.test(ref22) && await exists7(resolve12(cwd, ref22)) ? resolve12(cwd, ref22) : join15(cwd, "ancha", "worlds", `${ref22}.yaml`);
216222
+ const path7 = /\.ya?ml$/.test(ref22) && await exists7(resolve12(cwd, ref22)) ? resolve12(cwd, ref22) : join14(cwd, "ancha", "worlds", `${ref22}.yaml`);
216314
216223
  return await exists7(path7) ? { path: path7, world: await readWorldFile(cwd, path7) } : void 0;
216315
216224
  }
216316
216225
  async function readWorldFile(cwd, path7) {
216317
216226
  try {
216318
- const text29 = await readFile5(path7, "utf8"), kept = parsedWorlds.get(path7);
216227
+ const text29 = await readFile4(path7, "utf8"), kept = parsedWorlds.get(path7);
216319
216228
  if (kept?.text === text29) return structuredClone(kept.world);
216320
216229
  const world5 = parseWorldFile(parseSceneYaml(text29));
216321
216230
  parsedWorlds.delete(path7);
@@ -216332,7 +216241,7 @@ async function loadSceneOrTest(cwd, path7) {
216332
216241
  const file3 = resolve12(cwd, path7);
216333
216242
  let doc;
216334
216243
  try {
216335
- doc = parseSceneYaml(await readFile5(file3, "utf8"));
216244
+ doc = parseSceneYaml(await readFile4(file3, "utf8"));
216336
216245
  } catch {
216337
216246
  return { scene: await loadSceneFile(file3) };
216338
216247
  }
@@ -216385,46 +216294,6 @@ var init_scenes = __esm({
216385
216294
  }
216386
216295
  });
216387
216296
 
216388
- // backend/src/runner/invalid-trial.ts
216389
- import { mkdir as mkdir10 } from "node:fs/promises";
216390
- import { join as join16 } from "node:path";
216391
- async function invalidTrial(options4) {
216392
- const { scene: scene2, trial, dir: dir2, startedAt, error: error65, service = "world", envId, sessionId, capture: capture4 } = options4;
216393
- await mkdir10(dir2, { recursive: true });
216394
- const tail = await logTail(join16(dir2, "agent.log")).catch((failure6) => {
216395
- if (failure6?.code === "ENOENT") return [];
216396
- throw failure6;
216397
- });
216398
- return {
216399
- sceneId: scene2.id,
216400
- trial,
216401
- dir: dir2,
216402
- ...envId !== void 0 && { envId },
216403
- ...sessionId !== void 0 && { sessionId },
216404
- exit: "invalid",
216405
- exitCode: null,
216406
- realMs: startedAt === void 0 ? 0 : Math.round(performance.now() - startedAt),
216407
- ...capture4 !== void 0 && { simMs: capture4.simMs },
216408
- checks: capture4?.checks ?? [],
216409
- trace: capture4?.trace ?? [],
216410
- logTail: tail,
216411
- passed: false,
216412
- valid: false,
216413
- harnessIssues: [...capture4?.harnessIssues ?? [], {
216414
- kind: "world",
216415
- owner: "harness",
216416
- service,
216417
- message: `${error65.code}: ${error65.message}`
216418
- }]
216419
- };
216420
- }
216421
- var init_invalid_trial = __esm({
216422
- "backend/src/runner/invalid-trial.ts"() {
216423
- "use strict";
216424
- init_artifacts2();
216425
- }
216426
- });
216427
-
216428
216297
  // backend/src/actions.ts
216429
216298
  function actionsOf(scene2, trace) {
216430
216299
  const writes2 = writeTools(scene2);
@@ -216494,1286 +216363,1434 @@ var init_actions7 = __esm({
216494
216363
  }
216495
216364
  });
216496
216365
 
216497
- // backend/src/runner/run.ts
216498
- import { createHash as createHash57, randomInt } from "node:crypto";
216499
- import { access as access4, mkdir as mkdir11, readFile as readFile6, writeFile as writeFile8 } from "node:fs/promises";
216500
- import { dirname as dirname7, join as join17, relative as relative6, resolve as resolve13 } from "node:path";
216501
- function interrupted(dir2) {
216502
- return new AnchaError("USAGE", "run interrupted", dir2 === void 0 ? {} : { hint: `partial results in ${dir2}` });
216366
+ // backend/src/reproduction-text.ts
216367
+ function renderWrites(writes2) {
216368
+ const of = `${writes2.of} ${writes2.of === 1 ? "trial" : "trials"}`;
216369
+ if (!writes2.tools.length) return [` writes compared with production: none in production, none in this run's ${of}`];
216370
+ const called = (n2) => n2 === 0 ? "not called" : n2 === 1 ? "called" : `called ${n2} times`;
216371
+ const width = Math.max(...writes2.tools.map((w2) => w2.tool.length)), said = Math.max(...writes2.tools.map((w2) => called(w2.production).length));
216372
+ return [" writes compared with production:", ...writes2.tools.map((w2) => ` ${w2.tool.padEnd(width)} production: ${called(w2.production).padEnd(said)} this run: ${w2.trials} of ${of}`)];
216503
216373
  }
216504
- function newRunId(now11) {
216505
- const stamp6 = now11.toISOString().slice(0, 19).replace(/[-:]/g, "").replace("T", "-");
216506
- let suffix = "";
216507
- for (let i = 0; i < 4; i++) suffix += ID_ALPHABET2[randomInt(ID_ALPHABET2.length)];
216508
- return `run_${stamp6}_${suffix}`;
216374
+ function renderReproduction(reproductions, opts = {}) {
216375
+ if (opts.neverRan) return reproductions.map((r2) => `compared with production${r2.trace === void 0 ? "" : ` (trace ${r2.trace.slice(0, 12)})`}: ${r2.sceneId}
216376
+ => not compared: the agent never ran`).join("\n\n");
216377
+ return reproductions.map((r2) => {
216378
+ const width = Math.max(...r2.checks.map((c) => c.check.length));
216379
+ const rows33 = r2.checks.map((c) => ` ${c.check.padEnd(width)} ${c.production} in production \xB7 ${c.total === 0 ? "not run" : c.failed === 0 ? `passed ${c.total}/${c.total} here` : `failed ${c.failed}/${c.total} here`}`);
216380
+ const also = r2.verdict !== "differs" ? r2.checks.filter((c) => c.production === "passed" && c.failed > 0).map((c) => c.check) : [];
216381
+ const verdict = r2.error !== void 0 && r2.checks.length === 0 ? [] : [`=> ${SAY[r2.verdict]}`];
216382
+ return [
216383
+ `compared with production${r2.trace === void 0 ? "" : ` (trace ${r2.trace.slice(0, 12)})`}: ${r2.sceneId}`,
216384
+ ...rows33,
216385
+ ...verdict,
216386
+ ...r2.error !== void 0 ? [` grading production's record failed: ${r2.error}`] : [],
216387
+ ...also.length > 0 ? [` also failing here, though production passed: ${also.join(", ")}`] : [],
216388
+ // A failure here on a check production is not graded on yet is neither a match nor a regression: say how to grade both.
216389
+ ...r2.verdict !== "unknown" && r2.checks.some((c) => c.production === "unknown" && c.failed > 0) ? [` set OPENROUTER_API_KEY to grade ${r2.checks.filter((c) => c.production === "unknown" && c.failed > 0).map((c) => c.check).join(", ")} on production's record and here`] : [],
216390
+ ...r2.added.length > 0 ? [` checks added after saving, with no production result: ${r2.added.join(", ")}`] : [],
216391
+ // How much of the run stood on production's own answers (TRACE_PLAN_V2 §8.6).
216392
+ ...r2.answers ? [` answers to the agent's tools: ${["replayed", "replayed-elsewhere", "twin", "ran", "simulated", "validated", "failed"].filter((s3) => r2.answers[s3]).map((s3) => `${r2.answers[s3]} ${s3}`).join(", ")}${r2.answers.simulated ? "; simulated answers took the agent where production never went (ancha explain lists them)" : ""}`] : [],
216393
+ // What the agent changed, next to what production changed: an answer that needs no model (SPEC-020 R1).
216394
+ ...r2.writes !== void 0 && r2.writes.of > 0 ? renderWrites(r2.writes) : []
216395
+ ].join("\n");
216396
+ }).join("\n\n");
216509
216397
  }
216510
- async function recordsFor(scenePath, root3 = process.cwd()) {
216511
- if (scenePath === void 0) return void 0;
216512
- const top = resolve13(root3);
216513
- for (let dir2 = dirname7(resolve13(top, scenePath)); ; dir2 = dirname7(dir2)) {
216514
- const file3 = join17(dir2, "records.jsonl");
216515
- if (await access4(file3).then(() => true, () => false)) return file3;
216516
- if (dir2 === top || relative6(top, dir2).startsWith("..") || dirname7(dir2) === dir2) return void 0;
216398
+ var SAY;
216399
+ var init_reproduction_text = __esm({
216400
+ "backend/src/reproduction-text.ts"() {
216401
+ "use strict";
216402
+ SAY = {
216403
+ crashed: "the agent exited with an error in every trial, so this run says nothing about production's failure: fix the agent first",
216404
+ reproduced: "production's failure happens here too",
216405
+ partly: "production's failure happens here in part",
216406
+ "not-reproduced": "production's failure did not happen here",
216407
+ matches: "this run matches production, which passed these checks",
216408
+ differs: "checks production passed failed here",
216409
+ unknown: "set OPENROUTER_API_KEY and run again: a model grades these checks on production's record and on this run",
216410
+ ungraded: "the checks that compare with production could not be graded in this run, so it says nothing about production yet"
216411
+ };
216517
216412
  }
216413
+ });
216414
+
216415
+ // backend/src/report.ts
216416
+ import { readFile as readFile5, writeFile as writeFile7 } from "node:fs/promises";
216417
+ import { basename as basename5, dirname as dirname7, join as join15, relative as relative6, resolve as resolve13 } from "node:path";
216418
+ function okFalseError(response5) {
216419
+ if (typeof response5 !== "object" || response5 === null || response5.ok !== false) return void 0;
216420
+ const error65 = response5.error;
216421
+ return typeof error65 === "string" ? error65 : "unknown_error";
216518
216422
  }
216519
- async function recordsDigest(scenePath, root3) {
216520
- const file3 = await recordsFor(scenePath, root3);
216521
- return file3 === void 0 ? void 0 : createHash57("sha256").update(await readFile6(file3)).digest("hex");
216423
+ function excerptOf(entry3) {
216424
+ const response5 = entry3.response;
216425
+ const error65 = entry3.service === "tools" && typeof response5?.error === "string" ? response5.error : okFalseError(entry3.response);
216426
+ return {
216427
+ seq: entry3.seq,
216428
+ source: entry3.source,
216429
+ method: entry3.method,
216430
+ path: entry3.path,
216431
+ ...entry3.status !== void 0 && { status: entry3.status },
216432
+ ...error65 !== void 0 && { error: error65 },
216433
+ ...response5?.execution_status && { execution_status: response5.execution_status },
216434
+ ...response5?.error_type && { error_type: response5.error_type },
216435
+ ...entry3.service === "tools" && response5 && Object.hasOwn(response5, "result") && { result: response5.result },
216436
+ ...entry3.note !== void 0 && { note: entry3.note },
216437
+ ...entry3.issue !== void 0 && { issue: entry3.issue }
216438
+ };
216522
216439
  }
216523
- async function createEnvFor(backend, scene2, seed43, path7, people4) {
216524
- try {
216525
- return await backend.createEnv(scene2, seed43, { paused: true, ...people4 !== void 0 && { people: people4 } });
216526
- } catch (e) {
216527
- if (!(e instanceof AnchaError)) throw e;
216528
- const where3 = path7 === void 0 ? `test ${scene2.id}` : `test ${scene2.id} (${path7})`;
216529
- throw new AnchaError(e.code, `${where3}: ${e.message}`, {
216530
- ...e.hint !== void 0 && { hint: e.hint },
216531
- ...e.docs !== void 0 && { docs: e.docs },
216532
- cause: e
216533
- });
216534
- }
216440
+ function traceExcerpt(trace, evidence2) {
216441
+ trace = projectToolCalls(trace);
216442
+ if (evidence2.length === 0) return trace.slice(-FALLBACK_EXCERPT_CALLS).map(excerptOf);
216443
+ const wanted = new Set(evidence2);
216444
+ return trace.filter((e) => wanted.has(e.seq) || e.completion !== void 0 && wanted.has(e.completion.seq)).map(excerptOf);
216535
216445
  }
216536
- async function executeRun(opts) {
216537
- const { backend, agent, trials, trialOffset = 0, parallel, seed: seed43, outDir, onEvent, signal, scenePaths, realTimeouts, inheritedEnv = process.env } = opts;
216538
- if (opts.scenes !== void 0 && opts.cases !== void 0) throw new AnchaError("USAGE", "provide scenes or cases, not both");
216539
- const explicitCases = opts.cases !== void 0;
216540
- const cases = structuredClone(opts.cases ?? (opts.scenes ?? []).map((scene2) => ({ id: scene2.id, scene: scene2 })));
216541
- if (cases.length === 0) throw new AnchaError("USAGE", "a run requires at least one scene or case");
216542
- for (const item2 of cases) {
216543
- if (!/^[a-z0-9][a-z0-9_-]{0,191}$/.test(item2.id)) throw new AnchaError("SCENE_INVALID", `invalid case id ${JSON.stringify(item2.id)}`);
216544
- if (item2.seed !== void 0 && typeof item2.seed !== "string") throw new AnchaError("SCENE_INVALID", `invalid seed for case ${item2.id}`);
216545
- try {
216546
- const json35 = JSON.stringify(item2.identity ?? {});
216547
- if (json35 === void 0 || json35.length > 1e6 || Object.prototype.toString.call(item2.identity ?? {}) !== "[object Object]") throw new Error("invalid identity");
216548
- item2.identity = JSON.parse(json35);
216549
- } catch {
216550
- throw new AnchaError("SCENE_INVALID", `case ${item2.id} identity must be a JSON object smaller than 1 MB`);
216446
+ function summarizeScene(sceneId, trials, requestedTrials = trials.length) {
216447
+ const counts = countTrials(requestedTrials, trials.map(outcomeOf2));
216448
+ const checks2 = {};
216449
+ const failures = [];
216450
+ const agentIssues = [];
216451
+ const harnessIssues = [];
216452
+ const invalidTrials = counts.invalid;
216453
+ let skippedJudges = 0;
216454
+ const warnings2 = [];
216455
+ const gaps2 = /* @__PURE__ */ new Map();
216456
+ let agentCalls2 = 0;
216457
+ let totalMs = 0;
216458
+ let graded = false;
216459
+ for (const t of trials) {
216460
+ totalMs += t.realMs;
216461
+ for (const issue6 of trialIssues(t)) {
216462
+ if (harnessIssues.length < MAX_FAILURES_PER_SCENE) harnessIssues.push({ ...issue6, sceneId, trial: t.trial });
216463
+ }
216464
+ const exit = t.exit === "invalid" && t.originalExit === "spawn_failed" ? "spawn_failed" : t.exit;
216465
+ if (!t.passed && exit !== "invalid" && !exitedCleanly({ exit, exitCode: t.exitCode }) && agentIssues.length < MAX_FAILURES_PER_SCENE) {
216466
+ agentIssues.push({ sceneId, trial: t.trial, exit, exitCode: t.exitCode, realMs: t.realMs, log: join15(t.dir, "agent.log"), logTail: t.logTail, ...t.invocations !== void 0 && { invocations: t.invocations } });
216467
+ }
216468
+ const valid2 = trialValid(t);
216469
+ for (const c of t.checks) {
216470
+ if (valid2 && c.status !== "skipped" && c.error === void 0) graded = true;
216471
+ const tally = checks2[c.id] ??= { passed: 0, total: 0, required: c.required };
216472
+ tally.total++;
216473
+ if (c.status === "skipped") {
216474
+ tally.skipped = (tally.skipped ?? 0) + 1;
216475
+ skippedJudges++;
216476
+ } else if (!c.passed && (!valid2 || c.error !== void 0)) tally.invalid = (tally.invalid ?? 0) + 1;
216477
+ if (c.warning !== void 0) warnings2.push({ trial: t.trial, check: c.id, message: c.warning });
216478
+ if (c.passed) tally.passed++;
216479
+ if (c.required && !c.passed && c.error === void 0 && c.status !== "skipped" && failures.length < MAX_FAILURES_PER_SCENE) {
216480
+ failures.push({
216481
+ sceneId,
216482
+ trial: t.trial,
216483
+ check: c.id,
216484
+ expected: c.expected,
216485
+ actual: c.actual,
216486
+ explanation: c.explanation,
216487
+ traceExcerpt: traceExcerpt(t.trace, c.evidence),
216488
+ ...c.evidence.length === 0 && t.trace.length > FALLBACK_EXCERPT_CALLS && { traceExcerptOmitted: t.trace.length - FALLBACK_EXCERPT_CALLS }
216489
+ });
216490
+ }
216491
+ }
216492
+ for (const e of projectToolCalls(t.trace)) {
216493
+ if (e.source === "agent" && !isAgentAnswer(e)) agentCalls2++;
216494
+ if (e.gap === true) {
216495
+ const key4 = JSON.stringify([e.service, e.method, e.path]);
216496
+ const gap6 = gaps2.get(key4);
216497
+ const error65 = okFalseError(e.response) ?? (typeof e.response === "object" && e.response !== null && typeof e.response.message === "string" ? e.response.message : void 0);
216498
+ if (gap6 === void 0) gaps2.set(key4, { service: e.service, method: e.method, path: e.path, count: 1, ...e.status !== void 0 && { status: e.status }, ...error65 !== void 0 && { error: error65 } });
216499
+ else gap6.count++;
216500
+ }
216551
216501
  }
216552
216502
  }
216553
- const scenes = cases.map((item2) => item2.scene);
216554
- if (opts.runId !== void 0) validateRunId(opts.runId);
216555
- for (const [name5, value5] of [["trials", trials], ["parallel", parallel]]) {
216556
- if (!Number.isSafeInteger(value5) || value5 < 1) throw new AnchaError("USAGE", `${name5} must be a positive integer, got ${value5}`);
216557
- }
216558
- if (!Number.isSafeInteger(trialOffset) || trialOffset < 0 || !Number.isSafeInteger(trialOffset + trials)) throw new AnchaError("USAGE", `trialOffset must be a non-negative integer, got ${trialOffset}`);
216559
- if (!Number.isSafeInteger(cases.length * trials)) throw new AnchaError("USAGE", "total attempt count must be a safe integer");
216560
- if (agent.mode === "endpoint") {
216561
- validateEndpointAgent(agent, parallel);
216562
- for (const scene2 of scenes) validateAgentEnv(scene2, agent);
216563
- } else {
216564
- const calling = scenes.find((scene2) => scene2.world_rules?.app_calls?.length);
216565
- if (calling) throw new AnchaError("CONFIG_INVALID", `test ${calling.id} has app_calls, which need an app Ancha can call: set agent.url (and agent.start for an app Ancha starts)`);
216566
- }
216567
- const ids2 = cases.map((item2) => item2.id);
216568
- const duplicate2 = ids2.find((id14, i) => ids2.indexOf(id14) !== i);
216569
- if (duplicate2 !== void 0) {
216570
- throw new AnchaError("SCENE_INVALID", `${explicitCases ? "case" : "scene"} id "${duplicate2}" appears more than once in this run`, { hint: "case ids must be unique; use explicit cases for distinct data variations" });
216571
- }
216572
- for (const scene2 of scenes) validateAgentEnv(scene2, agent);
216573
- if (signal?.aborted) throw interrupted();
216574
- if (agent.mode === "endpoint") await preflightExecution(agent, scenes, signal);
216575
- else for (const input4 of [void 0, "per_event"]) {
216576
- const group5 = scenes.filter((scene2) => scene2.agent_input === input4);
216577
- if (group5.length) await preflightExecution({ ...agent, taskInput: sceneTaskInput(group5[0], agent.taskInput) }, group5, signal);
216578
- }
216579
- const cancellation = new AbortController();
216580
- const runningSignal = signal === void 0 ? cancellation.signal : AbortSignal.any([signal, cancellation.signal]);
216581
- const halt = {};
216582
- const fail8 = (error65) => {
216583
- halt.crash ??= { error: error65 };
216584
- cancellation.abort(error65);
216503
+ const passed = counts.passed;
216504
+ const actions = actionCounts(trials.filter(trialValid)), answers = answerCounts(trials.filter(trialValid));
216505
+ return {
216506
+ sceneId,
216507
+ counts,
216508
+ trials: trials.length,
216509
+ passed,
216510
+ passRate: counts.requested === 0 ? 0 : round4(passed / counts.requested),
216511
+ passAllK: allTrialsPassed(counts),
216512
+ checks: checks2,
216513
+ graded,
216514
+ agentIssues,
216515
+ harnessIssues,
216516
+ invalidTrials,
216517
+ skippedJudges,
216518
+ warnings: warnings2,
216519
+ failures,
216520
+ coverageGaps: [...gaps2.values()],
216521
+ meanRealMs: trials.length === 0 ? 0 : Math.round(totalMs / trials.length),
216522
+ agentCalls: agentCalls2,
216523
+ ...actions !== void 0 && { actions },
216524
+ ...answers !== void 0 && { answers },
216525
+ trialsDetail: trials.map((t) => ({ trial: t.trial, passed: outcomeOf2(t) === "passed", valid: trialValid(t), ...outcomeOf2(t) === "skipped" ? { outcome: "skipped" } : t.outcome ? { outcome: t.outcome } : {}, ...t.checks.some((c) => c.status === "skipped") && { skippedJudges: t.checks.filter((c) => c.status === "skipped").length }, exit: t.exit, ...t.originalExit !== void 0 && { originalExit: t.originalExit }, exitCode: t.exitCode, realMs: t.realMs, ...t.simMs !== void 0 && { simMs: t.simMs }, ...t.playOut !== void 0 && { playOut: t.playOut }, ...t.sessionId !== void 0 && { sessionId: t.sessionId }, dir: t.dir }))
216585
216526
  };
216586
- const pathOf5 = (item2) => scenePaths === void 0 ? void 0 : Object.hasOwn(scenePaths, item2.id) ? scenePaths[item2.id] : Object.hasOwn(scenePaths, item2.scene.id) ? scenePaths[item2.scene.id] : void 0;
216587
- const seedOf = (item2) => item2.seed ?? seed43 ?? `${item2.scene.id}:1`;
216588
- const owned2 = /* @__PURE__ */ new Map();
216589
- const acquire = async (item2, onFailure = fail8, onCreated) => {
216590
- const env2 = await createEnvFor(backend, item2.scene, seedOf(item2), pathOf5(item2), item2.people);
216591
- let timer;
216592
- let stopped2 = false;
216593
- let pending;
216594
- owned2.set(env2.id, { env: env2, async stop() {
216595
- stopped2 = true;
216596
- clearTimeout(timer);
216597
- await pending;
216598
- } });
216599
- onCreated?.(env2);
216600
- const lease = (await backend.listEnvs()).find((item3) => item3.id === env2.id);
216601
- if (!lease) throw new AnchaError("ENV_NOT_FOUND", `environment ${env2.id} disappeared during acquisition`);
216602
- const created3 = Date.parse(lease.createdAt);
216603
- const ttlMs = Date.parse(lease.expiresAt) - created3;
216604
- if (!Number.isFinite(ttlMs) || ttlMs <= 0) throw new AnchaError("SERVER_UNREACHABLE", `invalid lease metadata for environment ${env2.id}`);
216605
- const interval = Math.min(3e4, ttlMs / 3);
216606
- const renew = () => {
216607
- if (stopped2) return;
216608
- const requestedAt = performance.now();
216609
- pending = Promise.resolve().then(() => backend.renewEnv(env2.id)).then(() => {
216610
- if (!stopped2) {
216611
- timer = setTimeout(renew, Math.max(0, requestedAt + interval - performance.now()));
216612
- timer.unref();
216613
- }
216614
- }, (error65) => {
216615
- if (!stopped2) onFailure(error65 instanceof AnchaError ? error65 : new AnchaError("SERVER_UNREACHABLE", `cannot renew environment ${env2.id}`, { cause: error65 }));
216616
- });
216617
- };
216618
- timer = setTimeout(renew, Math.max(0, interval - (Date.now() - created3)));
216619
- timer.unref();
216620
- return env2;
216527
+ }
216528
+ function runVerdict(scenes, minPassRate) {
216529
+ if (scenes.some((scene2) => sceneFailed(scene2, minPassRate))) return "fail";
216530
+ return scenes.some((scene2) => scene2.graded === false) ? "ungraded" : "pass";
216531
+ }
216532
+ function summarize(run6, agent, minPassRate, options4 = {}) {
216533
+ const scenes = [...run6.results].map(([sceneId, value5]) => ({ ...summarizeScene(sceneId, value5.trials, value5.requestedTrials), ...value5.case && { scenarioId: value5.scene.id, case: value5.case } }));
216534
+ return {
216535
+ verdictVersion: VERDICT_VERSION,
216536
+ runId: run6.runId,
216537
+ startedAt: run6.startedAt,
216538
+ finishedAt: run6.finishedAt,
216539
+ agent,
216540
+ ...options4.agentCommand !== void 0 && { agentCommand: options4.agentCommand },
216541
+ minPassRate,
216542
+ verdict: runVerdict(scenes, minPassRate),
216543
+ scenes,
216544
+ ...options4.strict && { strict: { simulatedAnswers: [...run6.results].flatMap(([sceneId, { trials }]) => trials.filter((t) => trialValid(t) && (t.answers?.simulated ?? 0) > 0).map((t) => ({ sceneId, trial: t.trial, checks: t.checks.filter((c) => c.status !== "skipped" && c.error === void 0).map((c) => c.id) }))) } },
216545
+ ...[...run6.results.values()].some((value5) => value5.case) && { caseFingerprints: Object.fromEntries([...run6.results].flatMap(([id14, value5]) => value5.case ? [[id14, value5.case.fingerprint]] : [])) },
216546
+ sceneFingerprints: Object.fromEntries([...run6.results].map(([id14, { scene: scene2, records: records4 }]) => [id14, sceneFingerprint(records4 === void 0 ? scene2 : { scene: scene2, records: records4 })])),
216547
+ ...run6.agentEnvironment !== void 0 && { agentEnvironment: run6.agentEnvironment }
216621
216548
  };
216622
- const destroyAll = async (envs) => {
216623
- await Promise.all([...envs].map(async (env2) => {
216624
- const lease = owned2.get(env2.id);
216625
- if (!lease) return;
216626
- await lease.stop();
216627
- try {
216628
- await backend.destroyEnv(env2.id);
216629
- } catch (error65) {
216630
- fail8(error65);
216631
- } finally {
216632
- owned2.delete(env2.id);
216549
+ }
216550
+ function checkCounts(run6) {
216551
+ let passed = 0, failed = 0, skipped = 0, invalid35 = 0;
216552
+ for (const { trials } of run6.results.values()) for (const t of trials) {
216553
+ const valid2 = trialValid(t);
216554
+ for (const c of t.checks) {
216555
+ if (!valid2 || c.error !== void 0) invalid35++;
216556
+ else if (c.status === "skipped") skipped++;
216557
+ else if (c.passed) passed++;
216558
+ else failed++;
216559
+ }
216560
+ }
216561
+ return { evaluated: passed + failed, passed, failed, skipped, invalid: invalid35 };
216562
+ }
216563
+ function cloudExitCode(summary, counts, options4) {
216564
+ if (counts.invalidAttempts > 0 || counts.skippedAttempts > 0 || options4.terminalIntent === "failed") return CLOUD_EXIT2.invalid;
216565
+ if (counts.cancelledAttempts > 0 || options4.terminalIntent === "cancelled") return CLOUD_EXIT2.cancelled;
216566
+ if (options4.strict && hasStrictViolation(summary)) return CLOUD_EXIT2.strict;
216567
+ return summary.verdict === "pass" ? CLOUD_EXIT2.pass : CLOUD_EXIT2.fail;
216568
+ }
216569
+ function ungradedTests(s3) {
216570
+ return (s3.scenes ?? []).filter((scene2) => scene2.graded === false && (scene2.trialsDetail ?? []).some((t) => t.valid !== false)).map((scene2) => ({ sceneId: scene2.sceneId, checks: Object.keys(scene2.checks ?? {}).length }));
216571
+ }
216572
+ function ungradedLines(s3, indent2 = "") {
216573
+ return ungradedTests(s3).flatMap(({ sceneId, checks: checks2 }) => [
216574
+ checks2 === 0 ? `${indent2}ungraded: ${sceneId} has no checks, so nothing was graded` : `${indent2}ungraded: ${sceneId}: none of its ${checks2 === 1 ? "check was" : `${checks2} checks were`} evaluated, so nothing was graded`,
216575
+ `${indent2} add a check under checks: in its test file (ancha twins seed <tool> lists the checks a tool takes), then run it again`
216576
+ ]);
216577
+ }
216578
+ function hasStrictViolation(summary) {
216579
+ return summary.scenes.some((scene2) => scene2.coverageGaps.length > 0 || (scene2.answers?.simulatedIn ?? 0) > 0);
216580
+ }
216581
+ function strictSummaryLines(summary) {
216582
+ return (summary.strict?.simulatedAnswers ?? []).map((item2) => `--strict: ${item2.sceneId} trial ${item2.trial} used simulated tool answers; checks: ${item2.checks.join(", ") || "none evaluated"}`);
216583
+ }
216584
+ function agentEnvironmentClause(environment3) {
216585
+ if (environment3?.target === "container") return "agent sealed in a container";
216586
+ if (environment3?.target !== "host") return void 0;
216587
+ if (environment3.inheritAll) return "agent not sealed (network open, this shell's whole environment)";
216588
+ return `agent not sealed (network open, ${environment3.inherited} variables from this shell)`;
216589
+ }
216590
+ function withheldNamedBy(issue6, environment3) {
216591
+ const text29 = issue6.logTail.join("\n");
216592
+ return (environment3?.withheldInLogs ?? []).filter((name5) => /^[A-Z][A-Z0-9_]{3,}$/.test(name5) && new RegExp(`(?<![A-Za-z0-9_])${name5}(?![A-Za-z0-9_])`).test(text29));
216593
+ }
216594
+ function withheldHint(issue6, environment3) {
216595
+ const names5 = withheldNamedBy(issue6, environment3);
216596
+ if (names5.length === 0) return void 0;
216597
+ const one7 = names5.length === 1;
216598
+ const list18 = one7 ? names5[0] : `${names5.slice(0, -1).join(", ")} and ${names5.at(-1)}`;
216599
+ return `${list18} ${one7 ? "is" : "are"} set in this shell but ${one7 ? "was" : "were"} withheld from the agent: pass ${one7 ? "it" : "them"} with ${names5.map((name5) => `--pass-env ${name5}`).join(" ")} or list ${one7 ? "it" : "them"} under agent.pass_env in ancha.yaml`;
216600
+ }
216601
+ function crashLines(logTail3) {
216602
+ const lines2 = logTail3.filter((line2) => !CRASH_NOISE.test(line2));
216603
+ const last = lines2.findLastIndex((line2) => ERROR_LINE.test(line2));
216604
+ let start = last;
216605
+ while (start > 0 && start > last - 2 && ERROR_LINE.test(lines2[start - 1])) start--;
216606
+ return (start >= 0 ? lines2.slice(start, start + 3) : lines2.slice(-3)).map((line2) => line2.length > CRASH_LINE_MAX ? `${line2.slice(0, CRASH_LINE_MAX)}\u2026` : line2);
216607
+ }
216608
+ function agentNeverRan(s3) {
216609
+ if (s3.pytest) return void 0;
216610
+ const ended = [];
216611
+ for (const scene2 of s3.scenes) {
216612
+ if ((scene2.agentCalls ?? 0) > 0) return void 0;
216613
+ for (const t of scene2.trialsDetail ?? []) {
216614
+ const issue6 = (scene2.agentIssues ?? []).find((i) => i.trial === t.trial);
216615
+ const spawn8 = t.exit === "spawn_failed" || t.exit === "invalid" && (t.originalExit === "spawn_failed" || (scene2.harnessIssues ?? []).some((i) => i.trial === t.trial && i.message.startsWith("AGENT_SPAWN_FAILED")));
216616
+ if (spawn8) {
216617
+ ended.push({ exit: "spawn_failed", exitCode: t.exitCode, realMs: t.realMs, perEvent: false, issue: issue6 });
216618
+ continue;
216633
216619
  }
216634
- }));
216635
- };
216636
- try {
216637
- for (const item2 of cases) {
216638
- runningSignal.throwIfAborted();
216639
- const env2 = await acquire(item2);
216640
- await destroyAll([env2]);
216641
- runningSignal.throwIfAborted();
216620
+ if (t.exit !== "exited" || t.exitCode === 0 || t.passed) return void 0;
216621
+ const invocations = issue6?.invocations;
216622
+ if (invocations !== void 0 ? invocations.total === 0 || invocations.failed < invocations.total : t.realMs > NEVER_RAN_MS) return void 0;
216623
+ ended.push({ exit: "exited", exitCode: t.exitCode, realMs: t.realMs, perEvent: invocations !== void 0, issue: issue6 });
216642
216624
  }
216643
- } catch (error65) {
216644
- await destroyAll([...owned2.values()].map((item2) => item2.env));
216645
- if (signal?.aborted) throw interrupted();
216646
- throw halt.crash?.error ?? error65;
216647
216625
  }
216648
- const reservedPorts = /* @__PURE__ */ new Set();
216649
- const results = /* @__PURE__ */ new Map();
216650
- const frozen = cases.map((item2) => {
216651
- const value5 = { id: item2.id, scenarioId: item2.scene.id, seed: seedOf(item2), compiledFingerprint: sceneFingerprint(item2.scene), identity: item2.identity ?? {} };
216652
- const record28 = { ...value5, fingerprint: sceneFingerprint(value5) };
216653
- results.set(item2.id, { scene: item2.scene, trials: [], requestedTrials: trials, ...explicitCases && { case: record28 } });
216654
- return record28;
216655
- });
216656
- let finished = 0;
216657
- let observedAgentExit = false;
216658
- const stopped = () => halt.spawnFailure !== void 0 || halt.crash !== void 0 || signal?.aborted === true;
216659
- const startedAt = /* @__PURE__ */ new Date();
216660
- const runId2 = opts.runId ?? newRunId(startedAt);
216661
- const dir2 = join17(outDir, runId2);
216662
- let next2 = 0;
216663
- const total2 = cases.length * trials;
216664
- try {
216665
- await mkdir11(outDir, { recursive: true });
216666
- await mkdir11(dir2);
216667
- await writeFile8(join17(dir2, "inputs.json"), `${JSON.stringify({
216668
- schemaVersion: 1,
216669
- cases: sharedSeeds(frozen.map((value5, index) => ({ ...value5, scene: cases[index].scene }))),
216670
- // A world's seed once (run-inputs.ts). Names only, never values: what a later `ancha runs upload` redacts (hosting spec §3.1).
216671
- agentEnvironment: { passEnv: agent.passEnv ?? [], inheritEnv: agent.inheritEnv === true },
216672
- isolation: { execution: executionDescription(agent), toolWorld: "fresh-per-attempt", agentProcess: agent.mode === "endpoint" && agent.start === void 0 ? "external-setup-adapter" : "fresh-per-attempt", agentState: agent.execution?.mode === "container" ? "fresh-container-scratch" : "provided-namespace-only", limits: agent.execution?.mode === "container" ? "Local Linux container, read-only source, bounded scratch, scoped tool gateway and explicit model hosts; not a multi-tenant cloud security certification." : "Agent files and external memory are shared unless the agent uses ANCHA_STATE_DIR or ANCHA_ATTEMPT_ID. This is not host or network isolation." }
216673
- })}
216674
- `, { flag: "wx", mode: 384 });
216675
- const kept = /* @__PURE__ */ new Map();
216676
- for (const [index, item2] of cases.entries()) {
216677
- const source = await recordsFor(pathOf5(item2), opts.root);
216678
- if (source === void 0) continue;
216679
- const text29 = await readFile6(source), copy = join17(dir2, "records", `${index}.jsonl`);
216680
- await mkdir11(dirname7(copy), { recursive: true });
216681
- await writeFile8(copy, text29, { flag: "wx", mode: 384 });
216682
- kept.set(item2.id, copy);
216683
- results.get(item2.id).records = createHash57("sha256").update(text29).digest("hex");
216626
+ if (ended.length === 0) return void 0;
216627
+ const exits = new Set(ended.map((e) => e.exit)), codes = new Set(ended.map((e) => e.exitCode));
216628
+ const first2 = ended.find((e) => e.issue !== void 0)?.issue;
216629
+ const cloud = s3.target === "cloud";
216630
+ const withheld = first2 === void 0 || cloud ? void 0 : withheldHint(first2, s3.agentEnvironment);
216631
+ const fix = first2 === void 0 ? void 0 : likelyFix(first2.logTail, { target: s3.target, command: s3.agentCommand ?? s3.agent, ...withheld !== void 0 && { withheld } });
216632
+ const checksFailed = s3.scenes.reduce((n2, scene2) => n2 + Object.values(scene2.checks).filter((c) => c.required && c.total - c.passed - (c.skipped ?? 0) - (c.invalid ?? 0) > 0).length, 0);
216633
+ const exit = exits.size > 1 ? "mixed" : [...exits][0];
216634
+ return {
216635
+ attempts: ended.length,
216636
+ tests: s3.scenes.filter((scene2) => (scene2.trialsDetail ?? []).length > 0).length,
216637
+ exit,
216638
+ exitCode: codes.size === 1 ? ended[0].exitCode : null,
216639
+ ...exit === "exited" && codes.size === 1 && ended[0].exitCode === null && { signal: true },
216640
+ ...exit === "exited" && ended.every((e) => e.perEvent) && { perEvent: true },
216641
+ ms: Math.max(...ended.map((e) => e.realMs)),
216642
+ logTail: (first2?.logTail ?? []).filter((line2) => !CRASH_NOISE.test(line2)).slice(-10).map((line2) => line2.length > CRASH_LINE_MAX ? `${line2.slice(0, CRASH_LINE_MAX)}\u2026` : line2),
216643
+ ...first2 !== void 0 && !cloud && { log: first2.log },
216644
+ ...fix !== void 0 && { fix },
216645
+ checksFailed
216646
+ };
216647
+ }
216648
+ function neverRanHeadline(n2) {
216649
+ const time7 = `${n2.attempts === 1 ? "after" : "within"} ${spaced(n2.ms)}`;
216650
+ const how = n2.exit === "spawn_failed" ? n2.exitCode === 127 ? "its command was not found" : "its command could not be started" : n2.exit === "mixed" ? "it stopped before doing anything" : n2.perEvent ? n2.signal ? "it was killed by a signal each time it was started" : n2.exitCode === null ? "it exited with an error each time it was started" : `it exited with code ${n2.exitCode} each time it was started` : n2.signal ? `it was killed by a signal ${time7}` : n2.exitCode === null ? `it exited with an error ${time7}` : `it exited with code ${n2.exitCode} ${time7}`;
216651
+ const where3 = n2.attempts === 1 ? "" : n2.tests > 1 ? ` in all ${n2.attempts} attempts of ${n2.tests} tests` : n2.attempts === 2 ? " in both attempts" : ` in all ${n2.attempts} attempts`;
216652
+ return `Your agent didn't run: ${how}${where3}`;
216653
+ }
216654
+ function neverRanLines(n2, cwd) {
216655
+ const path7 = n2.log === void 0 || cwd === void 0 || relative6(cwd, n2.log).startsWith("..") ? n2.log : relative6(cwd, n2.log);
216656
+ const log3 = path7 === void 0 ? "log (from the cloud machine)" : `log (${path7})`;
216657
+ return [neverRanHeadline(n2), n2.logTail.length === 0 ? ` ${log3}: empty` : ` ${log3}:`, ...n2.logTail.map((line2) => ` ${line2}`), ...n2.fix === void 0 ? [] : [` likely fix: ${n2.fix}`]];
216658
+ }
216659
+ function neverRanChecksLine(n2, runId2, out) {
216660
+ if (n2.checksFailed === 0) return void 0;
216661
+ return `${n2.checksFailed} ${n2.checksFailed === 1 ? "check" : "checks"} failed because the agent never ran; ancha explain ${runId2}${out === void 0 ? "" : ` --out ${shellWord(out)}`} --all shows them`;
216662
+ }
216663
+ function retryCommands(s3, opts = {}) {
216664
+ const tests = opts.tests !== void 0 && opts.tests.length > 0 && opts.tests.length <= 3 ? ` ${opts.tests.map(shellWord).join(" ")}` : "";
216665
+ if (s3.target === "cloud") return ["ancha agent upload", `ancha run --on cloud${tests}`];
216666
+ const on = s3.target === "docker" ? " --on docker" : s3.target === "local" ? " --on local" : "";
216667
+ return [`ancha run${on}${tests}${opts.out === void 0 ? "" : ` --out ${shellWord(opts.out)}`}`];
216668
+ }
216669
+ function neverRanNextLine(n2, retry) {
216670
+ return `next: ${n2.fix === void 0 ? "fix what its log says" : "make the fix above"}, then ${retry.join(", then ")}`;
216671
+ }
216672
+ async function writeSummary(run6, summary) {
216673
+ await writeFile7(join15(run6.dir, "summary.json"), `${JSON.stringify(summary, null, 2)}
216674
+ `);
216675
+ await writeFile7(join15(dirname7(run6.dir), "latest"), `${run6.runId}
216676
+ `);
216677
+ }
216678
+ function formatRateDelta(value5) {
216679
+ const magnitude = Math.abs(value5 * 100);
216680
+ const rounded2 = Math.round(magnitude * 10) / 10;
216681
+ return `${value5 > 0 ? "+" : value5 < 0 ? "-" : ""}${rounded2 === 0 && magnitude > 0 ? magnitude.toPrecision(3) : rounded2} pp`;
216682
+ }
216683
+ function howItEnded(i) {
216684
+ switch (i.exit) {
216685
+ case "timeout":
216686
+ return `timed out after ${duration8(i.realMs)} and was killed`;
216687
+ case "spawn_failed":
216688
+ return i.exitCode === null ? "could not be started" : `failed to start (exit code ${i.exitCode})`;
216689
+ default: {
216690
+ const when13 = i.invocations?.failed ? `on ${i.invocations.failed} of ${i.invocations.total} events` : `after ${duration8(i.realMs)}`;
216691
+ return i.exitCode === null ? `was killed by a signal ${when13}` : `exited with code ${i.exitCode} ${when13}`;
216684
216692
  }
216685
- onEvent?.({ event: "run_started", runId: runId2, scenes: ids2, trials, parallel });
216686
- await Promise.all(Array.from({ length: Math.min(parallel, total2) }, async () => {
216687
- while (!stopped() && next2 < total2) {
216688
- const index = next2++;
216689
- const item2 = cases[index % cases.length];
216690
- const trial = Math.floor(index / cases.length) + 1 + trialOffset;
216691
- const trialDir = join17(dir2, `trial-${item2.id}-${trial}`);
216692
- const records4 = kept.get(item2.id);
216693
- const attempt = { id: `${runId2}/${item2.id}/${trial}`, caseId: item2.id, stateDir: resolve13(trialDir, "agent-state"), seed: seedOf(item2), ...records4 !== void 0 && { records: records4 }, ...opts.recordsDiagnostic && { recordsDiagnostic: { ...opts.recordsDiagnostic, attempt: trial } } };
216694
- const startedAt2 = performance.now();
216695
- const attemptCancellation = new AbortController();
216696
- const attemptSignal = AbortSignal.any([runningSignal, attemptCancellation.signal]);
216697
- let env2;
216698
- let sessionId;
216699
- let capture4;
216700
- const trialBackend = new Proxy(backend, { get(target5, key4) {
216701
- if (key4 === "prepareTrial") return async (...args) => {
216702
- const session2 = await backend.prepareTrial(...args);
216703
- sessionId = session2.id;
216704
- return session2;
216705
- };
216706
- if (key4 === "finishTrial") return async (...args) => {
216707
- capture4 = await backend.finishTrial(...args);
216708
- return capture4;
216709
- };
216710
- const member4 = target5[key4];
216711
- return typeof member4 === "function" ? member4.bind(target5) : member4;
216712
- } });
216713
- try {
216714
- let result;
216715
- try {
216716
- env2 = await acquire(item2, (error65) => {
216717
- if (error65 instanceof AnchaError && error65.code === "SERVER_UNREACHABLE") attemptCancellation.abort(error65);
216718
- else fail8(error65);
216719
- }, (created3) => {
216720
- env2 = created3;
216721
- });
216722
- attemptSignal.throwIfAborted();
216723
- const realTimeoutMs = realTimeouts === void 0 ? void 0 : Object.hasOwn(realTimeouts, item2.id) ? realTimeouts[item2.id] : Object.hasOwn(realTimeouts, item2.scene.id) ? realTimeouts[item2.scene.id] : void 0;
216724
- result = await runTrial({
216725
- backend: trialBackend,
216726
- env: env2,
216727
- scene: item2.scene,
216728
- agent,
216729
- trial,
216730
- dir: trialDir,
216731
- attempt,
216732
- signal: attemptSignal,
216733
- inheritedEnv,
216734
- reservedPorts,
216735
- ...opts.judge !== void 0 && { judge: opts.judge },
216736
- ...realTimeoutMs !== void 0 && { realTimeoutMs },
216737
- onCaptured: (value5) => {
216738
- capture4 = value5;
216739
- },
216740
- onPrepared: () => onEvent?.({ event: "trial_started", scene: item2.id, ...explicitCases && { caseId: item2.id }, trial, envId: env2.id }),
216741
- onAgentStarted: () => onEvent?.({ event: "agent_started", sceneId: item2.id, trial })
216742
- });
216743
- await owned2.get(env2.id)?.stop();
216744
- attemptSignal.throwIfAborted();
216745
- } catch (error65) {
216746
- const failure6 = attemptCancellation.signal.aborted && error65 instanceof Error && error65.name === "AbortError" ? attemptCancellation.signal.reason : error65;
216747
- if (runningSignal.aborted || !(failure6 instanceof AnchaError) || failure6.code !== "SERVER_UNREACHABLE") throw error65;
216748
- result = await invalidTrial({
216749
- scene: item2.scene,
216750
- trial,
216751
- dir: trialDir,
216752
- startedAt: startedAt2,
216753
- error: failure6,
216754
- ...env2 !== void 0 && { envId: env2.id },
216755
- ...sessionId !== void 0 && { sessionId },
216756
- ...capture4 !== void 0 && { capture: capture4 }
216757
- });
216758
- }
216759
- result.caseId = item2.id;
216760
- result.attemptId = attempt.id;
216761
- if (writeTools(item2.scene).size) result.actions = actionsOf(item2.scene, result.trace);
216762
- if (Object.keys(item2.scene.tools ?? {}).length) result.answers = answersOf(result.trace);
216763
- if (result.exit !== "invalid") {
216764
- if (!observedAgentExit && result.exit === "spawn_failed") halt.spawnFailure = result;
216765
- observedAgentExit = true;
216766
- }
216767
- finished++;
216768
- results.get(item2.id).trials.push(result);
216769
- await writeFile8(join17(trialDir, "result.json"), `${JSON.stringify({ ...result, trace: void 0 }, null, 2)}
216770
- `, { flag: "wx", mode: 384 });
216771
- onEvent?.({
216772
- event: "trial_finished",
216773
- scene: item2.id,
216774
- ...explicitCases && { caseId: item2.id },
216775
- trial,
216776
- passed: result.passed,
216777
- valid: result.valid,
216778
- graded: result.valid !== false && result.checks.some((check4) => check4.status !== "skipped" && check4.error === void 0),
216779
- warnings: result.checks.flatMap((check4) => check4.warning === void 0 ? [] : [`${check4.id}: ${check4.warning}`]),
216780
- exit: result.exit,
216781
- exitCode: result.exitCode,
216782
- realMs: result.realMs,
216783
- failedChecks: result.checks.filter((c) => c.required && !c.passed).map((c) => c.id)
216784
- });
216785
- } catch (error65) {
216786
- if (!signal?.aborted) fail8(error65);
216787
- } finally {
216788
- if (env2) await destroyAll([env2]);
216789
- }
216790
- }
216791
- }));
216792
- } finally {
216793
- await destroyAll([...owned2.values()].map((item2) => item2.env));
216794
216693
  }
216795
- for (const value5 of results.values()) value5.trials.sort((a, b) => a.trial - b.trial);
216796
- if (halt.crash !== void 0) throw halt.crash.error;
216797
- if (halt.spawnFailure !== void 0) {
216798
- throw new AnchaError("AGENT_SPAWN_FAILED", `agent command failed to start: ${agent.mode === "endpoint" ? agent.start : agent.command}`, {
216799
- hint: `check agent.command in ancha.yaml or --agent; see ${join17(halt.spawnFailure.dir, "agent.log")}`
216800
- });
216694
+ }
216695
+ function nonDefaultOut(cwd, out) {
216696
+ return out === void 0 || resolve13(cwd, out) === resolve13(cwd, DEFAULT_RUNS_DIR) ? void 0 : out;
216697
+ }
216698
+ function renderSummaryText(s3, opts = {}) {
216699
+ const lines2 = s3.replayOf === void 0 ? [] : [`replay of ${s3.replayOf}`];
216700
+ if (s3.pytest) lines2.push(`pytest ${s3.pytest.nodeId}: ${s3.pytest.outcome}${s3.pytest.invalid ? " [invalid]" : !s3.pytest.graded ? " (ungraded)" : ""}`);
216701
+ const never2 = agentNeverRan(s3);
216702
+ if (never2 !== void 0) lines2.push(...neverRanLines(never2, opts.cwd));
216703
+ for (const scene2 of s3.scenes) {
216704
+ const invalid35 = scene2.invalidTrials ?? 0;
216705
+ const ok = !sceneFailed(scene2, s3.minPassRate);
216706
+ const excluded3 = scene2.trialsDetail.filter((trial) => trial.outcome === "skipped" || trial.outcome === "xfailed").length;
216707
+ if (s3.pytest && !s3.pytest.graded) lines2.push(`\u2014 ${scene2.sceneId} ungraded${excluded3 ? ` (${excluded3} excluded)` : ""}${invalid35 ? " [invalid]" : ""}`);
216708
+ else if (ok && scene2.graded === false) lines2.push(`\u2014 ${scene2.sceneId} ungraded: ${scene2.trials} ${scene2.trials === 1 ? "trial" : "trials"}, no check evaluated`);
216709
+ else lines2.push(`${ok ? "\u2713" : "\u2717"} ${scene2.sceneId} ${scene2.passed}/${scene2.counts?.requested ?? scene2.trials} (${pct(scene2.passRate)}%)${invalid35 > 0 ? " [invalid]" : ""}${excluded3 ? ` (${excluded3} excluded)` : ""}`);
216710
+ if (never2 !== void 0) continue;
216711
+ if (invalid35 > 0) lines2.push(` \u2717 harness failure: ${invalid35}/${scene2.trials} trials invalid`);
216712
+ if ((scene2.skippedJudges ?? 0) > 0) lines2.push(` judge grading skipped: ${scene2.skippedJudges} check(s)`);
216713
+ for (const warning of scene2.warnings ?? []) lines2.push(` warning: trial ${warning.trial} ${warning.check}: ${warning.message.replaceAll("\n", "\n ")}`);
216714
+ for (const issue6 of scene2.harnessIssues ?? []) {
216715
+ lines2.push(` trial ${issue6.trial}: ${issue6.owner} ${issue6.kind} (${issue6.service}): ${issue6.message.replaceAll("\n", "\n ")}`);
216716
+ }
216717
+ const unclean = scene2.trialsDetail.filter((t) => !t.passed && t.exit !== "invalid" && !exitedCleanly(t)).length;
216718
+ const firstIssue = (scene2.agentIssues ?? [])[0];
216719
+ if (unclean > 0 && firstIssue !== void 0) {
216720
+ lines2.push(` \u2717 agent did not exit cleanly in ${unclean}/${scene2.trials} trials`);
216721
+ const why = crashLines(firstIssue.logTail);
216722
+ lines2.push(` trial ${firstIssue.trial}: ${howItEnded(firstIssue)}; its output is in ${firstIssue.log}${firstIssue.logTail.length === 0 ? " (empty)" : why.length > 0 ? ", ending:" : ""}`);
216723
+ lines2.push(...why.map((line2) => ` ${line2}`));
216724
+ const hint = withheldHint(firstIssue, s3.agentEnvironment);
216725
+ if (hint !== void 0) lines2.push(` ${hint}`);
216726
+ }
216727
+ for (const [id14, tally] of Object.entries(scene2.checks)) {
216728
+ const failed = tally.total - tally.passed - (tally.skipped ?? 0);
216729
+ if (!tally.required || failed === 0) continue;
216730
+ lines2.push(` \u2717 ${id14} failed in ${failed}/${tally.total} trials`);
216731
+ const first2 = scene2.failures.find((f2) => f2.check === id14);
216732
+ if (first2 !== void 0) lines2.push(` trial ${first2.trial}: ${first2.explanation.replaceAll("\n", "\n ")}`);
216733
+ }
216734
+ for (const g of scene2.coverageGaps.slice(0, SUMMARY_GAPS_SHOWN)) {
216735
+ lines2.push(` coverage gap: ${g.method} ${g.path} (${g.service}) x${g.count}`);
216736
+ }
216737
+ if (scene2.coverageGaps.length > SUMMARY_GAPS_SHOWN) {
216738
+ lines2.push(` \u2026 ${scene2.coverageGaps.length - SUMMARY_GAPS_SHOWN} more coverage gap(s)`);
216739
+ }
216740
+ if (scene2.answers !== void 0) {
216741
+ const { of, simulatedIn, bySource } = scene2.answers;
216742
+ const named5 = ANSWER_SOURCES2.filter(([source]) => bySource[source]).map(([source, label5]) => `${bySource[source]} ${label5}`);
216743
+ if (named5.length) lines2.push(` tool answers: ${named5.join(", ")}; ${simulatedIn}/${of} verdicts rest on simulated answers`);
216744
+ }
216745
+ if (scene2.actions !== void 0) {
216746
+ const { of, made } = scene2.actions, trials = `${of} valid ${of === 1 ? "trial" : "trials"}`;
216747
+ lines2.push(made.length ? ` writes, in how many of ${trials}:` : ` writes: none in ${trials}`);
216748
+ for (const action of made.slice(0, SUMMARY_ACTIONS_SHOWN)) lines2.push(` ${action.trials}/${of} ${actionLabel(action)}`);
216749
+ if (made.length > SUMMARY_ACTIONS_SHOWN) lines2.push(` \u2026 ${made.length - SUMMARY_ACTIONS_SHOWN} more`);
216750
+ }
216801
216751
  }
216802
- if (signal?.aborted && finished < scenes.length * trials) throw interrupted(dir2);
216803
- const crash = { twins: [...new Set(scenes.flatMap((scene2) => scene2.twins))], logTails: [...results.values()].flatMap((value5) => value5.trials.map((trial) => trial.logTail)) };
216804
- return { runId: runId2, dir: dir2, startedAt: startedAt.toISOString(), finishedAt: (/* @__PURE__ */ new Date()).toISOString(), results, agentEnvironment: describeAgentEnvironment(agent, inheritedEnv, crash) };
216752
+ const folded = never2 === void 0 ? void 0 : neverRanChecksLine(never2, s3.runId, opts.out);
216753
+ if (folded !== void 0) lines2.push(folded);
216754
+ if (never2 === void 0 && !s3.pytest) lines2.push(...ungradedLines(s3));
216755
+ lines2.push("");
216756
+ lines2.push(...strictSummaryLines(s3));
216757
+ if (s3.comparison !== void 0) lines2.push(...comparisonLines(s3.comparison));
216758
+ if ((opts.reproduction ?? []).length > 0) lines2.push(renderReproduction(opts.reproduction, { neverRan: never2 !== void 0 }), "");
216759
+ const noneGraded = s3.scenes.length > 0 && s3.scenes.every((scene2) => scene2.trials > 0 && (scene2.invalidTrials ?? 0) >= scene2.trials);
216760
+ lines2.push(`${s3.pytest && !s3.pytest.graded && !s3.pytest.invalid ? s3.pytest.outcome + " (ungraded)" : noneGraded ? "invalid (no trials graded)" : s3.verdict} (minimum pass rate ${pct(s3.minPassRate)}%) run ${s3.runId}`);
216761
+ const next2 = nextAfterRun(s3, opts);
216762
+ if (never2 !== void 0) lines2.push(neverRanNextLine(never2, next2));
216763
+ else if (next2.length > 0) lines2.push(`next: ${next2.join(", then ")}`);
216764
+ return lines2.join("\n").replaceAll(PATTERN_NOTE, "") + (lines2.some((line2) => line2.includes(PATTERN_NOTE)) ? `
216765
+ ${PATTERN_NOTE.trim()}` : "");
216805
216766
  }
216806
- var ID_ALPHABET2;
216807
- var init_run = __esm({
216808
- "backend/src/runner/run.ts"() {
216809
- "use strict";
216810
- init_src();
216811
- init_trial();
216812
- init_agent_input();
216813
- init_docker();
216814
- init_agent_env();
216815
- init_config();
216816
- init_run_state();
216817
- init_scenes();
216818
- init_invalid_trial();
216819
- init_actions7();
216820
- init_run_inputs();
216821
- ID_ALPHABET2 = "abcdefghijklmnopqrstuvwxyz0123456789";
216767
+ function comparisonLines(comparison2) {
216768
+ const lines2 = [`compared with ${comparison2.baselineRunId}: ${comparison2.regressed ? "regressed" : "no regression"}`];
216769
+ const counts = (c) => `${c.before.passed}/${c.before.total} \u2192 ${c.after.passed}/${c.after.total}`;
216770
+ for (const check4 of comparison2.droppedChecks ?? []) lines2.push(` \u2717 dropped: ${check4.sceneId} ${check4.check} ${counts(check4)}`);
216771
+ for (const scene2 of comparison2.scenes) {
216772
+ lines2.push(` ${scene2.sceneId}: ${pct(scene2.before)}% \u2192 ${pct(scene2.after)}% (${formatRateDelta(scene2.delta)})${scene2.beforeTrials === void 0 || scene2.afterTrials === void 0 ? "" : `; ${scene2.beforeTrials} \u2192 ${scene2.afterTrials} trials`}`);
216773
+ for (const check4 of (scene2.checks ?? []).filter((c) => c.delta > 0 || !c.required)) lines2.push(` ${check4.delta > 0 ? "improved" : "optional, dropped"}: ${check4.check} ${counts(check4)}`);
216774
+ for (const action of (scene2.actions ?? []).slice(0, SUMMARY_ACTIONS_SHOWN)) lines2.push(` write: ${actionLabel(action)} ${action.before.trials}/${action.before.of} \u2192 ${action.after.trials}/${action.after.of} trials`);
216775
+ if ((scene2.actions ?? []).length > SUMMARY_ACTIONS_SHOWN) lines2.push(` \u2026 ${scene2.actions.length - SUMMARY_ACTIONS_SHOWN} more changed writes`);
216822
216776
  }
216823
- });
216824
-
216825
- // backend/src/kit/connection-tools.ts
216826
- import { readFile as readFile8 } from "node:fs/promises";
216827
- import { join as join19 } from "node:path";
216828
- async function connectionTools(root3) {
216829
- const text29 = await readFile8(join19(root3, CONNECTION_TOOLS_PATH), "utf8").catch((error65) => {
216830
- if (error65.code === "ENOENT") return void 0;
216831
- throw error65;
216777
+ return lines2;
216778
+ }
216779
+ function nextAfterRun(s3, opts = {}) {
216780
+ if (agentNeverRan(s3) !== void 0) return retryCommands(s3, opts);
216781
+ const out = opts.out === void 0 ? "" : ` --out ${shellWord(opts.out)}`;
216782
+ const failed = s3.verdict === "fail" || s3.scenes.some((scene2) => scene2.failures.length > 0 || (scene2.agentIssues ?? []).length > 0 || (scene2.harnessIssues ?? []).length > 0 || (scene2.invalidTrials ?? 0) > 0);
216783
+ if (failed) return [`ancha explain ${s3.runId}${out}`];
216784
+ if (s3.verdict === "ungraded") return [];
216785
+ return s3.source === "pytest" ? [] : s3.comparison === void 0 ? [`ancha baseline save before${out}`] : [];
216786
+ }
216787
+ function uploadHintLine(runId2, workspace4, opts = {}) {
216788
+ return `ancha runs upload ${runId2}${opts.out === void 0 ? "" : ` --out ${shellWord(opts.out)}`} sends this run to ${workspace4}`;
216789
+ }
216790
+ function normalizeSummary(s3) {
216791
+ return { ...s3, scenes: s3.scenes.map((scene2) => ({
216792
+ ...scene2,
216793
+ agentIssues: scene2.agentIssues ?? [],
216794
+ harnessIssues: scene2.harnessIssues ?? [],
216795
+ invalidTrials: scene2.invalidTrials ?? 0,
216796
+ skippedJudges: scene2.skippedJudges ?? 0,
216797
+ warnings: scene2.warnings ?? []
216798
+ })) };
216799
+ }
216800
+ function explainAgentIssues(s3, opts = {}) {
216801
+ return s3.scenes.filter((scene2) => opts.scene === void 0 || scene2.sceneId === opts.scene).flatMap((scene2) => scene2.agentIssues ?? []).filter((i) => opts.trial === void 0 || i.trial === opts.trial).map((i) => {
216802
+ const hint = withheldHint(i, s3.agentEnvironment);
216803
+ return hint === void 0 ? i : { ...i, hint };
216832
216804
  });
216833
- if (text29 === void 0) return [];
216834
- const value5 = JSON.parse(text29);
216835
- if (!Array.isArray(value5) || value5.length > SUPPORTED_TWINS.length || value5.some((name5) => !SUPPORTED_TWINS.includes(name5))) {
216836
- throw new AnchaError("CONFIG_INVALID", "The connection tools must name Ancha twins.");
216837
- }
216838
- return [...new Set(value5)];
216839
216805
  }
216840
- function probeToolCalls(twins, trace) {
216841
- return twins.map((name5) => ({ name: name5, calls: trace.filter((entry3) => entry3.source === "agent" && entry3.service === name5 && !isAgentAnswer(entry3)).length }));
216806
+ function explainHarnessIssues(s3, opts = {}) {
216807
+ return s3.scenes.filter((scene2) => opts.scene === void 0 || scene2.sceneId === opts.scene).flatMap((scene2) => scene2.harnessIssues ?? []).filter((issue6) => opts.trial === void 0 || issue6.trial === opts.trial);
216842
216808
  }
216843
- var CONNECTION_TOOLS_PATH;
216844
- var init_connection_tools = __esm({
216845
- "backend/src/kit/connection-tools.ts"() {
216846
- "use strict";
216847
- init_src();
216848
- CONNECTION_TOOLS_PATH = "ancha/connection-tools.json";
216849
- }
216850
- });
216851
-
216852
- // backend/src/run-bundle.ts
216853
- import { createHash as createHash59 } from "node:crypto";
216854
- import { readdir as readdir3, readFile as readFile9 } from "node:fs/promises";
216855
- import { join as join21 } from "node:path";
216856
- import { gunzipSync as gunzipSync3, gzipSync } from "node:zlib";
216857
- function bundleSource(env2) {
216858
- return env2.CI === "true" || env2.GITHUB_ACTIONS ? "ci" : "cli";
216809
+ function explainGradingWarnings(s3, opts = {}) {
216810
+ return s3.scenes.filter((scene2) => opts.scene === void 0 || scene2.sceneId === opts.scene).flatMap((scene2) => (scene2.warnings ?? []).map((warning) => ({ sceneId: scene2.sceneId, ...warning }))).filter((warning) => opts.trial === void 0 || warning.trial === opts.trial);
216859
216811
  }
216860
- async function bundleSecrets(options4) {
216861
- const base3 = new Set(BASE_ENV);
216862
- const names5 = options4.inheritEnv ? Object.keys(options4.env).filter((name5) => !base3.has(name5) && !name5.startsWith("LC_")) : [...options4.passEnv ?? []];
216863
- const values2 = names5.map((name5) => options4.env[name5]);
216864
- const file3 = await readFile9(join21(options4.cwd, ".ancha/openrouter.env"), "utf8").catch(() => "");
216865
- for (const line2 of file3.split(/\r?\n/)) {
216866
- const match3 = /^\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*\s*=\s*(.*?)\s*$/.exec(line2);
216867
- if (match3) values2.push(match3[1].replace(/^(['"])(.*)\1$/, "$2"));
216868
- }
216869
- return [...new Set(values2.filter((value5) => typeof value5 === "string" && value5.length >= MIN_SECRET))].sort((a, b) => b.length - a.length);
216812
+ function explainCoverageGaps(s3, opts = {}) {
216813
+ return s3.scenes.filter((scene2) => opts.scene === void 0 || scene2.sceneId === opts.scene).flatMap((scene2) => scene2.coverageGaps.map((gap6) => ({ sceneId: scene2.sceneId, ...gap6, hint: `ancha twins coverage ${gap6.service}` })));
216870
216814
  }
216871
- function redact(data5, secrets2) {
216872
- if (secrets2.length === 0) return data5;
216873
- let text29 = data5.toString("utf8");
216874
- const before = text29;
216875
- for (const secret of secrets2) {
216876
- text29 = text29.split(secret).join("[redacted]");
216877
- const escaped = JSON.stringify(secret).slice(1, -1);
216878
- if (escaped !== secret) text29 = text29.split(escaped).join("[redacted]");
216879
- }
216880
- return text29 === before ? data5 : Buffer.from(text29, "utf8");
216815
+ function renderCoverageGap(g) {
216816
+ const answer = g.error !== void 0 ? `it answered ${g.error}` : g.status !== void 0 ? `it answered HTTP ${g.status}` : "it answered with an error";
216817
+ return `${g.sceneId} coverage gap: the agent called ${g.method} ${g.path}${g.count > 1 ? ` (${g.count} times)` : ""}, which the ${g.service} twin doesn't implement; ${answer} in the vendor's error shape. The agent's call may be right: see ${g.hint}`;
216881
216818
  }
216882
- function logTail2(data5, cap) {
216883
- const note2 = (cut5) => Buffer.from(`[ancha: agent.log was ${data5.length} bytes; the first ${cut5} bytes are left out]
216884
- `, "utf8");
216885
- let start = data5.length - (cap - note2(data5.length).length);
216886
- const newline = data5.indexOf(10, start);
216887
- if (newline !== -1 && newline < data5.length - 1) start = newline + 1;
216888
- return Buffer.concat([note2(start), data5.subarray(start)]);
216819
+ function renderHarnessIssue(i) {
216820
+ return `${i.sceneId} trial ${i.trial} \u2717 ${i.owner} ${i.kind} (${i.service}): ${i.message.replaceAll("\n", "\n ")}${i.seq === void 0 ? "" : ` (trace #${i.seq})`}`;
216889
216821
  }
216890
- function capFor(path7, inputsBytes = BUNDLE_LIMITS2.largeFileBytes) {
216891
- const name5 = path7.slice(path7.lastIndexOf("/") + 1);
216892
- return name5 === "trace.jsonl" || name5 === "state.json" ? BUNDLE_LIMITS2.largeFileBytes : name5 === "agent.log" ? BUNDLE_LIMITS2.agentLogBytes : path7 === "inputs.json" ? inputsBytes : BUNDLE_LIMITS2.fileBytes;
216822
+ function renderAgentIssue(i, cloud = false) {
216823
+ const lines2 = [`${i.sceneId} trial ${i.trial} \u2717 agent ${howItEnded(i)}`];
216824
+ const log3 = cloud ? "log (from the cloud machine)" : `log: ${i.log}`;
216825
+ if (i.logTail.length === 0) lines2.push(cloud ? ` ${log3}: empty` : ` ${log3} (empty)`);
216826
+ else lines2.push(` ${log3}, last ${i.logTail.length} line(s):`, ...i.logTail.map((l) => ` ${l}`));
216827
+ if (i.hint !== void 0) lines2.push(` ${i.hint}`);
216828
+ return lines2.join("\n");
216893
216829
  }
216894
- function readsLargeInputs(version6) {
216895
- const match3 = /^(\d+)\.(\d+)\.(\d+)/.exec(version6 ?? "");
216896
- if (!match3) return false;
216897
- const [major, minor, patch] = match3.slice(1).map(Number);
216898
- return major !== 0 ? major > 0 : minor !== 4 ? minor > 4 : patch >= 14;
216830
+ function explainPlayOuts(s3, opts = {}) {
216831
+ return s3.scenes.filter((scene2) => opts.scene === void 0 || scene2.sceneId === opts.scene).flatMap((scene2) => scene2.trialsDetail.flatMap((t) => t.playOut === void 0 || t.passed || opts.trial !== void 0 && t.trial !== opts.trial ? [] : [{ sceneId: scene2.sceneId, trial: t.trial, exitedAt: sinceStart2(t.playOut.fromMs), playedOutTo: sinceStart2(t.playOut.toMs), realMs: t.realMs }]));
216899
216832
  }
216900
- async function runFiles(runDir, source) {
216901
- const root3 = await readdir3(runDir, { withFileTypes: true });
216902
- const paths2 = ["summary.json", "inputs.json", "reproduction.json", "cloud.json"].filter((name5) => allowedFor(source, name5) && root3.some((entry3) => entry3.isFile() && entry3.name === name5));
216903
- for (const dir2 of root3.filter((entry3) => entry3.isDirectory()).map((entry3) => entry3.name).sort()) {
216904
- for (const file3 of (await readdir3(join21(runDir, dir2), { withFileTypes: true })).filter((entry3) => entry3.isFile()).map((entry3) => entry3.name).sort()) {
216905
- if (allowedFor(source, `${dir2}/${file3}`)) paths2.push(`${dir2}/${file3}`);
216833
+ function renderPlayOut(p2) {
216834
+ return `${p2.sceneId} trial ${p2.trial} the agent exited at ${p2.exitedAt} (after ${duration8(p2.realMs)}); the world played out to ${p2.playedOutTo} without it`;
216835
+ }
216836
+ function sinceStart2(ms2) {
216837
+ let rest2 = Math.round(Math.abs(ms2) / 1e3);
216838
+ const parts3 = [];
216839
+ for (const [unit, size2] of [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]]) {
216840
+ if (rest2 >= size2) {
216841
+ parts3.push(`${Math.floor(rest2 / size2)}${unit}`);
216842
+ rest2 %= size2;
216906
216843
  }
216907
216844
  }
216908
- return paths2;
216845
+ return `${ms2 < 0 && parts3.length > 0 ? "-" : "+"}${parts3.join("") || "0s"}`;
216909
216846
  }
216910
- async function packRun(options4) {
216911
- if (options4.source === "cloud" && !CLOUD_RUN_ID.test(options4.runId)) throw new AnchaError("USAGE", `run ${options4.runId} is not a cloud run`, { hint: "a cloud run has its job's run_cloud_ id" });
216912
- const paths2 = await runFiles(options4.runDir, options4.source);
216913
- if (!paths2.includes("summary.json")) throw new AnchaError("USAGE", `run ${options4.runId} has no summary.json`, { hint: "only a finished run can be uploaded; ancha status <id> shows where it stands" });
216914
- const most = entriesFor(options4.source);
216915
- if (paths2.length + 1 > most) throw tooBig2(`run ${options4.runId} has ${paths2.length} files to upload; a run bundle holds at most ${most - 1} besides its manifest`);
216916
- const entries4 = [], omitted = [];
216917
- for (const path7 of paths2) {
216918
- let data5 = redact(await readFile9(join21(options4.runDir, path7)), options4.secrets);
216919
- const cap = capFor(path7, options4.inputsBytes);
216920
- if (data5.length > cap) {
216921
- if (path7.endsWith("/agent.log")) data5 = logTail2(data5, cap);
216922
- else if (options4.source === "cloud" && MANDATORY_CLOUD_PATH.test(path7)) throw tooBig2(`run ${options4.runId}: ${path7} is ${data5.length} bytes; a run keeps at most ${cap}`);
216923
- else {
216924
- omitted.push({ path: path7, bytes: data5.length, cap });
216925
- continue;
216926
- }
216847
+ async function withWorldEvidence(s3, runDir, failures) {
216848
+ const starts = /* @__PURE__ */ new Map();
216849
+ try {
216850
+ const inputs2 = JSON.parse(await readFile5(join15(runDir, "inputs.json"), "utf8"));
216851
+ for (const item2 of inputs2.cases ?? []) {
216852
+ const start = Date.parse(item2.scene?.start_time ?? "");
216853
+ if (Number.isFinite(start)) starts.set(item2.id, start);
216927
216854
  }
216928
- entries4.push({ path: path7, data: data5 });
216855
+ } catch {
216929
216856
  }
216930
- const unpacked = entries4.reduce((sum6, entry3) => sum6 + entry3.data.length, 0);
216931
- if (unpacked > BUNDLE_LIMITS2.unpackedBytes) throw tooBig2(`run ${options4.runId} holds ${(unpacked / MB).toFixed(1)} MB to upload; a run bundle holds at most ${BUNDLE_LIMITS2.unpackedBytes / MB} MB unpacked`);
216932
- const manifest2 = {
216933
- version: 1,
216934
- runId: options4.runId,
216935
- createdAt: options4.createdAt,
216936
- source: options4.source,
216937
- project: options4.project,
216938
- cli: options4.cli,
216939
- files: entries4.map((entry3) => ({ path: entry3.path, bytes: entry3.data.length, sha256: sha2564(entry3.data) })),
216940
- ...omitted.length > 0 && { omitted }
216857
+ const files2 = /* @__PURE__ */ new Map();
216858
+ const explanations = (f2) => {
216859
+ const key4 = `${f2.sceneId}/${f2.trial}`;
216860
+ let file3 = files2.get(key4);
216861
+ if (file3 === void 0) {
216862
+ const dir2 = s3.scenes.find((scene2) => scene2.sceneId === f2.sceneId)?.trialsDetail.find((t) => t.trial === f2.trial)?.dir;
216863
+ file3 = dir2 === void 0 ? Promise.resolve([]) : readFile5(join15(runDir, basename5(dir2), "explain.json"), "utf8").then((text29) => {
216864
+ const value5 = JSON.parse(text29);
216865
+ return Array.isArray(value5) ? value5 : [];
216866
+ }).catch(() => []);
216867
+ files2.set(key4, file3);
216868
+ }
216869
+ return file3;
216941
216870
  };
216942
- const mtime = Date.parse(options4.createdAt);
216943
- const tar = writeTar([{ path: "bundle.json", data: Buffer.from(`${JSON.stringify(manifest2, null, 2)}
216944
- `, "utf8") }, ...entries4], Number.isNaN(mtime) ? 0 : mtime);
216945
- const archive = gzipSync(tar, { level: 9 });
216946
- if (archive.length > BUNDLE_LIMITS2.compressedBytes) throw tooBig2(`run ${options4.runId} compresses to ${(archive.length / MB).toFixed(1)} MB; a run bundle is at most ${BUNDLE_LIMITS2.compressedBytes / MB} MB`);
216947
- return { archive, manifest: manifest2 };
216871
+ return Promise.all(failures.map(async (f2) => {
216872
+ const why = (await explanations(f2)).find((e) => e.checkId === f2.check);
216873
+ if (why === void 0) return f2;
216874
+ const start = starts.get(f2.sceneId);
216875
+ const evidence2 = why.evidence.map((e) => {
216876
+ if ("at" in e && typeof e.at === "string") return e;
216877
+ const at4 = Date.parse(e.simAt);
216878
+ return start === void 0 || !Number.isFinite(at4) ? e : { ...e, at: sinceStart2(at4 - start) };
216879
+ });
216880
+ return { ...f2, kind: why.kind, evidence: evidence2, conversation: why.conversation, people: why.people };
216881
+ }));
216948
216882
  }
216949
- function header3(path7, size2, mtimeMs) {
216950
- const block2 = Buffer.alloc(512);
216951
- let name5 = path7, prefix2 = "";
216952
- if (Buffer.byteLength(path7) > 100) {
216953
- const cut5 = path7.lastIndexOf("/");
216954
- [prefix2, name5] = [path7.slice(0, cut5), path7.slice(cut5 + 1)];
216955
- if (cut5 < 0 || Buffer.byteLength(name5) > 100 || Buffer.byteLength(prefix2) > 155) throw new AnchaError("INTERNAL", `bundle path too long for ustar: ${path7}`);
216883
+ function evidenceLine(e) {
216884
+ const text29 = e.excerpt ?? "";
216885
+ if (e.from === void 0 && e.to === void 0) return text29;
216886
+ switch (e.type) {
216887
+ case "message":
216888
+ return `${e.from ?? e.to}${e.where === void 0 ? "" : ` ${e.where}`}: ${text29}`;
216889
+ case "decision":
216890
+ return `${e.from ?? e.to} decided ${text29}`;
216891
+ case "knowledge":
216892
+ return `${e.to ?? "someone"} learned ${text29}${e.from === void 0 ? "" : ` from ${e.from}`}`;
216893
+ case "gate":
216894
+ return `${e.to ?? e.from}: ${text29}`;
216895
+ default:
216896
+ return `${e.from ?? "the agent"} called ${text29}`;
216956
216897
  }
216957
- const octal = (value5, width) => `${value5.toString(8).padStart(width - 1, "0")}\0`;
216958
- block2.write(name5, 0, 100, "utf8");
216959
- block2.write(octal(420, 8), 100, 8, "ascii");
216960
- block2.write(octal(0, 8), 108, 8, "ascii");
216961
- block2.write(octal(0, 8), 116, 8, "ascii");
216962
- block2.write(octal(size2, 12), 124, 12, "ascii");
216963
- block2.write(octal(Math.floor(mtimeMs / 1e3), 12), 136, 12, "ascii");
216964
- block2.fill(32, 148, 156);
216965
- block2.write("0", 156, 1, "ascii");
216966
- block2.write("ustar\0", 257, 6, "ascii");
216967
- block2.write("00", 263, 2, "ascii");
216968
- block2.write(prefix2, 345, 155, "utf8");
216969
- let sum6 = 0;
216970
- for (const byte of block2) sum6 += byte;
216971
- block2.write(`${sum6.toString(8).padStart(6, "0")}\0 `, 148, 8, "ascii");
216972
- return block2;
216973
216898
  }
216974
- function writeTar(entries4, mtimeMs) {
216975
- const parts3 = [];
216976
- for (const entry3 of entries4) {
216977
- parts3.push(header3(entry3.path, entry3.data.length, mtimeMs), entry3.data);
216978
- const pad3 = (512 - entry3.data.length % 512) % 512;
216979
- if (pad3) parts3.push(Buffer.alloc(pad3));
216899
+ function explainFailures(s3, opts = {}) {
216900
+ return s3.scenes.filter((scene2) => opts.scene === void 0 || scene2.sceneId === opts.scene).flatMap((scene2) => scene2.failures).filter((f2) => opts.trial === void 0 || f2.trial === opts.trial);
216901
+ }
216902
+ function renderFailure(f2) {
216903
+ const lines2 = [`${f2.sceneId} trial ${f2.trial} \u2717 ${f2.check}`];
216904
+ lines2.push(` expected: ${f2.expected}`);
216905
+ lines2.push(` actual: ${f2.actual}`);
216906
+ lines2.push(` why: ${f2.explanation.replaceAll("\n", "\n ")}`);
216907
+ if (f2.traceExcerpt.length > 0) {
216908
+ lines2.push(" trace:");
216909
+ if ((f2.traceExcerptOmitted ?? 0) > 0) lines2.push(` \u2026 ${f2.traceExcerptOmitted} earlier trace entries omitted; see trace.jsonl`);
216910
+ for (const e of f2.traceExcerpt) {
216911
+ const outcome4 = [e.status, e.execution_status, e.error_type, e.error === void 0 ? void 0 : `ok:false ${e.error}`, e.note, e.issue === void 0 ? void 0 : `${e.issue.owner} ${e.issue.kind}: ${e.issue.message}`].filter((p2) => p2 !== void 0);
216912
+ lines2.push(` #${e.seq} ${e.source} ${e.method} ${e.path}${outcome4.length === 0 ? "" : ` -> ${outcome4.join(" ")}`}`);
216913
+ }
216980
216914
  }
216981
- parts3.push(Buffer.alloc(1024));
216982
- return Buffer.concat(parts3);
216915
+ lines2.push(...worldAccountLines(f2, " ", new Set(f2.traceExcerpt.map((e) => String(e.seq)))));
216916
+ return lines2.join("\n");
216983
216917
  }
216984
- function readBundle(archive) {
216985
- const tar = gunzipSync3(archive, { maxOutputLength: BUNDLE_LIMITS2.unpackedBytes + 1024 * 1024 });
216986
- const entries4 = [];
216987
- for (let offset18 = 0; offset18 + 512 <= tar.length; ) {
216988
- const block2 = tar.subarray(offset18, offset18 + 512);
216989
- if (block2.every((byte) => byte === 0)) break;
216990
- const field6 = (start, length) => block2.subarray(start, start + length).toString("utf8").replace(/\0.*$/s, "");
216991
- const name5 = field6(0, 100), prefix2 = field6(345, 155), size2 = parseInt(field6(124, 12).trim(), 8);
216992
- if (!Number.isSafeInteger(size2) || size2 < 0 || field6(156, 1) !== "0" && field6(156, 1) !== "") throw new AnchaError("USAGE", `bundle entry ${name5} is not a regular file`);
216993
- const path7 = prefix2 ? `${prefix2}/${name5}` : name5;
216994
- entries4.push({ path: path7, data: Buffer.from(tar.subarray(offset18 + 512, offset18 + 512 + size2)) });
216995
- offset18 += 512 + Math.ceil(size2 / 512) * 512;
216918
+ function worldAccountLines(f2, indent2, shownCalls = /* @__PURE__ */ new Set()) {
216919
+ const lines2 = [];
216920
+ const evidence2 = (f2.evidence ?? []).filter((e) => !(e.type === "call" && e.id !== void 0 && shownCalls.has(e.id)));
216921
+ if (evidence2.length > 0) lines2.push(`${indent2}evidence:`, ...evidence2.map((e) => `${indent2} ${e.at ?? e.simAt} ${evidenceLine(e)}`));
216922
+ if ((f2.conversation ?? []).length > 0) lines2.push(`${indent2}conversation:`, ...f2.conversation.map((line2) => `${indent2} ${line2}`));
216923
+ for (const [person5, state3] of Object.entries(f2.people ?? {})) {
216924
+ lines2.push(`${indent2}${person5}:`);
216925
+ if (state3.knows.length > 0) lines2.push(`${indent2} knows: ${state3.knows.join("; ")}`);
216926
+ if (state3.decisions.length > 0) lines2.push(`${indent2} decisions: ${state3.decisions.join("; ")}`);
216927
+ if (state3.knows.length === 0 && state3.decisions.length === 0) lines2.push(`${indent2} knew nothing and decided nothing`);
216996
216928
  }
216997
- return entries4;
216929
+ return lines2;
216998
216930
  }
216999
- function validateBundle(archive) {
217000
- if (archive.length > BUNDLE_LIMITS2.compressedBytes) throw tooBig2(`bundle is ${archive.length} bytes compressed`);
217001
- const entries4 = readBundle(archive);
217002
- if (entries4.length > BUNDLE_LIMITS2.cloudEntries) throw tooBig2(`bundle has ${entries4.length} entries`);
217003
- let unpacked = 0;
217004
- for (const entry3 of entries4) {
217005
- if (!BUNDLE_PATH2.test(entry3.path)) throw new AnchaError("USAGE", `bundle entry not allowed: ${entry3.path}`);
217006
- if (entry3.path !== "bundle.json" && entry3.data.length > capFor(entry3.path)) throw tooBig2(`bundle entry ${entry3.path} is ${entry3.data.length} bytes`);
217007
- unpacked += entry3.data.length;
216931
+ function renderExplain(s3, opts = {}, failures = explainFailures(s3, opts)) {
216932
+ const never2 = agentNeverRan(s3), cloud = s3.target === "cloud";
216933
+ if (never2 !== void 0 && !opts.all && opts.scene === void 0 && opts.trial === void 0) {
216934
+ const folded = neverRanChecksLine(never2, s3.runId, opts.out);
216935
+ return [...neverRanLines(never2, opts.cwd), ...folded === void 0 ? [] : [folded]].join("\n");
217008
216936
  }
217009
- if (unpacked > BUNDLE_LIMITS2.unpackedBytes) throw tooBig2(`bundle unpacks to ${unpacked} bytes`);
217010
- const manifestEntry = entries4.find((entry3) => entry3.path === "bundle.json");
217011
- if (!manifestEntry) throw new AnchaError("USAGE", "bundle has no bundle.json");
217012
- const manifest2 = JSON.parse(manifestEntry.data.toString("utf8"));
217013
- if (entries4.length > entriesFor(manifest2.source)) throw tooBig2(`bundle has ${entries4.length} entries`);
217014
- const foreign = entries4.find((entry3) => !allowedFor(manifest2.source, entry3.path));
217015
- if (foreign) throw new AnchaError("USAGE", `bundle entry not allowed: ${foreign.path}`);
217016
- if (manifest2.source === "cloud" !== CLOUD_RUN_ID.test(manifest2.runId)) throw new AnchaError("USAGE", "a cloud run has a run_cloud_ id and source cloud");
217017
- const byPath = new Map(entries4.map((entry3) => [entry3.path, entry3.data]));
217018
- for (const file3 of manifest2.files) {
217019
- const data5 = byPath.get(file3.path);
217020
- if (!data5 || data5.length !== file3.bytes || sha2564(data5) !== file3.sha256) throw new AnchaError("USAGE", `bundle.json disagrees with ${file3.path}`);
216937
+ const issues = explainHarnessIssues(s3, opts);
216938
+ const agentIssues = explainAgentIssues(s3, opts);
216939
+ const exits = explainPlayOuts(s3, opts), told = /* @__PURE__ */ new Set();
216940
+ const failureBlocks = failures.flatMap((f2) => {
216941
+ const key4 = `${f2.sceneId}/${f2.trial}`, exit = told.has(key4) ? void 0 : exits.find((p2) => `${p2.sceneId}/${p2.trial}` === key4);
216942
+ if (exit === void 0) return [renderFailure(f2)];
216943
+ told.add(key4);
216944
+ return [renderPlayOut(exit), renderFailure(f2)];
216945
+ });
216946
+ const untold = exits.filter((p2) => !told.has(`${p2.sceneId}/${p2.trial}`)).map(renderPlayOut);
216947
+ const blocks2 = [...never2 === void 0 ? [] : [neverRanLines(never2, opts.cwd).join("\n")], ...issues.map(renderHarnessIssue), ...agentIssues.map((issue6) => renderAgentIssue(issue6, cloud)), ...untold, ...failureBlocks];
216948
+ if (s3.pytest) blocks2.unshift(`pytest ${s3.pytest.nodeId}: ${s3.pytest.outcome}${s3.pytest.invalid ? " [invalid]" : !s3.pytest.graded ? " (ungraded)" : ""}; ${s3.pytest.phases.map((phase) => `${phase.when} ${phase.outcome}${phase.errorCode ? ` (${phase.errorCode})` : ""}`).join(", ")}`);
216949
+ for (const warning of explainGradingWarnings(s3, opts)) blocks2.push(`${warning.sceneId} trial ${warning.trial} warning ${warning.check}: ${warning.message}`);
216950
+ blocks2.push(...explainCoverageGaps(s3, opts).map(renderCoverageGap));
216951
+ const ungraded = ungradedLines({ scenes: s3.scenes.filter((scene2) => opts.scene === void 0 || scene2.sceneId === opts.scene) });
216952
+ if (ungraded.length > 0 && !s3.pytest) blocks2.push(ungraded.join("\n"));
216953
+ const withheld = s3.agentEnvironment?.target === "host" && !s3.agentEnvironment.inheritAll ? s3.agentEnvironment.withheld ?? 0 : 0;
216954
+ if (withheld > 0 && blocks2.length > 0 && !agentIssues.some((i) => i.hint !== void 0)) blocks2.push(`environment: ${withheld} variables from this shell were withheld from the agent. If it needs one (a provider key, say), pass it with --pass-env NAME or list it under agent.pass_env in ancha.yaml.`);
216955
+ const shown3 = new Set(failures.map((f2) => `${f2.sceneId}/${f2.trial}`));
216956
+ for (const scene2 of s3.scenes) {
216957
+ if (opts.scene !== void 0 && scene2.sceneId !== opts.scene) continue;
216958
+ const issueTrials = new Set(issues.filter((i) => i.sceneId === scene2.sceneId && i.owner === "harness").map((i) => i.trial));
216959
+ const invalidMissing = scene2.trialsDetail.filter((t) => t.valid === false && (opts.trial === void 0 || t.trial === opts.trial) && !issueTrials.has(t.trial));
216960
+ if (invalidMissing.length > 0) {
216961
+ blocks2.push(`${scene2.sceneId}: no detail kept for invalid trial(s) ${invalidMissing.map((t) => t.trial).join(", ")} (at most ${MAX_FAILURES_PER_SCENE} issues per test); see trace.jsonl and checks.json in each trial directory, e.g. ${invalidMissing[0].dir}`);
216962
+ }
216963
+ const missing8 = scene2.trialsDetail.filter((t) => !t.passed && (!s3.pytest || t.valid && t.outcome !== "skipped" && t.outcome !== "xfailed") && (opts.trial === void 0 || t.trial === opts.trial) && !shown3.has(`${scene2.sceneId}/${t.trial}`));
216964
+ if (missing8.length > 0) {
216965
+ const trials = missing8.length > 10 ? `${missing8.slice(0, 10).map((t) => t.trial).join(", ")} and ${missing8.length - 10} more` : missing8.map((t) => t.trial).join(", ");
216966
+ blocks2.push(`${scene2.sceneId}: no detail kept for failed trial(s) ${trials} (at most ${MAX_FAILURES_PER_SCENE} failures per test); see checks.json and trace.jsonl in each trial directory, e.g. ${missing8[0].dir}`);
216967
+ }
217021
216968
  }
217022
- if (!byPath.has("summary.json")) throw new AnchaError("USAGE", "bundle has no summary.json");
217023
- return manifest2;
216969
+ if (blocks2.length === 0) return "no failed checks to explain";
216970
+ const text29 = blocks2.join("\n\n");
216971
+ return text29.includes(PATTERN_NOTE) ? `${text29.replaceAll(PATTERN_NOTE, "")}
216972
+
216973
+ ${PATTERN_NOTE.trim()}` : text29;
217024
216974
  }
217025
- var BUNDLE_PATH2, CLOUD_ONLY_PATH, CLOUD_RUN_ID, MANDATORY_CLOUD_PATH, MB, BUNDLE_LIMITS2, MIN_SECRET, entriesFor, allowedFor, sha2564, tooBig2;
217026
- var init_run_bundle = __esm({
217027
- "backend/src/run-bundle.ts"() {
216975
+ var CLOUD_EXIT2, MAX_FAILURES_PER_SCENE, DEFAULT_RUNS_DIR, exitedCleanly, FALLBACK_EXCERPT_CALLS, round4, trialIssues, trialValid, outcomeOf2, sceneFailed, CRASH_NOISE, ERROR_LINE, CRASH_LINE_MAX, NEVER_RAN_MS, spaced, pct, SUMMARY_GAPS_SHOWN, SUMMARY_ACTIONS_SHOWN, ANSWER_SOURCES2, duration8, shellWord, PATTERN_NOTE;
216976
+ var init_report2 = __esm({
216977
+ "backend/src/report.ts"() {
217028
216978
  "use strict";
217029
216979
  init_src();
217030
- init_agent_env();
217031
- BUNDLE_PATH2 = /^(bundle\.json|summary\.json|inputs\.json|reproduction\.json|cloud\.json|trial-[A-Za-z0-9_-]{1,191}-[0-9]{1,4}\/(agent\.log|trace\.jsonl|state\.json|people-timeline\.json|explain\.json|checks\.json|result\.json|task-input\.json|execution\.json))$/;
217032
- CLOUD_ONLY_PATH = /^(reproduction\.json|cloud\.json|trial-[A-Za-z0-9_-]{1,191}-[0-9]{1,4}\/execution\.json)$/;
217033
- CLOUD_RUN_ID = /^run_cloud_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
217034
- MANDATORY_CLOUD_PATH = /^(summary\.json|trial-[^/]+\/(result\.json|checks\.json|trace\.jsonl))$/;
217035
- MB = 1024 * 1024;
217036
- BUNDLE_LIMITS2 = { entries: 1200, cloudEntries: 2e3, compressedBytes: 50 * MB, unpackedBytes: 200 * MB, largeFileBytes: 12 * MB, fileBytes: 4 * MB, agentLogBytes: 4 * MB };
217037
- MIN_SECRET = 8;
217038
- entriesFor = (source) => source === "cloud" ? BUNDLE_LIMITS2.cloudEntries : BUNDLE_LIMITS2.entries;
217039
- allowedFor = (source, path7) => BUNDLE_PATH2.test(path7) && (source === "cloud" || !CLOUD_ONLY_PATH.test(path7));
217040
- sha2564 = (data5) => createHash59("sha256").update(data5).digest("hex");
217041
- tooBig2 = (message7) => new AnchaError("USAGE", message7, { hint: "upload a run with fewer trials, or run fewer trials per test" });
217042
- }
217043
- });
217044
-
217045
- // backend/src/harness-issues.ts
217046
- var init_harness_issues2 = __esm({
217047
- "backend/src/harness-issues.ts"() {
217048
- "use strict";
216980
+ init_harness_issues2();
216981
+ init_scenes();
216982
+ init_actions7();
216983
+ init_reproduction_text();
216984
+ init_agent_fix();
217049
216985
  init_src();
216986
+ CLOUD_EXIT2 = { pass: 0, fail: 1, cancelled: 2, invalid: 3, strict: 4 };
216987
+ MAX_FAILURES_PER_SCENE = 20;
216988
+ DEFAULT_RUNS_DIR = ".ancha/runs";
216989
+ exitedCleanly = (t) => t.exit === "done" || t.exit === "idle" || t.exit === "exited" && t.exitCode === 0;
216990
+ FALLBACK_EXCERPT_CALLS = 10;
216991
+ round4 = (n2) => Math.round(n2 * 1e4) / 1e4;
216992
+ trialIssues = (t) => t.harnessIssues ?? collectHarnessIssues(t.trace, t.checks);
216993
+ trialValid = (t) => t.valid !== false && t.exit !== "invalid" && !trialIssues(t).some((i) => i.owner === "harness");
216994
+ outcomeOf2 = (t) => trialOutcome({ ...t, valid: trialValid(t), outcome: t.checks.some((check4) => check4.required && check4.status === "skipped") ? "skipped" : t.outcome });
216995
+ sceneFailed = (scene2, minPassRate) => (scene2.invalidTrials ?? 0) > 0 || !scene2.counts || !meetsPassRate(scene2.counts, minPassRate);
216996
+ CRASH_NOISE = /^\s*$|^\s+at\s|^\s*… \d+ more frames$|^\s*[~^]+\s*$|^\s*[{}]\s*$|^Node\.js v\d/;
216997
+ ERROR_LINE = /error|exception|fatal|panic/i;
216998
+ CRASH_LINE_MAX = 200;
216999
+ NEVER_RAN_MS = 5e3;
217000
+ spaced = (ms2) => ms2 < 1e3 ? `${ms2} ms` : `${(ms2 / 1e3).toFixed(1)} s`;
217001
+ pct = (rate) => String(Math.round(rate * 1e3) / 10);
217002
+ SUMMARY_GAPS_SHOWN = 10;
217003
+ SUMMARY_ACTIONS_SHOWN = 8;
217004
+ ANSWER_SOURCES2 = [["replayed", "replayed"], ["replayed-elsewhere", "replayed from another conversation"], ["twin", "by twins"], ["ran", "ran the tool itself"], ["simulated", "simulated"], ["failed", "failed"]];
217005
+ duration8 = (ms2) => ms2 < 1e3 ? `${ms2}ms` : `${(ms2 / 1e3).toFixed(1)}s`;
217006
+ shellWord = (dir2) => /^[\w./@%+=:,-]+$/.test(dir2) ? dir2 : `'${dir2.replaceAll("'", `'\\''`)}'`;
217007
+ PATTERN_NOTE = ' Patterns are "<METHOD> <PATH>" matched against the service-relative path, and * is a wildcard.';
217050
217008
  }
217051
217009
  });
217052
217010
 
217053
- // backend/src/reproduction-text.ts
217054
- function renderWrites(writes2) {
217055
- const of = `${writes2.of} ${writes2.of === 1 ? "trial" : "trials"}`;
217056
- if (!writes2.tools.length) return [` writes compared with production: none in production, none in this run's ${of}`];
217057
- const called = (n2) => n2 === 0 ? "not called" : n2 === 1 ? "called" : `called ${n2} times`;
217058
- const width = Math.max(...writes2.tools.map((w2) => w2.tool.length)), said = Math.max(...writes2.tools.map((w2) => called(w2.production).length));
217059
- return [" writes compared with production:", ...writes2.tools.map((w2) => ` ${w2.tool.padEnd(width)} production: ${called(w2.production).padEnd(said)} this run: ${w2.trials} of ${of}`)];
217011
+ // backend/src/run-store.ts
217012
+ import { readFile as readFile6, stat as stat2 } from "node:fs/promises";
217013
+ import { join as join16, resolve as resolve14 } from "node:path";
217014
+ async function latestRunId(cwd, out) {
217015
+ if (out !== void 0) return resolveRunId(cwd, "latest", out);
217016
+ const dir2 = resolve14(cwd, DEFAULT_RUNS_DIR);
217017
+ let local2;
217018
+ try {
217019
+ const path7 = join16(dir2, "latest");
217020
+ local2 = { runId: (await readFile6(path7, "utf8")).trim(), time: (await stat2(path7)).mtimeMs };
217021
+ } catch (error65) {
217022
+ if (!isEnoent(error65)) throw error65;
217023
+ }
217024
+ const text29 = await readFile6(join16(dir2, "latest-cloud"), "utf8").catch((error65) => {
217025
+ if (!isEnoent(error65)) throw error65;
217026
+ return void 0;
217027
+ });
217028
+ if (text29 !== void 0) {
217029
+ try {
217030
+ const cloud = JSON.parse(text29);
217031
+ const time7 = typeof cloud?.submittedAt === "string" ? Date.parse(cloud.submittedAt) : NaN;
217032
+ if (typeof cloud?.runId === "string" && RUN_CLOUD_ID.test(cloud.runId) && Number.isFinite(time7) && (local2 === void 0 || time7 > local2.time)) return cloud.runId;
217033
+ } catch {
217034
+ }
217035
+ }
217036
+ return local2?.runId ?? resolveRunId(cwd, "latest");
217060
217037
  }
217061
- function renderReproduction(reproductions, opts = {}) {
217062
- if (opts.neverRan) return reproductions.map((r2) => `compared with production${r2.trace === void 0 ? "" : ` (trace ${r2.trace.slice(0, 12)})`}: ${r2.sceneId}
217063
- => not compared: the agent never ran`).join("\n\n");
217064
- return reproductions.map((r2) => {
217065
- const width = Math.max(...r2.checks.map((c) => c.check.length));
217066
- const rows33 = r2.checks.map((c) => ` ${c.check.padEnd(width)} ${c.production} in production \xB7 ${c.total === 0 ? "not run" : c.failed === 0 ? `passed ${c.total}/${c.total} here` : `failed ${c.failed}/${c.total} here`}`);
217067
- const also = r2.verdict !== "differs" ? r2.checks.filter((c) => c.production === "passed" && c.failed > 0).map((c) => c.check) : [];
217068
- const verdict = r2.error !== void 0 && r2.checks.length === 0 ? [] : [`=> ${SAY[r2.verdict]}`];
217069
- return [
217070
- `compared with production${r2.trace === void 0 ? "" : ` (trace ${r2.trace.slice(0, 12)})`}: ${r2.sceneId}`,
217071
- ...rows33,
217072
- ...verdict,
217073
- ...r2.error !== void 0 ? [` grading production's record failed: ${r2.error}`] : [],
217074
- ...also.length > 0 ? [` also failing here, though production passed: ${also.join(", ")}`] : [],
217075
- // A failure here on a check production is not graded on yet is neither a match nor a regression: say how to grade both.
217076
- ...r2.verdict !== "unknown" && r2.checks.some((c) => c.production === "unknown" && c.failed > 0) ? [` set OPENROUTER_API_KEY to grade ${r2.checks.filter((c) => c.production === "unknown" && c.failed > 0).map((c) => c.check).join(", ")} on production's record and here`] : [],
217077
- ...r2.added.length > 0 ? [` checks added after saving, with no production result: ${r2.added.join(", ")}`] : [],
217078
- // How much of the run stood on production's own answers (TRACE_PLAN_V2 §8.6).
217079
- ...r2.answers ? [` answers to the agent's tools: ${["replayed", "replayed-elsewhere", "twin", "ran", "simulated", "validated", "failed"].filter((s3) => r2.answers[s3]).map((s3) => `${r2.answers[s3]} ${s3}`).join(", ")}${r2.answers.simulated ? "; simulated answers took the agent where production never went (ancha explain lists them)" : ""}`] : [],
217080
- // What the agent changed, next to what production changed: an answer that needs no model (SPEC-020 R1).
217081
- ...r2.writes !== void 0 && r2.writes.of > 0 ? renderWrites(r2.writes) : []
217082
- ].join("\n");
217083
- }).join("\n\n");
217038
+ async function resolveRunId(cwd, ref22, out) {
217039
+ const dir2 = resolve14(cwd, out ?? DEFAULT_RUNS_DIR);
217040
+ let runId2 = ref22;
217041
+ if (ref22 === "latest") {
217042
+ try {
217043
+ runId2 = (await readFile6(join16(dir2, "latest"), "utf8")).trim();
217044
+ } catch (e) {
217045
+ if (isEnoent(e)) throw new AnchaError("USAGE", `no runs found in ${dir2}`, { hint: "run `ancha run` first", cause: e });
217046
+ throw e;
217047
+ }
217048
+ }
217049
+ return runId2;
217084
217050
  }
217085
- var SAY;
217086
- var init_reproduction_text = __esm({
217087
- "backend/src/reproduction-text.ts"() {
217051
+ async function loadRunSummary(cwd, ref22, out) {
217052
+ const dir2 = resolve14(cwd, out ?? DEFAULT_RUNS_DIR);
217053
+ const hint = `see ${out ?? DEFAULT_RUNS_DIR}/`;
217054
+ const runId2 = await resolveRunId(cwd, ref22, out);
217055
+ if (!RUN_ID.test(runId2)) throw new AnchaError("USAGE", `unknown run ${JSON.stringify(runId2)}`, { hint });
217056
+ let text29;
217057
+ try {
217058
+ text29 = await readFile6(join16(dir2, runId2, "summary.json"), "utf8");
217059
+ } catch (e) {
217060
+ if (!isEnoent(e)) throw e;
217061
+ if (await stat2(join16(dir2, runId2)).then((s4) => s4.isDirectory(), () => false)) {
217062
+ throw new AnchaError("USAGE", `run ${runId2} has no summary.json (it may have been interrupted)`, {
217063
+ hint: `its trial directories (agent.log, trace.jsonl, \u2026) are in ${join16(out ?? DEFAULT_RUNS_DIR, runId2)}/; run \`ancha run\` again for a summary`,
217064
+ cause: e
217065
+ });
217066
+ }
217067
+ throw new AnchaError("USAGE", `unknown run ${JSON.stringify(runId2)}`, { hint, cause: e });
217068
+ }
217069
+ let summary;
217070
+ try {
217071
+ summary = JSON.parse(text29);
217072
+ } catch (e) {
217073
+ throw new AnchaError("INTERNAL", `${join16(dir2, runId2, "summary.json")} is not valid JSON`, { cause: e });
217074
+ }
217075
+ const s3 = summary;
217076
+ if (typeof s3 !== "object" || s3 === null || s3.runId !== runId2 || !Array.isArray(s3.scenes)) {
217077
+ throw new AnchaError("INTERNAL", `${join16(dir2, runId2, "summary.json")} is not a run summary`);
217078
+ }
217079
+ return normalizeSummary(s3);
217080
+ }
217081
+ var RUN_ID, isEnoent;
217082
+ var init_run_store = __esm({
217083
+ "backend/src/run-store.ts"() {
217088
217084
  "use strict";
217089
- SAY = {
217090
- crashed: "the agent exited with an error in every trial, so this run says nothing about production's failure: fix the agent first",
217091
- reproduced: "production's failure happens here too",
217092
- partly: "production's failure happens here in part",
217093
- "not-reproduced": "production's failure did not happen here",
217094
- matches: "this run matches production, which passed these checks",
217095
- differs: "checks production passed failed here",
217096
- unknown: "set OPENROUTER_API_KEY and run again: a model grades these checks on production's record and on this run",
217097
- ungraded: "the checks that compare with production could not be graded in this run, so it says nothing about production yet"
217098
- };
217085
+ init_src();
217086
+ init_report2();
217087
+ init_jobs_contract();
217088
+ RUN_ID = /^[A-Za-z0-9_][\w.-]*$/;
217089
+ isEnoent = (e) => e?.code === "ENOENT";
217099
217090
  }
217100
217091
  });
217101
217092
 
217102
- // backend/src/report.ts
217103
- import { readFile as readFile10, writeFile as writeFile9 } from "node:fs/promises";
217104
- import { basename as basename6, dirname as dirname9, join as join22, relative as relative8, resolve as resolve15 } from "node:path";
217105
- function okFalseError(response5) {
217106
- if (typeof response5 !== "object" || response5 === null || response5.ok !== false) return void 0;
217107
- const error65 = response5.error;
217108
- return typeof error65 === "string" ? error65 : "unknown_error";
217093
+ // backend/src/runner/run-state.ts
217094
+ import { randomBytes as randomBytes5 } from "node:crypto";
217095
+ import { mkdir as mkdir9, readFile as readFile7, rename as rename2, stat as stat3, writeFile as writeFile8 } from "node:fs/promises";
217096
+ import { join as join17 } from "node:path";
217097
+ function validateRunId(runId2) {
217098
+ if (runId2.length > 128 || !/^run_[A-Za-z0-9_-]+$/.test(runId2)) throw new AnchaError("USAGE", "invalid run id", { hint: "use the run id returned by run" });
217109
217099
  }
217110
- function excerptOf(entry3) {
217111
- const response5 = entry3.response;
217112
- const error65 = entry3.service === "tools" && typeof response5?.error === "string" ? response5.error : okFalseError(entry3.response);
217113
- return {
217114
- seq: entry3.seq,
217115
- source: entry3.source,
217116
- method: entry3.method,
217117
- path: entry3.path,
217118
- ...entry3.status !== void 0 && { status: entry3.status },
217119
- ...error65 !== void 0 && { error: error65 },
217120
- ...response5?.execution_status && { execution_status: response5.execution_status },
217121
- ...response5?.error_type && { error_type: response5.error_type },
217122
- ...entry3.service === "tools" && response5 && Object.hasOwn(response5, "result") && { result: response5.result },
217123
- ...entry3.note !== void 0 && { note: entry3.note },
217124
- ...entry3.issue !== void 0 && { issue: entry3.issue }
217125
- };
217100
+ async function reserveRun(outDir, totalTrials) {
217101
+ if (!Number.isSafeInteger(totalTrials) || totalTrials < 1) throw new AnchaError("USAGE", "total trials must be a positive safe integer");
217102
+ await mkdir9(join17(outDir, ".status"), { recursive: true });
217103
+ for (; ; ) {
217104
+ const now11 = (/* @__PURE__ */ new Date()).toISOString();
217105
+ const runId2 = `run_${now11.slice(0, 19).replace(/[-:]/g, "").replace("T", "-")}_${randomBytes5(8).toString("hex")}`;
217106
+ if (await stat3(join17(outDir, runId2)).then(() => true, () => false)) continue;
217107
+ const state3 = { version: 1, runId: runId2, state: "starting", pid: process.pid, startedAt: now11, updatedAt: now11, completedTrials: 0, totalTrials };
217108
+ try {
217109
+ await writeFile8(pathOf4(outDir, runId2), JSON.stringify(state3), { flag: "wx", mode: 384 });
217110
+ return state3;
217111
+ } catch (error65) {
217112
+ if (error65.code !== "EEXIST") throw error65;
217113
+ }
217114
+ }
217126
217115
  }
217127
- function traceExcerpt(trace, evidence2) {
217128
- trace = projectToolCalls(trace);
217129
- if (evidence2.length === 0) return trace.slice(-FALLBACK_EXCERPT_CALLS).map(excerptOf);
217130
- const wanted = new Set(evidence2);
217131
- return trace.filter((e) => wanted.has(e.seq) || e.completion !== void 0 && wanted.has(e.completion.seq)).map(excerptOf);
217116
+ async function saveRunState(outDir, state3) {
217117
+ validateRunId(state3.runId);
217118
+ const path7 = pathOf4(outDir, state3.runId);
217119
+ const tmp = `${path7}.${process.pid}.${randomBytes5(6).toString("hex")}.tmp`;
217120
+ await writeFile8(tmp, JSON.stringify(state3), { mode: 384 });
217121
+ await rename2(tmp, path7);
217132
217122
  }
217133
- function summarizeScene(sceneId, trials, requestedTrials = trials.length) {
217134
- const counts = countTrials(requestedTrials, trials.map(outcomeOf2));
217135
- const checks2 = {};
217136
- const failures = [];
217137
- const agentIssues = [];
217138
- const harnessIssues = [];
217139
- const invalidTrials = counts.invalid;
217140
- let skippedJudges = 0;
217141
- const warnings2 = [];
217142
- const gaps2 = /* @__PURE__ */ new Map();
217143
- let agentCalls2 = 0;
217144
- let totalMs = 0;
217145
- let graded = false;
217146
- for (const t of trials) {
217147
- totalMs += t.realMs;
217148
- for (const issue6 of trialIssues(t)) {
217149
- if (harnessIssues.length < MAX_FAILURES_PER_SCENE) harnessIssues.push({ ...issue6, sceneId, trial: t.trial });
217150
- }
217151
- const exit = t.exit === "invalid" && t.originalExit === "spawn_failed" ? "spawn_failed" : t.exit;
217152
- if (!t.passed && exit !== "invalid" && !exitedCleanly({ exit, exitCode: t.exitCode }) && agentIssues.length < MAX_FAILURES_PER_SCENE) {
217153
- agentIssues.push({ sceneId, trial: t.trial, exit, exitCode: t.exitCode, realMs: t.realMs, log: join22(t.dir, "agent.log"), logTail: t.logTail, ...t.invocations !== void 0 && { invocations: t.invocations } });
217123
+ async function readRunState(outDir, runId2) {
217124
+ validateRunId(runId2);
217125
+ let value5;
217126
+ try {
217127
+ value5 = JSON.parse(await readFile7(pathOf4(outDir, runId2), "utf8"));
217128
+ } catch (error65) {
217129
+ if (error65.code === "ENOENT") {
217130
+ const summary = await loadRunSummary(outDir, runId2, ".");
217131
+ const completedTrials = summary.scenes.reduce((sum6, scene2) => sum6 + (scene2.counts?.completed ?? scene2.trialsDetail?.length ?? scene2.trials), 0);
217132
+ const totalTrials = summary.scenes.reduce((sum6, scene2) => sum6 + (scene2.counts?.requested ?? scene2.trials), 0);
217133
+ const exitCode = summary.exitCode;
217134
+ if (!["pass", "fail", "ungraded"].includes(summary.verdict) || !Number.isFinite(Date.parse(summary.startedAt)) || !Number.isFinite(Date.parse(summary.finishedAt)) || !Number.isSafeInteger(completedTrials) || !Number.isSafeInteger(totalTrials) || completedTrials < 0 || totalTrials < completedTrials || exitCode !== void 0 && (!Number.isInteger(exitCode) || exitCode < 0 || exitCode > 4)) throw new AnchaError("INTERNAL", "invalid completed run status");
217135
+ return {
217136
+ version: 1,
217137
+ runId: runId2,
217138
+ state: "finished",
217139
+ startedAt: summary.startedAt,
217140
+ updatedAt: summary.finishedAt,
217141
+ completedTrials,
217142
+ totalTrials,
217143
+ ...exitCode === void 0 ? { error: { code: "INTERNAL", message: "Run finished; exit code is unknown because the saved summary has no exitCode." } } : { exitCode }
217144
+ };
217154
217145
  }
217155
- const valid2 = trialValid(t);
217156
- for (const c of t.checks) {
217157
- if (valid2 && c.status !== "skipped" && c.error === void 0) graded = true;
217158
- const tally = checks2[c.id] ??= { passed: 0, total: 0, required: c.required };
217159
- tally.total++;
217160
- if (c.status === "skipped") {
217161
- tally.skipped = (tally.skipped ?? 0) + 1;
217162
- skippedJudges++;
217163
- } else if (!c.passed && (!valid2 || c.error !== void 0)) tally.invalid = (tally.invalid ?? 0) + 1;
217164
- if (c.warning !== void 0) warnings2.push({ trial: t.trial, check: c.id, message: c.warning });
217165
- if (c.passed) tally.passed++;
217166
- if (c.required && !c.passed && c.error === void 0 && c.status !== "skipped" && failures.length < MAX_FAILURES_PER_SCENE) {
217167
- failures.push({
217168
- sceneId,
217169
- trial: t.trial,
217170
- check: c.id,
217171
- expected: c.expected,
217172
- actual: c.actual,
217173
- explanation: c.explanation,
217174
- traceExcerpt: traceExcerpt(t.trace, c.evidence),
217175
- ...c.evidence.length === 0 && t.trace.length > FALLBACK_EXCERPT_CALLS && { traceExcerptOmitted: t.trace.length - FALLBACK_EXCERPT_CALLS }
217176
- });
217177
- }
217146
+ throw new AnchaError("INTERNAL", "cannot read run status", { cause: error65 });
217147
+ }
217148
+ const state3 = value5;
217149
+ if (state3 === null || typeof state3 !== "object" || state3.version !== 1 || state3.runId !== runId2 || !["starting", "running", "finished", "failed", "interrupted"].includes(state3.state) || typeof state3.pid !== "number" || !Number.isSafeInteger(state3.pid) || state3.pid <= 0 || !Number.isSafeInteger(state3.completedTrials) || !Number.isSafeInteger(state3.totalTrials) || state3.completedTrials < 0 || state3.totalTrials < state3.completedTrials || !Number.isFinite(Date.parse(state3.updatedAt)) || !Number.isFinite(Date.parse(state3.startedAt)) || terminal(state3) && (!Number.isInteger(state3.exitCode) || state3.exitCode < 0 || state3.exitCode > 4) || state3.error !== void 0 && (state3.error === null || !isErrorCode(state3.error.code) || typeof state3.error.message !== "string") || state3.upload !== void 0 && (typeof state3.upload !== "object" || state3.upload === null || ("error" in state3.upload ? !isErrorCode(state3.upload.error?.code) || typeof state3.upload.error.message !== "string" : typeof state3.upload.url !== "string"))) {
217150
+ throw new AnchaError("INTERNAL", "invalid run status");
217151
+ }
217152
+ if (!terminal(state3)) {
217153
+ let alive4 = true;
217154
+ try {
217155
+ process.kill(state3.pid, 0);
217156
+ } catch (error65) {
217157
+ alive4 = error65.code !== "ESRCH";
217178
217158
  }
217179
- for (const e of projectToolCalls(t.trace)) {
217180
- if (e.source === "agent" && !isAgentAnswer(e)) agentCalls2++;
217181
- if (e.gap === true) {
217182
- const key4 = JSON.stringify([e.service, e.method, e.path]);
217183
- const gap6 = gaps2.get(key4);
217184
- const error65 = okFalseError(e.response) ?? (typeof e.response === "object" && e.response !== null && typeof e.response.message === "string" ? e.response.message : void 0);
217185
- if (gap6 === void 0) gaps2.set(key4, { service: e.service, method: e.method, path: e.path, count: 1, ...e.status !== void 0 && { status: e.status }, ...error65 !== void 0 && { error: error65 } });
217186
- else gap6.count++;
217187
- }
217159
+ if (!alive4 || Date.now() - Date.parse(state3.updatedAt) > 15e3) {
217160
+ return { ...state3, state: "failed", exitCode: 3, error: { code: "INTERNAL", message: alive4 ? "run worker heartbeat expired; completion is unknown" : "run worker exited without a terminal status" } };
217188
217161
  }
217189
217162
  }
217190
- const passed = counts.passed;
217191
- const actions = actionCounts(trials.filter(trialValid)), answers = answerCounts(trials.filter(trialValid));
217163
+ return state3;
217164
+ }
217165
+ function stateWriter(outDir, initial) {
217166
+ let state3 = initial;
217167
+ let pending = Promise.resolve();
217168
+ let failure6;
217169
+ const update3 = (patch) => {
217170
+ state3 = { ...state3, ...patch, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
217171
+ const snapshot = state3;
217172
+ const publication = pending.then(() => saveRunState(outDir, snapshot));
217173
+ pending = publication.catch((error65) => {
217174
+ failure6 ??= error65;
217175
+ });
217176
+ return publication;
217177
+ };
217178
+ const backgroundUpdate = (patch) => {
217179
+ void update3(patch).catch(() => {
217180
+ });
217181
+ };
217182
+ const timer = setInterval(() => {
217183
+ backgroundUpdate({});
217184
+ }, 1e3);
217185
+ timer.unref();
217192
217186
  return {
217193
- sceneId,
217194
- counts,
217195
- trials: trials.length,
217196
- passed,
217197
- passRate: counts.requested === 0 ? 0 : round4(passed / counts.requested),
217198
- passAllK: allTrialsPassed(counts),
217199
- checks: checks2,
217200
- graded,
217201
- agentIssues,
217202
- harnessIssues,
217203
- invalidTrials,
217204
- skippedJudges,
217205
- warnings: warnings2,
217206
- failures,
217207
- coverageGaps: [...gaps2.values()],
217208
- meanRealMs: trials.length === 0 ? 0 : Math.round(totalMs / trials.length),
217209
- agentCalls: agentCalls2,
217210
- ...actions !== void 0 && { actions },
217211
- ...answers !== void 0 && { answers },
217212
- trialsDetail: trials.map((t) => ({ trial: t.trial, passed: outcomeOf2(t) === "passed", valid: trialValid(t), ...outcomeOf2(t) === "skipped" ? { outcome: "skipped" } : t.outcome ? { outcome: t.outcome } : {}, ...t.checks.some((c) => c.status === "skipped") && { skippedJudges: t.checks.filter((c) => c.status === "skipped").length }, exit: t.exit, ...t.originalExit !== void 0 && { originalExit: t.originalExit }, exitCode: t.exitCode, realMs: t.realMs, ...t.simMs !== void 0 && { simMs: t.simMs }, ...t.playOut !== void 0 && { playOut: t.playOut }, ...t.sessionId !== void 0 && { sessionId: t.sessionId }, dir: t.dir }))
217187
+ update: update3,
217188
+ trialFinished() {
217189
+ backgroundUpdate({ completedTrials: state3.completedTrials + 1 });
217190
+ },
217191
+ async finish(patch) {
217192
+ clearInterval(timer);
217193
+ await update3(patch);
217194
+ if (failure6 !== void 0) throw failure6;
217195
+ }
217213
217196
  };
217214
217197
  }
217215
- function runVerdict(scenes, minPassRate) {
217216
- if (scenes.some((scene2) => sceneFailed(scene2, minPassRate))) return "fail";
217217
- return scenes.some((scene2) => scene2.graded === false) ? "ungraded" : "pass";
217218
- }
217219
- function summarize(run6, agent, minPassRate, options4 = {}) {
217220
- const scenes = [...run6.results].map(([sceneId, value5]) => ({ ...summarizeScene(sceneId, value5.trials, value5.requestedTrials), ...value5.case && { scenarioId: value5.scene.id, case: value5.case } }));
217198
+ var terminal, pathOf4;
217199
+ var init_run_state = __esm({
217200
+ "backend/src/runner/run-state.ts"() {
217201
+ "use strict";
217202
+ init_src();
217203
+ init_run_store();
217204
+ terminal = (state3) => ["finished", "failed", "interrupted"].includes(state3.state);
217205
+ pathOf4 = (outDir, runId2) => join17(outDir, ".status", `${runId2}.json`);
217206
+ }
217207
+ });
217208
+
217209
+ // backend/src/runner/invalid-trial.ts
217210
+ import { mkdir as mkdir10 } from "node:fs/promises";
217211
+ import { join as join18 } from "node:path";
217212
+ async function invalidTrial(options4) {
217213
+ const { scene: scene2, trial, dir: dir2, startedAt, error: error65, service = "world", envId, sessionId, capture: capture4 } = options4;
217214
+ await mkdir10(dir2, { recursive: true });
217215
+ const tail = await logTail(join18(dir2, "agent.log")).catch((failure6) => {
217216
+ if (failure6?.code === "ENOENT") return [];
217217
+ throw failure6;
217218
+ });
217221
217219
  return {
217222
- verdictVersion: VERDICT_VERSION,
217223
- runId: run6.runId,
217224
- startedAt: run6.startedAt,
217225
- finishedAt: run6.finishedAt,
217226
- agent,
217227
- ...options4.agentCommand !== void 0 && { agentCommand: options4.agentCommand },
217228
- minPassRate,
217229
- verdict: runVerdict(scenes, minPassRate),
217230
- scenes,
217231
- ...options4.strict && { strict: { simulatedAnswers: [...run6.results].flatMap(([sceneId, { trials }]) => trials.filter((t) => trialValid(t) && (t.answers?.simulated ?? 0) > 0).map((t) => ({ sceneId, trial: t.trial, checks: t.checks.filter((c) => c.status !== "skipped" && c.error === void 0).map((c) => c.id) }))) } },
217232
- ...[...run6.results.values()].some((value5) => value5.case) && { caseFingerprints: Object.fromEntries([...run6.results].flatMap(([id14, value5]) => value5.case ? [[id14, value5.case.fingerprint]] : [])) },
217233
- sceneFingerprints: Object.fromEntries([...run6.results].map(([id14, { scene: scene2, records: records4 }]) => [id14, sceneFingerprint(records4 === void 0 ? scene2 : { scene: scene2, records: records4 })])),
217234
- ...run6.agentEnvironment !== void 0 && { agentEnvironment: run6.agentEnvironment }
217220
+ sceneId: scene2.id,
217221
+ trial,
217222
+ dir: dir2,
217223
+ ...envId !== void 0 && { envId },
217224
+ ...sessionId !== void 0 && { sessionId },
217225
+ exit: "invalid",
217226
+ exitCode: null,
217227
+ realMs: startedAt === void 0 ? 0 : Math.round(performance.now() - startedAt),
217228
+ ...capture4 !== void 0 && { simMs: capture4.simMs },
217229
+ checks: capture4?.checks ?? [],
217230
+ trace: capture4?.trace ?? [],
217231
+ logTail: tail,
217232
+ passed: false,
217233
+ valid: false,
217234
+ harnessIssues: [...capture4?.harnessIssues ?? [], {
217235
+ kind: "world",
217236
+ owner: "harness",
217237
+ service,
217238
+ message: `${error65.code}: ${error65.message}`
217239
+ }]
217235
217240
  };
217236
217241
  }
217237
- function checkCounts(run6) {
217238
- let passed = 0, failed = 0, skipped = 0, invalid35 = 0;
217239
- for (const { trials } of run6.results.values()) for (const t of trials) {
217240
- const valid2 = trialValid(t);
217241
- for (const c of t.checks) {
217242
- if (!valid2 || c.error !== void 0) invalid35++;
217243
- else if (c.status === "skipped") skipped++;
217244
- else if (c.passed) passed++;
217245
- else failed++;
217246
- }
217242
+ var init_invalid_trial = __esm({
217243
+ "backend/src/runner/invalid-trial.ts"() {
217244
+ "use strict";
217245
+ init_artifacts2();
217247
217246
  }
217248
- return { evaluated: passed + failed, passed, failed, skipped, invalid: invalid35 };
217249
- }
217250
- function cloudExitCode(summary, counts, options4) {
217251
- if (counts.invalidAttempts > 0 || counts.skippedAttempts > 0 || options4.terminalIntent === "failed") return CLOUD_EXIT2.invalid;
217252
- if (counts.cancelledAttempts > 0 || options4.terminalIntent === "cancelled") return CLOUD_EXIT2.cancelled;
217253
- if (options4.strict && hasStrictViolation(summary)) return CLOUD_EXIT2.strict;
217254
- return summary.verdict === "pass" ? CLOUD_EXIT2.pass : CLOUD_EXIT2.fail;
217255
- }
217256
- function ungradedTests(s3) {
217257
- return (s3.scenes ?? []).filter((scene2) => scene2.graded === false && (scene2.trialsDetail ?? []).some((t) => t.valid !== false)).map((scene2) => ({ sceneId: scene2.sceneId, checks: Object.keys(scene2.checks ?? {}).length }));
217258
- }
217259
- function ungradedLines(s3, indent2 = "") {
217260
- return ungradedTests(s3).flatMap(({ sceneId, checks: checks2 }) => [
217261
- checks2 === 0 ? `${indent2}ungraded: ${sceneId} has no checks, so nothing was graded` : `${indent2}ungraded: ${sceneId}: none of its ${checks2 === 1 ? "check was" : `${checks2} checks were`} evaluated, so nothing was graded`,
217262
- `${indent2} add a check under checks: in its test file (ancha twins seed <tool> lists the checks a tool takes), then run it again`
217263
- ]);
217264
- }
217265
- function hasStrictViolation(summary) {
217266
- return summary.scenes.some((scene2) => scene2.coverageGaps.length > 0 || (scene2.answers?.simulatedIn ?? 0) > 0);
217267
- }
217268
- function strictSummaryLines(summary) {
217269
- return (summary.strict?.simulatedAnswers ?? []).map((item2) => `--strict: ${item2.sceneId} trial ${item2.trial} used simulated tool answers; checks: ${item2.checks.join(", ") || "none evaluated"}`);
217247
+ });
217248
+
217249
+ // backend/src/runner/run.ts
217250
+ import { createHash as createHash57, randomInt } from "node:crypto";
217251
+ import { access as access4, mkdir as mkdir11, readFile as readFile8, writeFile as writeFile9 } from "node:fs/promises";
217252
+ import { dirname as dirname8, join as join19, relative as relative7, resolve as resolve15 } from "node:path";
217253
+ function interrupted(dir2) {
217254
+ return new AnchaError("USAGE", "run interrupted", dir2 === void 0 ? {} : { hint: `partial results in ${dir2}` });
217270
217255
  }
217271
- function agentEnvironmentClause(environment3) {
217272
- if (environment3?.target === "container") return "agent sealed in a container";
217273
- if (environment3?.target !== "host") return void 0;
217274
- if (environment3.inheritAll) return "agent not sealed (network open, this shell's whole environment)";
217275
- return `agent not sealed (network open, ${environment3.inherited} variables from this shell)`;
217256
+ function newRunId(now11) {
217257
+ const stamp6 = now11.toISOString().slice(0, 19).replace(/[-:]/g, "").replace("T", "-");
217258
+ let suffix = "";
217259
+ for (let i = 0; i < 4; i++) suffix += ID_ALPHABET2[randomInt(ID_ALPHABET2.length)];
217260
+ return `run_${stamp6}_${suffix}`;
217276
217261
  }
217277
- function withheldNamedBy(issue6, environment3) {
217278
- const text29 = issue6.logTail.join("\n");
217279
- return (environment3?.withheldInLogs ?? []).filter((name5) => /^[A-Z][A-Z0-9_]{3,}$/.test(name5) && new RegExp(`(?<![A-Za-z0-9_])${name5}(?![A-Za-z0-9_])`).test(text29));
217262
+ async function recordsFor(scenePath, root3 = process.cwd()) {
217263
+ if (scenePath === void 0) return void 0;
217264
+ const top = resolve15(root3);
217265
+ for (let dir2 = dirname8(resolve15(top, scenePath)); ; dir2 = dirname8(dir2)) {
217266
+ const file3 = join19(dir2, "records.jsonl");
217267
+ if (await access4(file3).then(() => true, () => false)) return file3;
217268
+ if (dir2 === top || relative7(top, dir2).startsWith("..") || dirname8(dir2) === dir2) return void 0;
217269
+ }
217280
217270
  }
217281
- function withheldHint(issue6, environment3) {
217282
- const names5 = withheldNamedBy(issue6, environment3);
217283
- if (names5.length === 0) return void 0;
217284
- const one7 = names5.length === 1;
217285
- const list18 = one7 ? names5[0] : `${names5.slice(0, -1).join(", ")} and ${names5.at(-1)}`;
217286
- return `${list18} ${one7 ? "is" : "are"} set in this shell but ${one7 ? "was" : "were"} withheld from the agent: pass ${one7 ? "it" : "them"} with ${names5.map((name5) => `--pass-env ${name5}`).join(" ")} or list ${one7 ? "it" : "them"} under agent.pass_env in ancha.yaml`;
217271
+ async function recordsDigest(scenePath, root3) {
217272
+ const file3 = await recordsFor(scenePath, root3);
217273
+ return file3 === void 0 ? void 0 : createHash57("sha256").update(await readFile8(file3)).digest("hex");
217287
217274
  }
217288
- function crashLines(logTail3) {
217289
- const lines2 = logTail3.filter((line2) => !CRASH_NOISE.test(line2));
217290
- const last = lines2.findLastIndex((line2) => ERROR_LINE.test(line2));
217291
- let start = last;
217292
- while (start > 0 && start > last - 2 && ERROR_LINE.test(lines2[start - 1])) start--;
217293
- return (start >= 0 ? lines2.slice(start, start + 3) : lines2.slice(-3)).map((line2) => line2.length > CRASH_LINE_MAX ? `${line2.slice(0, CRASH_LINE_MAX)}\u2026` : line2);
217275
+ async function createEnvFor(backend, scene2, seed43, path7, people4) {
217276
+ try {
217277
+ return await backend.createEnv(scene2, seed43, { paused: true, ...people4 !== void 0 && { people: people4 } });
217278
+ } catch (e) {
217279
+ if (!(e instanceof AnchaError)) throw e;
217280
+ const where3 = path7 === void 0 ? `test ${scene2.id}` : `test ${scene2.id} (${path7})`;
217281
+ throw new AnchaError(e.code, `${where3}: ${e.message}`, {
217282
+ ...e.hint !== void 0 && { hint: e.hint },
217283
+ ...e.docs !== void 0 && { docs: e.docs },
217284
+ cause: e
217285
+ });
217286
+ }
217294
217287
  }
217295
- function agentNeverRan(s3) {
217296
- if (s3.pytest) return void 0;
217297
- const ended = [];
217298
- for (const scene2 of s3.scenes) {
217299
- if ((scene2.agentCalls ?? 0) > 0) return void 0;
217300
- for (const t of scene2.trialsDetail ?? []) {
217301
- const issue6 = (scene2.agentIssues ?? []).find((i) => i.trial === t.trial);
217302
- const spawn8 = t.exit === "spawn_failed" || t.exit === "invalid" && (t.originalExit === "spawn_failed" || (scene2.harnessIssues ?? []).some((i) => i.trial === t.trial && i.message.startsWith("AGENT_SPAWN_FAILED")));
217303
- if (spawn8) {
217304
- ended.push({ exit: "spawn_failed", exitCode: t.exitCode, realMs: t.realMs, perEvent: false, issue: issue6 });
217305
- continue;
217306
- }
217307
- if (t.exit !== "exited" || t.exitCode === 0 || t.passed) return void 0;
217308
- const invocations = issue6?.invocations;
217309
- if (invocations !== void 0 ? invocations.total === 0 || invocations.failed < invocations.total : t.realMs > NEVER_RAN_MS) return void 0;
217310
- ended.push({ exit: "exited", exitCode: t.exitCode, realMs: t.realMs, perEvent: invocations !== void 0, issue: issue6 });
217288
+ async function executeRun(opts) {
217289
+ const { backend, agent, trials, trialOffset = 0, parallel, seed: seed43, outDir, onEvent, signal, scenePaths, realTimeouts, inheritedEnv = process.env } = opts;
217290
+ if (opts.scenes !== void 0 && opts.cases !== void 0) throw new AnchaError("USAGE", "provide scenes or cases, not both");
217291
+ const explicitCases = opts.cases !== void 0;
217292
+ const cases = structuredClone(opts.cases ?? (opts.scenes ?? []).map((scene2) => ({ id: scene2.id, scene: scene2 })));
217293
+ if (cases.length === 0) throw new AnchaError("USAGE", "a run requires at least one scene or case");
217294
+ for (const item2 of cases) {
217295
+ if (!/^[a-z0-9][a-z0-9_-]{0,191}$/.test(item2.id)) throw new AnchaError("SCENE_INVALID", `invalid case id ${JSON.stringify(item2.id)}`);
217296
+ if (item2.seed !== void 0 && typeof item2.seed !== "string") throw new AnchaError("SCENE_INVALID", `invalid seed for case ${item2.id}`);
217297
+ try {
217298
+ const json35 = JSON.stringify(item2.identity ?? {});
217299
+ if (json35 === void 0 || json35.length > 1e6 || Object.prototype.toString.call(item2.identity ?? {}) !== "[object Object]") throw new Error("invalid identity");
217300
+ item2.identity = JSON.parse(json35);
217301
+ } catch {
217302
+ throw new AnchaError("SCENE_INVALID", `case ${item2.id} identity must be a JSON object smaller than 1 MB`);
217311
217303
  }
217312
217304
  }
217313
- if (ended.length === 0) return void 0;
217314
- const exits = new Set(ended.map((e) => e.exit)), codes = new Set(ended.map((e) => e.exitCode));
217315
- const first2 = ended.find((e) => e.issue !== void 0)?.issue;
217316
- const cloud = s3.target === "cloud";
217317
- const withheld = first2 === void 0 || cloud ? void 0 : withheldHint(first2, s3.agentEnvironment);
217318
- const fix = first2 === void 0 ? void 0 : likelyFix(first2.logTail, { target: s3.target, command: s3.agentCommand ?? s3.agent, ...withheld !== void 0 && { withheld } });
217319
- const checksFailed = s3.scenes.reduce((n2, scene2) => n2 + Object.values(scene2.checks).filter((c) => c.required && c.total - c.passed - (c.skipped ?? 0) - (c.invalid ?? 0) > 0).length, 0);
217320
- const exit = exits.size > 1 ? "mixed" : [...exits][0];
217321
- return {
217322
- attempts: ended.length,
217323
- tests: s3.scenes.filter((scene2) => (scene2.trialsDetail ?? []).length > 0).length,
217324
- exit,
217325
- exitCode: codes.size === 1 ? ended[0].exitCode : null,
217326
- ...exit === "exited" && codes.size === 1 && ended[0].exitCode === null && { signal: true },
217327
- ...exit === "exited" && ended.every((e) => e.perEvent) && { perEvent: true },
217328
- ms: Math.max(...ended.map((e) => e.realMs)),
217329
- logTail: (first2?.logTail ?? []).filter((line2) => !CRASH_NOISE.test(line2)).slice(-10).map((line2) => line2.length > CRASH_LINE_MAX ? `${line2.slice(0, CRASH_LINE_MAX)}\u2026` : line2),
217330
- ...first2 !== void 0 && !cloud && { log: first2.log },
217331
- ...fix !== void 0 && { fix },
217332
- checksFailed
217305
+ const scenes = cases.map((item2) => item2.scene);
217306
+ if (opts.runId !== void 0) validateRunId(opts.runId);
217307
+ for (const [name5, value5] of [["trials", trials], ["parallel", parallel]]) {
217308
+ if (!Number.isSafeInteger(value5) || value5 < 1) throw new AnchaError("USAGE", `${name5} must be a positive integer, got ${value5}`);
217309
+ }
217310
+ if (!Number.isSafeInteger(trialOffset) || trialOffset < 0 || !Number.isSafeInteger(trialOffset + trials)) throw new AnchaError("USAGE", `trialOffset must be a non-negative integer, got ${trialOffset}`);
217311
+ if (!Number.isSafeInteger(cases.length * trials)) throw new AnchaError("USAGE", "total attempt count must be a safe integer");
217312
+ if (agent.mode === "endpoint") {
217313
+ validateEndpointAgent(agent, parallel);
217314
+ for (const scene2 of scenes) validateAgentEnv(scene2, agent);
217315
+ } else {
217316
+ const calling = scenes.find((scene2) => scene2.world_rules?.app_calls?.length);
217317
+ if (calling) throw new AnchaError("CONFIG_INVALID", `test ${calling.id} has app_calls, which need an app Ancha can call: set agent.url (and agent.start for an app Ancha starts)`);
217318
+ }
217319
+ const ids2 = cases.map((item2) => item2.id);
217320
+ const duplicate2 = ids2.find((id14, i) => ids2.indexOf(id14) !== i);
217321
+ if (duplicate2 !== void 0) {
217322
+ throw new AnchaError("SCENE_INVALID", `${explicitCases ? "case" : "scene"} id "${duplicate2}" appears more than once in this run`, { hint: "case ids must be unique; use explicit cases for distinct data variations" });
217323
+ }
217324
+ for (const scene2 of scenes) validateAgentEnv(scene2, agent);
217325
+ if (signal?.aborted) throw interrupted();
217326
+ if (agent.mode === "endpoint") await preflightExecution(agent, scenes, signal);
217327
+ else for (const input4 of [void 0, "per_event"]) {
217328
+ const group5 = scenes.filter((scene2) => scene2.agent_input === input4);
217329
+ if (group5.length) await preflightExecution({ ...agent, taskInput: sceneTaskInput(group5[0], agent.taskInput) }, group5, signal);
217330
+ }
217331
+ const cancellation = new AbortController();
217332
+ const runningSignal = signal === void 0 ? cancellation.signal : AbortSignal.any([signal, cancellation.signal]);
217333
+ const halt = {};
217334
+ const fail8 = (error65) => {
217335
+ halt.crash ??= { error: error65 };
217336
+ cancellation.abort(error65);
217333
217337
  };
217334
- }
217335
- function neverRanHeadline(n2) {
217336
- const time7 = `${n2.attempts === 1 ? "after" : "within"} ${spaced(n2.ms)}`;
217337
- const how = n2.exit === "spawn_failed" ? n2.exitCode === 127 ? "its command was not found" : "its command could not be started" : n2.exit === "mixed" ? "it stopped before doing anything" : n2.perEvent ? n2.signal ? "it was killed by a signal each time it was started" : n2.exitCode === null ? "it exited with an error each time it was started" : `it exited with code ${n2.exitCode} each time it was started` : n2.signal ? `it was killed by a signal ${time7}` : n2.exitCode === null ? `it exited with an error ${time7}` : `it exited with code ${n2.exitCode} ${time7}`;
217338
- const where3 = n2.attempts === 1 ? "" : n2.tests > 1 ? ` in all ${n2.attempts} attempts of ${n2.tests} tests` : n2.attempts === 2 ? " in both attempts" : ` in all ${n2.attempts} attempts`;
217339
- return `Your agent didn't run: ${how}${where3}`;
217340
- }
217341
- function neverRanLines(n2, cwd) {
217342
- const path7 = n2.log === void 0 || cwd === void 0 || relative8(cwd, n2.log).startsWith("..") ? n2.log : relative8(cwd, n2.log);
217343
- const log3 = path7 === void 0 ? "log (from the cloud machine)" : `log (${path7})`;
217344
- return [neverRanHeadline(n2), n2.logTail.length === 0 ? ` ${log3}: empty` : ` ${log3}:`, ...n2.logTail.map((line2) => ` ${line2}`), ...n2.fix === void 0 ? [] : [` likely fix: ${n2.fix}`]];
217345
- }
217346
- function neverRanChecksLine(n2, runId2, out) {
217347
- if (n2.checksFailed === 0) return void 0;
217348
- return `${n2.checksFailed} ${n2.checksFailed === 1 ? "check" : "checks"} failed because the agent never ran; ancha explain ${runId2}${out === void 0 ? "" : ` --out ${shellWord(out)}`} --all shows them`;
217349
- }
217350
- function retryCommands(s3, opts = {}) {
217351
- const tests = opts.tests !== void 0 && opts.tests.length > 0 && opts.tests.length <= 3 ? ` ${opts.tests.map(shellWord).join(" ")}` : "";
217352
- if (s3.target === "cloud") return ["ancha agent upload", `ancha run --on cloud${tests}`];
217353
- const on = s3.target === "docker" ? " --on docker" : s3.target === "local" ? " --on local" : "";
217354
- return [`ancha run${on}${tests}${opts.out === void 0 ? "" : ` --out ${shellWord(opts.out)}`}`];
217355
- }
217356
- function neverRanNextLine(n2, retry) {
217357
- return `next: ${n2.fix === void 0 ? "fix what its log says" : "make the fix above"}, then ${retry.join(", then ")}`;
217358
- }
217359
- async function writeSummary(run6, summary) {
217360
- await writeFile9(join22(run6.dir, "summary.json"), `${JSON.stringify(summary, null, 2)}
217361
- `);
217362
- await writeFile9(join22(dirname9(run6.dir), "latest"), `${run6.runId}
217363
- `);
217364
- }
217365
- function formatRateDelta(value5) {
217366
- const magnitude = Math.abs(value5 * 100);
217367
- const rounded2 = Math.round(magnitude * 10) / 10;
217368
- return `${value5 > 0 ? "+" : value5 < 0 ? "-" : ""}${rounded2 === 0 && magnitude > 0 ? magnitude.toPrecision(3) : rounded2} pp`;
217369
- }
217370
- function howItEnded(i) {
217371
- switch (i.exit) {
217372
- case "timeout":
217373
- return `timed out after ${duration8(i.realMs)} and was killed`;
217374
- case "spawn_failed":
217375
- return i.exitCode === null ? "could not be started" : `failed to start (exit code ${i.exitCode})`;
217376
- default: {
217377
- const when13 = i.invocations?.failed ? `on ${i.invocations.failed} of ${i.invocations.total} events` : `after ${duration8(i.realMs)}`;
217378
- return i.exitCode === null ? `was killed by a signal ${when13}` : `exited with code ${i.exitCode} ${when13}`;
217338
+ const pathOf5 = (item2) => scenePaths === void 0 ? void 0 : Object.hasOwn(scenePaths, item2.id) ? scenePaths[item2.id] : Object.hasOwn(scenePaths, item2.scene.id) ? scenePaths[item2.scene.id] : void 0;
217339
+ const seedOf = (item2) => item2.seed ?? seed43 ?? `${item2.scene.id}:1`;
217340
+ const owned2 = /* @__PURE__ */ new Map();
217341
+ const acquire = async (item2, onFailure = fail8, onCreated) => {
217342
+ const env2 = await createEnvFor(backend, item2.scene, seedOf(item2), pathOf5(item2), item2.people);
217343
+ let timer;
217344
+ let stopped2 = false;
217345
+ let pending;
217346
+ owned2.set(env2.id, { env: env2, async stop() {
217347
+ stopped2 = true;
217348
+ clearTimeout(timer);
217349
+ await pending;
217350
+ } });
217351
+ onCreated?.(env2);
217352
+ const lease = (await backend.listEnvs()).find((item3) => item3.id === env2.id);
217353
+ if (!lease) throw new AnchaError("ENV_NOT_FOUND", `environment ${env2.id} disappeared during acquisition`);
217354
+ const created3 = Date.parse(lease.createdAt);
217355
+ const ttlMs = Date.parse(lease.expiresAt) - created3;
217356
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0) throw new AnchaError("SERVER_UNREACHABLE", `invalid lease metadata for environment ${env2.id}`);
217357
+ const interval = Math.min(3e4, ttlMs / 3);
217358
+ const renew = () => {
217359
+ if (stopped2) return;
217360
+ const requestedAt = performance.now();
217361
+ pending = Promise.resolve().then(() => backend.renewEnv(env2.id)).then(() => {
217362
+ if (!stopped2) {
217363
+ timer = setTimeout(renew, Math.max(0, requestedAt + interval - performance.now()));
217364
+ timer.unref();
217365
+ }
217366
+ }, (error65) => {
217367
+ if (!stopped2) onFailure(error65 instanceof AnchaError ? error65 : new AnchaError("SERVER_UNREACHABLE", `cannot renew environment ${env2.id}`, { cause: error65 }));
217368
+ });
217369
+ };
217370
+ timer = setTimeout(renew, Math.max(0, interval - (Date.now() - created3)));
217371
+ timer.unref();
217372
+ return env2;
217373
+ };
217374
+ const destroyAll = async (envs) => {
217375
+ await Promise.all([...envs].map(async (env2) => {
217376
+ const lease = owned2.get(env2.id);
217377
+ if (!lease) return;
217378
+ await lease.stop();
217379
+ try {
217380
+ await backend.destroyEnv(env2.id);
217381
+ } catch (error65) {
217382
+ fail8(error65);
217383
+ } finally {
217384
+ owned2.delete(env2.id);
217385
+ }
217386
+ }));
217387
+ };
217388
+ try {
217389
+ for (const item2 of cases) {
217390
+ runningSignal.throwIfAborted();
217391
+ const env2 = await acquire(item2);
217392
+ await destroyAll([env2]);
217393
+ runningSignal.throwIfAborted();
217379
217394
  }
217395
+ } catch (error65) {
217396
+ await destroyAll([...owned2.values()].map((item2) => item2.env));
217397
+ if (signal?.aborted) throw interrupted();
217398
+ throw halt.crash?.error ?? error65;
217380
217399
  }
217381
- }
217382
- function nonDefaultOut(cwd, out) {
217383
- return out === void 0 || resolve15(cwd, out) === resolve15(cwd, DEFAULT_RUNS_DIR) ? void 0 : out;
217384
- }
217385
- function renderSummaryText(s3, opts = {}) {
217386
- const lines2 = s3.replayOf === void 0 ? [] : [`replay of ${s3.replayOf}`];
217387
- if (s3.pytest) lines2.push(`pytest ${s3.pytest.nodeId}: ${s3.pytest.outcome}${s3.pytest.invalid ? " [invalid]" : !s3.pytest.graded ? " (ungraded)" : ""}`);
217388
- const never2 = agentNeverRan(s3);
217389
- if (never2 !== void 0) lines2.push(...neverRanLines(never2, opts.cwd));
217390
- for (const scene2 of s3.scenes) {
217391
- const invalid35 = scene2.invalidTrials ?? 0;
217392
- const ok = !sceneFailed(scene2, s3.minPassRate);
217393
- const excluded3 = scene2.trialsDetail.filter((trial) => trial.outcome === "skipped" || trial.outcome === "xfailed").length;
217394
- if (s3.pytest && !s3.pytest.graded) lines2.push(`\u2014 ${scene2.sceneId} ungraded${excluded3 ? ` (${excluded3} excluded)` : ""}${invalid35 ? " [invalid]" : ""}`);
217395
- else if (ok && scene2.graded === false) lines2.push(`\u2014 ${scene2.sceneId} ungraded: ${scene2.trials} ${scene2.trials === 1 ? "trial" : "trials"}, no check evaluated`);
217396
- else lines2.push(`${ok ? "\u2713" : "\u2717"} ${scene2.sceneId} ${scene2.passed}/${scene2.counts?.requested ?? scene2.trials} (${pct(scene2.passRate)}%)${invalid35 > 0 ? " [invalid]" : ""}${excluded3 ? ` (${excluded3} excluded)` : ""}`);
217397
- if (never2 !== void 0) continue;
217398
- if (invalid35 > 0) lines2.push(` \u2717 harness failure: ${invalid35}/${scene2.trials} trials invalid`);
217399
- if ((scene2.skippedJudges ?? 0) > 0) lines2.push(` judge grading skipped: ${scene2.skippedJudges} check(s)`);
217400
- for (const warning of scene2.warnings ?? []) lines2.push(` warning: trial ${warning.trial} ${warning.check}: ${warning.message.replaceAll("\n", "\n ")}`);
217401
- for (const issue6 of scene2.harnessIssues ?? []) {
217402
- lines2.push(` trial ${issue6.trial}: ${issue6.owner} ${issue6.kind} (${issue6.service}): ${issue6.message.replaceAll("\n", "\n ")}`);
217403
- }
217404
- const unclean = scene2.trialsDetail.filter((t) => !t.passed && t.exit !== "invalid" && !exitedCleanly(t)).length;
217405
- const firstIssue = (scene2.agentIssues ?? [])[0];
217406
- if (unclean > 0 && firstIssue !== void 0) {
217407
- lines2.push(` \u2717 agent did not exit cleanly in ${unclean}/${scene2.trials} trials`);
217408
- const why = crashLines(firstIssue.logTail);
217409
- lines2.push(` trial ${firstIssue.trial}: ${howItEnded(firstIssue)}; its output is in ${firstIssue.log}${firstIssue.logTail.length === 0 ? " (empty)" : why.length > 0 ? ", ending:" : ""}`);
217410
- lines2.push(...why.map((line2) => ` ${line2}`));
217411
- const hint = withheldHint(firstIssue, s3.agentEnvironment);
217412
- if (hint !== void 0) lines2.push(` ${hint}`);
217413
- }
217414
- for (const [id14, tally] of Object.entries(scene2.checks)) {
217415
- const failed = tally.total - tally.passed - (tally.skipped ?? 0);
217416
- if (!tally.required || failed === 0) continue;
217417
- lines2.push(` \u2717 ${id14} failed in ${failed}/${tally.total} trials`);
217418
- const first2 = scene2.failures.find((f2) => f2.check === id14);
217419
- if (first2 !== void 0) lines2.push(` trial ${first2.trial}: ${first2.explanation.replaceAll("\n", "\n ")}`);
217420
- }
217421
- for (const g of scene2.coverageGaps.slice(0, SUMMARY_GAPS_SHOWN)) {
217422
- lines2.push(` coverage gap: ${g.method} ${g.path} (${g.service}) x${g.count}`);
217423
- }
217424
- if (scene2.coverageGaps.length > SUMMARY_GAPS_SHOWN) {
217425
- lines2.push(` \u2026 ${scene2.coverageGaps.length - SUMMARY_GAPS_SHOWN} more coverage gap(s)`);
217426
- }
217427
- if (scene2.answers !== void 0) {
217428
- const { of, simulatedIn, bySource } = scene2.answers;
217429
- const named5 = ANSWER_SOURCES2.filter(([source]) => bySource[source]).map(([source, label5]) => `${bySource[source]} ${label5}`);
217430
- if (named5.length) lines2.push(` tool answers: ${named5.join(", ")}; ${simulatedIn}/${of} verdicts rest on simulated answers`);
217431
- }
217432
- if (scene2.actions !== void 0) {
217433
- const { of, made } = scene2.actions, trials = `${of} valid ${of === 1 ? "trial" : "trials"}`;
217434
- lines2.push(made.length ? ` writes, in how many of ${trials}:` : ` writes: none in ${trials}`);
217435
- for (const action of made.slice(0, SUMMARY_ACTIONS_SHOWN)) lines2.push(` ${action.trials}/${of} ${actionLabel(action)}`);
217436
- if (made.length > SUMMARY_ACTIONS_SHOWN) lines2.push(` \u2026 ${made.length - SUMMARY_ACTIONS_SHOWN} more`);
217400
+ const reservedPorts = /* @__PURE__ */ new Set();
217401
+ const results = /* @__PURE__ */ new Map();
217402
+ const frozen = cases.map((item2) => {
217403
+ const value5 = { id: item2.id, scenarioId: item2.scene.id, seed: seedOf(item2), compiledFingerprint: sceneFingerprint(item2.scene), identity: item2.identity ?? {} };
217404
+ const record28 = { ...value5, fingerprint: sceneFingerprint(value5) };
217405
+ results.set(item2.id, { scene: item2.scene, trials: [], requestedTrials: trials, ...explicitCases && { case: record28 } });
217406
+ return record28;
217407
+ });
217408
+ let finished = 0;
217409
+ let observedAgentExit = false;
217410
+ const stopped = () => halt.spawnFailure !== void 0 || halt.crash !== void 0 || signal?.aborted === true;
217411
+ const startedAt = /* @__PURE__ */ new Date();
217412
+ const runId2 = opts.runId ?? newRunId(startedAt);
217413
+ const dir2 = join19(outDir, runId2);
217414
+ let next2 = 0;
217415
+ const total2 = cases.length * trials;
217416
+ try {
217417
+ await mkdir11(outDir, { recursive: true });
217418
+ await mkdir11(dir2);
217419
+ await writeFile9(join19(dir2, "inputs.json"), `${JSON.stringify({
217420
+ schemaVersion: 1,
217421
+ cases: sharedSeeds(frozen.map((value5, index) => ({ ...value5, scene: cases[index].scene }))),
217422
+ // A world's seed once (run-inputs.ts). Names only, never values: what a later `ancha runs upload` redacts (hosting spec §3.1).
217423
+ agentEnvironment: { passEnv: agent.passEnv ?? [], inheritEnv: agent.inheritEnv === true },
217424
+ isolation: { execution: executionDescription(agent), toolWorld: "fresh-per-attempt", agentProcess: agent.mode === "endpoint" && agent.start === void 0 ? "external-setup-adapter" : "fresh-per-attempt", agentState: agent.execution?.mode === "container" ? "fresh-container-scratch" : "provided-namespace-only", limits: agent.execution?.mode === "container" ? "Local Linux container, read-only source, bounded scratch, scoped tool gateway and explicit model hosts; not a multi-tenant cloud security certification." : "Agent files and external memory are shared unless the agent uses ANCHA_STATE_DIR or ANCHA_ATTEMPT_ID. This is not host or network isolation." }
217425
+ })}
217426
+ `, { flag: "wx", mode: 384 });
217427
+ const kept = /* @__PURE__ */ new Map();
217428
+ for (const [index, item2] of cases.entries()) {
217429
+ const source = await recordsFor(pathOf5(item2), opts.root);
217430
+ if (source === void 0) continue;
217431
+ const text29 = await readFile8(source), copy = join19(dir2, "records", `${index}.jsonl`);
217432
+ await mkdir11(dirname8(copy), { recursive: true });
217433
+ await writeFile9(copy, text29, { flag: "wx", mode: 384 });
217434
+ kept.set(item2.id, copy);
217435
+ results.get(item2.id).records = createHash57("sha256").update(text29).digest("hex");
217437
217436
  }
217437
+ onEvent?.({ event: "run_started", runId: runId2, scenes: ids2, trials, parallel });
217438
+ await Promise.all(Array.from({ length: Math.min(parallel, total2) }, async () => {
217439
+ while (!stopped() && next2 < total2) {
217440
+ const index = next2++;
217441
+ const item2 = cases[index % cases.length];
217442
+ const trial = Math.floor(index / cases.length) + 1 + trialOffset;
217443
+ const trialDir = join19(dir2, `trial-${item2.id}-${trial}`);
217444
+ const records4 = kept.get(item2.id);
217445
+ const attempt = { id: `${runId2}/${item2.id}/${trial}`, caseId: item2.id, stateDir: resolve15(trialDir, "agent-state"), seed: seedOf(item2), ...records4 !== void 0 && { records: records4 }, ...opts.recordsDiagnostic && { recordsDiagnostic: { ...opts.recordsDiagnostic, attempt: trial } } };
217446
+ const startedAt2 = performance.now();
217447
+ const attemptCancellation = new AbortController();
217448
+ const attemptSignal = AbortSignal.any([runningSignal, attemptCancellation.signal]);
217449
+ let env2;
217450
+ let sessionId;
217451
+ let capture4;
217452
+ const trialBackend = new Proxy(backend, { get(target5, key4) {
217453
+ if (key4 === "prepareTrial") return async (...args) => {
217454
+ const session2 = await backend.prepareTrial(...args);
217455
+ sessionId = session2.id;
217456
+ return session2;
217457
+ };
217458
+ if (key4 === "finishTrial") return async (...args) => {
217459
+ capture4 = await backend.finishTrial(...args);
217460
+ return capture4;
217461
+ };
217462
+ const member4 = target5[key4];
217463
+ return typeof member4 === "function" ? member4.bind(target5) : member4;
217464
+ } });
217465
+ try {
217466
+ let result;
217467
+ try {
217468
+ env2 = await acquire(item2, (error65) => {
217469
+ if (error65 instanceof AnchaError && error65.code === "SERVER_UNREACHABLE") attemptCancellation.abort(error65);
217470
+ else fail8(error65);
217471
+ }, (created3) => {
217472
+ env2 = created3;
217473
+ });
217474
+ attemptSignal.throwIfAborted();
217475
+ const realTimeoutMs = realTimeouts === void 0 ? void 0 : Object.hasOwn(realTimeouts, item2.id) ? realTimeouts[item2.id] : Object.hasOwn(realTimeouts, item2.scene.id) ? realTimeouts[item2.scene.id] : void 0;
217476
+ result = await runTrial({
217477
+ backend: trialBackend,
217478
+ env: env2,
217479
+ scene: item2.scene,
217480
+ agent,
217481
+ trial,
217482
+ dir: trialDir,
217483
+ attempt,
217484
+ signal: attemptSignal,
217485
+ inheritedEnv,
217486
+ reservedPorts,
217487
+ ...opts.judge !== void 0 && { judge: opts.judge },
217488
+ ...realTimeoutMs !== void 0 && { realTimeoutMs },
217489
+ onCaptured: (value5) => {
217490
+ capture4 = value5;
217491
+ },
217492
+ onPrepared: () => onEvent?.({ event: "trial_started", scene: item2.id, ...explicitCases && { caseId: item2.id }, trial, envId: env2.id }),
217493
+ onAgentStarted: () => onEvent?.({ event: "agent_started", sceneId: item2.id, trial })
217494
+ });
217495
+ await owned2.get(env2.id)?.stop();
217496
+ attemptSignal.throwIfAborted();
217497
+ } catch (error65) {
217498
+ const failure6 = attemptCancellation.signal.aborted && error65 instanceof Error && error65.name === "AbortError" ? attemptCancellation.signal.reason : error65;
217499
+ if (runningSignal.aborted || !(failure6 instanceof AnchaError) || failure6.code !== "SERVER_UNREACHABLE") throw error65;
217500
+ result = await invalidTrial({
217501
+ scene: item2.scene,
217502
+ trial,
217503
+ dir: trialDir,
217504
+ startedAt: startedAt2,
217505
+ error: failure6,
217506
+ ...env2 !== void 0 && { envId: env2.id },
217507
+ ...sessionId !== void 0 && { sessionId },
217508
+ ...capture4 !== void 0 && { capture: capture4 }
217509
+ });
217510
+ }
217511
+ result.caseId = item2.id;
217512
+ result.attemptId = attempt.id;
217513
+ if (writeTools(item2.scene).size) result.actions = actionsOf(item2.scene, result.trace);
217514
+ if (Object.keys(item2.scene.tools ?? {}).length) result.answers = answersOf(result.trace);
217515
+ if (result.exit !== "invalid") {
217516
+ if (!observedAgentExit && result.exit === "spawn_failed") halt.spawnFailure = result;
217517
+ observedAgentExit = true;
217518
+ }
217519
+ finished++;
217520
+ results.get(item2.id).trials.push(result);
217521
+ await writeFile9(join19(trialDir, "result.json"), `${JSON.stringify({ ...result, trace: void 0 }, null, 2)}
217522
+ `, { flag: "wx", mode: 384 });
217523
+ onEvent?.({
217524
+ event: "trial_finished",
217525
+ scene: item2.id,
217526
+ ...explicitCases && { caseId: item2.id },
217527
+ trial,
217528
+ passed: result.passed,
217529
+ valid: result.valid,
217530
+ graded: result.valid !== false && result.checks.some((check4) => check4.status !== "skipped" && check4.error === void 0),
217531
+ warnings: result.checks.flatMap((check4) => check4.warning === void 0 ? [] : [`${check4.id}: ${check4.warning}`]),
217532
+ exit: result.exit,
217533
+ exitCode: result.exitCode,
217534
+ realMs: result.realMs,
217535
+ failedChecks: result.checks.filter((c) => c.required && !c.passed).map((c) => c.id)
217536
+ });
217537
+ } catch (error65) {
217538
+ if (!signal?.aborted) fail8(error65);
217539
+ } finally {
217540
+ if (env2) await destroyAll([env2]);
217541
+ }
217542
+ }
217543
+ }));
217544
+ } finally {
217545
+ await destroyAll([...owned2.values()].map((item2) => item2.env));
217438
217546
  }
217439
- const folded = never2 === void 0 ? void 0 : neverRanChecksLine(never2, s3.runId, opts.out);
217440
- if (folded !== void 0) lines2.push(folded);
217441
- if (never2 === void 0 && !s3.pytest) lines2.push(...ungradedLines(s3));
217442
- lines2.push("");
217443
- lines2.push(...strictSummaryLines(s3));
217444
- if (s3.comparison !== void 0) lines2.push(...comparisonLines(s3.comparison));
217445
- if ((opts.reproduction ?? []).length > 0) lines2.push(renderReproduction(opts.reproduction, { neverRan: never2 !== void 0 }), "");
217446
- const noneGraded = s3.scenes.length > 0 && s3.scenes.every((scene2) => scene2.trials > 0 && (scene2.invalidTrials ?? 0) >= scene2.trials);
217447
- lines2.push(`${s3.pytest && !s3.pytest.graded && !s3.pytest.invalid ? s3.pytest.outcome + " (ungraded)" : noneGraded ? "invalid (no trials graded)" : s3.verdict} (minimum pass rate ${pct(s3.minPassRate)}%) run ${s3.runId}`);
217448
- const next2 = nextAfterRun(s3, opts);
217449
- if (never2 !== void 0) lines2.push(neverRanNextLine(never2, next2));
217450
- else if (next2.length > 0) lines2.push(`next: ${next2.join(", then ")}`);
217451
- return lines2.join("\n").replaceAll(PATTERN_NOTE, "") + (lines2.some((line2) => line2.includes(PATTERN_NOTE)) ? `
217452
- ${PATTERN_NOTE.trim()}` : "");
217453
- }
217454
- function comparisonLines(comparison2) {
217455
- const lines2 = [`compared with ${comparison2.baselineRunId}: ${comparison2.regressed ? "regressed" : "no regression"}`];
217456
- const counts = (c) => `${c.before.passed}/${c.before.total} \u2192 ${c.after.passed}/${c.after.total}`;
217457
- for (const check4 of comparison2.droppedChecks ?? []) lines2.push(` \u2717 dropped: ${check4.sceneId} ${check4.check} ${counts(check4)}`);
217458
- for (const scene2 of comparison2.scenes) {
217459
- lines2.push(` ${scene2.sceneId}: ${pct(scene2.before)}% \u2192 ${pct(scene2.after)}% (${formatRateDelta(scene2.delta)})${scene2.beforeTrials === void 0 || scene2.afterTrials === void 0 ? "" : `; ${scene2.beforeTrials} \u2192 ${scene2.afterTrials} trials`}`);
217460
- for (const check4 of (scene2.checks ?? []).filter((c) => c.delta > 0 || !c.required)) lines2.push(` ${check4.delta > 0 ? "improved" : "optional, dropped"}: ${check4.check} ${counts(check4)}`);
217461
- for (const action of (scene2.actions ?? []).slice(0, SUMMARY_ACTIONS_SHOWN)) lines2.push(` write: ${actionLabel(action)} ${action.before.trials}/${action.before.of} \u2192 ${action.after.trials}/${action.after.of} trials`);
217462
- if ((scene2.actions ?? []).length > SUMMARY_ACTIONS_SHOWN) lines2.push(` \u2026 ${scene2.actions.length - SUMMARY_ACTIONS_SHOWN} more changed writes`);
217463
- }
217464
- return lines2;
217465
- }
217466
- function nextAfterRun(s3, opts = {}) {
217467
- if (agentNeverRan(s3) !== void 0) return retryCommands(s3, opts);
217468
- const out = opts.out === void 0 ? "" : ` --out ${shellWord(opts.out)}`;
217469
- const failed = s3.verdict === "fail" || s3.scenes.some((scene2) => scene2.failures.length > 0 || (scene2.agentIssues ?? []).length > 0 || (scene2.harnessIssues ?? []).length > 0 || (scene2.invalidTrials ?? 0) > 0);
217470
- if (failed) return [`ancha explain ${s3.runId}${out}`];
217471
- if (s3.verdict === "ungraded") return [];
217472
- return s3.source === "pytest" ? [] : s3.comparison === void 0 ? [`ancha baseline save before${out}`] : [];
217473
- }
217474
- function uploadHintLine(runId2, workspace4, opts = {}) {
217475
- return `ancha runs upload ${runId2}${opts.out === void 0 ? "" : ` --out ${shellWord(opts.out)}`} sends this run to ${workspace4}`;
217476
- }
217477
- function normalizeSummary(s3) {
217478
- return { ...s3, scenes: s3.scenes.map((scene2) => ({
217479
- ...scene2,
217480
- agentIssues: scene2.agentIssues ?? [],
217481
- harnessIssues: scene2.harnessIssues ?? [],
217482
- invalidTrials: scene2.invalidTrials ?? 0,
217483
- skippedJudges: scene2.skippedJudges ?? 0,
217484
- warnings: scene2.warnings ?? []
217485
- })) };
217547
+ for (const value5 of results.values()) value5.trials.sort((a, b) => a.trial - b.trial);
217548
+ if (halt.crash !== void 0) throw halt.crash.error;
217549
+ if (halt.spawnFailure !== void 0) {
217550
+ throw new AnchaError("AGENT_SPAWN_FAILED", `agent command failed to start: ${agent.mode === "endpoint" ? agent.start : agent.command}`, {
217551
+ hint: `check agent.command in ancha.yaml or --agent; see ${join19(halt.spawnFailure.dir, "agent.log")}`
217552
+ });
217553
+ }
217554
+ if (signal?.aborted && finished < scenes.length * trials) throw interrupted(dir2);
217555
+ const crash = { twins: [...new Set(scenes.flatMap((scene2) => scene2.twins))], logTails: [...results.values()].flatMap((value5) => value5.trials.map((trial) => trial.logTail)) };
217556
+ return { runId: runId2, dir: dir2, startedAt: startedAt.toISOString(), finishedAt: (/* @__PURE__ */ new Date()).toISOString(), results, agentEnvironment: describeAgentEnvironment(agent, inheritedEnv, crash) };
217486
217557
  }
217487
- function explainAgentIssues(s3, opts = {}) {
217488
- return s3.scenes.filter((scene2) => opts.scene === void 0 || scene2.sceneId === opts.scene).flatMap((scene2) => scene2.agentIssues ?? []).filter((i) => opts.trial === void 0 || i.trial === opts.trial).map((i) => {
217489
- const hint = withheldHint(i, s3.agentEnvironment);
217490
- return hint === void 0 ? i : { ...i, hint };
217558
+ var ID_ALPHABET2;
217559
+ var init_run = __esm({
217560
+ "backend/src/runner/run.ts"() {
217561
+ "use strict";
217562
+ init_src();
217563
+ init_trial();
217564
+ init_agent_input();
217565
+ init_docker();
217566
+ init_agent_env();
217567
+ init_config();
217568
+ init_run_state();
217569
+ init_scenes();
217570
+ init_invalid_trial();
217571
+ init_actions7();
217572
+ init_run_inputs();
217573
+ ID_ALPHABET2 = "abcdefghijklmnopqrstuvwxyz0123456789";
217574
+ }
217575
+ });
217576
+
217577
+ // backend/src/kit/connection-tools.ts
217578
+ import { readFile as readFile10 } from "node:fs/promises";
217579
+ import { join as join21 } from "node:path";
217580
+ async function connectionTools(root3) {
217581
+ const text29 = await readFile10(join21(root3, CONNECTION_TOOLS_PATH), "utf8").catch((error65) => {
217582
+ if (error65.code === "ENOENT") return void 0;
217583
+ throw error65;
217491
217584
  });
217585
+ if (text29 === void 0) return [];
217586
+ const value5 = JSON.parse(text29);
217587
+ if (!Array.isArray(value5) || value5.length > SUPPORTED_TWINS.length || value5.some((name5) => !SUPPORTED_TWINS.includes(name5))) {
217588
+ throw new AnchaError("CONFIG_INVALID", "The connection tools must name Ancha twins.");
217589
+ }
217590
+ return [...new Set(value5)];
217492
217591
  }
217493
- function explainHarnessIssues(s3, opts = {}) {
217494
- return s3.scenes.filter((scene2) => opts.scene === void 0 || scene2.sceneId === opts.scene).flatMap((scene2) => scene2.harnessIssues ?? []).filter((issue6) => opts.trial === void 0 || issue6.trial === opts.trial);
217495
- }
217496
- function explainGradingWarnings(s3, opts = {}) {
217497
- return s3.scenes.filter((scene2) => opts.scene === void 0 || scene2.sceneId === opts.scene).flatMap((scene2) => (scene2.warnings ?? []).map((warning) => ({ sceneId: scene2.sceneId, ...warning }))).filter((warning) => opts.trial === void 0 || warning.trial === opts.trial);
217592
+ function probeToolCalls(twins, trace) {
217593
+ return twins.map((name5) => ({ name: name5, calls: trace.filter((entry3) => entry3.source === "agent" && entry3.service === name5 && !isAgentAnswer(entry3)).length }));
217498
217594
  }
217499
- function explainCoverageGaps(s3, opts = {}) {
217500
- return s3.scenes.filter((scene2) => opts.scene === void 0 || scene2.sceneId === opts.scene).flatMap((scene2) => scene2.coverageGaps.map((gap6) => ({ sceneId: scene2.sceneId, ...gap6, hint: `ancha twins coverage ${gap6.service}` })));
217595
+ var CONNECTION_TOOLS_PATH;
217596
+ var init_connection_tools = __esm({
217597
+ "backend/src/kit/connection-tools.ts"() {
217598
+ "use strict";
217599
+ init_src();
217600
+ CONNECTION_TOOLS_PATH = "ancha/connection-tools.json";
217601
+ }
217602
+ });
217603
+
217604
+ // backend/src/run-bundle.ts
217605
+ import { createHash as createHash59 } from "node:crypto";
217606
+ import { readdir as readdir3, readFile as readFile11 } from "node:fs/promises";
217607
+ import { join as join23 } from "node:path";
217608
+ import { gunzipSync as gunzipSync3, gzipSync } from "node:zlib";
217609
+ function bundleSource(env2) {
217610
+ return env2.CI === "true" || env2.GITHUB_ACTIONS ? "ci" : "cli";
217501
217611
  }
217502
- function renderCoverageGap(g) {
217503
- const answer = g.error !== void 0 ? `it answered ${g.error}` : g.status !== void 0 ? `it answered HTTP ${g.status}` : "it answered with an error";
217504
- return `${g.sceneId} coverage gap: the agent called ${g.method} ${g.path}${g.count > 1 ? ` (${g.count} times)` : ""}, which the ${g.service} twin doesn't implement; ${answer} in the vendor's error shape. The agent's call may be right: see ${g.hint}`;
217612
+ async function bundleSecrets(options4) {
217613
+ const base3 = new Set(BASE_ENV);
217614
+ const names5 = options4.inheritEnv ? Object.keys(options4.env).filter((name5) => !base3.has(name5) && !name5.startsWith("LC_")) : [...options4.passEnv ?? []];
217615
+ const values2 = names5.map((name5) => options4.env[name5]);
217616
+ const file3 = await readFile11(join23(options4.cwd, ".ancha/openrouter.env"), "utf8").catch(() => "");
217617
+ for (const line2 of file3.split(/\r?\n/)) {
217618
+ const match3 = /^\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*\s*=\s*(.*?)\s*$/.exec(line2);
217619
+ if (match3) values2.push(match3[1].replace(/^(['"])(.*)\1$/, "$2"));
217620
+ }
217621
+ return [...new Set(values2.filter((value5) => typeof value5 === "string" && value5.length >= MIN_SECRET))].sort((a, b) => b.length - a.length);
217505
217622
  }
217506
- function renderHarnessIssue(i) {
217507
- return `${i.sceneId} trial ${i.trial} \u2717 ${i.owner} ${i.kind} (${i.service}): ${i.message.replaceAll("\n", "\n ")}${i.seq === void 0 ? "" : ` (trace #${i.seq})`}`;
217623
+ function redact(data5, secrets2) {
217624
+ if (secrets2.length === 0) return data5;
217625
+ let text29 = data5.toString("utf8");
217626
+ const before = text29;
217627
+ for (const secret of secrets2) {
217628
+ text29 = text29.split(secret).join("[redacted]");
217629
+ const escaped = JSON.stringify(secret).slice(1, -1);
217630
+ if (escaped !== secret) text29 = text29.split(escaped).join("[redacted]");
217631
+ }
217632
+ return text29 === before ? data5 : Buffer.from(text29, "utf8");
217508
217633
  }
217509
- function renderAgentIssue(i, cloud = false) {
217510
- const lines2 = [`${i.sceneId} trial ${i.trial} \u2717 agent ${howItEnded(i)}`];
217511
- const log3 = cloud ? "log (from the cloud machine)" : `log: ${i.log}`;
217512
- if (i.logTail.length === 0) lines2.push(cloud ? ` ${log3}: empty` : ` ${log3} (empty)`);
217513
- else lines2.push(` ${log3}, last ${i.logTail.length} line(s):`, ...i.logTail.map((l) => ` ${l}`));
217514
- if (i.hint !== void 0) lines2.push(` ${i.hint}`);
217515
- return lines2.join("\n");
217634
+ function logTail2(data5, cap) {
217635
+ const note2 = (cut5) => Buffer.from(`[ancha: agent.log was ${data5.length} bytes; the first ${cut5} bytes are left out]
217636
+ `, "utf8");
217637
+ let start = data5.length - (cap - note2(data5.length).length);
217638
+ const newline = data5.indexOf(10, start);
217639
+ if (newline !== -1 && newline < data5.length - 1) start = newline + 1;
217640
+ return Buffer.concat([note2(start), data5.subarray(start)]);
217516
217641
  }
217517
- function explainPlayOuts(s3, opts = {}) {
217518
- return s3.scenes.filter((scene2) => opts.scene === void 0 || scene2.sceneId === opts.scene).flatMap((scene2) => scene2.trialsDetail.flatMap((t) => t.playOut === void 0 || t.passed || opts.trial !== void 0 && t.trial !== opts.trial ? [] : [{ sceneId: scene2.sceneId, trial: t.trial, exitedAt: sinceStart2(t.playOut.fromMs), playedOutTo: sinceStart2(t.playOut.toMs), realMs: t.realMs }]));
217642
+ function capFor(path7, inputsBytes = BUNDLE_LIMITS2.largeFileBytes) {
217643
+ const name5 = path7.slice(path7.lastIndexOf("/") + 1);
217644
+ return name5 === "trace.jsonl" || name5 === "state.json" ? BUNDLE_LIMITS2.largeFileBytes : name5 === "agent.log" ? BUNDLE_LIMITS2.agentLogBytes : path7 === "inputs.json" ? inputsBytes : BUNDLE_LIMITS2.fileBytes;
217519
217645
  }
217520
- function renderPlayOut(p2) {
217521
- return `${p2.sceneId} trial ${p2.trial} the agent exited at ${p2.exitedAt} (after ${duration8(p2.realMs)}); the world played out to ${p2.playedOutTo} without it`;
217646
+ function readsLargeInputs(version6) {
217647
+ const match3 = /^(\d+)\.(\d+)\.(\d+)/.exec(version6 ?? "");
217648
+ if (!match3) return false;
217649
+ const [major, minor, patch] = match3.slice(1).map(Number);
217650
+ return major !== 0 ? major > 0 : minor !== 4 ? minor > 4 : patch >= 14;
217522
217651
  }
217523
- function sinceStart2(ms2) {
217524
- let rest2 = Math.round(Math.abs(ms2) / 1e3);
217525
- const parts3 = [];
217526
- for (const [unit, size2] of [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]]) {
217527
- if (rest2 >= size2) {
217528
- parts3.push(`${Math.floor(rest2 / size2)}${unit}`);
217529
- rest2 %= size2;
217652
+ async function runFiles(runDir, source) {
217653
+ const root3 = await readdir3(runDir, { withFileTypes: true });
217654
+ const paths2 = ["summary.json", "inputs.json", "reproduction.json", "cloud.json"].filter((name5) => allowedFor(source, name5) && root3.some((entry3) => entry3.isFile() && entry3.name === name5));
217655
+ for (const dir2 of root3.filter((entry3) => entry3.isDirectory()).map((entry3) => entry3.name).sort()) {
217656
+ for (const file3 of (await readdir3(join23(runDir, dir2), { withFileTypes: true })).filter((entry3) => entry3.isFile()).map((entry3) => entry3.name).sort()) {
217657
+ if (allowedFor(source, `${dir2}/${file3}`)) paths2.push(`${dir2}/${file3}`);
217530
217658
  }
217531
217659
  }
217532
- return `${ms2 < 0 && parts3.length > 0 ? "-" : "+"}${parts3.join("") || "0s"}`;
217660
+ return paths2;
217533
217661
  }
217534
- async function withWorldEvidence(s3, runDir, failures) {
217535
- const starts = /* @__PURE__ */ new Map();
217536
- try {
217537
- const inputs2 = JSON.parse(await readFile10(join22(runDir, "inputs.json"), "utf8"));
217538
- for (const item2 of inputs2.cases ?? []) {
217539
- const start = Date.parse(item2.scene?.start_time ?? "");
217540
- if (Number.isFinite(start)) starts.set(item2.id, start);
217662
+ async function packRun(options4) {
217663
+ if (options4.source === "cloud" && !CLOUD_RUN_ID.test(options4.runId)) throw new AnchaError("USAGE", `run ${options4.runId} is not a cloud run`, { hint: "a cloud run has its job's run_cloud_ id" });
217664
+ const paths2 = await runFiles(options4.runDir, options4.source);
217665
+ if (!paths2.includes("summary.json")) throw new AnchaError("USAGE", `run ${options4.runId} has no summary.json`, { hint: "only a finished run can be uploaded; ancha status <id> shows where it stands" });
217666
+ const most = entriesFor(options4.source);
217667
+ if (paths2.length + 1 > most) throw tooBig2(`run ${options4.runId} has ${paths2.length} files to upload; a run bundle holds at most ${most - 1} besides its manifest`);
217668
+ const entries4 = [], omitted = [];
217669
+ for (const path7 of paths2) {
217670
+ let data5 = redact(await readFile11(join23(options4.runDir, path7)), options4.secrets);
217671
+ const cap = capFor(path7, options4.inputsBytes);
217672
+ if (data5.length > cap) {
217673
+ if (path7.endsWith("/agent.log")) data5 = logTail2(data5, cap);
217674
+ else if (options4.source === "cloud" && MANDATORY_CLOUD_PATH.test(path7)) throw tooBig2(`run ${options4.runId}: ${path7} is ${data5.length} bytes; a run keeps at most ${cap}`);
217675
+ else {
217676
+ omitted.push({ path: path7, bytes: data5.length, cap });
217677
+ continue;
217678
+ }
217541
217679
  }
217542
- } catch {
217680
+ entries4.push({ path: path7, data: data5 });
217543
217681
  }
217544
- const files2 = /* @__PURE__ */ new Map();
217545
- const explanations = (f2) => {
217546
- const key4 = `${f2.sceneId}/${f2.trial}`;
217547
- let file3 = files2.get(key4);
217548
- if (file3 === void 0) {
217549
- const dir2 = s3.scenes.find((scene2) => scene2.sceneId === f2.sceneId)?.trialsDetail.find((t) => t.trial === f2.trial)?.dir;
217550
- file3 = dir2 === void 0 ? Promise.resolve([]) : readFile10(join22(runDir, basename6(dir2), "explain.json"), "utf8").then((text29) => {
217551
- const value5 = JSON.parse(text29);
217552
- return Array.isArray(value5) ? value5 : [];
217553
- }).catch(() => []);
217554
- files2.set(key4, file3);
217555
- }
217556
- return file3;
217682
+ const unpacked = entries4.reduce((sum6, entry3) => sum6 + entry3.data.length, 0);
217683
+ if (unpacked > BUNDLE_LIMITS2.unpackedBytes) throw tooBig2(`run ${options4.runId} holds ${(unpacked / MB).toFixed(1)} MB to upload; a run bundle holds at most ${BUNDLE_LIMITS2.unpackedBytes / MB} MB unpacked`);
217684
+ const manifest2 = {
217685
+ version: 1,
217686
+ runId: options4.runId,
217687
+ createdAt: options4.createdAt,
217688
+ source: options4.source,
217689
+ project: options4.project,
217690
+ cli: options4.cli,
217691
+ files: entries4.map((entry3) => ({ path: entry3.path, bytes: entry3.data.length, sha256: sha2564(entry3.data) })),
217692
+ ...omitted.length > 0 && { omitted }
217557
217693
  };
217558
- return Promise.all(failures.map(async (f2) => {
217559
- const why = (await explanations(f2)).find((e) => e.checkId === f2.check);
217560
- if (why === void 0) return f2;
217561
- const start = starts.get(f2.sceneId);
217562
- const evidence2 = why.evidence.map((e) => {
217563
- if ("at" in e && typeof e.at === "string") return e;
217564
- const at4 = Date.parse(e.simAt);
217565
- return start === void 0 || !Number.isFinite(at4) ? e : { ...e, at: sinceStart2(at4 - start) };
217566
- });
217567
- return { ...f2, kind: why.kind, evidence: evidence2, conversation: why.conversation, people: why.people };
217568
- }));
217569
- }
217570
- function evidenceLine(e) {
217571
- const text29 = e.excerpt ?? "";
217572
- if (e.from === void 0 && e.to === void 0) return text29;
217573
- switch (e.type) {
217574
- case "message":
217575
- return `${e.from ?? e.to}${e.where === void 0 ? "" : ` ${e.where}`}: ${text29}`;
217576
- case "decision":
217577
- return `${e.from ?? e.to} decided ${text29}`;
217578
- case "knowledge":
217579
- return `${e.to ?? "someone"} learned ${text29}${e.from === void 0 ? "" : ` from ${e.from}`}`;
217580
- case "gate":
217581
- return `${e.to ?? e.from}: ${text29}`;
217582
- default:
217583
- return `${e.from ?? "the agent"} called ${text29}`;
217584
- }
217585
- }
217586
- function explainFailures(s3, opts = {}) {
217587
- return s3.scenes.filter((scene2) => opts.scene === void 0 || scene2.sceneId === opts.scene).flatMap((scene2) => scene2.failures).filter((f2) => opts.trial === void 0 || f2.trial === opts.trial);
217588
- }
217589
- function renderFailure(f2) {
217590
- const lines2 = [`${f2.sceneId} trial ${f2.trial} \u2717 ${f2.check}`];
217591
- lines2.push(` expected: ${f2.expected}`);
217592
- lines2.push(` actual: ${f2.actual}`);
217593
- lines2.push(` why: ${f2.explanation.replaceAll("\n", "\n ")}`);
217594
- if (f2.traceExcerpt.length > 0) {
217595
- lines2.push(" trace:");
217596
- if ((f2.traceExcerptOmitted ?? 0) > 0) lines2.push(` \u2026 ${f2.traceExcerptOmitted} earlier trace entries omitted; see trace.jsonl`);
217597
- for (const e of f2.traceExcerpt) {
217598
- const outcome4 = [e.status, e.execution_status, e.error_type, e.error === void 0 ? void 0 : `ok:false ${e.error}`, e.note, e.issue === void 0 ? void 0 : `${e.issue.owner} ${e.issue.kind}: ${e.issue.message}`].filter((p2) => p2 !== void 0);
217599
- lines2.push(` #${e.seq} ${e.source} ${e.method} ${e.path}${outcome4.length === 0 ? "" : ` -> ${outcome4.join(" ")}`}`);
217600
- }
217601
- }
217602
- lines2.push(...worldAccountLines(f2, " ", new Set(f2.traceExcerpt.map((e) => String(e.seq)))));
217603
- return lines2.join("\n");
217604
- }
217605
- function worldAccountLines(f2, indent2, shownCalls = /* @__PURE__ */ new Set()) {
217606
- const lines2 = [];
217607
- const evidence2 = (f2.evidence ?? []).filter((e) => !(e.type === "call" && e.id !== void 0 && shownCalls.has(e.id)));
217608
- if (evidence2.length > 0) lines2.push(`${indent2}evidence:`, ...evidence2.map((e) => `${indent2} ${e.at ?? e.simAt} ${evidenceLine(e)}`));
217609
- if ((f2.conversation ?? []).length > 0) lines2.push(`${indent2}conversation:`, ...f2.conversation.map((line2) => `${indent2} ${line2}`));
217610
- for (const [person5, state3] of Object.entries(f2.people ?? {})) {
217611
- lines2.push(`${indent2}${person5}:`);
217612
- if (state3.knows.length > 0) lines2.push(`${indent2} knows: ${state3.knows.join("; ")}`);
217613
- if (state3.decisions.length > 0) lines2.push(`${indent2} decisions: ${state3.decisions.join("; ")}`);
217614
- if (state3.knows.length === 0 && state3.decisions.length === 0) lines2.push(`${indent2} knew nothing and decided nothing`);
217615
- }
217616
- return lines2;
217694
+ const mtime = Date.parse(options4.createdAt);
217695
+ const tar = writeTar([{ path: "bundle.json", data: Buffer.from(`${JSON.stringify(manifest2, null, 2)}
217696
+ `, "utf8") }, ...entries4], Number.isNaN(mtime) ? 0 : mtime);
217697
+ const archive = gzipSync(tar, { level: 9 });
217698
+ if (archive.length > BUNDLE_LIMITS2.compressedBytes) throw tooBig2(`run ${options4.runId} compresses to ${(archive.length / MB).toFixed(1)} MB; a run bundle is at most ${BUNDLE_LIMITS2.compressedBytes / MB} MB`);
217699
+ return { archive, manifest: manifest2 };
217617
217700
  }
217618
- function renderExplain(s3, opts = {}, failures = explainFailures(s3, opts)) {
217619
- const never2 = agentNeverRan(s3), cloud = s3.target === "cloud";
217620
- if (never2 !== void 0 && !opts.all && opts.scene === void 0 && opts.trial === void 0) {
217621
- const folded = neverRanChecksLine(never2, s3.runId, opts.out);
217622
- return [...neverRanLines(never2, opts.cwd), ...folded === void 0 ? [] : [folded]].join("\n");
217623
- }
217624
- const issues = explainHarnessIssues(s3, opts);
217625
- const agentIssues = explainAgentIssues(s3, opts);
217626
- const exits = explainPlayOuts(s3, opts), told = /* @__PURE__ */ new Set();
217627
- const failureBlocks = failures.flatMap((f2) => {
217628
- const key4 = `${f2.sceneId}/${f2.trial}`, exit = told.has(key4) ? void 0 : exits.find((p2) => `${p2.sceneId}/${p2.trial}` === key4);
217629
- if (exit === void 0) return [renderFailure(f2)];
217630
- told.add(key4);
217631
- return [renderPlayOut(exit), renderFailure(f2)];
217632
- });
217633
- const untold = exits.filter((p2) => !told.has(`${p2.sceneId}/${p2.trial}`)).map(renderPlayOut);
217634
- const blocks2 = [...never2 === void 0 ? [] : [neverRanLines(never2, opts.cwd).join("\n")], ...issues.map(renderHarnessIssue), ...agentIssues.map((issue6) => renderAgentIssue(issue6, cloud)), ...untold, ...failureBlocks];
217635
- if (s3.pytest) blocks2.unshift(`pytest ${s3.pytest.nodeId}: ${s3.pytest.outcome}${s3.pytest.invalid ? " [invalid]" : !s3.pytest.graded ? " (ungraded)" : ""}; ${s3.pytest.phases.map((phase) => `${phase.when} ${phase.outcome}${phase.errorCode ? ` (${phase.errorCode})` : ""}`).join(", ")}`);
217636
- for (const warning of explainGradingWarnings(s3, opts)) blocks2.push(`${warning.sceneId} trial ${warning.trial} warning ${warning.check}: ${warning.message}`);
217637
- blocks2.push(...explainCoverageGaps(s3, opts).map(renderCoverageGap));
217638
- const ungraded = ungradedLines({ scenes: s3.scenes.filter((scene2) => opts.scene === void 0 || scene2.sceneId === opts.scene) });
217639
- if (ungraded.length > 0 && !s3.pytest) blocks2.push(ungraded.join("\n"));
217640
- const withheld = s3.agentEnvironment?.target === "host" && !s3.agentEnvironment.inheritAll ? s3.agentEnvironment.withheld ?? 0 : 0;
217641
- if (withheld > 0 && blocks2.length > 0 && !agentIssues.some((i) => i.hint !== void 0)) blocks2.push(`environment: ${withheld} variables from this shell were withheld from the agent. If it needs one (a provider key, say), pass it with --pass-env NAME or list it under agent.pass_env in ancha.yaml.`);
217642
- const shown3 = new Set(failures.map((f2) => `${f2.sceneId}/${f2.trial}`));
217643
- for (const scene2 of s3.scenes) {
217644
- if (opts.scene !== void 0 && scene2.sceneId !== opts.scene) continue;
217645
- const issueTrials = new Set(issues.filter((i) => i.sceneId === scene2.sceneId && i.owner === "harness").map((i) => i.trial));
217646
- const invalidMissing = scene2.trialsDetail.filter((t) => t.valid === false && (opts.trial === void 0 || t.trial === opts.trial) && !issueTrials.has(t.trial));
217647
- if (invalidMissing.length > 0) {
217648
- blocks2.push(`${scene2.sceneId}: no detail kept for invalid trial(s) ${invalidMissing.map((t) => t.trial).join(", ")} (at most ${MAX_FAILURES_PER_SCENE} issues per test); see trace.jsonl and checks.json in each trial directory, e.g. ${invalidMissing[0].dir}`);
217649
- }
217650
- const missing8 = scene2.trialsDetail.filter((t) => !t.passed && (!s3.pytest || t.valid && t.outcome !== "skipped" && t.outcome !== "xfailed") && (opts.trial === void 0 || t.trial === opts.trial) && !shown3.has(`${scene2.sceneId}/${t.trial}`));
217651
- if (missing8.length > 0) {
217652
- const trials = missing8.length > 10 ? `${missing8.slice(0, 10).map((t) => t.trial).join(", ")} and ${missing8.length - 10} more` : missing8.map((t) => t.trial).join(", ");
217653
- blocks2.push(`${scene2.sceneId}: no detail kept for failed trial(s) ${trials} (at most ${MAX_FAILURES_PER_SCENE} failures per test); see checks.json and trace.jsonl in each trial directory, e.g. ${missing8[0].dir}`);
217654
- }
217701
+ function header3(path7, size2, mtimeMs) {
217702
+ const block2 = Buffer.alloc(512);
217703
+ let name5 = path7, prefix2 = "";
217704
+ if (Buffer.byteLength(path7) > 100) {
217705
+ const cut5 = path7.lastIndexOf("/");
217706
+ [prefix2, name5] = [path7.slice(0, cut5), path7.slice(cut5 + 1)];
217707
+ if (cut5 < 0 || Buffer.byteLength(name5) > 100 || Buffer.byteLength(prefix2) > 155) throw new AnchaError("INTERNAL", `bundle path too long for ustar: ${path7}`);
217655
217708
  }
217656
- if (blocks2.length === 0) return "no failed checks to explain";
217657
- const text29 = blocks2.join("\n\n");
217658
- return text29.includes(PATTERN_NOTE) ? `${text29.replaceAll(PATTERN_NOTE, "")}
217659
-
217660
- ${PATTERN_NOTE.trim()}` : text29;
217709
+ const octal = (value5, width) => `${value5.toString(8).padStart(width - 1, "0")}\0`;
217710
+ block2.write(name5, 0, 100, "utf8");
217711
+ block2.write(octal(420, 8), 100, 8, "ascii");
217712
+ block2.write(octal(0, 8), 108, 8, "ascii");
217713
+ block2.write(octal(0, 8), 116, 8, "ascii");
217714
+ block2.write(octal(size2, 12), 124, 12, "ascii");
217715
+ block2.write(octal(Math.floor(mtimeMs / 1e3), 12), 136, 12, "ascii");
217716
+ block2.fill(32, 148, 156);
217717
+ block2.write("0", 156, 1, "ascii");
217718
+ block2.write("ustar\0", 257, 6, "ascii");
217719
+ block2.write("00", 263, 2, "ascii");
217720
+ block2.write(prefix2, 345, 155, "utf8");
217721
+ let sum6 = 0;
217722
+ for (const byte of block2) sum6 += byte;
217723
+ block2.write(`${sum6.toString(8).padStart(6, "0")}\0 `, 148, 8, "ascii");
217724
+ return block2;
217661
217725
  }
217662
- var CLOUD_EXIT2, MAX_FAILURES_PER_SCENE, DEFAULT_RUNS_DIR, exitedCleanly, FALLBACK_EXCERPT_CALLS, round4, trialIssues, trialValid, outcomeOf2, sceneFailed, CRASH_NOISE, ERROR_LINE, CRASH_LINE_MAX, NEVER_RAN_MS, spaced, pct, SUMMARY_GAPS_SHOWN, SUMMARY_ACTIONS_SHOWN, ANSWER_SOURCES2, duration8, shellWord, PATTERN_NOTE;
217663
- var init_report2 = __esm({
217664
- "backend/src/report.ts"() {
217665
- "use strict";
217666
- init_src();
217667
- init_harness_issues2();
217668
- init_scenes();
217669
- init_actions7();
217670
- init_reproduction_text();
217671
- init_agent_fix();
217672
- init_src();
217673
- CLOUD_EXIT2 = { pass: 0, fail: 1, cancelled: 2, invalid: 3, strict: 4 };
217674
- MAX_FAILURES_PER_SCENE = 20;
217675
- DEFAULT_RUNS_DIR = ".ancha/runs";
217676
- exitedCleanly = (t) => t.exit === "done" || t.exit === "idle" || t.exit === "exited" && t.exitCode === 0;
217677
- FALLBACK_EXCERPT_CALLS = 10;
217678
- round4 = (n2) => Math.round(n2 * 1e4) / 1e4;
217679
- trialIssues = (t) => t.harnessIssues ?? collectHarnessIssues(t.trace, t.checks);
217680
- trialValid = (t) => t.valid !== false && t.exit !== "invalid" && !trialIssues(t).some((i) => i.owner === "harness");
217681
- outcomeOf2 = (t) => trialOutcome({ ...t, valid: trialValid(t), outcome: t.checks.some((check4) => check4.required && check4.status === "skipped") ? "skipped" : t.outcome });
217682
- sceneFailed = (scene2, minPassRate) => (scene2.invalidTrials ?? 0) > 0 || !scene2.counts || !meetsPassRate(scene2.counts, minPassRate);
217683
- CRASH_NOISE = /^\s*$|^\s+at\s|^\s*… \d+ more frames$|^\s*[~^]+\s*$|^\s*[{}]\s*$|^Node\.js v\d/;
217684
- ERROR_LINE = /error|exception|fatal|panic/i;
217685
- CRASH_LINE_MAX = 200;
217686
- NEVER_RAN_MS = 5e3;
217687
- spaced = (ms2) => ms2 < 1e3 ? `${ms2} ms` : `${(ms2 / 1e3).toFixed(1)} s`;
217688
- pct = (rate) => String(Math.round(rate * 1e3) / 10);
217689
- SUMMARY_GAPS_SHOWN = 10;
217690
- SUMMARY_ACTIONS_SHOWN = 8;
217691
- ANSWER_SOURCES2 = [["replayed", "replayed"], ["replayed-elsewhere", "replayed from another conversation"], ["twin", "by twins"], ["ran", "ran the tool itself"], ["simulated", "simulated"], ["failed", "failed"]];
217692
- duration8 = (ms2) => ms2 < 1e3 ? `${ms2}ms` : `${(ms2 / 1e3).toFixed(1)}s`;
217693
- shellWord = (dir2) => /^[\w./@%+=:,-]+$/.test(dir2) ? dir2 : `'${dir2.replaceAll("'", `'\\''`)}'`;
217694
- PATTERN_NOTE = ' Patterns are "<METHOD> <PATH>" matched against the service-relative path, and * is a wildcard.';
217695
- }
217696
- });
217697
-
217698
- // backend/src/run-store.ts
217699
- import { readFile as readFile12, stat as stat5 } from "node:fs/promises";
217700
- import { join as join25, resolve as resolve18 } from "node:path";
217701
- async function latestRunId(cwd, out) {
217702
- if (out !== void 0) return resolveRunId(cwd, "latest", out);
217703
- const dir2 = resolve18(cwd, DEFAULT_RUNS_DIR);
217704
- let local2;
217705
- try {
217706
- const path7 = join25(dir2, "latest");
217707
- local2 = { runId: (await readFile12(path7, "utf8")).trim(), time: (await stat5(path7)).mtimeMs };
217708
- } catch (error65) {
217709
- if (!isEnoent(error65)) throw error65;
217710
- }
217711
- const text29 = await readFile12(join25(dir2, "latest-cloud"), "utf8").catch((error65) => {
217712
- if (!isEnoent(error65)) throw error65;
217713
- return void 0;
217714
- });
217715
- if (text29 !== void 0) {
217716
- try {
217717
- const cloud = JSON.parse(text29);
217718
- const time7 = typeof cloud?.submittedAt === "string" ? Date.parse(cloud.submittedAt) : NaN;
217719
- if (typeof cloud?.runId === "string" && RUN_CLOUD_ID.test(cloud.runId) && Number.isFinite(time7) && (local2 === void 0 || time7 > local2.time)) return cloud.runId;
217720
- } catch {
217721
- }
217726
+ function writeTar(entries4, mtimeMs) {
217727
+ const parts3 = [];
217728
+ for (const entry3 of entries4) {
217729
+ parts3.push(header3(entry3.path, entry3.data.length, mtimeMs), entry3.data);
217730
+ const pad3 = (512 - entry3.data.length % 512) % 512;
217731
+ if (pad3) parts3.push(Buffer.alloc(pad3));
217722
217732
  }
217723
- return local2?.runId ?? resolveRunId(cwd, "latest");
217733
+ parts3.push(Buffer.alloc(1024));
217734
+ return Buffer.concat(parts3);
217724
217735
  }
217725
- async function resolveRunId(cwd, ref22, out) {
217726
- const dir2 = resolve18(cwd, out ?? DEFAULT_RUNS_DIR);
217727
- let runId2 = ref22;
217728
- if (ref22 === "latest") {
217729
- try {
217730
- runId2 = (await readFile12(join25(dir2, "latest"), "utf8")).trim();
217731
- } catch (e) {
217732
- if (isEnoent(e)) throw new AnchaError("USAGE", `no runs found in ${dir2}`, { hint: "run `ancha run` first", cause: e });
217733
- throw e;
217734
- }
217736
+ function readBundle(archive) {
217737
+ const tar = gunzipSync3(archive, { maxOutputLength: BUNDLE_LIMITS2.unpackedBytes + 1024 * 1024 });
217738
+ const entries4 = [];
217739
+ for (let offset18 = 0; offset18 + 512 <= tar.length; ) {
217740
+ const block2 = tar.subarray(offset18, offset18 + 512);
217741
+ if (block2.every((byte) => byte === 0)) break;
217742
+ const field6 = (start, length) => block2.subarray(start, start + length).toString("utf8").replace(/\0.*$/s, "");
217743
+ const name5 = field6(0, 100), prefix2 = field6(345, 155), size2 = parseInt(field6(124, 12).trim(), 8);
217744
+ if (!Number.isSafeInteger(size2) || size2 < 0 || field6(156, 1) !== "0" && field6(156, 1) !== "") throw new AnchaError("USAGE", `bundle entry ${name5} is not a regular file`);
217745
+ const path7 = prefix2 ? `${prefix2}/${name5}` : name5;
217746
+ entries4.push({ path: path7, data: Buffer.from(tar.subarray(offset18 + 512, offset18 + 512 + size2)) });
217747
+ offset18 += 512 + Math.ceil(size2 / 512) * 512;
217735
217748
  }
217736
- return runId2;
217749
+ return entries4;
217737
217750
  }
217738
- async function loadRunSummary(cwd, ref22, out) {
217739
- const dir2 = resolve18(cwd, out ?? DEFAULT_RUNS_DIR);
217740
- const hint = `see ${out ?? DEFAULT_RUNS_DIR}/`;
217741
- const runId2 = await resolveRunId(cwd, ref22, out);
217742
- if (!RUN_ID.test(runId2)) throw new AnchaError("USAGE", `unknown run ${JSON.stringify(runId2)}`, { hint });
217743
- let text29;
217744
- try {
217745
- text29 = await readFile12(join25(dir2, runId2, "summary.json"), "utf8");
217746
- } catch (e) {
217747
- if (!isEnoent(e)) throw e;
217748
- if (await stat5(join25(dir2, runId2)).then((s4) => s4.isDirectory(), () => false)) {
217749
- throw new AnchaError("USAGE", `run ${runId2} has no summary.json (it may have been interrupted)`, {
217750
- hint: `its trial directories (agent.log, trace.jsonl, \u2026) are in ${join25(out ?? DEFAULT_RUNS_DIR, runId2)}/; run \`ancha run\` again for a summary`,
217751
- cause: e
217752
- });
217753
- }
217754
- throw new AnchaError("USAGE", `unknown run ${JSON.stringify(runId2)}`, { hint, cause: e });
217755
- }
217756
- let summary;
217757
- try {
217758
- summary = JSON.parse(text29);
217759
- } catch (e) {
217760
- throw new AnchaError("INTERNAL", `${join25(dir2, runId2, "summary.json")} is not valid JSON`, { cause: e });
217751
+ function validateBundle(archive) {
217752
+ if (archive.length > BUNDLE_LIMITS2.compressedBytes) throw tooBig2(`bundle is ${archive.length} bytes compressed`);
217753
+ const entries4 = readBundle(archive);
217754
+ if (entries4.length > BUNDLE_LIMITS2.cloudEntries) throw tooBig2(`bundle has ${entries4.length} entries`);
217755
+ let unpacked = 0;
217756
+ for (const entry3 of entries4) {
217757
+ if (!BUNDLE_PATH2.test(entry3.path)) throw new AnchaError("USAGE", `bundle entry not allowed: ${entry3.path}`);
217758
+ if (entry3.path !== "bundle.json" && entry3.data.length > capFor(entry3.path)) throw tooBig2(`bundle entry ${entry3.path} is ${entry3.data.length} bytes`);
217759
+ unpacked += entry3.data.length;
217761
217760
  }
217762
- const s3 = summary;
217763
- if (typeof s3 !== "object" || s3 === null || s3.runId !== runId2 || !Array.isArray(s3.scenes)) {
217764
- throw new AnchaError("INTERNAL", `${join25(dir2, runId2, "summary.json")} is not a run summary`);
217761
+ if (unpacked > BUNDLE_LIMITS2.unpackedBytes) throw tooBig2(`bundle unpacks to ${unpacked} bytes`);
217762
+ const manifestEntry = entries4.find((entry3) => entry3.path === "bundle.json");
217763
+ if (!manifestEntry) throw new AnchaError("USAGE", "bundle has no bundle.json");
217764
+ const manifest2 = JSON.parse(manifestEntry.data.toString("utf8"));
217765
+ if (entries4.length > entriesFor(manifest2.source)) throw tooBig2(`bundle has ${entries4.length} entries`);
217766
+ const foreign = entries4.find((entry3) => !allowedFor(manifest2.source, entry3.path));
217767
+ if (foreign) throw new AnchaError("USAGE", `bundle entry not allowed: ${foreign.path}`);
217768
+ if (manifest2.source === "cloud" !== CLOUD_RUN_ID.test(manifest2.runId)) throw new AnchaError("USAGE", "a cloud run has a run_cloud_ id and source cloud");
217769
+ const byPath = new Map(entries4.map((entry3) => [entry3.path, entry3.data]));
217770
+ for (const file3 of manifest2.files) {
217771
+ const data5 = byPath.get(file3.path);
217772
+ if (!data5 || data5.length !== file3.bytes || sha2564(data5) !== file3.sha256) throw new AnchaError("USAGE", `bundle.json disagrees with ${file3.path}`);
217765
217773
  }
217766
- return normalizeSummary(s3);
217774
+ if (!byPath.has("summary.json")) throw new AnchaError("USAGE", "bundle has no summary.json");
217775
+ return manifest2;
217767
217776
  }
217768
- var RUN_ID, isEnoent;
217769
- var init_run_store = __esm({
217770
- "backend/src/run-store.ts"() {
217777
+ var BUNDLE_PATH2, CLOUD_ONLY_PATH, CLOUD_RUN_ID, MANDATORY_CLOUD_PATH, MB, BUNDLE_LIMITS2, MIN_SECRET, entriesFor, allowedFor, sha2564, tooBig2;
217778
+ var init_run_bundle = __esm({
217779
+ "backend/src/run-bundle.ts"() {
217771
217780
  "use strict";
217772
217781
  init_src();
217773
- init_report2();
217774
- init_jobs_contract();
217775
- RUN_ID = /^[A-Za-z0-9_][\w.-]*$/;
217776
- isEnoent = (e) => e?.code === "ENOENT";
217782
+ init_agent_env();
217783
+ BUNDLE_PATH2 = /^(bundle\.json|summary\.json|inputs\.json|reproduction\.json|cloud\.json|trial-[A-Za-z0-9_-]{1,191}-[0-9]{1,4}\/(agent\.log|trace\.jsonl|state\.json|people-timeline\.json|explain\.json|checks\.json|result\.json|task-input\.json|execution\.json))$/;
217784
+ CLOUD_ONLY_PATH = /^(reproduction\.json|cloud\.json|trial-[A-Za-z0-9_-]{1,191}-[0-9]{1,4}\/execution\.json)$/;
217785
+ CLOUD_RUN_ID = /^run_cloud_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
217786
+ MANDATORY_CLOUD_PATH = /^(summary\.json|trial-[^/]+\/(result\.json|checks\.json|trace\.jsonl))$/;
217787
+ MB = 1024 * 1024;
217788
+ BUNDLE_LIMITS2 = { entries: 1200, cloudEntries: 2e3, compressedBytes: 50 * MB, unpackedBytes: 200 * MB, largeFileBytes: 12 * MB, fileBytes: 4 * MB, agentLogBytes: 4 * MB };
217789
+ MIN_SECRET = 8;
217790
+ entriesFor = (source) => source === "cloud" ? BUNDLE_LIMITS2.cloudEntries : BUNDLE_LIMITS2.entries;
217791
+ allowedFor = (source, path7) => BUNDLE_PATH2.test(path7) && (source === "cloud" || !CLOUD_ONLY_PATH.test(path7));
217792
+ sha2564 = (data5) => createHash59("sha256").update(data5).digest("hex");
217793
+ tooBig2 = (message7) => new AnchaError("USAGE", message7, { hint: "upload a run with fewer trials, or run fewer trials per test" });
217777
217794
  }
217778
217795
  });
217779
217796
 
@@ -217804,8 +217821,8 @@ async function preflightFiles(cwd, files2) {
217804
217821
  for (let i = 1; i <= parts3.length; i++) {
217805
217822
  const part = join27(root3, ...parts3.slice(0, i));
217806
217823
  try {
217807
- const stat19 = await lstat4(part);
217808
- if (stat19.isSymbolicLink() || (i < parts3.length ? !stat19.isDirectory() : !stat19.isFile())) throw invalid31(`unsafe scaffold target: ${relative9(root3, part)}`);
217824
+ const stat20 = await lstat4(part);
217825
+ if (stat20.isSymbolicLink() || (i < parts3.length ? !stat20.isDirectory() : !stat20.isFile())) throw invalid31(`unsafe scaffold target: ${relative9(root3, part)}`);
217809
217826
  } catch (error65) {
217810
217827
  if (error65.code !== "ENOENT") throw error65;
217811
217828
  }
@@ -221062,8 +221079,8 @@ async function manifest(root3, name5) {
221062
221079
  let file3;
221063
221080
  try {
221064
221081
  file3 = await open7(join39(root3, name5), constants9.O_RDONLY | constants9.O_NOFOLLOW | constants9.O_NONBLOCK);
221065
- const stat19 = await file3.stat();
221066
- if (!stat19.isFile() || stat19.size > 32 * 1024 * 1024) throw new Error();
221082
+ const stat20 = await file3.stat();
221083
+ if (!stat20.isFile() || stat20.size > 32 * 1024 * 1024) throw new Error();
221067
221084
  return await file3.readFile("utf8");
221068
221085
  } catch (error65) {
221069
221086
  if (error65.code === "ENOENT") return void 0;
@@ -227788,16 +227805,16 @@ init_backend();
227788
227805
  init_src();
227789
227806
  init_credentials();
227790
227807
  import { execFile as execFile4 } from "node:child_process";
227791
- import { mkdtemp as mkdtemp4, readFile as readFile11, rm as rm3, stat as stat4, writeFile as writeFile11 } from "node:fs/promises";
227808
+ import { mkdtemp as mkdtemp4, readFile as readFile12, rm as rm3, stat as stat5, writeFile as writeFile11 } from "node:fs/promises";
227792
227809
  import { tmpdir as tmpdir3 } from "node:os";
227793
- import { basename as basename7, join as join24, resolve as resolve17 } from "node:path";
227810
+ import { basename as basename7, join as join25, resolve as resolve18 } from "node:path";
227794
227811
  import { promisify as promisify4 } from "node:util";
227795
227812
 
227796
227813
  // backend/src/cloud/dependencies.ts
227797
227814
  import { execFile as execFile3 } from "node:child_process";
227798
227815
  import { constants as constants6 } from "node:fs";
227799
- import { access as access5, lstat as lstat2, open as open4, readFile as readFile7, realpath as realpath3, stat as stat3 } from "node:fs/promises";
227800
- import { basename as basename5, dirname as dirname8, isAbsolute as isAbsolute5, join as join18, posix as posix3, relative as relative7, resolve as resolve14, sep as sep3 } from "node:path";
227816
+ import { access as access5, lstat as lstat2, open as open4, readFile as readFile9, realpath as realpath3, stat as stat4 } from "node:fs/promises";
227817
+ import { basename as basename6, dirname as dirname9, isAbsolute as isAbsolute5, join as join20, posix as posix3, relative as relative8, resolve as resolve16, sep as sep3 } from "node:path";
227801
227818
  import { promisify as promisify3 } from "node:util";
227802
227819
 
227803
227820
  // node_modules/.pnpm/tinyglobby@0.2.17/node_modules/tinyglobby/dist/index.mjs
@@ -227925,10 +227942,10 @@ var resolveSymlinksAsync = function(path7, state3, callback$1) {
227925
227942
  queue.enqueue();
227926
227943
  fs.realpath(path7, (error65, resolvedPath) => {
227927
227944
  if (error65) return queue.dequeue(suppressErrors ? null : error65, state3);
227928
- fs.stat(resolvedPath, (error$1, stat19) => {
227945
+ fs.stat(resolvedPath, (error$1, stat20) => {
227929
227946
  if (error$1) return queue.dequeue(suppressErrors ? null : error$1, state3);
227930
- if (stat19.isDirectory() && isRecursive2(path7, resolvedPath, state3)) return queue.dequeue(null, state3);
227931
- callback$1(stat19, resolvedPath);
227947
+ if (stat20.isDirectory() && isRecursive2(path7, resolvedPath, state3)) return queue.dequeue(null, state3);
227948
+ callback$1(stat20, resolvedPath);
227932
227949
  queue.dequeue(null, state3);
227933
227950
  });
227934
227951
  });
@@ -227938,9 +227955,9 @@ var resolveSymlinks = function(path7, state3, callback$1) {
227938
227955
  queue.enqueue();
227939
227956
  try {
227940
227957
  const resolvedPath = fs.realpathSync(path7);
227941
- const stat19 = fs.statSync(resolvedPath);
227942
- if (stat19.isDirectory() && isRecursive2(path7, resolvedPath, state3)) return;
227943
- callback$1(stat19, resolvedPath);
227958
+ const stat20 = fs.statSync(resolvedPath);
227959
+ if (stat20.isDirectory() && isRecursive2(path7, resolvedPath, state3)) return;
227960
+ callback$1(stat20, resolvedPath);
227944
227961
  } catch (e) {
227945
227962
  if (!suppressErrors) throw e;
227946
227963
  }
@@ -228137,8 +228154,8 @@ var Walker = class {
228137
228154
  this.walkDirectory(this.state, path7, path7, depth - 1, this.walk);
228138
228155
  } else if (this.resolveSymlink && entry3.isSymbolicLink()) {
228139
228156
  let path7 = joinPathWithBasePath(entry3.name, directoryPath);
228140
- this.resolveSymlink(path7, this.state, (stat19, resolvedPath) => {
228141
- if (stat19.isDirectory()) {
228157
+ this.resolveSymlink(path7, this.state, (stat20, resolvedPath) => {
228158
+ if (stat20.isDirectory()) {
228142
228159
  resolvedPath = normalizePath(resolvedPath, this.state.options);
228143
228160
  if (exclude && exclude(entry3.name, useRealPaths ? resolvedPath : path7 + pathSeparator)) return;
228144
228161
  this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path7 + pathSeparator, depth - 1, this.walk);
@@ -228590,11 +228607,11 @@ ${lines2.join("\n")}`, { hint: "restore each file, or change the field that name
228590
228607
  async function cloudAgentCwd(root3, configPath, config11) {
228591
228608
  const base3 = await realpath3(root3);
228592
228609
  const configured = config11.agent?.cwd ?? ".";
228593
- const cwd = config11.agent?.cwd === void 0 ? base3 : resolve14(base3, dirname8(configPath), configured);
228610
+ const cwd = config11.agent?.cwd === void 0 ? base3 : resolve16(base3, dirname9(configPath), configured);
228594
228611
  const inside3 = (path7) => path7 === base3 || path7.startsWith(`${base3}${sep3}`);
228595
228612
  if (isAbsolute5(configured) || !inside3(cwd)) throw new AnchaError("CONFIG_INVALID", "agent.cwd must name a directory inside the bundle relative to ancha.yaml");
228596
228613
  const actual = await realpath3(cwd).catch(() => void 0);
228597
- if (actual === void 0 || !(await stat3(actual)).isDirectory()) throw new AnchaError("CONFIG_INVALID", `agent.cwd: ${configured} is not a directory in the bundle`);
228614
+ if (actual === void 0 || !(await stat4(actual)).isDirectory()) throw new AnchaError("CONFIG_INVALID", `agent.cwd: ${configured} is not a directory in the bundle`);
228598
228615
  if (!inside3(actual)) throw new AnchaError("CONFIG_INVALID", "agent.cwd reaches outside the bundle through a symbolic link");
228599
228616
  return cwd;
228600
228617
  }
@@ -228629,7 +228646,7 @@ function yarnReleasePath(path7, text29) {
228629
228646
  return posix3.join(posix3.dirname(path7), release2);
228630
228647
  }
228631
228648
  async function readYarnConfig(root3, path7) {
228632
- const file3 = join18(await realpath3(root3), path7);
228649
+ const file3 = join20(await realpath3(root3), path7);
228633
228650
  if (await realpath3(file3) !== file3) throw new AnchaError("CONFIG_INVALID", `${path7} must be a regular file inside the bundle`);
228634
228651
  const handle30 = await open4(file3, constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
228635
228652
  try {
@@ -228641,7 +228658,7 @@ async function readYarnConfig(root3, path7) {
228641
228658
  }
228642
228659
  }
228643
228660
  async function anchaIgnore(root3) {
228644
- return (await readFile7(join18(root3, ".anchaignore"), "utf8").catch(() => "")).split("\n").map((line2) => line2.trim()).filter((line2) => line2 && !line2.startsWith("#")).flatMap((pattern) => {
228661
+ return (await readFile9(join20(root3, ".anchaignore"), "utf8").catch(() => "")).split("\n").map((line2) => line2.trim()).filter((line2) => line2 && !line2.startsWith("#")).flatMap((pattern) => {
228645
228662
  const bare = pattern.replace(/^\//, "").replace(/\/$/, "");
228646
228663
  return pattern.startsWith("/") ? [bare, `${bare}/**`] : [bare, `${bare}/**`, `**/${bare}`, `**/${bare}/**`];
228647
228664
  });
@@ -228653,7 +228670,7 @@ async function projectFiles(root3, options4 = {}) {
228653
228670
  const files2 = (listed2 ?? [...kept]).filter((path7) => kept.has(path7) && visible5(path7));
228654
228671
  if (options4.links && listed2 !== void 0) {
228655
228672
  const folders3 = new Set([...kept].flatMap((path7) => path7.split("/").slice(0, -1).map((_, i, parts3) => parts3.slice(0, i + 1).join("/"))));
228656
- for (const path7 of listed2) if (!kept.has(path7) && folders3.has(path7) && visible5(path7) && (await lstat2(join18(root3, path7)).catch(() => void 0))?.isSymbolicLink()) files2.push(path7);
228673
+ for (const path7 of listed2) if (!kept.has(path7) && folders3.has(path7) && visible5(path7) && (await lstat2(join20(root3, path7)).catch(() => void 0))?.isSymbolicLink()) files2.push(path7);
228657
228674
  }
228658
228675
  return files2.sort();
228659
228676
  }
@@ -228662,7 +228679,7 @@ async function filesUnder(root3, folder2) {
228662
228679
  return found.filter((path7) => !excludedPath(path7)).sort();
228663
228680
  }
228664
228681
  function projectPath(root3, path7, what) {
228665
- const rel = relative7(resolve14(root3), resolve14(root3, path7));
228682
+ const rel = relative8(resolve16(root3), resolve16(root3, path7));
228666
228683
  if (rel === "" || rel === ".." || rel.startsWith(`..${sep3}`) || isAbsolute5(rel)) throw new AnchaError("CONFIG_INVALID", `${what} ${path7} is outside the project`, { hint: `a cloud run carries files inside ${root3}; move it there` });
228667
228684
  return rel.split(sep3).join("/");
228668
228685
  }
@@ -228674,7 +228691,7 @@ function refuseExcluded(path7, what) {
228674
228691
  var exists2 = (path7) => access5(path7).then(() => true, () => false);
228675
228692
  var readJson = async (path7) => {
228676
228693
  try {
228677
- const value5 = JSON.parse(await readFile7(path7, "utf8"));
228694
+ const value5 = JSON.parse(await readFile9(path7, "utf8"));
228678
228695
  return value5 !== null && typeof value5 === "object" && !Array.isArray(value5) ? value5 : void 0;
228679
228696
  } catch {
228680
228697
  return void 0;
@@ -228686,9 +228703,9 @@ function beside(file3, value5) {
228686
228703
  return posix3.normalize(posix3.join(posix3.dirname(file3), value5));
228687
228704
  }
228688
228705
  function worldCandidates(root3, test3, id14) {
228689
- const file3 = resolve14(root3, test3);
228690
- const nearby = basename5(dirname8(file3)) === "tests" ? [join18(dirname8(file3), "..", "worlds", `${id14}.yaml`)] : [];
228691
- return [.../* @__PURE__ */ new Set([...nearby, join18(root3, "ancha", "worlds", `${id14}.yaml`)])];
228706
+ const file3 = resolve16(root3, test3);
228707
+ const nearby = basename6(dirname9(file3)) === "tests" ? [join20(dirname9(file3), "..", "worlds", `${id14}.yaml`)] : [];
228708
+ return [.../* @__PURE__ */ new Set([...nearby, join20(root3, "ancha", "worlds", `${id14}.yaml`)])];
228692
228709
  }
228693
228710
  function namedFiles(path7, doc) {
228694
228711
  if (!record24(doc)) return [];
@@ -228711,14 +228728,14 @@ async function loadTests(root3, paths2) {
228711
228728
  for (const path7 of tests) {
228712
228729
  let doc;
228713
228730
  try {
228714
- doc = parseSceneYaml(await readFile7(join18(root3, path7), "utf8"));
228731
+ doc = parseSceneYaml(await readFile9(join20(root3, path7), "utf8"));
228715
228732
  } catch {
228716
228733
  continue;
228717
228734
  }
228718
- for (const reference3 of namedFiles(path7, doc)) if (!await exists2(join18(root3, reference3.to))) missing8.push(`${path7}: ${reference3.field}: ${reference3.to} is missing`);
228735
+ for (const reference3 of namedFiles(path7, doc)) if (!await exists2(join20(root3, reference3.to))) missing8.push(`${path7}: ${reference3.field}: ${reference3.to} is missing`);
228719
228736
  if (isTestFile(doc) && typeof doc.world === "string") {
228720
228737
  const id14 = doc.world, candidates = worldCandidates(root3, path7, id14);
228721
- if (!(await Promise.all(candidates.map(exists2))).some(Boolean)) missing8.push(`${path7}: world: ${candidates.map((file3) => relative7(root3, file3).split(sep3).join("/")).join(" or ")} is missing`);
228738
+ if (!(await Promise.all(candidates.map(exists2))).some(Boolean)) missing8.push(`${path7}: world: ${candidates.map((file3) => relative8(root3, file3).split(sep3).join("/")).join(" or ")} is missing`);
228722
228739
  }
228723
228740
  }
228724
228741
  if (missing8.length) throw missingReference(missing8);
@@ -228729,20 +228746,20 @@ async function loadTests(root3, paths2) {
228729
228746
  return loaded;
228730
228747
  }
228731
228748
  async function caseProvenance(root3, test3) {
228732
- const dir2 = dirname8(join18(root3, test3.path));
228749
+ const dir2 = dirname9(join20(root3, test3.path));
228733
228750
  const external2 = /* @__PURE__ */ new Set();
228734
- const production3 = await readJson(join18(dir2, "production.json"));
228751
+ const production3 = await readJson(join20(dir2, "production.json"));
228735
228752
  if (typeof production3?.trace === "string" && production3.trace) external2.add(production3.trace);
228736
- const provenance = await readJson(join18(dir2, "provenance.json"));
228753
+ const provenance = await readJson(join20(dir2, "provenance.json"));
228737
228754
  if (record24(provenance?.summary) && typeof provenance.summary.trace === "string" && provenance.summary.trace) external2.add(provenance.summary.trace);
228738
228755
  if (record24(provenance?.conversation) && Array.isArray(provenance.conversation.traces)) {
228739
228756
  for (const trace of provenance.conversation.traces) if (typeof trace === "string" && trace) external2.add(trace);
228740
228757
  }
228741
- const pulled = /^# ancha pull: (\S+) /m.exec(await readFile7(join18(root3, test3.path), "utf8").catch(() => ""));
228758
+ const pulled = /^# ancha pull: (\S+) /m.exec(await readFile9(join20(root3, test3.path), "utf8").catch(() => ""));
228742
228759
  return { caseId: test3.scene.id, traceIds: [], externalTraceIds: [...external2].sort(), ...pulled !== null && { testId: pulled[1] } };
228743
228760
  }
228744
228761
  async function bundleInventory(input4) {
228745
- const root3 = resolve14(input4.root);
228762
+ const root3 = resolve16(input4.root);
228746
228763
  const cwd = await cloudAgentCwd(root3, input4.configPath, input4.config);
228747
228764
  const roles2 = /* @__PURE__ */ new Map();
228748
228765
  const add = (path7, role3) => {
@@ -228760,7 +228777,7 @@ async function bundleInventory(input4) {
228760
228777
  add(test3.path, "test");
228761
228778
  let doc;
228762
228779
  try {
228763
- doc = parseSceneYaml(await readFile7(join18(root3, test3.path), "utf8"));
228780
+ doc = parseSceneYaml(await readFile9(join20(root3, test3.path), "utf8"));
228764
228781
  } catch {
228765
228782
  doc = void 0;
228766
228783
  }
@@ -228775,12 +228792,12 @@ async function bundleInventory(input4) {
228775
228792
  link8(test3.path, "world", world5, "world", "world");
228776
228793
  let worldDoc;
228777
228794
  try {
228778
- worldDoc = parseSceneYaml(await readFile7(join18(root3, world5), "utf8"));
228795
+ worldDoc = parseSceneYaml(await readFile9(join20(root3, world5), "utf8"));
228779
228796
  } catch {
228780
228797
  worldDoc = void 0;
228781
228798
  }
228782
228799
  for (const reference3 of namedFiles(world5, worldDoc)) {
228783
- if (!await exists2(join18(root3, reference3.to))) missing8.push(`${world5}: ${reference3.field}: ${reference3.to} is missing`);
228800
+ if (!await exists2(join20(root3, reference3.to))) missing8.push(`${world5}: ${reference3.field}: ${reference3.to} is missing`);
228784
228801
  else link8(world5, reference3.field, reference3.to, reference3.kind, reference3.role);
228785
228802
  }
228786
228803
  }
@@ -228788,16 +228805,16 @@ async function bundleInventory(input4) {
228788
228805
  if (records4 !== void 0) link8(test3.path, "records", projectPath(root3, records4, `${test3.path}: records:`), "records", "runtime-data");
228789
228806
  for (const [name5, role3] of Object.entries(COMPANIONS)) {
228790
228807
  const to = posix3.join(posix3.dirname(test3.path), name5);
228791
- if (await exists2(join18(root3, to))) link8(test3.path, name5, to, role3, role3);
228808
+ if (await exists2(join20(root3, to))) link8(test3.path, name5, to, role3, role3);
228792
228809
  }
228793
228810
  }
228794
228811
  if (missing8.length) throw missingReference(missing8);
228795
228812
  for (const selection of input4.bundleFiles ?? []) {
228796
228813
  const path7 = projectPath(root3, selection, "--bundle-file");
228797
228814
  refuseExcluded(path7, "--bundle-file");
228798
- const stat19 = await lstat2(join18(root3, path7)).catch(() => void 0);
228799
- if (stat19 === void 0) throw missingReference([`--bundle-file: ${path7} is missing`]);
228800
- for (const file3 of stat19.isDirectory() ? await filesUnder(root3, path7) : [path7]) add(file3, "runtime-data");
228815
+ const stat20 = await lstat2(join20(root3, path7)).catch(() => void 0);
228816
+ if (stat20 === void 0) throw missingReference([`--bundle-file: ${path7} is missing`]);
228817
+ for (const file3 of stat20.isDirectory() ? await filesUnder(root3, path7) : [path7]) add(file3, "runtime-data");
228801
228818
  }
228802
228819
  if (input4.baseline !== void 0) add(input4.baseline, "checks");
228803
228820
  const policy = input4.config.agent?.execution;
@@ -228810,9 +228827,9 @@ async function bundleInventory(input4) {
228810
228827
  }
228811
228828
  const path7 = projectPath(root3, selection, "agent.execution.files:");
228812
228829
  refuseExcluded(path7, "agent.execution.files:");
228813
- const stat19 = await lstat2(join18(root3, path7)).catch(() => void 0);
228814
- if (stat19 === void 0) throw missingReference([`${input4.configPath}: agent.execution.files: ${path7} is missing`]);
228815
- if (stat19.isDirectory()) candidates.push(...await filesUnder(root3, path7));
228830
+ const stat20 = await lstat2(join20(root3, path7)).catch(() => void 0);
228831
+ if (stat20 === void 0) throw missingReference([`${input4.configPath}: agent.execution.files: ${path7} is missing`]);
228832
+ if (stat20.isDirectory()) candidates.push(...await filesUnder(root3, path7));
228816
228833
  else {
228817
228834
  candidates.push(path7);
228818
228835
  selected2.add(path7);
@@ -228821,7 +228838,7 @@ async function bundleInventory(input4) {
228821
228838
  const sceneDirs = (await glob3(["**/scene.yaml"], { cwd: root3, onlyFiles: true, ignore: ["**/node_modules/**"] })).map((path7) => posix3.dirname(path7));
228822
228839
  const scenes = new Set(await glob3(input4.config.scenes, { cwd: root3, onlyFiles: true, ignore: ["**/node_modules/**"] }));
228823
228840
  const definition3 = (path7) => path7 === "ancha.yaml" || path7.startsWith("ancha/") || scenes.has(path7) || sceneDirs.some((dir2) => dir2 === "." ? /^(?:scene\.yaml|(?:oracle|null)\.m?[jt]s)$/.test(path7) : path7.startsWith(`${dir2}/`));
228824
- const agentDir = relative7(await realpath3(root3), cwd).split(sep3).join("/") || ".";
228841
+ const agentDir = relative8(await realpath3(root3), cwd).split(sep3).join("/") || ".";
228825
228842
  for (const path7 of new Set(candidates)) {
228826
228843
  if (selected2.has(path7) && definition3(path7)) {
228827
228844
  throw new AnchaError("CONFIG_INVALID", `${path7} is one of the project's tests or its config, which stay with the grader`, {
@@ -228860,7 +228877,7 @@ ${conflicts.map(([path7, set2]) => `${path7} (${[...set2].sort().join(", ")})`).
228860
228877
  init_src();
228861
228878
  init_credentials();
228862
228879
  import { access as access7, mkdir as mkdir12, mkdtemp as mkdtemp3, rename as rename3, rm as rm2, writeFile as writeFile10 } from "node:fs/promises";
228863
- import { dirname as dirname10, join as join23 } from "node:path";
228880
+ import { dirname as dirname10, join as join24 } from "node:path";
228864
228881
  import { setTimeout as sleep9 } from "node:timers/promises";
228865
228882
 
228866
228883
  // backend/src/cloud/bundle.ts
@@ -228870,7 +228887,7 @@ init_jobs_contract();
228870
228887
  import { createHash as createHash58 } from "node:crypto";
228871
228888
  import { constants as constants7 } from "node:fs";
228872
228889
  import { lstat as lstat3, open as open5, realpath as realpath4 } from "node:fs/promises";
228873
- import { join as join20 } from "node:path";
228890
+ import { join as join22 } from "node:path";
228874
228891
  import { crc32 as crc323, deflateRawSync as deflateRawSync2, gunzipSync as gunzipSync2 } from "node:zlib";
228875
228892
  var shared = jobs_contract_exports;
228876
228893
  var MIB2 = 1024 * 1024;
@@ -228879,19 +228896,19 @@ var sha2563 = (data5) => createHash58("sha256").update(data5).digest("hex");
228879
228896
  var mib2 = (bytes3) => `${(bytes3 / MIB2).toFixed(1)} MiB`;
228880
228897
  var tooBig = (message7, hint = "leave large files out with .anchaignore, or select the agent's files with agent.execution.files") => new AnchaError("CONFIG_INVALID", message7, { hint });
228881
228898
  async function readProjectFile(root3, path7) {
228882
- const file3 = join20(root3, ...path7.split("/"));
228883
- const stat19 = await lstat3(file3).catch(() => void 0);
228884
- if (stat19 === void 0) throw new AnchaError("CONFIG_INVALID", `${path7} is missing`, { hint: "restore it, or change what names it" });
228885
- if (stat19.isSymbolicLink()) throw new AnchaError("CONFIG_INVALID", `${path7} is a symbolic link; a cloud bundle carries regular files`, { hint: "copy what it points to into the project, or leave it out with .anchaignore" });
228886
- if (!stat19.isFile()) throw new AnchaError("CONFIG_INVALID", `${path7} is not a regular file`, { hint: "leave it out with .anchaignore" });
228887
- if (stat19.nlink > 1) throw new AnchaError("CONFIG_INVALID", `${path7} is a hard link; a cloud bundle carries files with one name`, { hint: "copy it to a file of its own, or leave it out with .anchaignore" });
228899
+ const file3 = join22(root3, ...path7.split("/"));
228900
+ const stat20 = await lstat3(file3).catch(() => void 0);
228901
+ if (stat20 === void 0) throw new AnchaError("CONFIG_INVALID", `${path7} is missing`, { hint: "restore it, or change what names it" });
228902
+ if (stat20.isSymbolicLink()) throw new AnchaError("CONFIG_INVALID", `${path7} is a symbolic link; a cloud bundle carries regular files`, { hint: "copy what it points to into the project, or leave it out with .anchaignore" });
228903
+ if (!stat20.isFile()) throw new AnchaError("CONFIG_INVALID", `${path7} is not a regular file`, { hint: "leave it out with .anchaignore" });
228904
+ if (stat20.nlink > 1) throw new AnchaError("CONFIG_INVALID", `${path7} is a hard link; a cloud bundle carries files with one name`, { hint: "copy it to a file of its own, or leave it out with .anchaignore" });
228888
228905
  if (await realpath4(file3) !== file3) throw new AnchaError("CONFIG_INVALID", `${path7} reaches outside the project through a symbolic link`, { hint: "copy the files into the project, or leave the folder out with .anchaignore" });
228889
- if (stat19.size > shared.BUNDLE_LIMITS.fileBytes) throw tooBig(`${path7} holds ${mib2(stat19.size)}; a file in a cloud bundle holds at most ${mib2(shared.BUNDLE_LIMITS.fileBytes)}`);
228906
+ if (stat20.size > shared.BUNDLE_LIMITS.fileBytes) throw tooBig(`${path7} holds ${mib2(stat20.size)}; a file in a cloud bundle holds at most ${mib2(shared.BUNDLE_LIMITS.fileBytes)}`);
228890
228907
  const handle30 = await open5(file3, constants7.O_RDONLY | constants7.O_NOFOLLOW);
228891
228908
  try {
228892
228909
  const data5 = await handle30.readFile();
228893
- if (data5.length !== stat19.size) throw new AnchaError("CONFIG_INVALID", `${path7} changed while it was read`, { hint: "run the command again" });
228894
- return { data: data5, executable: (stat19.mode & 73) !== 0 };
228910
+ if (data5.length !== stat20.size) throw new AnchaError("CONFIG_INVALID", `${path7} changed while it was read`, { hint: "run the command again" });
228911
+ return { data: data5, executable: (stat20.mode & 73) !== 0 };
228895
228912
  } finally {
228896
228913
  await handle30.close();
228897
228914
  }
@@ -229114,7 +229131,7 @@ function formatTable(rows33) {
229114
229131
 
229115
229132
  // packages/cli/src/onboarding.ts
229116
229133
  import { access as access6 } from "node:fs/promises";
229117
- import { resolve as resolve16 } from "node:path";
229134
+ import { resolve as resolve17 } from "node:path";
229118
229135
  init_src();
229119
229136
  init_credentials();
229120
229137
  var CHECKS = [["agentConnected", "Agent uploaded", "Upload your agent"], ["testsAdded", "Tests added", "Add tests"], ["firstGradedCloudRun", "Tests run in the cloud", "Run your tests"]];
@@ -229135,7 +229152,7 @@ async function listsTests(ctx) {
229135
229152
  async function nextFromHere(ctx, onboarding) {
229136
229153
  const { checks: checks2, nextCommand } = withOwnNext(onboarding);
229137
229154
  const open13 = CHECKS.find(([key4]) => !checks2[key4].done)?.[0];
229138
- const configured = ctx.globals().config !== void 0 || await access6(resolve16(ctx.io.cwd, "ancha.yaml")).then(() => true, () => false);
229155
+ const configured = ctx.globals().config !== void 0 || await access6(resolve17(ctx.io.cwd, "ancha.yaml")).then(() => true, () => false);
229139
229156
  if (open13 === "testsAdded" || open13 === void 0) return configured && await listsTests(ctx) ? [NEXT_COMMANDS.firstGradedCloudRun] : [nextCommand];
229140
229157
  if (open13 !== "agentConnected" && open13 !== "firstGradedCloudRun") return [nextCommand];
229141
229158
  return configured ? [nextCommand] : [INIT, nextCommand];
@@ -229199,21 +229216,21 @@ function onThisComputer(ref22) {
229199
229216
  }
229200
229217
  var CLOUD_JOB_FILE = "cloud-job.json";
229201
229218
  async function cachedCloudRun(ctx, id14, runsDir) {
229202
- const dir2 = join23(runsDir, id14);
229203
- if (await access7(join23(dir2, CLOUD_JOB_FILE)).then(() => true, () => false)) return dir2;
229219
+ const dir2 = join24(runsDir, id14);
229220
+ if (await access7(join24(dir2, CLOUD_JOB_FILE)).then(() => true, () => false)) return dir2;
229204
229221
  if (!shared.RUN_CLOUD_ID.test(id14)) throw new AnchaError("USAGE", `${id14} is not a cloud run; a connection check has no run report`, { hint: `ancha runs show ${id14}` });
229205
229222
  const ws = await jobWorkspace(ctx, id14), detail3 = await getJob(ws, id14);
229206
229223
  if (!shared.TERMINAL_JOB_STATES.includes(detail3.job.state)) throw new AnchaError("SESSION_CONFLICT", `${id14} has not finished`, { hint: `ancha wait ${id14}, then ancha report ${id14} --html` });
229207
229224
  const archive = await getArchive(ws, id14), manifest2 = validateBundle(archive);
229208
229225
  if (manifest2.runId !== id14 || manifest2.source !== "cloud") throw new AnchaError("INTERNAL", `the workspace answered another run's archive for ${id14}`);
229209
229226
  await mkdir12(runsDir, { recursive: true });
229210
- const temp = await mkdtemp3(join23(runsDir, `.${id14}-`));
229227
+ const temp = await mkdtemp3(join24(runsDir, `.${id14}-`));
229211
229228
  try {
229212
229229
  for (const entry3 of readBundle(archive)) {
229213
- await mkdir12(dirname10(join23(temp, entry3.path)), { recursive: true });
229214
- await writeFile10(join23(temp, entry3.path), entry3.data, { mode: 384 });
229230
+ await mkdir12(dirname10(join24(temp, entry3.path)), { recursive: true });
229231
+ await writeFile10(join24(temp, entry3.path), entry3.data, { mode: 384 });
229215
229232
  }
229216
- await writeFile10(join23(temp, CLOUD_JOB_FILE), `${JSON.stringify(detail3, null, 2)}
229233
+ await writeFile10(join24(temp, CLOUD_JOB_FILE), `${JSON.stringify(detail3, null, 2)}
229217
229234
  `, { mode: 384 });
229218
229235
  await rm2(dir2, { recursive: true, force: true });
229219
229236
  await rename3(temp, dir2);
@@ -229613,8 +229630,8 @@ async function forward(ctx, serverUrl3, words8, raw3) {
229613
229630
  argv.push(arg);
229614
229631
  continue;
229615
229632
  }
229616
- const path7 = resolve17(ctx.io.cwd, value5), name5 = basename7(path7).replace(/[^A-Za-z0-9._-]/g, "-").replace(/^[^A-Za-z0-9]+/, "").slice(0, 100) || "file";
229617
- const content2 = await readFile11(path7).catch(() => void 0);
229633
+ const path7 = resolve18(ctx.io.cwd, value5), name5 = basename7(path7).replace(/[^A-Za-z0-9._-]/g, "-").replace(/^[^A-Za-z0-9]+/, "").slice(0, 100) || "file";
229634
+ const content2 = await readFile12(path7).catch(() => void 0);
229618
229635
  if (content2 === void 0) {
229619
229636
  if (flag5 === "--test") {
229620
229637
  argv.push(flag5, value5);
@@ -229631,9 +229648,9 @@ async function forward(ctx, serverUrl3, words8, raw3) {
229631
229648
  argv.push(arg);
229632
229649
  continue;
229633
229650
  }
229634
- const name5 = slug11(optionValue(args, "--name") ?? (words8[1] === "update" ? args[0] : basename7(resolve17(ctx.io.cwd, value5))));
229651
+ const name5 = slug11(optionValue(args, "--name") ?? (words8[1] === "update" ? args[0] : basename7(resolve18(ctx.io.cwd, value5))));
229635
229652
  await refuseWhileConnecting(server, key4, words8[1] === "update" ? args[0] : void 0, optionValue(args, "--name"));
229636
- const uploaded = await uploadProject(server, key4, name5, resolve17(ctx.io.cwd, value5));
229653
+ const uploaded = await uploadProject(server, key4, name5, resolve18(ctx.io.cwd, value5));
229637
229654
  argv.push("--cwd", uploaded.project_path);
229638
229655
  } else argv.push(arg);
229639
229656
  }
@@ -229742,18 +229759,18 @@ function withWorkspace(line2, workspace4) {
229742
229759
  }
229743
229760
  }
229744
229761
  async function packProject(dir2) {
229745
- const root3 = resolve17(dir2);
229746
- if (!(await stat4(root3).catch(() => void 0))?.isDirectory()) throw new AnchaError("USAGE", `${dir2} is not a folder`, { hint: "pass the agent project folder to --cwd" });
229762
+ const root3 = resolve18(dir2);
229763
+ if (!(await stat5(root3).catch(() => void 0))?.isDirectory()) throw new AnchaError("USAGE", `${dir2} is not a folder`, { hint: "pass the agent project folder to --cwd" });
229747
229764
  const files2 = await projectFiles(root3);
229748
229765
  if (files2.length === 0) throw new AnchaError("USAGE", `${dir2} has no files to upload`, { hint: "check .gitignore and .anchaignore" });
229749
229766
  let bytes3 = 0;
229750
- for (const path7 of files2) bytes3 += (await stat4(join24(root3, path7))).size;
229767
+ for (const path7 of files2) bytes3 += (await stat5(join25(root3, path7))).size;
229751
229768
  if (bytes3 > MAX_PROJECT_BYTES) throw new AnchaError("USAGE", `${dir2} holds ${(bytes3 / 1024 / 1024).toFixed(1)} MB to upload; the limit is 200 MB`, { hint: "leave large files out with .anchaignore" });
229752
- const temporary = await mkdtemp4(join24(tmpdir3(), "ancha-pack-"));
229769
+ const temporary = await mkdtemp4(join25(tmpdir3(), "ancha-pack-"));
229753
229770
  try {
229754
- await writeFile11(join24(temporary, "files"), files2.join("\0"));
229755
- await run3("tar", ["-czf", join24(temporary, "project.tar.gz"), "-C", root3, "--null", "-T", join24(temporary, "files")], { maxBuffer: 16 * 1024 * 1024 });
229756
- return { archive: await readFile11(join24(temporary, "project.tar.gz")), files: files2.length, bytes: bytes3 };
229771
+ await writeFile11(join25(temporary, "files"), files2.join("\0"));
229772
+ await run3("tar", ["-czf", join25(temporary, "project.tar.gz"), "-C", root3, "--null", "-T", join25(temporary, "files")], { maxBuffer: 16 * 1024 * 1024 });
229773
+ return { archive: await readFile12(join25(temporary, "project.tar.gz")), files: files2.length, bytes: bytes3 };
229757
229774
  } finally {
229758
229775
  await rm3(temporary, { recursive: true, force: true });
229759
229776
  }
@@ -233504,7 +233521,8 @@ async function replayRun(ctx, input4, runId2, detach) {
233504
233521
  throw new AnchaError("SESSION_CONFLICT", `the run with this --idempotency-key is ${state3.state}: ${runId2}`, { hint: `ancha wait ${runId2}${input4.out === void 0 ? "" : ` --out ${input4.out}`}` });
233505
233522
  }
233506
233523
  const summary = await loadRunSummary(ctx.io.cwd, runId2, input4.out);
233507
- ctx.exitCode = state3.exitCode ?? 0;
233524
+ ctx.exitCode = state3.exitCode ?? 3;
233525
+ if (state3.error) ctx.out.error(new AnchaError(state3.error.code, state3.error.message));
233508
233526
  if (ctx.out.json) ctx.out.event({ event: "run_finished", summary, next: nextAfterRun(summary, { out: nonDefaultOut(ctx.io.cwd, input4.out) }), replayed: true, ...state3.upload !== void 0 && { upload: state3.upload } });
233509
233527
  else ctx.out.result(summary, () => `replayed run ${runId2} (same --idempotency-key)
233510
233528
 
@@ -234886,9 +234904,12 @@ function registerStatus(program2, ctx) {
234886
234904
  }
234887
234905
  const id14 = await resolveRunId(ctx.io.cwd, ref22, opts.out);
234888
234906
  const state3 = await readRunState(resolve37(ctx.io.cwd, opts.out ?? DEFAULT_RUNS_DIR), id14);
234889
- ctx.out.result(state3, () => `${state3.runId} ${state3.state} ${state3.completedTrials}/${state3.totalTrials}`);
234907
+ ctx.out.result(state3, () => `${state3.runId} ${state3.state} ${state3.completedTrials}/${state3.totalTrials}${state3.error ? `
234908
+ ${state3.error.message}` : ""}`);
234909
+ if (terminal(state3) && state3.exitCode === void 0) ctx.exitCode = 3;
234890
234910
  });
234891
234911
  program2.command("wait").description("observe a run until completion; interrupting the observer leaves the run active").argument("<id>", "run id (run_\u2026, run_cloud_\u2026)").option("--out <dir>", "run directory (default: .ancha/runs)").action(async (id14, opts) => {
234912
+ if (id14 === "latest") id14 = await latestRunId(ctx.io.cwd, opts.out);
234892
234913
  if (isCloudId(id14)) {
234893
234914
  const ws = await jobWorkspace(ctx, id14);
234894
234915
  const status5 = await getStatus(ws, id14);
@@ -234902,6 +234923,7 @@ function registerStatus(program2, ctx) {
234902
234923
  const state3 = await readRunState(resolve37(ctx.io.cwd, opts.out ?? DEFAULT_RUNS_DIR), id14);
234903
234924
  if (terminal(state3)) {
234904
234925
  if (state3.state === "finished") {
234926
+ if (state3.error) ctx.out.error(new AnchaError(state3.error.code, state3.error.message));
234905
234927
  emitFinished(ctx, await loadRunSummary(ctx.io.cwd, id14, opts.out), opts.out, state3.upload);
234906
234928
  if (!ctx.out.json && state3.upload !== void 0 && "error" in state3.upload) ctx.out.info(`${state3.upload.required ? "error" : "warning"}: ${state3.upload.error.message}${state3.upload.error.hint !== void 0 ? `
234907
234929
  hint: ${state3.upload.error.hint}` : ""}`);
@@ -234947,6 +234969,8 @@ hint: ${state3.upload.error.hint}` : ""}`);
234947
234969
  for (const line2 of complete.slice(printed)) ctx.out.event(JSON.parse(line2));
234948
234970
  printed = complete.length;
234949
234971
  if (!opts.follow || terminal(state3)) {
234972
+ if (printed === 0) ctx.out.result({ runId: id14, events: [], message: "No events were recorded for this run." }, () => "No events were recorded for this run.");
234973
+ if (terminal(state3) && state3.exitCode === void 0 && state3.error) ctx.exitCode = ctx.out.error(new AnchaError(state3.error.code, state3.error.message));
234950
234974
  if (opts.follow) ctx.exitCode = state3.exitCode ?? 3;
234951
234975
  return;
234952
234976
  }
@@ -237576,7 +237600,7 @@ function parseTools(value5) {
237576
237600
  }
237577
237601
  return SUPPORTED_TWINS.filter((twin) => names5.some((name5) => key4(twin) === key4(name5) || key4(toolName(twin)) === key4(name5)));
237578
237602
  }
237579
- async function wireExistingConfig(cwd) {
237603
+ async function wireExistingConfig(cwd, fillMissing) {
237580
237604
  const target5 = join56(cwd, "ancha.yaml");
237581
237605
  let text29;
237582
237606
  try {
@@ -237592,10 +237616,11 @@ async function wireExistingConfig(cwd) {
237592
237616
  }
237593
237617
  if (agent === void 0 || agent.mode === "endpoint" || !agent.command) return void 0;
237594
237618
  const task2 = await taskSetup(cwd, agent.command, { command: agent.command, env: agent.env, ...agent.input !== void 0 && { input: agent.input }, ...agent.answer !== void 0 && { answer: agent.answer } });
237619
+ if (!fillMissing || task2.wiring?.command !== void 0 || Object.keys(task2.wiring?.env ?? {}).some((name5) => Object.hasOwn(agent.env ?? {}, name5))) task2.wiring = null;
237620
+ if (!fillMissing) task2.stdin = null;
237595
237621
  if (task2.wiring === null && task2.stdin === null) return task2;
237596
237622
  const doc = (0, import_yaml17.parseDocument)(text29);
237597
237623
  for (const [name5, value5] of Object.entries(task2.wiring?.env ?? {})) doc.setIn(["agent", "env", name5], value5);
237598
- if (task2.wiring?.command !== void 0) doc.setIn(["agent", "command"], task2.wiring.command);
237599
237624
  if (task2.stdin !== null) doc.setIn(["agent", "input"], "stdin");
237600
237625
  const next2 = doc.toString({ lineWidth: 0 });
237601
237626
  try {
@@ -237639,12 +237664,12 @@ function registerKit(program2, ctx) {
237639
237664
  const unchecked = twins.filter((twin) => !hasAccessCheck(twin));
237640
237665
  const defaultTemplate = opts.template === "starter" && command.getOptionValueSource("template") !== "cli";
237641
237666
  const own2 = opts.template === "starter" ? await ownStarter(ctx.io.cwd) : void 0;
237642
- const existing2 = defaultTemplate ? (await glob3("scenes/**/scene.yaml", { cwd: ctx.io.cwd, onlyFiles: true, followSymbolicLinks: false })).sort().filter((path7) => own2 === void 0 || path7 !== "scenes/starter/scene.yaml") : [];
237667
+ const existing2 = defaultTemplate ? (await glob3(["scenes/**/scene.yaml", "ancha/tests/**/*.{yaml,yml}", ...existingConfig?.scenes ?? []], { cwd: ctx.io.cwd, onlyFiles: true, followSymbolicLinks: false })).sort().filter((path7) => own2 === void 0 || path7 !== "scenes/starter/scene.yaml") : [];
237643
237668
  const cloud = await cloudWorkspace(ctx, { code: "USAGE", message: "no workspace", hint: "" }).then(() => true, () => false);
237644
237669
  const noStarter = defaultTemplate && (existing2.length > 0 || cloud);
237645
237670
  const starter = opts.template === "starter" && (!noStarter || own2 !== void 0);
237646
237671
  const tests = (await glob3(["scenes/**/scene.yaml", "ancha/tests/**/*.yaml", ...existingConfig?.scenes ?? []], { cwd: ctx.io.cwd, onlyFiles: true, followSymbolicLinks: false })).filter((path7) => own2 === void 0 || path7 !== "scenes/starter/scene.yaml");
237647
- const traces = await lstat9(join56(ctx.io.cwd, "traces")).then((stat19) => stat19.isDirectory(), () => false);
237672
+ const traces = await lstat9(join56(ctx.io.cwd, "traces")).then((stat20) => stat20.isDirectory(), () => false);
237648
237673
  const dataSize = data5 === "none" ? void 0 : data5 !== void 0 ? data5.size : used.includes("netsuite") && opts.intent === void 0 && tests.length === 0 && !traces ? "m" : void 0;
237649
237674
  const pe = dataSize === void 0 ? void 0 : netsuiteData(dataSize);
237650
237675
  const existingTwins = await Promise.all(existing2.map((path7) => loadSceneFile(join56(ctx.io.cwd, path7)).then((scene2) => scene2.twins, () => [])));
@@ -237671,9 +237696,18 @@ min_pass_rate: 1
237671
237696
  }
237672
237697
  const result = await applyScaffold(ctx.io.cwd, files2.filter((file3) => !rewritten.includes(file3)));
237673
237698
  const agents = await installAgents(ctx.io.cwd);
237699
+ let savedCommand;
237674
237700
  if (configured) {
237675
- task2 = await wireExistingConfig(ctx.io.cwd);
237676
- if (task2?.wiring) updated.push("ancha.yaml");
237701
+ if (opts.agent !== void 0 && existingConfig !== void 0 && existingConfig.agent?.mode !== "endpoint" && !existingAgent?.command) {
237702
+ const doc = (0, import_yaml17.parseDocument)(configText);
237703
+ doc.setIn(["agent", "command"], opts.agent);
237704
+ const next3 = doc.toString({ lineWidth: 0, flowCollectionPadding: false });
237705
+ parseConfigText(next3);
237706
+ await rewrite(ctx.io.cwd, "ancha.yaml", next3);
237707
+ savedCommand = opts.agent;
237708
+ updated.push("ancha.yaml");
237709
+ } else task2 = await wireExistingConfig(ctx.io.cwd, opts.agent === void 0);
237710
+ if (task2?.wiring || task2?.stdin) updated.push("ancha.yaml");
237677
237711
  if (pe && await listTests(ctx.io.cwd, pe.tests) && !updated.includes("ancha.yaml")) updated.push("ancha.yaml");
237678
237712
  }
237679
237713
  if (agents === "created") result.created.push("AGENTS.md");
@@ -237695,7 +237729,15 @@ min_pass_rate: 1
237695
237729
  generated = { world: { id: world5.id, file: world5.world, people: world5.people, ...notGenerated.added.length > 0 && { exampleData: notGenerated.added } }, test: { id: test3.id, file: test3.file, checks: test3.checks }, ...(world5.modelCredit ?? test3.modelCredit) && { modelCredit: "workspace" } };
237696
237730
  result.created.push(...world5.files, test3.file, test3.record);
237697
237731
  }
237698
- const runs = existingAgent?.command ? { command: existingAgent.command, source: "ancha.yaml" } : detection.agent === null ? void 0 : { command: detection.agent, source: detection.agentSource };
237732
+ const savedConfig = await readFile41(join56(ctx.io.cwd, "ancha.yaml"), "utf8").then((text29) => {
237733
+ try {
237734
+ return parseConfigText(text29);
237735
+ } catch {
237736
+ return void 0;
237737
+ }
237738
+ });
237739
+ const savedAgent = savedConfig?.agent;
237740
+ const runs = savedAgent?.mode === "endpoint" || !savedAgent?.command ? void 0 : { command: savedAgent.command, source: "ancha.yaml" };
237699
237741
  const next2 = runs === void 0 ? ["set agent.command in ancha.yaml", cloud ? "ancha agent upload" : "ancha run"] : generated ? cloud ? ["ancha agent upload", `ancha run ${generated.test.file}`] : [`ancha run ${generated.test.file}`] : cloud ? ["ancha agent upload", starter || existing2.length > 0 || pe ? "ancha run" : "ancha traces upload ./traces"] : ["ancha run"];
237700
237742
  const taskInput = task2 === void 0 ? void 0 : {
237701
237743
  native: task2.scan.native,
@@ -237708,18 +237750,19 @@ min_pass_rate: 1
237708
237750
  };
237709
237751
  const agentTools3 = { tools: used, given: given2 !== void 0, ...given2 === void 0 && { from: found.from } };
237710
237752
  const dataOutput = pe && { dataset: `netsuite-pe@${NETSUITE_PE_VERSION}`, size: pe.size, world: pe.world, evals: pe.evals, tests: pe.tests.length, subsidiaries: pe.counts.subsidiaries ?? 0, transactions: pe.counts.transactions ?? 0 };
237711
- const output2 = { ...result, updated, detection, template: opts.template, agentTools: agentTools3, ...starter && { tools: twins, ...unchecked.length > 0 && { unchecked } }, ...existing2.length > 0 && { scenes: existing2 }, ...dataOutput && { data: dataOutput }, ...generated, ...taskInput && { taskInput }, next: next2 };
237712
- const agent = runs === void 0 ? "no start command found (package.json scripts.start, Procfile, pyproject.toml, Dockerfile)" : `${runs.command}${runs.source === "explicit" ? "" : ` (from ${runs.source})`}`;
237753
+ const output2 = { ...result, updated, detection, ...savedCommand !== void 0 && { savedCommand }, template: opts.template, agentTools: agentTools3, ...starter && { tools: twins, ...unchecked.length > 0 && { unchecked } }, ...existing2.length > 0 && { scenes: existing2 }, ...dataOutput && { data: dataOutput }, ...generated, ...taskInput && { taskInput }, next: next2 };
237754
+ const agent = runs === void 0 ? "no start command in ancha.yaml; set agent.command to start your agent" : `${runs.command} (from ${runs.source})`;
237713
237755
  const names5 = (list18) => list18.map(toolName).join(", ");
237714
237756
  ctx.out.result(output2, () => [
237715
237757
  `Created ${result.created.length} files; updated ${updated.length}; preserved ${result.skipped.length}.`,
237716
237758
  `agent: ${agent}`,
237759
+ ...savedCommand !== void 0 ? ["Saved agent.command in ancha.yaml."] : [],
237717
237760
  // The tools it uses, and where each one showed: what the coding agent confirms with the person (SPEC-053, Jay).
237718
237761
  given2 !== void 0 ? `tools: ${names5(given2)} (from --tools)` : used.length > 0 ? `tools: ${used.map((twin) => `${toolName(twin)} (from ${found.from[twin]})`).join(", ")}` : "tools: none found in its dependencies or source; name them with ancha init --tools <tools>, e.g. --tools netsuite,slack",
237719
237762
  ...task2 !== void 0 ? [taskLine(task2), answerLine(task2)] : [],
237720
237763
  ...task2 !== void 0 && netsuiteLine(task2, !configured && mapsNetsuite) !== void 0 ? [netsuiteLine(task2, !configured && mapsNetsuite)] : [],
237721
237764
  ...starter ? [`starter: ${names5(twins)}${used.length > 0 ? "" : " (the template's tools)"}${rewritten.length > 0 && own2 !== void 0 ? `; rewritten from the one an earlier ancha init wrote for ${names5(own2)}` : ""}`] : [],
237722
- ...existing2.length > 0 ? [`scenes: ${existing2.length} already in scenes/ (${existing2.slice(0, 2).join(", ")}${existing2.length > 2 ? ", \u2026" : ""})${result.created.includes("ancha.yaml") ? "; ancha.yaml runs them" : ""}; ancha init --template starter adds the starter test`] : [],
237765
+ ...existing2.length > 0 ? [`scenes: ${existing2.length} already in this project (${existing2.slice(0, 2).join(", ")}${existing2.length > 2 ? ", \u2026" : ""}); ancha init --template starter adds the starter test`] : [],
237723
237766
  ...starter && unchecked.length > 0 ? [` ${names5(unchecked)}: seeded; no access check, since ${unchecked.length === 1 ? "its" : "their"} requests need signing or a token exchange; add checks of your own`] : [],
237724
237767
  ...dataOutput ? [`data: NetSuite world ${pe.id} (${dataOutput.subsidiaries} subsidiaries, ${dataOutput.transactions.toLocaleString("en-US")} transactions) and ${dataOutput.tests} tests (10 read tasks, 15 write workflows)`] : [],
237725
237768
  ...generated ? [`world: ${generated.world.file} (people: ${generated.world.people.join(", ") || "none"})`] : [],
@@ -239459,6 +239502,8 @@ var CliRuns = class {
239459
239502
  init_src();
239460
239503
  init_baselines();
239461
239504
  init_privacy();
239505
+ init_src();
239506
+ init_run_inputs();
239462
239507
  function withToolViews(evidence2) {
239463
239508
  const state3 = evidence2.state && typeof evidence2.state === "object" ? evidence2.state : {};
239464
239509
  return { ...evidence2, toolViews: Object.fromEntries(Object.entries(state3).map(([tool, value5]) => [tool, toolDataView(tool, value5)])) };
@@ -240878,9 +240923,22 @@ ${TEST_RUN_HINT}`);
240878
240923
  ctx.out.result(saved, () => `${saved.name}: ${saved.id}
240879
240924
  Run again with ancha test run ${saved.id}`);
240880
240925
  });
240881
- tests.command("list").description("list saved tests").action(async () => {
240926
+ tests.command("list").description("list project test files and saved tests").action(async () => {
240882
240927
  const result = await withSetups(ctx, (store) => store.list());
240883
- ctx.out.result(result, () => [...result.setups.map((saved) => `${saved.id} ${saved.name} ${saved.scenes.length} scenarios \xD7 ${saved.trials} attempts`), ...result.errors.map((error65) => `${error65.id}: ${error65.message}`)].join("\n") || "No saved tests. Use ancha test save after a completed run.");
240928
+ let scenes = [];
240929
+ try {
240930
+ scenes = (await ctx.loadConfig()).scenes;
240931
+ } catch (error65) {
240932
+ const problem = toErrorJson(error65);
240933
+ ctx.io.stderr.write(`warning[${problem.code}]: test file discovery: ${problem.message.replaceAll("\n", " ")}
240934
+ `);
240935
+ }
240936
+ const files2 = (await glob3([...scenes, "scenes/**/scene.yaml", "ancha/tests/**/*.{yaml,yml}"], { cwd: ctx.io.cwd, onlyFiles: true, followSymbolicLinks: false })).sort();
240937
+ ctx.out.result({ ...result, files: files2 }, () => [
240938
+ ...result.setups.map((saved) => `${saved.id} ${saved.name} ${saved.scenes.length} scenarios \xD7 ${saved.trials} attempts`),
240939
+ ...result.errors.map((error65) => `${error65.id}: ${error65.message}`),
240940
+ ...files2.length ? ["Test files (run with ancha run <file>):", ...files2] : []
240941
+ ].join("\n") || "No tests. Create one with ancha test new or import evals with ancha test import.");
240884
240942
  });
240885
240943
  tests.command("show").argument("<id>").description("show the agent, scenarios, repetitions and pinned versions").action(async (id14) => {
240886
240944
  const saved = await withSetups(ctx, (store) => store.get(id14));
@@ -260219,8 +260277,8 @@ function registerWorldRecord(command, ctx) {
260219
260277
  }
260220
260278
  let input4;
260221
260279
  try {
260222
- const stat19 = await handle30.stat();
260223
- if (!stat19.isFile() || stat19.size > 64e6) throw new AnchaError("USAGE", "pytest record must be a regular file of at most 64 MB");
260280
+ const stat20 = await handle30.stat();
260281
+ if (!stat20.isFile() || stat20.size > 64e6) throw new AnchaError("USAGE", "pytest record must be a regular file of at most 64 MB");
260224
260282
  const text29 = await handle30.readFile("utf8");
260225
260283
  if (Buffer.byteLength(text29) > 64e6) throw new AnchaError("USAGE", "pytest record exceeds 64 MB");
260226
260284
  try {
@@ -260252,7 +260310,11 @@ function registerWorld(program2, ctx) {
260252
260310
  });
260253
260311
  command.command("list").option("--include-archived", "include archived worlds").action(async (options4) => {
260254
260312
  const value5 = await withService(ctx, (service) => service.worlds({ includeArchived: options4.includeArchived }));
260255
- ctx.out.result(value5, () => formatTable(value5.worlds.map((world5) => [world5.id, world5.name, String(world5.revision), world5.configuration.preset.datasets.map((data5) => data5.tool).join(", ")])));
260313
+ const files2 = (await glob3("ancha/worlds/**/*.{yaml,yml}", { cwd: ctx.io.cwd, onlyFiles: true, followSymbolicLinks: false })).sort();
260314
+ ctx.out.result({ ...value5, files: files2 }, () => [
260315
+ ...value5.worlds.length ? [formatTable(value5.worlds.map((world5) => [world5.id, world5.name, String(world5.revision), world5.configuration.preset.datasets.map((data5) => data5.tool).join(", ")]))] : [],
260316
+ ...files2.length ? ["World files:", ...files2] : []
260317
+ ].join("\n") || "No worlds. Create one with ancha world gen or ancha world create.");
260256
260318
  });
260257
260319
  command.command("show").argument("<id>").option("--revision <number>", "historical revision").action(async (id14, options4) => {
260258
260320
  const value5 = await withService(ctx, (service) => service.world(id14, options4.revision ? integer12(options4.revision, "revision") : void 0));
@@ -260689,7 +260751,7 @@ function registerSchema(program2, ctx) {
260689
260751
  // packages/cli/src/commands/runs.ts
260690
260752
  var import_yaml20 = __toESM(require_dist(), 1);
260691
260753
  init_src();
260692
- import { mkdir as mkdir33, readFile as readFile53, writeFile as writeFile36 } from "node:fs/promises";
260754
+ import { mkdir as mkdir33, readFile as readFile53, stat as stat17, writeFile as writeFile36 } from "node:fs/promises";
260693
260755
  import { basename as basename14, join as join69, relative as relative22, resolve as resolve52 } from "node:path";
260694
260756
  init_report2();
260695
260757
  init_run_store();
@@ -260910,6 +260972,16 @@ next page: ancha runs list --cursor ${page18.nextCursor}`}`);
260910
260972
  onThisComputer(ref22);
260911
260973
  const summary = await loadRunSummary(ctx.io.cwd, ref22, options4.out);
260912
260974
  const dest = resolve52(ctx.io.cwd, options4.dest ?? join69(".ancha", "exports", summary.runId));
260975
+ for (const scene2 of summary.scenes) for (const trial of scene2.trialsDetail) {
260976
+ const trace = join69(resolve52(ctx.io.cwd, trial.dir), "trace.jsonl");
260977
+ const recorded2 = await stat17(trace).then((file3) => file3.isFile(), (error65) => {
260978
+ if (error65.code === "ENOENT") return false;
260979
+ throw error65;
260980
+ });
260981
+ if (!recorded2) throw new AnchaError("USAGE", `Cannot export ${summary.runId}: ${scene2.sceneId} attempt ${trial.trial} has no recorded world trace.`, {
260982
+ hint: `ancha report ${summary.runId}${options4.out === void 0 ? "" : ` --out ${shellWord(options4.out)}`} shows the saved result; export a run with captured world traces`
260983
+ });
260984
+ }
260913
260985
  await mkdir33(dest, { recursive: true });
260914
260986
  const inputs2 = await readFile53(join69(resolve52(ctx.io.cwd, options4.out ?? DEFAULT_RUNS_DIR), summary.runId, "inputs.json"), "utf8").then((text29) => JSON.parse(text29), () => ({}));
260915
260987
  const files2 = [], cases = withSeeds(inputs2.cases ?? []);
@@ -260994,7 +261066,7 @@ next: ancha wait ${id14}`);
260994
261066
 
260995
261067
  // packages/cli/src/commands/traces.ts
260996
261068
  import { createHash as createHash77 } from "node:crypto";
260997
- import { access as access15, readFile as readFile55, mkdir as mkdir34, stat as stat18, writeFile as writeFile37 } from "node:fs/promises";
261069
+ import { access as access15, readFile as readFile55, mkdir as mkdir34, stat as stat19, writeFile as writeFile37 } from "node:fs/promises";
260998
261070
  import { basename as basename16, dirname as dirname25, join as join70, relative as relative25, resolve as resolve54 } from "node:path";
260999
261071
  import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util";
261000
261072
  var import_yaml21 = __toESM(require_dist(), 1);
@@ -261121,7 +261193,7 @@ async function listTraces(source, { limit: limit2, since, name: name5 }, env2, f
261121
261193
  }
261122
261194
 
261123
261195
  // packages/cli/src/trace-files.ts
261124
- import { readFile as readFile54, stat as stat17 } from "node:fs/promises";
261196
+ import { readFile as readFile54, stat as stat18 } from "node:fs/promises";
261125
261197
  import { basename as basename15, relative as relative23, resolve as resolve53 } from "node:path";
261126
261198
  init_src();
261127
261199
  var MB3 = 1024 * 1024;
@@ -261132,7 +261204,7 @@ async function findTraceFiles(cwd, args) {
261132
261204
  const found = /* @__PURE__ */ new Set();
261133
261205
  for (const arg of args) {
261134
261206
  const path7 = resolve53(cwd, arg);
261135
- const kind2 = await stat17(path7).then((s3) => s3.isDirectory() ? "dir" : s3.isFile() ? "file" : void 0, () => void 0);
261207
+ const kind2 = await stat18(path7).then((s3) => s3.isDirectory() ? "dir" : s3.isFile() ? "file" : void 0, () => void 0);
261136
261208
  if (kind2 === "file") {
261137
261209
  found.add(path7);
261138
261210
  continue;
@@ -262099,7 +262171,7 @@ function registerTraces(program2, ctx) {
262099
262171
  } else {
262100
262172
  texts4 = await readTraceTexts(ctx.io.cwd, await findTraceFiles(ctx.io.cwd, paths2));
262101
262173
  const one7 = paths2.length === 1 ? resolve54(ctx.io.cwd, paths2[0]) : void 0;
262102
- name5 = one7 && await stat18(one7).then(() => true, () => false) ? basename16(one7).slice(0, 80) : "traces";
262174
+ name5 = one7 && await stat19(one7).then(() => true, () => false) ? basename16(one7).slice(0, 80) : "traces";
262103
262175
  }
262104
262176
  const { units, skipped, read: read7 } = await traceUnits(texts4);
262105
262177
  if (!units.length) {