@tangle-network/agent-eval 2.0.19 → 2.0.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.
Files changed (31) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/benchmarks/index.js +2 -2
  3. package/dist/campaign/index.js +6 -6
  4. package/dist/{campaign-CJRlis5N.js → campaign-DPB35MjP.js} +25 -8
  5. package/dist/{campaign-CJRlis5N.js.map → campaign-DPB35MjP.js.map} +1 -1
  6. package/dist/cli.js +2144 -25
  7. package/dist/cli.js.map +1 -1
  8. package/dist/contract/index.js +5 -5
  9. package/dist/{define-agent-eval-Dd6hFx0-.js → define-agent-eval-CBhYD7Gq.js} +3 -3
  10. package/dist/{define-agent-eval-Dd6hFx0-.js.map → define-agent-eval-CBhYD7Gq.js.map} +1 -1
  11. package/dist/index.js +4 -4
  12. package/dist/{llm-judge-Bf3p1WNA.js → llm-judge-DRHTRT66.js} +2 -2
  13. package/dist/{llm-judge-Bf3p1WNA.js.map → llm-judge-DRHTRT66.js.map} +1 -1
  14. package/dist/multishot/index.js +2 -2
  15. package/dist/openapi.json +1 -1
  16. package/dist/{optimization-method-BO2sb1m4.js → optimization-method-B-NFaHom.js} +3 -3
  17. package/dist/{optimization-method-BO2sb1m4.js.map → optimization-method-B-NFaHom.js.map} +1 -1
  18. package/dist/run-improvement-loop-D9IAZviC.d.ts.map +1 -1
  19. package/dist/search/index.js +2 -2
  20. package/dist/{search-kernel-D96Eibc_.js → search-kernel-DezUrquk.js} +3 -3
  21. package/dist/{search-kernel-D96Eibc_.js.map → search-kernel-DezUrquk.js.map} +1 -1
  22. package/dist/{search-summary-DjgKz7B1.js → search-summary-DOhRouoT.js} +2 -2
  23. package/dist/{search-summary-DjgKz7B1.js.map → search-summary-DOhRouoT.js.map} +1 -1
  24. package/dist/{self-improve-BiTuylQQ.js → self-improve-Dm9PvLF2.js} +2 -2
  25. package/dist/{self-improve-BiTuylQQ.js.map → self-improve-Dm9PvLF2.js.map} +1 -1
  26. package/dist/{skillopt-optimization-method-CJkejuSP.js → skillopt-optimization-method-QZoNbg57.js} +2 -2
  27. package/dist/{skillopt-optimization-method-CJkejuSP.js.map → skillopt-optimization-method-QZoNbg57.js.map} +1 -1
  28. package/dist/{tree-lU9KWuxr.js → tree-DBvepwFt.js} +2 -2
  29. package/dist/{tree-lU9KWuxr.js.map → tree-DBvepwFt.js.map} +1 -1
  30. package/docs/real-work.md +81 -0
  31. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,20 +1,26 @@
1
1
  #!/usr/bin/env node
2
- import { c as errorMessage, s as ValidationError } from "./errors-DeEEV9Vx.js";
2
+ import { c as errorMessage, r as ConfigError, s as ValidationError, t as AgentEvalError } from "./errors-DeEEV9Vx.js";
3
+ import { a as hashCanonical, i as compareCodeUnits } from "./canonical-DKgL_Wby.js";
3
4
  import { l as costForTokenPricing } from "./cost-ledger-ni6f77QJ.js";
4
5
  import { i as replaySearchLedgerText } from "./search-ledger-C7DywY8N.js";
5
- import { o as operatorYield, s as INSUFFICIENT_FROM } from "./search-kernel-D96Eibc_.js";
6
- import { t as renderSearchSummary } from "./search-summary-DjgKz7B1.js";
6
+ import { o as operatorYield, s as INSUFFICIENT_FROM } from "./search-kernel-DezUrquk.js";
7
+ import { n as isRecord, t as extractJsonPayload } from "./json-DtvZNAU9.js";
8
+ import { t as renderSearchSummary } from "./search-summary-DOhRouoT.js";
7
9
  import { l as SEARCH_LEDGER_BATCH_MAX_BYTES, m as SearchRunKindSchema, r as shipSearchLedger, s as hostedTenantFromEnv, t as SearchShipConflictError } from "./search-shipper-l6wUUWtc.js";
10
+ import { n as runBoundedProcess } from "./bounded-process-BZrWXIKW.js";
8
11
  import { n as createChatClient } from "./chat-client-TkNgQDLj.js";
9
12
  import { a as privacyHit, f as appendRolloutLines, n as runRolloutReleaseCli, r as PRIVACY_RULE_NAMES, u as gateReceiptRolloutLines } from "./hf-dataset-B0s2ZAhQ.js";
10
13
  import { i as harnessSessionRolloutLines, n as harnessSessionRefs } from "./harness-session-lines-CTh1-uOb.js";
11
14
  import { B as renderSkillUsageTable, H as claudeCodeSkillSessions, J as withChangeLedger, L as afterInvocation, R as buildSkillUsageReport, V as codexSkillSessions, W as readSkillFile, q as readChangeLedger, t as runAnalystBenchmarkCommand, z as instant } from "./benchmark-command-DOQeozeM.js";
12
15
  import { i as buildOpenApi, l as handleVersion, o as runRpcBatch, r as startServerAsync, s as runRpcOnce } from "./server-B-7vXS9T.js";
13
- import { b as editCreditText, f as landscape, g as surfaceTextEdits, l as metaSearch, m as formatLandscape, n as taskMatrix, o as skillManifold, r as formatSkillManifold, s as renderMetaSearchText, t as tree, v as front, y as editCredit } from "./tree-lU9KWuxr.js";
16
+ import { b as editCreditText, f as landscape, g as surfaceTextEdits, l as metaSearch, m as formatLandscape, n as taskMatrix, o as skillManifold, r as formatSkillManifold, s as renderMetaSearchText, t as tree, v as front, y as editCredit } from "./tree-DBvepwFt.js";
14
17
  import { a as analyzeSupervisorRun, i as renderSupervisorRunMarkdown, r as renderSupervisorRunHeadline, t as runtimeRunRolloutLines } from "./runtime-rollouts-CE0MbQPq.js";
15
- import { createHash } from "node:crypto";
16
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
17
- import { dirname, join, resolve } from "node:path";
18
+ import { createHash, randomUUID } from "node:crypto";
19
+ import { z } from "zod";
20
+ import { appendFileSync, chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
21
+ import { dirname, join, relative, resolve, sep } from "node:path";
22
+ import { hostname } from "node:os";
23
+ import { spawnSync } from "node:child_process";
18
24
  import { fileURLToPath, pathToFileURL } from "node:url";
19
25
  import { appendFile, open, readFile, rm, stat } from "node:fs/promises";
20
26
  // src/cli-config.ts
@@ -33,13 +39,13 @@ import { appendFile, open, readFile, rm, stat } from "node:fs/promises";
33
39
  * `llm_not_configured` instead of calling an unintended endpoint.
34
40
  */
35
41
  function resolveCliProviderRoute(env = process.env) {
36
- const explicitBaseUrl = nonEmpty(env.AGENT_EVAL_LLM_BASE_URL);
37
- const explicitApiKey = nonEmpty(env.AGENT_EVAL_LLM_API_KEY);
38
- const openAiApiKey = nonEmpty(env.OPENAI_API_KEY);
39
- const tangleApiKey = nonEmpty(env.TANGLE_API_KEY);
40
- const baseUrl = explicitBaseUrl ?? nonEmpty(env.OPENAI_BASE_URL) ?? nonEmpty(env.TANGLE_ROUTER_URL) ?? (openAiApiKey ? "https://api.openai.com/v1" : void 0) ?? (tangleApiKey ? "https://router.tangle.tools/v1" : void 0);
42
+ const explicitBaseUrl = nonEmpty$1(env.AGENT_EVAL_LLM_BASE_URL);
43
+ const explicitApiKey = nonEmpty$1(env.AGENT_EVAL_LLM_API_KEY);
44
+ const openAiApiKey = nonEmpty$1(env.OPENAI_API_KEY);
45
+ const tangleApiKey = nonEmpty$1(env.TANGLE_API_KEY);
46
+ const baseUrl = explicitBaseUrl ?? nonEmpty$1(env.OPENAI_BASE_URL) ?? nonEmpty$1(env.TANGLE_ROUTER_URL) ?? (openAiApiKey ? "https://api.openai.com/v1" : void 0) ?? (tangleApiKey ? "https://router.tangle.tools/v1" : void 0);
41
47
  const apiKey = explicitApiKey ?? openAiApiKey ?? tangleApiKey;
42
- const model = nonEmpty(env.AGENT_EVAL_LLM_MODEL) ?? nonEmpty(env.OPENAI_MODEL) ?? nonEmpty(env.TANGLE_MODEL);
48
+ const model = nonEmpty$1(env.AGENT_EVAL_LLM_MODEL) ?? nonEmpty$1(env.OPENAI_MODEL) ?? nonEmpty$1(env.TANGLE_MODEL);
43
49
  if (!baseUrl || !apiKey) return void 0;
44
50
  return {
45
51
  baseUrl,
@@ -81,7 +87,7 @@ function cliChatClient(route, defaultModel) {
81
87
  }
82
88
  };
83
89
  }
84
- function nonEmpty(value) {
90
+ function nonEmpty$1(value) {
85
91
  const trimmed = value?.trim();
86
92
  return trimmed ? trimmed : void 0;
87
93
  }
@@ -106,8 +112,8 @@ const FORMATS$2 = [
106
112
  "json",
107
113
  "table"
108
114
  ];
109
- const USAGE$2 = "usage: agent-eval skill-usage <sessions-dir> [--harness claude-code|codex] [--since <7d|36h|90m|ISO time>] [--format both|json|table] [--limit <rows>] [--pricing <rates.json>]";
110
- const PROCESS_IO$2 = {
115
+ const USAGE$3 = "usage: agent-eval skill-usage <sessions-dir> [--harness claude-code|codex] [--since <7d|36h|90m|ISO time>] [--format both|json|table] [--limit <rows>] [--pricing <rates.json>]";
116
+ const PROCESS_IO$3 = {
111
117
  stdout: (text) => {
112
118
  process.stdout.write(text);
113
119
  },
@@ -200,9 +206,9 @@ function readPricingFile(path) {
200
206
  }
201
207
  return rates;
202
208
  }
203
- async function runSkillUsageCommand(argv, io = PROCESS_IO$2) {
209
+ async function runSkillUsageCommand(argv, io = PROCESS_IO$3) {
204
210
  if (argv.includes("--help") || argv.includes("-h")) {
205
- io.stdout(`${USAGE$2}\n`);
211
+ io.stdout(`${USAGE$3}\n`);
206
212
  return 0;
207
213
  }
208
214
  let args;
@@ -213,7 +219,7 @@ async function runSkillUsageCommand(argv, io = PROCESS_IO$2) {
213
219
  rates = args.pricing === null ? void 0 : readPricingFile(resolve(args.pricing));
214
220
  sinceMs = args.since === null ? void 0 : parseSince(args.since, (io.now ?? Date.now)());
215
221
  } catch (error) {
216
- io.stderr(`${errorMessage(error)}\n${USAGE$2}\n`);
222
+ io.stderr(`${errorMessage(error)}\n${USAGE$3}\n`);
217
223
  return 2;
218
224
  }
219
225
  try {
@@ -1043,8 +1049,8 @@ const FORMATS$1 = [
1043
1049
  "json",
1044
1050
  "table"
1045
1051
  ];
1046
- const USAGE$1 = "usage: agent-eval procedure-registry <sessions-dir> [--harness claude-code|codex] [--ledger <search-ledger.jsonl>]... [--since <7d|36h|90m|ISO time>] [--outcomes <changes.json>] [--change-ledger <changes.jsonl>]... [--intents [<labeler.mjs>]] [--format both|json|table] [--limit <rows>] [--pricing <rates.json>]";
1047
- const PROCESS_IO$1 = {
1052
+ const USAGE$2 = "usage: agent-eval procedure-registry <sessions-dir> [--harness claude-code|codex] [--ledger <search-ledger.jsonl>]... [--since <7d|36h|90m|ISO time>] [--outcomes <changes.json>] [--change-ledger <changes.jsonl>]... [--intents [<labeler.mjs>]] [--format both|json|table] [--limit <rows>] [--pricing <rates.json>]";
1053
+ const PROCESS_IO$2 = {
1048
1054
  stdout: (text) => {
1049
1055
  process.stdout.write(text);
1050
1056
  },
@@ -1135,9 +1141,9 @@ async function readLedger(path) {
1135
1141
  if (typeof first.searchId !== "string") throw new Error(`${path} line 1 names no searchId`);
1136
1142
  return replaySearchLedgerText(text, first.searchId, path);
1137
1143
  }
1138
- async function runProcedureRegistryCommand(argv, io = PROCESS_IO$1) {
1144
+ async function runProcedureRegistryCommand(argv, io = PROCESS_IO$2) {
1139
1145
  if (argv.includes("--help") || argv.includes("-h")) {
1140
- io.stdout(`${USAGE$1}\n`);
1146
+ io.stdout(`${USAGE$2}\n`);
1141
1147
  return 0;
1142
1148
  }
1143
1149
  let args;
@@ -1150,7 +1156,7 @@ async function runProcedureRegistryCommand(argv, io = PROCESS_IO$1) {
1150
1156
  sinceMs = args.since === null ? void 0 : parseSince(args.since, (io.now ?? Date.now)());
1151
1157
  if (args.outcomes !== null) outcomes = readOutcomes(resolve(args.outcomes));
1152
1158
  } catch (error) {
1153
- io.stderr(`${errorMessage(error)}\n${USAGE$1}\n`);
1159
+ io.stderr(`${errorMessage(error)}\n${USAGE$2}\n`);
1154
1160
  return 2;
1155
1161
  }
1156
1162
  try {
@@ -1181,6 +1187,2112 @@ async function runProcedureRegistryCommand(argv, io = PROCESS_IO$1) {
1181
1187
  return 1;
1182
1188
  }
1183
1189
  }
1190
+ // src/real-work/config.ts
1191
+ /**
1192
+ * The builder's configuration: which repositories to read, how each one's own
1193
+ * gate runs, and which commands stand in as solvers. Everything a product
1194
+ * decides arrives here; the builder ships no product's values.
1195
+ */
1196
+ const nonEmpty = z.string().min(1);
1197
+ const timeoutMs = z.number().int().positive();
1198
+ const repoSchema = z.strictObject({
1199
+ /** `owner/name`; the task id and family are built from it. */
1200
+ name: z.string().regex(/^[\w.-]+\/[\w.-]+$/, "repository name must be owner/name"),
1201
+ /** Anything `git clone` accepts. */
1202
+ url: nonEmpty,
1203
+ defaultBranch: nonEmpty.default("main"),
1204
+ /** Which per-test result parser reads the gate's output. */
1205
+ runner: z.enum([
1206
+ "jest",
1207
+ "vitest",
1208
+ "tap",
1209
+ "cargo",
1210
+ "pytest",
1211
+ "go"
1212
+ ]).default("tap"),
1213
+ /** The image a task's environment names. Recorded, not pulled. */
1214
+ image: nonEmpty.default("node:22"),
1215
+ gate: z.strictObject({
1216
+ command: nonEmpty,
1217
+ /** How the gate is restricted to a change's test files. */
1218
+ mode: z.enum([
1219
+ "argv",
1220
+ "env",
1221
+ "none"
1222
+ ]).default("argv"),
1223
+ lockfile: nonEmpty.default("package-lock.json"),
1224
+ timeout: timeoutMs.default(12e4)
1225
+ }).optional(),
1226
+ /** Installs the frozen environment; run after every clean checkout. */
1227
+ build: z.strictObject({
1228
+ command: nonEmpty,
1229
+ outputs: z.array(nonEmpty).default([
1230
+ "dist",
1231
+ "build",
1232
+ ".cache"
1233
+ ]),
1234
+ timeout: timeoutMs.default(6e5)
1235
+ }).optional(),
1236
+ /** The ref whose lockfile every environment must match. Defaults to the default branch. */
1237
+ gateRef: nonEmpty.optional(),
1238
+ service: z.strictObject({
1239
+ needs: z.boolean().default(false),
1240
+ gateHas: z.boolean().default(false),
1241
+ services: z.array(z.unknown()).default([])
1242
+ }).optional(),
1243
+ graderAuthorKind: nonEmpty.default("merged-change")
1244
+ });
1245
+ /**
1246
+ * A caller-defined change kind. A change matches when one of its paths has a
1247
+ * segment equal to or starting with one of `pathSegments`, or when its subject
1248
+ * or one of its added lines matches `linePattern` (case-insensitive). Rules are
1249
+ * tried in order before the built-in change types.
1250
+ */
1251
+ const kindRuleSchema = z.strictObject({
1252
+ kind: z.string().regex(/^[a-z][a-z0-9-]*$/, "a kind is a lowercase identifier"),
1253
+ pathSegments: z.array(nonEmpty).optional(),
1254
+ linePattern: nonEmpty.optional()
1255
+ }).refine((rule) => rule.pathSegments !== void 0 || rule.linePattern !== void 0, { message: "a kind rule needs pathSegments, linePattern or both" });
1256
+ const configSchema = z.strictObject({
1257
+ repos: z.array(repoSchema).min(1),
1258
+ windowDays: z.number().positive().default(90),
1259
+ outDir: nonEmpty.default("real-work-out"),
1260
+ /** A change with more added lines than this is `too-large`. */
1261
+ maxAddedLines: z.number().int().positive().default(400),
1262
+ /** A change touching more files than this is `too-large`. */
1263
+ maxFiles: z.number().int().positive().default(60),
1264
+ /** Paths (exact, or a prefix) whose change alone is `generated-only`. */
1265
+ generatedOnly: z.array(nonEmpty).default([
1266
+ "package-lock.json",
1267
+ "pnpm-lock.yaml",
1268
+ "dist/",
1269
+ "generated/"
1270
+ ]),
1271
+ kinds: z.array(kindRuleSchema).default([]),
1272
+ builderAgent: nonEmpty.default("real-work-builder"),
1273
+ /** The command recorded in the manifest, when the caller ran the builder some other way. */
1274
+ builderCommand: nonEmpty.optional(),
1275
+ /** The builder commit, required only when the builder does not run from a git checkout. */
1276
+ builderCommit: z.string().regex(/^[0-9a-f]{40}$/).optional(),
1277
+ /** Pins the build time, and with it the census window. */
1278
+ builtAt: z.string().refine((value) => Number.isFinite(Date.parse(value)), "builtAt must be an ISO time").optional(),
1279
+ visibility: nonEmpty.default("private"),
1280
+ /** Invoked as `<command> <workdir> <gate> <prompt>`. */
1281
+ middleModel: z.strictObject({
1282
+ name: nonEmpty,
1283
+ command: nonEmpty,
1284
+ timeout: timeoutMs.default(6e5)
1285
+ }),
1286
+ /** Invoked as `<command> <workdir> <prompt> <storesRoot>`, the tools in `REAL_WORK_RETRIEVAL_TOOLS`. */
1287
+ retrieval: z.strictObject({
1288
+ scope: z.literal("tasks").default("tasks"),
1289
+ tools: z.array(nonEmpty).min(1).default([
1290
+ "qmd",
1291
+ "knowledge",
1292
+ "search"
1293
+ ]),
1294
+ command: nonEmpty,
1295
+ timeout: timeoutMs.default(6e5)
1296
+ }),
1297
+ audit: z.strictObject({
1298
+ agent: nonEmpty,
1299
+ count: z.number().int().positive().nullable().default(null)
1300
+ }).default({
1301
+ agent: "outside-auditor",
1302
+ count: null
1303
+ }),
1304
+ seal: z.strictObject({
1305
+ minTest: z.number().int().positive().default(40),
1306
+ maxTestShare: z.number().positive().max(1).default(.4),
1307
+ minPerRepo: z.number().int().positive().default(5)
1308
+ }).default({
1309
+ minTest: 40,
1310
+ maxTestShare: .4,
1311
+ minPerRepo: 5
1312
+ }),
1313
+ /** Where receipts ran, for example a gate or a sandbox. The id defaults to this machine's hostname. */
1314
+ host: z.strictObject({
1315
+ kind: nonEmpty.default("local"),
1316
+ id: nonEmpty.optional()
1317
+ }).default({ kind: "local" }),
1318
+ /** The directory holding the memory, knowledge, docs and history stores. */
1319
+ stores: z.strictObject({ root: nonEmpty }).optional(),
1320
+ /** Grade at most this many buildable candidates per invocation. */
1321
+ gradeBatchSize: z.number().int().positive().optional()
1322
+ });
1323
+ function parseRealWorkConfig(value) {
1324
+ const parsed = configSchema.safeParse(value);
1325
+ if (!parsed.success) {
1326
+ const issues = parsed.error.issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`).join("; ");
1327
+ throw new ConfigError(`real-work config is invalid: ${issues}`);
1328
+ }
1329
+ const config = parsed.data;
1330
+ for (const rule of config.kinds) if (rule.linePattern !== void 0) try {
1331
+ new RegExp(rule.linePattern, "i");
1332
+ } catch (error) {
1333
+ throw new ConfigError(`kind ${rule.kind}: linePattern is not a regular expression`, { cause: error });
1334
+ }
1335
+ return {
1336
+ ...config,
1337
+ stores: config.stores ?? { root: join(config.outDir, ".work", "stores") }
1338
+ };
1339
+ }
1340
+ function loadRealWorkConfig(path) {
1341
+ let raw;
1342
+ try {
1343
+ raw = JSON.parse(readFileSync(path, "utf8"));
1344
+ } catch (error) {
1345
+ throw new ConfigError(`cannot read real-work config ${path}`, { cause: error });
1346
+ }
1347
+ return parseRealWorkConfig(raw);
1348
+ }
1349
+ function repoNamed(config, name) {
1350
+ const repo = config.repos.find((candidate) => candidate.name === name);
1351
+ if (!repo) throw new ConfigError(`repository ${name} is in the build state but not in the config`);
1352
+ return repo;
1353
+ }
1354
+ // src/real-work/files.ts
1355
+ /**
1356
+ * File walks, byte digests and durable JSON writes for the real-work builder.
1357
+ * `sha256Of` hashes raw bytes (a file, a log, a line); structured values go
1358
+ * through the package's one canonical encoder.
1359
+ */
1360
+ function sha256Of(content) {
1361
+ return `sha256:${createHash("sha256").update(content).digest("hex")}`;
1362
+ }
1363
+ /**
1364
+ * Every non-directory entry under `root`, as sorted `/`-separated relative
1365
+ * paths. Symlinks are listed and never followed, so a package manager's
1366
+ * virtual store is walked once, through its real directory.
1367
+ */
1368
+ function walkFiles(root, skipDirectories = [".git"]) {
1369
+ const out = [];
1370
+ const walk = (directory) => {
1371
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
1372
+ const full = join(directory, entry.name);
1373
+ if (entry.isDirectory()) {
1374
+ if (!skipDirectories.includes(entry.name)) walk(full);
1375
+ } else out.push(relative(root, full).split(sep).join("/"));
1376
+ }
1377
+ };
1378
+ walk(root);
1379
+ return out.sort();
1380
+ }
1381
+ /** Write JSON through a temporary file and a rename, so a reader never sees half a file. */
1382
+ function writeJsonAtomic(path, value) {
1383
+ mkdirSync(dirname(path), { recursive: true });
1384
+ const temporary = `${path}.${process.pid}.tmp`;
1385
+ writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`);
1386
+ renameSync(temporary, path);
1387
+ }
1388
+ function readJsonFile(path) {
1389
+ return JSON.parse(readFileSync(path, "utf8"));
1390
+ }
1391
+ function isFile(path) {
1392
+ try {
1393
+ return statSync(path).isFile();
1394
+ } catch {
1395
+ return false;
1396
+ }
1397
+ }
1398
+ /** Write a file and make it read-only: how a grader is mounted into a checkout. */
1399
+ function writeReadOnly(path, content) {
1400
+ mkdirSync(dirname(path), { recursive: true });
1401
+ try {
1402
+ chmodSync(path, 420);
1403
+ } catch {}
1404
+ writeFileSync(path, content);
1405
+ chmodSync(path, 292);
1406
+ }
1407
+ // src/real-work/process.ts
1408
+ /**
1409
+ * Process execution for the real-work builder.
1410
+ *
1411
+ * Git plumbing runs synchronously: it is short, local and its output is the
1412
+ * data the builder reads. A repository's gate, its environment build and every
1413
+ * solver command are someone else's programs, so they run through
1414
+ * `runBoundedProcess`, which bounds them in time and kills their whole process
1415
+ * group. No command passes through a shell.
1416
+ */
1417
+ const GIT_MAX_BUFFER = 268435456;
1418
+ const COMMAND_MAX_OUTPUT = 67108864;
1419
+ /**
1420
+ * Split a command string into an argument vector. Single and double quotes
1421
+ * group words; nothing else is interpreted, because no shell reads the result.
1422
+ */
1423
+ function tokenizeCommand(command) {
1424
+ const argv = [];
1425
+ let current = "";
1426
+ let inWord = false;
1427
+ let quote = null;
1428
+ for (const char of command) if (quote !== null) {
1429
+ if (char === quote) quote = null;
1430
+ else current += char;
1431
+ } else if (char === "\"" || char === "'") {
1432
+ quote = char;
1433
+ inWord = true;
1434
+ } else if (/\s/.test(char)) {
1435
+ if (inWord) argv.push(current);
1436
+ current = "";
1437
+ inWord = false;
1438
+ } else {
1439
+ current += char;
1440
+ inWord = true;
1441
+ }
1442
+ if (quote !== null) throw new Error(`unterminated quote in command: ${command}`);
1443
+ if (inWord) argv.push(current);
1444
+ return argv;
1445
+ }
1446
+ function git(args, options = {}) {
1447
+ const result = spawnSync("git", args, {
1448
+ cwd: options.cwd,
1449
+ encoding: "utf8",
1450
+ maxBuffer: GIT_MAX_BUFFER,
1451
+ env: {
1452
+ ...process.env,
1453
+ ...options.env
1454
+ }
1455
+ });
1456
+ const spawned = result.error === void 0;
1457
+ return {
1458
+ ok: spawned && result.status === 0,
1459
+ exitCode: result.status ?? 1,
1460
+ stdout: result.stdout ?? "",
1461
+ stderr: spawned ? result.stderr ?? "" : String(result.error?.message),
1462
+ spawned,
1463
+ timedOut: false
1464
+ };
1465
+ }
1466
+ /** Run git and return its stdout, or throw with its stderr. */
1467
+ function gitOrThrow(args, options = {}) {
1468
+ const result = git(args, options);
1469
+ if (!result.ok) throw new Error(`git ${args.join(" ")} failed: ${result.stderr.trim()}`);
1470
+ return result.stdout;
1471
+ }
1472
+ async function runCommand(argv, options) {
1473
+ const [program, ...args] = argv;
1474
+ if (program === void 0) throw new Error("cannot run an empty command");
1475
+ const result = await runBoundedProcess({
1476
+ command: program,
1477
+ args,
1478
+ cwd: options.cwd,
1479
+ env: options.env,
1480
+ envMode: "merge",
1481
+ timeoutMs: options.timeoutMs,
1482
+ maxOutputBytes: COMMAND_MAX_OUTPUT
1483
+ });
1484
+ const killed = result.killedByTimeout || result.killedBySignal;
1485
+ return {
1486
+ ok: result.spawned && !killed && result.exitCode === 0,
1487
+ exitCode: result.exitCode,
1488
+ stdout: result.stdout,
1489
+ stderr: result.runnerError === void 0 ? result.stderr : `${result.stderr}\n${result.runnerError}`,
1490
+ spawned: result.spawned,
1491
+ timedOut: result.killedByTimeout
1492
+ };
1493
+ }
1494
+ // src/real-work/git-history.ts
1495
+ /**
1496
+ * What the builder reads from git: a bare cache per repository, the merged
1497
+ * changes on its default branch, and each change's files and added lines.
1498
+ * Every value comes from a git object; nothing here is inferred.
1499
+ */
1500
+ const slugOf = (value) => value.replace(/[^A-Za-z0-9._-]+/g, "-");
1501
+ function cachePath(outDir, repo) {
1502
+ return join(outDir, ".work", "cache", `${slugOf(repo.name)}.git`);
1503
+ }
1504
+ /**
1505
+ * A bare clone of the repository's branches, fetched again on every call so a
1506
+ * resumed build sees merges made since the last one. A cache that can be
1507
+ * neither cloned nor fetched is an error, never an empty history.
1508
+ */
1509
+ function ensureCache(outDir, repo) {
1510
+ const cache = cachePath(outDir, repo);
1511
+ if (!existsSync(cache)) {
1512
+ gitOrThrow([
1513
+ "clone",
1514
+ "--bare",
1515
+ "--quiet",
1516
+ repo.url,
1517
+ cache
1518
+ ]);
1519
+ return cache;
1520
+ }
1521
+ gitOrThrow([
1522
+ "fetch",
1523
+ "--quiet",
1524
+ "--prune",
1525
+ "origin",
1526
+ "+refs/heads/*:refs/heads/*"
1527
+ ], { cwd: cache });
1528
+ return cache;
1529
+ }
1530
+ const LOG_FORMAT = "%H%x09%P%x09%cI%x09%an%x09%ae%x09%s";
1531
+ /**
1532
+ * First-parent merges on the default branch, newest first, optionally bounded
1533
+ * by committer time. A later fix is looked for in the same list, so a merge on
1534
+ * some other branch never counts as one.
1535
+ */
1536
+ function listMerges(cache, repo, window = {}) {
1537
+ const args = [
1538
+ "log",
1539
+ "--first-parent",
1540
+ "--merges",
1541
+ "--no-show-signature"
1542
+ ];
1543
+ if (window.sinceMs !== void 0) args.push(`--since=${new Date(window.sinceMs).toISOString()}`);
1544
+ if (window.untilMs !== void 0) args.push(`--until=${new Date(window.untilMs).toISOString()}`);
1545
+ args.push(`--pretty=format:${LOG_FORMAT}`, repo.defaultBranch, "--");
1546
+ return gitOrThrow(args, { cwd: cache }).split("\n").filter(Boolean).map((line) => {
1547
+ const [mergedCommit = "", parents = "", mergedAt = "", authorName = "", authorEmail = "", subject = ""] = line.split(" ");
1548
+ const [firstParent = "", branchTip] = parents.split(" ");
1549
+ const prMatch = subject.match(/#(\d+)/);
1550
+ return {
1551
+ mergedCommit,
1552
+ snapshotCommit: firstParent,
1553
+ mergedAt,
1554
+ subject,
1555
+ branchSubject: branchTip === void 0 ? subject : commitSubject(cache, branchTip),
1556
+ authorName,
1557
+ authorEmail,
1558
+ prNumber: prMatch?.[1] === void 0 ? null : Number(prMatch[1])
1559
+ };
1560
+ });
1561
+ }
1562
+ function commitSubject(cache, commit) {
1563
+ return git([
1564
+ "show",
1565
+ "-s",
1566
+ "--no-show-signature",
1567
+ "--pretty=format:%s",
1568
+ commit
1569
+ ], { cwd: cache }).stdout.trim() || "merged change";
1570
+ }
1571
+ /** Files a change touched. Renames are reported as a deletion and an addition. */
1572
+ function changedFiles(cache, from, to) {
1573
+ return gitOrThrow([
1574
+ "diff-tree",
1575
+ "-r",
1576
+ "--no-commit-id",
1577
+ "--name-status",
1578
+ "--no-renames",
1579
+ from,
1580
+ to
1581
+ ], { cwd: cache }).split("\n").filter(Boolean).map((line) => {
1582
+ const [status = "", path = ""] = line.split(" ");
1583
+ const code = status.charAt(0);
1584
+ if (code !== "A" && code !== "M" && code !== "D" && code !== "T") throw new Error(`unexpected diff-tree status ${status} for ${path}`);
1585
+ return {
1586
+ path,
1587
+ status: code
1588
+ };
1589
+ });
1590
+ }
1591
+ /** The lines a change added to one file, without their leading `+`. */
1592
+ function addedLines(cache, from, to, path) {
1593
+ const res = git([
1594
+ "diff",
1595
+ "--no-ext-diff",
1596
+ "--no-color",
1597
+ "--no-renames",
1598
+ from,
1599
+ to,
1600
+ "--",
1601
+ path
1602
+ ], { cwd: cache });
1603
+ if (!res.ok) return [];
1604
+ const lines = [];
1605
+ for (const line of res.stdout.split("\n")) {
1606
+ if (line.startsWith("+++")) continue;
1607
+ if (line.startsWith("+")) lines.push(line.slice(1));
1608
+ }
1609
+ return lines;
1610
+ }
1611
+ /** A file's content at a commit, or null when the file does not exist there. */
1612
+ function blobContent(cache, ref, path) {
1613
+ const res = git([
1614
+ "cat-file",
1615
+ "blob",
1616
+ `${ref}:${path}`
1617
+ ], { cwd: cache });
1618
+ return res.ok ? res.stdout : null;
1619
+ }
1620
+ function candidateIdOf(repo, merge) {
1621
+ const name = repo.name.split("/")[1] ?? repo.name;
1622
+ return `${slugOf(name)}-${merge.prNumber ?? merge.mergedCommit.slice(0, 8)}`;
1623
+ }
1624
+ // src/real-work/runner-output.ts
1625
+ /**
1626
+ * Per-test results read from a test runner's own output. A parser reports only
1627
+ * what the output names; output it cannot read yields no tests, which the
1628
+ * pipeline rejects as `no-tests` rather than guessing a verdict.
1629
+ */
1630
+ const unique = (names) => [...new Set(names)];
1631
+ const result = (passedTests, failedTests) => ({
1632
+ passed: passedTests.length,
1633
+ failed: failedTests.length,
1634
+ passedTests: unique(passedTests),
1635
+ failedTests: unique(failedTests)
1636
+ });
1637
+ function parseJsonReport(text) {
1638
+ try {
1639
+ const value = JSON.parse(extractJsonPayload(text));
1640
+ return isRecord(value) ? value : null;
1641
+ } catch {
1642
+ return null;
1643
+ }
1644
+ }
1645
+ /** jest `--json` and vitest `--reporter=json`: `testResults[].assertionResults[]`. */
1646
+ function parseJestShape(text) {
1647
+ const report = parseJsonReport(text);
1648
+ const passedTests = [];
1649
+ const failedTests = [];
1650
+ const suites = report !== null && Array.isArray(report.testResults) ? report.testResults : [];
1651
+ for (const suite of suites) {
1652
+ if (!isRecord(suite) || !Array.isArray(suite.assertionResults)) continue;
1653
+ for (const assertion of suite.assertionResults) {
1654
+ if (!isRecord(assertion)) continue;
1655
+ const name = String(assertion.fullName ?? assertion.title ?? suite.name);
1656
+ if (assertion.status === "passed") passedTests.push(name);
1657
+ else if (assertion.status === "failed") failedTests.push(name);
1658
+ }
1659
+ }
1660
+ return result(passedTests, failedTests);
1661
+ }
1662
+ /** TAP: `ok N - name` / `not ok N - name`; a `# SKIP` or `# TODO` failure is not a failure. */
1663
+ function parseTap(text) {
1664
+ const passedTests = [];
1665
+ const failedTests = [];
1666
+ for (const line of text.split("\n")) {
1667
+ const match = line.match(/^(not )?ok(?:\s+\d+)?\s+-\s+(.+?)\s*(#\s*(SKIP|TODO)\b.*|#.*)?$/i);
1668
+ if (!match?.[2]) continue;
1669
+ const name = match[2].trim();
1670
+ if (match[4] !== void 0) continue;
1671
+ if (match[1]) failedTests.push(name);
1672
+ else passedTests.push(name);
1673
+ }
1674
+ return result(passedTests, failedTests);
1675
+ }
1676
+ /** cargo test: `test <path> ... ok|FAILED`. */
1677
+ function parseCargo(text) {
1678
+ const passedTests = [];
1679
+ const failedTests = [];
1680
+ for (const line of text.split("\n")) {
1681
+ const match = line.match(/^test\s+(\S+)\s+\.\.\.\s+(ok|FAILED)\b/);
1682
+ if (!match?.[1]) continue;
1683
+ if (match[2] === "ok") passedTests.push(match[1]);
1684
+ else failedTests.push(match[1]);
1685
+ }
1686
+ return result(passedTests, failedTests);
1687
+ }
1688
+ /** pytest -v (`path::name PASSED`), falling back to the short summary (`FAILED path::name`). */
1689
+ function parsePytest(text) {
1690
+ const passedTests = [];
1691
+ const failedTests = [];
1692
+ for (const line of text.split("\n")) {
1693
+ const match = line.match(/^(\S+::\S+?)\s+(PASSED|FAILED|ERROR|SKIPPED|XFAIL|XPASS)(?:\s*\[[^\]]*\])?\s*$/);
1694
+ if (!match?.[1]) continue;
1695
+ if (match[2] === "PASSED" || match[2] === "XPASS") passedTests.push(match[1]);
1696
+ else if (match[2] === "FAILED" || match[2] === "ERROR") failedTests.push(match[1]);
1697
+ }
1698
+ if (passedTests.length === 0 && failedTests.length === 0) for (const line of text.split("\n")) {
1699
+ const match = line.match(/^(FAILED|PASSED)\s+(\S+::\S+?)(?:\s+-.*)?$/);
1700
+ if (!match?.[2]) continue;
1701
+ if (match[1] === "FAILED") failedTests.push(match[2]);
1702
+ else passedTests.push(match[2]);
1703
+ }
1704
+ return result(passedTests, failedTests);
1705
+ }
1706
+ /** go test -v: `--- PASS: TestName (0.00s)` / `--- FAIL: ...`, subtests included. */
1707
+ function parseGo(text) {
1708
+ const passedTests = [];
1709
+ const failedTests = [];
1710
+ for (const line of text.split("\n")) {
1711
+ const match = line.match(/^\s*---\s+(PASS|FAIL):\s+(\S+)/);
1712
+ if (!match?.[2]) continue;
1713
+ if (match[1] === "PASS") passedTests.push(match[2]);
1714
+ else failedTests.push(match[2]);
1715
+ }
1716
+ return result(passedTests, failedTests);
1717
+ }
1718
+ const PARSERS = {
1719
+ jest: parseJestShape,
1720
+ vitest: parseJestShape,
1721
+ tap: parseTap,
1722
+ cargo: parseCargo,
1723
+ pytest: parsePytest,
1724
+ go: parseGo
1725
+ };
1726
+ /**
1727
+ * Read the tests a run reported. A JSON runner is read from its report file
1728
+ * when it wrote one, else from stdout alone: stderr carries code frames whose
1729
+ * braces would corrupt the payload. Line runners read stdout and stderr.
1730
+ */
1731
+ function parseRunnerOutput(runner, output) {
1732
+ if (runner === "jest" || runner === "vitest") return PARSERS[runner](output.report ?? output.stdout);
1733
+ return PARSERS[runner](`${output.stdout}\n${output.stderr}`);
1734
+ }
1735
+ // src/real-work/grader.ts
1736
+ /**
1737
+ * A task's grader is the repository's own gate restricted to the test files the
1738
+ * merged change added or changed, with those files mounted read-only into the
1739
+ * checkout after any solver has finished.
1740
+ */
1741
+ /** Paths under a test directory, or named as a test file, in the common layouts. */
1742
+ const TEST_PATH = /(^|\/)(tests?|__tests__|spec|acceptance|fixtures)\/|\.(test|spec)\.[a-z]+$|_test\.[a-z]+$|test_[^/]*\.py$/i;
1743
+ function isTestFile(path) {
1744
+ return TEST_PATH.test(path);
1745
+ }
1746
+ /** The grader's files as the commit that authored them holds them. */
1747
+ function graderAt(cache, repo, commit, testPaths) {
1748
+ const gate = repo.gate;
1749
+ if (!gate) throw new Error(`repository ${repo.name} declares no gate command`);
1750
+ const files = [];
1751
+ for (const path of [...testPaths].sort()) {
1752
+ const content = blobContent(cache, commit, path);
1753
+ if (content !== null) files.push({
1754
+ path,
1755
+ content
1756
+ });
1757
+ }
1758
+ if (files.length === 0) throw new Error(`no grader files at ${commit}`);
1759
+ const paths = files.map((file) => file.path);
1760
+ const sha256 = hashCanonical(files.map((file) => [file.path, sha256Of(file.content)]));
1761
+ if (gate.mode === "none") return {
1762
+ paths,
1763
+ files,
1764
+ sha256,
1765
+ command: gate.command,
1766
+ env: {}
1767
+ };
1768
+ if (gate.mode === "env") return {
1769
+ paths,
1770
+ files,
1771
+ sha256,
1772
+ command: gate.command,
1773
+ env: { TEST_FILES: paths.join(" ") }
1774
+ };
1775
+ const args = paths.map((path) => /\s/.test(path) ? `"${path}"` : path).join(" ");
1776
+ return {
1777
+ paths,
1778
+ files,
1779
+ sha256,
1780
+ command: `${gate.command} ${args}`,
1781
+ env: {}
1782
+ };
1783
+ }
1784
+ function mountGrader(workdir, grader) {
1785
+ for (const file of grader.files) writeReadOnly(join(workdir, file.path), file.content);
1786
+ }
1787
+ /**
1788
+ * Run the grader in a checkout and read its per-test results. vitest writes
1789
+ * its JSON report to `--outputFile`, so for that runner the flags are added
1790
+ * when the gate does not name a report, and the report is read back.
1791
+ */
1792
+ async function runGrader(workdir, repo, grader) {
1793
+ let argv = tokenizeCommand(grader.command);
1794
+ let reportPath = null;
1795
+ if (repo.runner === "vitest") {
1796
+ const at = argv.findIndex((arg) => arg === "--outputFile" || arg.startsWith("--outputFile="));
1797
+ const declared = at < 0 ? void 0 : argv[at];
1798
+ if (declared !== void 0) {
1799
+ const value = declared === "--outputFile" ? argv[at + 1] ?? "" : declared.slice(13);
1800
+ reportPath = resolve(workdir, value);
1801
+ } else if (!argv.includes("--reporter=json")) {
1802
+ reportPath = join(workdir, ".real-work-vitest.json");
1803
+ argv = [
1804
+ ...argv,
1805
+ "--reporter=json",
1806
+ `--outputFile=${reportPath}`
1807
+ ];
1808
+ }
1809
+ }
1810
+ const res = await runCommand(argv, {
1811
+ cwd: workdir,
1812
+ env: grader.env,
1813
+ timeoutMs: repo.gate?.timeout ?? 12e4
1814
+ });
1815
+ const report = reportPath !== null && isFile(reportPath) ? readFileSync(reportPath, "utf8") : null;
1816
+ return {
1817
+ ...parseRunnerOutput(repo.runner, {
1818
+ stdout: res.stdout,
1819
+ stderr: res.stderr,
1820
+ report
1821
+ }),
1822
+ exitCode: res.exitCode,
1823
+ log: `exit ${res.exitCode}\n${res.stdout}\n${res.stderr}`,
1824
+ environmentError: false
1825
+ };
1826
+ }
1827
+ const segmentMatches = (segment, token) => {
1828
+ const s = segment.toLowerCase();
1829
+ const t = token.toLowerCase();
1830
+ return t.endsWith("*") ? s.startsWith(t.slice(0, -1)) : s === t;
1831
+ };
1832
+ /**
1833
+ * A change's kind. The caller's rules are tried in order; the first that
1834
+ * matches names the kind. Otherwise the change type comes from its own subject:
1835
+ * perf, refactor, test (or a change touching only test files), fix, else feature.
1836
+ */
1837
+ function classifyKind(change, rules) {
1838
+ const lines = [change.subject, ...change.addedLines];
1839
+ for (const rule of rules) {
1840
+ const tokens = rule.pathSegments ?? [];
1841
+ if (change.paths.some((path) => path.split("/").some((segment) => tokens.some((token) => segmentMatches(segment, token))))) return rule.kind;
1842
+ if (rule.linePattern !== void 0) {
1843
+ const pattern = new RegExp(rule.linePattern, "i");
1844
+ if (lines.some((line) => pattern.test(line))) return rule.kind;
1845
+ }
1846
+ }
1847
+ const subject = change.subject.toLowerCase();
1848
+ if (/\b(perf|performance|optimi[sz]\w*)\b/.test(subject)) return "perf";
1849
+ if (/\b(refactor\w*|cleanup|clean up|renam\w*|prune)\b/.test(subject)) return "refactor";
1850
+ if (/\b(tests?|coverage)\b/.test(subject) || change.paths.length > 0 && change.paths.every(isTestFile)) return "test";
1851
+ if (/\b(fix\w*|bug\w*|patch\w*|repair\w*|regression)\b/.test(subject)) return "fix";
1852
+ return "feature";
1853
+ }
1854
+ // src/real-work/harness.ts
1855
+ /**
1856
+ * The run harness: a clean checkout at a commit, the frozen environment
1857
+ * installed, the grader mounted read-only, and the gate run. A solver acts on
1858
+ * the checkout before the grader is mounted, and every path it changed is
1859
+ * recorded.
1860
+ */
1861
+ function removeDirectory(path) {
1862
+ rmSync(path, {
1863
+ recursive: true,
1864
+ force: true
1865
+ });
1866
+ }
1867
+ /**
1868
+ * A working clone of `source` at `dest`, reused when one is already there.
1869
+ * Reuse requires `dest/.git` itself: a directory inside some other checkout
1870
+ * must never be mistaken for a clone and cleaned.
1871
+ */
1872
+ function ensureRunClone(source, dest) {
1873
+ if (existsSync(join(dest, ".git"))) return dest;
1874
+ removeDirectory(dest);
1875
+ gitOrThrow([
1876
+ "clone",
1877
+ "--quiet",
1878
+ source,
1879
+ dest
1880
+ ]);
1881
+ return dest;
1882
+ }
1883
+ /** Reset the checkout to exactly the tree of `commit`: nothing untracked, ignored or modified survives. */
1884
+ function checkoutTree(workdir, commit) {
1885
+ git([
1886
+ "clean",
1887
+ "-q",
1888
+ "-f",
1889
+ "-d",
1890
+ "-x"
1891
+ ], { cwd: workdir });
1892
+ gitOrThrow([
1893
+ "checkout",
1894
+ "--quiet",
1895
+ "--force",
1896
+ "--detach",
1897
+ commit
1898
+ ], { cwd: workdir });
1899
+ git([
1900
+ "clean",
1901
+ "-q",
1902
+ "-f",
1903
+ "-d",
1904
+ "-x"
1905
+ ], { cwd: workdir });
1906
+ gitOrThrow([
1907
+ "reset",
1908
+ "--hard",
1909
+ "-q",
1910
+ commit
1911
+ ], { cwd: workdir });
1912
+ }
1913
+ /** Content hash of every working-tree file outside `.git` and `node_modules`. */
1914
+ function treeState(workdir) {
1915
+ const state = /* @__PURE__ */ new Map();
1916
+ for (const path of walkFiles(workdir, [".git", "node_modules"])) try {
1917
+ state.set(path, sha256Of(readFileSync(join(workdir, path))));
1918
+ } catch {}
1919
+ return state;
1920
+ }
1921
+ /** Paths whose content changed or appeared, and paths that disappeared. */
1922
+ function changedPaths(before, after) {
1923
+ const changed = /* @__PURE__ */ new Set();
1924
+ for (const [path, hash] of after) if (before.get(path) !== hash) changed.add(path);
1925
+ for (const path of before.keys()) if (!after.has(path)) changed.add(path);
1926
+ return [...changed].sort();
1927
+ }
1928
+ async function installEnvironment(workdir, repo) {
1929
+ if (!repo.build) return null;
1930
+ return await runCommand(tokenizeCommand(repo.build.command), {
1931
+ cwd: workdir,
1932
+ timeoutMs: repo.build.timeout
1933
+ });
1934
+ }
1935
+ const environmentFailure = (installed) => ({
1936
+ exitCode: installed.exitCode === 0 ? 1 : installed.exitCode,
1937
+ passed: 0,
1938
+ failed: 0,
1939
+ passedTests: [],
1940
+ failedTests: [],
1941
+ environmentError: true,
1942
+ log: `environment install failed\n${installed.stdout}\n${installed.stderr}`
1943
+ });
1944
+ /** One graded run: clean checkout at `applied` (or the snapshot), install, mount, run. */
1945
+ async function gradedRun(workdir, run) {
1946
+ checkoutTree(workdir, run.applied ?? run.snapshot);
1947
+ const installed = await installEnvironment(workdir, run.repo);
1948
+ if (installed && !installed.ok) return environmentFailure(installed);
1949
+ mountGrader(workdir, run.grader);
1950
+ return await runGrader(workdir, run.repo, run.grader);
1951
+ }
1952
+ /**
1953
+ * A solver run: the solver works on a clean checkout of `snapshot` with the
1954
+ * environment installed; then the harness mounts the grader and grades.
1955
+ */
1956
+ async function solverRun(workdir, run) {
1957
+ checkoutTree(workdir, run.snapshot);
1958
+ const installed = await installEnvironment(workdir, run.repo);
1959
+ if (installed && !installed.ok) throw new Error(`environment install failed: ${installed.stdout}\n${installed.stderr}`);
1960
+ const before = treeState(workdir);
1961
+ const report = await run.solver({
1962
+ workdir,
1963
+ repo: run.repo,
1964
+ prompt: run.prompt
1965
+ });
1966
+ const wrote = changedPaths(before, treeState(workdir));
1967
+ mountGrader(workdir, run.grader);
1968
+ return {
1969
+ run: await runGrader(workdir, run.repo, run.grader),
1970
+ wrote,
1971
+ report
1972
+ };
1973
+ }
1974
+ // src/real-work/environment.ts
1975
+ /**
1976
+ * A task's environment is the repository's own build, run twice in two clean
1977
+ * directories at the snapshot from the same frozen lockfile.
1978
+ *
1979
+ * - `treeDigest` covers the source tree at the snapshot, without the install
1980
+ * and build outputs.
1981
+ * - `imageDigest` covers the installed tree. Symlinks hash as their link text,
1982
+ * pnpm's timestamped bookkeeping is left out, and the build directory's own
1983
+ * path is normalized so two directories can compare equal.
1984
+ *
1985
+ * Both builds must exit 0 and agree on both digests, or the candidate is
1986
+ * `env-unbuildable`.
1987
+ */
1988
+ const INSTALL_BOOKKEEPING = ["node_modules/.modules.yaml", "node_modules/.pnpm-workspace-state-v1.json"];
1989
+ /** A symlink hashes its link text; a file hashes its bytes. */
1990
+ function entrySha(path, replace = []) {
1991
+ if (lstatSync(path).isSymbolicLink()) {
1992
+ let target = readlinkSync(path);
1993
+ for (const [from, to] of replace) target = target.split(from).join(to);
1994
+ return sha256Of(target);
1995
+ }
1996
+ let content = readFileSync(path);
1997
+ for (const [from, to] of replace) if (content.includes(from)) content = Buffer.from(content.toString("utf8").split(from).join(to));
1998
+ return sha256Of(content);
1999
+ }
2000
+ /** Digest of a directory: the canonical form of its sorted `[path, sha256]` pairs. */
2001
+ function linkPreservingTreeDigest(root, options = {}) {
2002
+ const exclude = options.exclude ?? [];
2003
+ const pairs = walkFiles(root).filter((path) => !exclude.some((pattern) => path === pattern || path.startsWith(`${pattern}/`))).map((path) => [path, entrySha(join(root, path), options.replace)]);
2004
+ return hashCanonical(pairs);
2005
+ }
2006
+ function lockfileSha(cache, ref, lockfile) {
2007
+ const content = blobContent(cache, ref, lockfile);
2008
+ if (content === null) throw new Error(`lockfile ${lockfile} not found at ${ref}`);
2009
+ return sha256Of(content);
2010
+ }
2011
+ async function buildEnvironment(cache, repo, at) {
2012
+ const lockfile = lockfileSha(cache, at.snapshot, repo.gate?.lockfile ?? "package-lock.json");
2013
+ if (!repo.build) return {
2014
+ buildable: false,
2015
+ builds: [],
2016
+ lockfileSha256: lockfile,
2017
+ error: "no build command"
2018
+ };
2019
+ const outputs = ["node_modules", ...repo.build.outputs];
2020
+ const builds = [];
2021
+ let error = null;
2022
+ for (let index = 1; index <= 2; index++) {
2023
+ const id = randomUUID().slice(0, 8);
2024
+ const dir = join(at.workRoot, `env-build-${index}-${id}`);
2025
+ try {
2026
+ ensureRunClone(cache, dir);
2027
+ checkoutTree(dir, at.snapshot);
2028
+ const installed = await installEnvironment(dir, repo);
2029
+ const replace = [.../* @__PURE__ */ new Set([dir, realpathSync(dir)])].map((from) => [from, "~BUILD~"]);
2030
+ builds.push({
2031
+ buildId: `build-${index}-${id}`,
2032
+ exitCode: installed?.exitCode ?? 1,
2033
+ treeDigest: linkPreservingTreeDigest(dir, { exclude: outputs }),
2034
+ imageDigest: linkPreservingTreeDigest(dir, {
2035
+ exclude: INSTALL_BOOKKEEPING,
2036
+ replace
2037
+ })
2038
+ });
2039
+ } catch (caught) {
2040
+ error = caught instanceof Error ? caught.message : String(caught);
2041
+ break;
2042
+ } finally {
2043
+ removeDirectory(dir);
2044
+ }
2045
+ }
2046
+ const [first, second] = builds;
2047
+ return {
2048
+ buildable: error === null && first !== void 0 && second !== void 0 && builds.every((build) => build.exitCode === 0) && first.treeDigest === second.treeDigest && first.imageDigest === second.imageDigest,
2049
+ builds,
2050
+ lockfileSha256: lockfile,
2051
+ error
2052
+ };
2053
+ }
2054
+ /** Where receipts run: the configured host kind, and its id or this machine's hostname. */
2055
+ function receiptMachine(config) {
2056
+ return {
2057
+ kind: config.host.kind,
2058
+ id: config.host.id ?? hostname()
2059
+ };
2060
+ }
2061
+ function receiptDigestOf(receipt) {
2062
+ const { receiptDigest: _digest, ...rest } = receipt;
2063
+ return hashCanonical(rest);
2064
+ }
2065
+ async function takeReceipt(cache, workdir, run) {
2066
+ try {
2067
+ ensureRunClone(cache, workdir);
2068
+ const details = [];
2069
+ const logs = [];
2070
+ for (let index = 0; index < 3; index++) {
2071
+ const result = await gradedRun(workdir, run);
2072
+ details.push(result);
2073
+ logs.push(`--- run ${index + 1} ---\n${result.log}`);
2074
+ if (result.environmentError) break;
2075
+ }
2076
+ const verdict = details.find((result) => result.exitCode !== 0) ?? details[0];
2077
+ if (verdict === void 0) throw new Error("a receipt ran no grader");
2078
+ const unsigned = {
2079
+ snapshotCommit: run.snapshot,
2080
+ appliedCommit: run.applied,
2081
+ graderSha256: run.grader.sha256,
2082
+ exitCode: verdict.exitCode,
2083
+ passed: verdict.passed,
2084
+ failed: verdict.failed,
2085
+ failedTests: [...verdict.failedTests],
2086
+ passedTests: [...verdict.passedTests],
2087
+ clean: true,
2088
+ host: {
2089
+ ...run.machine,
2090
+ runId: randomUUID()
2091
+ },
2092
+ logSha256: sha256Of(logs.join("\n")),
2093
+ ranAt: (/* @__PURE__ */ new Date()).toISOString(),
2094
+ runs: details.map((result) => ({
2095
+ exitCode: result.exitCode,
2096
+ failedTests: [...result.failedTests]
2097
+ }))
2098
+ };
2099
+ return {
2100
+ receipt: {
2101
+ ...unsigned,
2102
+ receiptDigest: receiptDigestOf(unsigned)
2103
+ },
2104
+ environmentError: details.some((result) => result.environmentError)
2105
+ };
2106
+ } finally {
2107
+ removeDirectory(workdir);
2108
+ }
2109
+ }
2110
+ /** The runs agree on their exit code and on the set of failing tests. */
2111
+ function runsAgree(runs) {
2112
+ return new Set(runs.map((run) => `${run.exitCode}:${[...run.failedTests].sort().join("|")}`)).size === 1;
2113
+ }
2114
+ function receiptVerdict(receipt) {
2115
+ return {
2116
+ passes: receipt.exitCode === 0 && receipt.failed === 0 && receipt.passed >= 1,
2117
+ fails: receipt.exitCode !== 0 && receipt.failed >= 1 && receipt.failedTests.length > 0
2118
+ };
2119
+ }
2120
+ const DAY_MS$1 = 864e5;
2121
+ function findLaterFixes(cache, task, merges, untilMs) {
2122
+ const codePaths = new Set(changedFiles(cache, task.snapshotCommit, task.mergedCommit).map((file) => file.path).filter((path) => !isTestFile(path)));
2123
+ const mergedAt = Date.parse(task.mergedAt);
2124
+ const fixes = [];
2125
+ for (const merge of merges) {
2126
+ if (merge.mergedCommit === task.mergedCommit) continue;
2127
+ const at = Date.parse(merge.mergedAt);
2128
+ const after = at - mergedAt;
2129
+ if (!(after > 0 && after <= 7 * DAY_MS$1) || at > untilMs) continue;
2130
+ const paths = changedFiles(cache, merge.snapshotCommit, merge.mergedCommit).map((file) => file.path);
2131
+ const testPaths = paths.filter(isTestFile);
2132
+ if (testPaths.length === 0) continue;
2133
+ if (!paths.some((path) => codePaths.has(path))) continue;
2134
+ if (testPaths.some((path) => task.heldBackPaths.includes(path))) continue;
2135
+ fixes.push({
2136
+ merge,
2137
+ testPaths
2138
+ });
2139
+ }
2140
+ return fixes;
2141
+ }
2142
+ /**
2143
+ * The later-fix record for one candidate fix, or null when its receipts do not
2144
+ * show the shipped change failing the fix's tests and the fix passing them.
2145
+ */
2146
+ async function buildLaterFix(cache, repo, task, fix, run) {
2147
+ const grader = graderAt(cache, repo, fix.merge.mergedCommit, fix.testPaths);
2148
+ const receiptFor = (applied, name) => takeReceipt(cache, join(run.workRoot, `${task.id}-${name}`), {
2149
+ repo,
2150
+ snapshot: task.snapshotCommit,
2151
+ applied,
2152
+ grader,
2153
+ machine: run.machine
2154
+ });
2155
+ const merged = await receiptFor(task.mergedCommit, "later-fix-merged");
2156
+ if (merged.environmentError) return null;
2157
+ const fixed = await receiptFor(fix.merge.mergedCommit, "later-fix-fix");
2158
+ if (fixed.environmentError) return null;
2159
+ const mergedFails = runsAgree(merged.receipt.runs) && receiptVerdict(merged.receipt).fails;
2160
+ const fixPasses = runsAgree(fixed.receipt.runs) && receiptVerdict(fixed.receipt).passes;
2161
+ if (!mergedFails || !fixPasses) return null;
2162
+ const testIds = [.../* @__PURE__ */ new Set([
2163
+ ...fixed.receipt.failedTests,
2164
+ ...fixed.receipt.passedTests,
2165
+ ...merged.receipt.failedTests
2166
+ ])];
2167
+ return {
2168
+ laterFix: {
2169
+ fixCommit: fix.merge.mergedCommit,
2170
+ fixMergedAt: fix.merge.mergedAt,
2171
+ touchedPaths: changedFiles(cache, fix.merge.snapshotCommit, fix.merge.mergedCommit).map((file) => file.path),
2172
+ hiddenGrader: {
2173
+ paths: grader.paths,
2174
+ testIds,
2175
+ sha256: grader.sha256,
2176
+ author: {
2177
+ kind: "fix-change",
2178
+ ref: fix.merge.authorEmail
2179
+ }
2180
+ },
2181
+ receipts: {
2182
+ merged: merged.receipt,
2183
+ fix: fixed.receipt
2184
+ }
2185
+ },
2186
+ grader
2187
+ };
2188
+ }
2189
+ // src/real-work/report.ts
2190
+ /**
2191
+ * The delivered pages: `manifest.json`, `candidates.json`, `yield.json`,
2192
+ * `tasks/<id>.json`, `spread.json` and `retrieval.json`. Every value is read
2193
+ * from the build state; the report computes nothing a stage did not measure.
2194
+ */
2195
+ const MANIFEST_SCHEMA = "real-work-benchmark.v2";
2196
+ function taskPage(task, config, context) {
2197
+ const repo = config.repos.find((candidate) => candidate.name === task.repo);
2198
+ if (!repo?.gate || task.timeCut === null || task.split === null) throw new Error(`task ${task.id} reached the report before every stage recorded it`);
2199
+ return {
2200
+ id: task.id,
2201
+ repo: task.repo,
2202
+ kind: task.kind,
2203
+ family: `${task.repo}/${task.kind}`,
2204
+ prNumber: task.prNumber,
2205
+ snapshotCommit: task.snapshotCommit,
2206
+ mergedParent: task.snapshotCommit,
2207
+ mergedCommit: task.mergedCommit,
2208
+ mergedAt: task.mergedAt,
2209
+ builderCommit: context.builderCommit,
2210
+ prompt: task.prompt,
2211
+ split: task.split,
2212
+ solvers: task.solvers,
2213
+ solution: { files: task.changeFiles.map((file) => ({
2214
+ path: file.path,
2215
+ postSha256: file.postSha256,
2216
+ addedLineHashes: file.addedLineHashes
2217
+ })) },
2218
+ snapshot: { touched: task.changeFiles.map((file) => ({
2219
+ path: file.path,
2220
+ sha256: file.snapshotSha256
2221
+ })) },
2222
+ heldBack: {
2223
+ paths: task.heldBackPaths,
2224
+ inSnapshot: false
2225
+ },
2226
+ grader: {
2227
+ kind: "tests",
2228
+ command: task.grader.command,
2229
+ env: task.grader.env,
2230
+ paths: task.grader.paths,
2231
+ testIds: task.testIds,
2232
+ sha256: task.grader.sha256,
2233
+ author: task.graderAuthor
2234
+ },
2235
+ graderIntegrity: {
2236
+ mountedReadOnly: true,
2237
+ solverWrites: task.solverWrites
2238
+ },
2239
+ environment: {
2240
+ image: repo.image,
2241
+ gateCommand: repo.gate.command,
2242
+ lockfileSha256: context.lockfileSha256,
2243
+ needsService: repo.service?.needs ?? false,
2244
+ gateHasService: repo.service?.gateHas ?? false,
2245
+ services: repo.service?.services ?? [],
2246
+ builds: context.environment.builds
2247
+ },
2248
+ timeCut: {
2249
+ baseTime: task.timeCut.baseTime,
2250
+ fullHistory: false,
2251
+ latestObjectTime: task.timeCut.latestObjectTime,
2252
+ indexes: [],
2253
+ canaries: task.timeCut.canaries.map((canary) => ({
2254
+ store: canary.store,
2255
+ token: canary.token,
2256
+ plantedAt: canary.plantedAt,
2257
+ probeQueries: canary.probeQueries,
2258
+ solverContextSha256: canary.solverContextSha256,
2259
+ hits: canary.hits
2260
+ }))
2261
+ },
2262
+ receipts: task.receipts,
2263
+ ...task.laterFix === null ? {} : { laterFix: task.laterFix }
2264
+ };
2265
+ }
2266
+ function writeReport(config, state, build) {
2267
+ const { outDir } = config;
2268
+ if (state.seal === null) throw new Error("the report needs a sealed build");
2269
+ const candidates = state.candidates.map((candidate) => ({
2270
+ id: candidate.id,
2271
+ repo: candidate.repo,
2272
+ prNumber: candidate.prNumber,
2273
+ mergedCommit: candidate.mergedCommit,
2274
+ mergedAt: candidate.mergedAt,
2275
+ reason: candidate.reason
2276
+ }));
2277
+ const byReason = {};
2278
+ for (const candidate of candidates) byReason[candidate.reason] = (byReason[candidate.reason] ?? 0) + 1;
2279
+ const taskIds = new Set(state.tasks.map((task) => task.id));
2280
+ writeJsonAtomic(join(outDir, "candidates.json"), candidates);
2281
+ writeJsonAtomic(join(outDir, "yield.json"), {
2282
+ candidates: candidates.length,
2283
+ tasks: state.tasks.length,
2284
+ yield: Math.round(state.tasks.length / Math.max(1, candidates.length) * 1e4) / 1e4,
2285
+ byReason
2286
+ });
2287
+ for (const task of state.tasks) {
2288
+ const environment = state.environments[task.id];
2289
+ if (!environment) throw new Error(`task ${task.id} has no environment record`);
2290
+ writeJsonAtomic(join(outDir, "tasks", `${task.id}.json`), taskPage(task, config, {
2291
+ builderCommit: build.builder.commit,
2292
+ lockfileSha256: state.repoLockfiles[task.repo] ?? null,
2293
+ environment
2294
+ }));
2295
+ }
2296
+ const repoGates = {};
2297
+ for (const repo of config.repos) repoGates[repo.name] = {
2298
+ command: repo.gate?.command ?? null,
2299
+ lockfileSha256: state.repoLockfiles[repo.name] ?? null
2300
+ };
2301
+ writeJsonAtomic(join(outDir, "manifest.json"), {
2302
+ schema: MANIFEST_SCHEMA,
2303
+ builtAt: build.builtAt,
2304
+ visibility: config.visibility,
2305
+ builder: build.builder,
2306
+ agents: [.../* @__PURE__ */ new Set([config.builderAgent, config.middleModel.name])],
2307
+ repoGates,
2308
+ census: state.census,
2309
+ seal: {
2310
+ testSetSha256: state.seal.testSetSha256,
2311
+ sealedAt: state.seal.sealedAt
2312
+ },
2313
+ tasks: state.tasks.map((task) => task.id),
2314
+ audit: { reruns: state.auditReruns }
2315
+ });
2316
+ writeJsonAtomic(join(outDir, "spread.json"), {
2317
+ middleModel: config.middleModel.name,
2318
+ cells: state.spreadCells.filter((cell) => taskIds.has(cell.task))
2319
+ });
2320
+ const notesAnswered = new Set(state.candidates.filter((candidate) => candidate.reason === "answer-in-notes").map((candidate) => candidate.id));
2321
+ writeJsonAtomic(join(outDir, "retrieval.json"), { cells: state.retrievalCells.filter((cell) => taskIds.has(cell.task) || notesAnswered.has(cell.task)) });
2322
+ }
2323
+ // src/real-work/seal.ts
2324
+ /**
2325
+ * The seal: train, selection and test splits, assigned deterministically from
2326
+ * the tasks' merge times and ids, and the digest that fixes the test set.
2327
+ *
2328
+ * The test split holds at least `minTest` tasks and at most `maxTestShare` of
2329
+ * all tasks; every repository with at least `minPerRepo` tasks is represented
2330
+ * in it; and train and selection each hold at least one task. Tasks are taken
2331
+ * at a stride through the merge-time order, so the test set spans the window.
2332
+ */
2333
+ /** sha256 of the sorted test task ids joined by newlines. */
2334
+ function testSetSha256(testIds) {
2335
+ return sha256Of([...testIds].sort(compareCodeUnits).join("\n"));
2336
+ }
2337
+ function sealSplits(tasks, { minTest, maxTestShare, minPerRepo }) {
2338
+ if (tasks.length === 0) throw new Error("seal: there are no tasks to split");
2339
+ const maxTest = Math.floor(tasks.length * maxTestShare);
2340
+ if (minTest > maxTest) throw new Error(`seal: ${tasks.length} tasks cannot hold a test split of at least ${minTest} within ${maxTestShare} of all tasks (at most ${maxTest})`);
2341
+ const ordered = [...tasks].sort((a, b) => compareCodeUnits(`${a.mergedAt} ${a.id}`, `${b.mergedAt} ${b.id}`));
2342
+ const perRepo = /* @__PURE__ */ new Map();
2343
+ for (const task of tasks) perRepo.set(task.repo, (perRepo.get(task.repo) ?? 0) + 1);
2344
+ const bigRepos = [...perRepo].filter(([, count]) => count >= minPerRepo).map(([repo]) => repo);
2345
+ const testCount = Math.min(maxTest, Math.max(minTest, bigRepos.length, Math.ceil(tasks.length * maxTestShare / 3)));
2346
+ const test = /* @__PURE__ */ new Set();
2347
+ for (const repo of bigRepos) {
2348
+ if (test.size >= testCount) break;
2349
+ const first = ordered.find((task) => task.repo === repo);
2350
+ if (first) test.add(first.id);
2351
+ }
2352
+ const pool = ordered.filter((task) => !test.has(task.id));
2353
+ const stride = Math.max(1, Math.floor(pool.length / Math.max(1, testCount - test.size)));
2354
+ for (let index = 0; test.size < testCount && index < pool.length; index += stride) {
2355
+ const task = pool[index];
2356
+ if (task) test.add(task.id);
2357
+ }
2358
+ for (const task of ordered) {
2359
+ if (test.size >= testCount) break;
2360
+ test.add(task.id);
2361
+ }
2362
+ const rest = ordered.filter((task) => !test.has(task.id));
2363
+ if (rest.length < 2) throw new Error(`seal: ${rest.length} tasks remain outside the test split; train and selection must each hold one`);
2364
+ const selectionCount = Math.max(1, Math.min(rest.length - 1, Math.ceil(rest.length / 4)));
2365
+ const selection = new Set(rest.slice(0, selectionCount).map((task) => task.id));
2366
+ const splits = /* @__PURE__ */ new Map();
2367
+ for (const task of ordered) splits.set(task.id, test.has(task.id) ? "test" : selection.has(task.id) ? "selection" : "train");
2368
+ const testIds = [...test].sort(compareCodeUnits);
2369
+ return {
2370
+ splits,
2371
+ testIds,
2372
+ testSetSha256: testSetSha256(testIds)
2373
+ };
2374
+ }
2375
+ // src/real-work/solvers.ts
2376
+ /**
2377
+ * The controls that show a task separates setups. The oracle applies the real
2378
+ * change, the null solver does nothing, and the middle model is the caller's
2379
+ * command. The retrieval control is a caller's command with search over the
2380
+ * stores alone. Every verdict comes from a real grader run.
2381
+ */
2382
+ const BYTES_PER_TOKEN = 4;
2383
+ /** The last `TOKENS <n>` line a solver printed, which is how it reports its usage. */
2384
+ function reportedTokens(output) {
2385
+ const line = output.split("\n").reverse().find((candidate) => /^TOKENS\s+\d+$/.test(candidate.trim()));
2386
+ return line === void 0 ? null : Number(line.trim().split(/\s+/)[1]);
2387
+ }
2388
+ function applyChange(workdir, files) {
2389
+ let bytes = 0;
2390
+ for (const file of files) {
2391
+ const dest = join(workdir, file.path);
2392
+ if (file.content === null) rmSync(dest, { force: true });
2393
+ else {
2394
+ mkdirSync(dirname(dest), { recursive: true });
2395
+ writeFileSync(dest, file.content);
2396
+ bytes += Buffer.byteLength(file.content);
2397
+ }
2398
+ }
2399
+ return bytes;
2400
+ }
2401
+ /** Applies every file of the real change except the graders, which only the harness writes. */
2402
+ function oracleSolver(change, guarded) {
2403
+ return async ({ workdir }) => ({
2404
+ kind: "apply-merged-change",
2405
+ tokens: null,
2406
+ appliedBytes: applyChange(workdir, change.filter((file) => !guarded.has(file.path)))
2407
+ });
2408
+ }
2409
+ const nullSolver = async () => ({
2410
+ kind: "no-op",
2411
+ tokens: null,
2412
+ appliedBytes: 0
2413
+ });
2414
+ /**
2415
+ * The caller's model, invoked as `<command> <workdir> <gate> <prompt>`. A
2416
+ * model that exits nonzero has still attempted the task and is graded; a
2417
+ * command that cannot start is a measurement failure and stops the build.
2418
+ */
2419
+ function middleSolver(model) {
2420
+ return async ({ workdir, repo, prompt }) => {
2421
+ const res = await runCommand([
2422
+ ...tokenizeCommand(model.command),
2423
+ workdir,
2424
+ repo.gate?.command ?? "",
2425
+ prompt
2426
+ ], { timeoutMs: model.timeout });
2427
+ if (!res.spawned) throw new Error(`the middle model command did not start: ${res.stderr}`);
2428
+ return {
2429
+ kind: "model",
2430
+ tokens: reportedTokens(`${res.stdout}\n${res.stderr}`),
2431
+ appliedBytes: 0
2432
+ };
2433
+ };
2434
+ }
2435
+ /**
2436
+ * The notes-only control, invoked as `<command> <workdir> <prompt> <storesRoot>`
2437
+ * with the allowed tools in `REAL_WORK_RETRIEVAL_TOOLS`. It must attempt the
2438
+ * task, so a failing command stops the build instead of reading as a miss.
2439
+ */
2440
+ function retrievalSolver(retrieval, storesRoot) {
2441
+ return async ({ workdir, prompt }) => {
2442
+ const res = await runCommand([
2443
+ ...tokenizeCommand(retrieval.command),
2444
+ workdir,
2445
+ prompt,
2446
+ storesRoot
2447
+ ], {
2448
+ timeoutMs: retrieval.timeout,
2449
+ env: { REAL_WORK_RETRIEVAL_TOOLS: retrieval.tools.join(",") }
2450
+ });
2451
+ if (!res.ok) throw new Error(`the retrieval solver failed: ${res.stdout}\n${res.stderr}`);
2452
+ return {
2453
+ kind: "notes-only",
2454
+ tokens: reportedTokens(`${res.stdout}\n${res.stderr}`),
2455
+ appliedBytes: 0,
2456
+ tools: [...retrieval.tools]
2457
+ };
2458
+ };
2459
+ }
2460
+ async function runSolverCell(workdir, task, run) {
2461
+ const { run: graded, wrote, report } = await solverRun(workdir, {
2462
+ repo: run.repo,
2463
+ snapshot: task.solverSnapshot,
2464
+ grader: run.grader,
2465
+ solver: run.solver,
2466
+ prompt: task.prompt
2467
+ });
2468
+ const estimated = Math.max(1, Math.ceil((Buffer.byteLength(task.prompt) + report.appliedBytes) / BYTES_PER_TOKEN));
2469
+ return {
2470
+ cell: {
2471
+ task: task.id,
2472
+ solver: run.name,
2473
+ pass: graded.exitCode === 0 && graded.failed === 0 && graded.passed >= 1,
2474
+ runId: randomUUID(),
2475
+ tokens: report.tokens ?? estimated,
2476
+ tokensSource: report.tokens === null ? "estimated" : "reported"
2477
+ },
2478
+ wrote,
2479
+ report
2480
+ };
2481
+ }
2482
+ // src/real-work/state.ts
2483
+ /**
2484
+ * The build's persisted state, `<outDir>/.work/state.json`. Each stage extends
2485
+ * it and checkpoints after every candidate, so an interrupted build resumes
2486
+ * from the last completed stage and the candidates still `pending`.
2487
+ */
2488
+ const emptyState = () => ({
2489
+ stagesRun: [],
2490
+ census: {},
2491
+ candidates: [],
2492
+ repoLockfiles: {},
2493
+ environments: {},
2494
+ tasks: [],
2495
+ spreadCells: [],
2496
+ retrievalCells: [],
2497
+ auditReruns: [],
2498
+ seal: null
2499
+ });
2500
+ /** The build context, resumed from the persisted state when there is one. */
2501
+ function openBuild(config) {
2502
+ const workRoot = join(config.outDir, ".work");
2503
+ const statePath = join(workRoot, "state.json");
2504
+ let state = emptyState();
2505
+ if (existsSync(statePath)) {
2506
+ const saved = readJsonFile(statePath);
2507
+ if (saved === null || typeof saved !== "object" || !Array.isArray(saved.stagesRun)) throw new Error(`${statePath} is not a real-work build state`);
2508
+ state = {
2509
+ ...state,
2510
+ ...saved
2511
+ };
2512
+ }
2513
+ return {
2514
+ config,
2515
+ workRoot,
2516
+ statePath,
2517
+ state
2518
+ };
2519
+ }
2520
+ function saveState(ctx) {
2521
+ writeJsonAtomic(ctx.statePath, ctx.state);
2522
+ }
2523
+ // src/real-work/time-cut.ts
2524
+ /**
2525
+ * The time cut: what a solver may see is the snapshot and nothing after it.
2526
+ *
2527
+ * The solver's repository is one orphan commit of the snapshot tree with every
2528
+ * held-back test removed. Remotes, branches, tags and reflogs are deleted and
2529
+ * unreachable objects pruned, so neither the original history nor a held-back
2530
+ * blob survives. Receipts and audits keep using the original snapshot.
2531
+ *
2532
+ * Canaries are fresh random tokens planted in the four stores after the base.
2533
+ * The probe proves each is findable in its store, then counts its occurrences
2534
+ * in the solver's context: the prompt and every file of the solver's repository.
2535
+ */
2536
+ function assertSafeRelativePath(path) {
2537
+ const parts = path.split("/");
2538
+ if (path === "" || path.startsWith("/") || path.includes("\0") || parts.some((part) => part === "" || part === "." || part === "..")) throw new Error(`unsafe held-back path: ${JSON.stringify(path)}`);
2539
+ }
2540
+ const commitTime = (dir, commit) => gitOrThrow([
2541
+ "show",
2542
+ "-s",
2543
+ "--no-show-signature",
2544
+ "--pretty=format:%cI",
2545
+ commit
2546
+ ], { cwd: dir }).trim();
2547
+ /** Cut the solver's repository at `snapshot` into `dest`. Throws when the cut leaks. */
2548
+ function cutTaskRepo(cache, branch, snapshot, dest, heldBackPaths) {
2549
+ for (const path of heldBackPaths) assertSafeRelativePath(path);
2550
+ gitOrThrow([
2551
+ "clone",
2552
+ "--quiet",
2553
+ "--single-branch",
2554
+ "--no-checkout",
2555
+ "--branch",
2556
+ branch,
2557
+ cache,
2558
+ dest
2559
+ ]);
2560
+ gitOrThrow([
2561
+ "checkout",
2562
+ "--quiet",
2563
+ "--detach",
2564
+ snapshot
2565
+ ], { cwd: dest });
2566
+ const baseTime = commitTime(dest, snapshot);
2567
+ if (heldBackPaths.length > 0) gitOrThrow([
2568
+ "rm",
2569
+ "-r",
2570
+ "--quiet",
2571
+ "--ignore-unmatch",
2572
+ "--",
2573
+ ...heldBackPaths
2574
+ ], { cwd: dest });
2575
+ const runCommit = gitOrThrow([
2576
+ "commit-tree",
2577
+ "--no-gpg-sign",
2578
+ gitOrThrow(["write-tree"], { cwd: dest }).trim(),
2579
+ "-m",
2580
+ "Time-cut solver snapshot"
2581
+ ], {
2582
+ cwd: dest,
2583
+ env: {
2584
+ GIT_AUTHOR_NAME: "Time cut",
2585
+ GIT_AUTHOR_EMAIL: "time-cut@localhost",
2586
+ GIT_COMMITTER_NAME: "Time cut",
2587
+ GIT_COMMITTER_EMAIL: "time-cut@localhost",
2588
+ GIT_AUTHOR_DATE: baseTime,
2589
+ GIT_COMMITTER_DATE: baseTime
2590
+ }
2591
+ }).trim();
2592
+ gitOrThrow([
2593
+ "checkout",
2594
+ "--quiet",
2595
+ "--detach",
2596
+ runCommit
2597
+ ], { cwd: dest });
2598
+ git([
2599
+ "remote",
2600
+ "remove",
2601
+ "origin"
2602
+ ], { cwd: dest });
2603
+ const branches = gitOrThrow([
2604
+ "for-each-ref",
2605
+ "--format=%(refname:short)",
2606
+ "refs/heads"
2607
+ ], { cwd: dest });
2608
+ for (const name of branches.split("\n").filter(Boolean)) gitOrThrow([
2609
+ "branch",
2610
+ "-D",
2611
+ name
2612
+ ], { cwd: dest });
2613
+ const tags = gitOrThrow(["tag", "-l"], { cwd: dest }).split("\n").filter(Boolean);
2614
+ if (tags.length > 0) gitOrThrow([
2615
+ "tag",
2616
+ "-d",
2617
+ ...tags
2618
+ ], { cwd: dest });
2619
+ gitOrThrow([
2620
+ "reflog",
2621
+ "expire",
2622
+ "--expire=all",
2623
+ "--all"
2624
+ ], { cwd: dest });
2625
+ gitOrThrow([
2626
+ "gc",
2627
+ "--quiet",
2628
+ "--prune=now"
2629
+ ], { cwd: dest });
2630
+ const latestObjectTime = latestCommitTime(dest);
2631
+ if (Date.parse(latestObjectTime) > Date.parse(baseTime)) throw new Error(`the solver repository ${dest} holds a commit from ${latestObjectTime}, after the base ${baseTime}`);
2632
+ if (git([
2633
+ "cat-file",
2634
+ "-e",
2635
+ `${snapshot}^{commit}`
2636
+ ], { cwd: dest }).ok) throw new Error(`the solver repository ${dest} still holds the original snapshot ${snapshot}`);
2637
+ return {
2638
+ baseTime,
2639
+ latestObjectTime,
2640
+ runCommit
2641
+ };
2642
+ }
2643
+ /** The latest committer time of any commit reachable from a ref or HEAD. */
2644
+ function latestCommitTime(dir) {
2645
+ const out = gitOrThrow([
2646
+ "log",
2647
+ "--all",
2648
+ "HEAD",
2649
+ "--no-show-signature",
2650
+ "--pretty=format:%cI"
2651
+ ], { cwd: dir });
2652
+ let latest = null;
2653
+ for (const time of out.split("\n").filter(Boolean)) if (latest === null || Date.parse(time) > Date.parse(latest)) latest = time;
2654
+ if (latest === null) throw new Error(`no commit is reachable in ${dir}`);
2655
+ return latest;
2656
+ }
2657
+ /** Plant one fresh token in each store, dated now, which is after any snapshot. */
2658
+ function plantCanaries(storesRoot, baseTime) {
2659
+ const plantedAt = (/* @__PURE__ */ new Date()).toISOString();
2660
+ if (!(Date.parse(plantedAt) > Date.parse(baseTime))) throw new Error(`canaries must be planted after the base ${baseTime}`);
2661
+ const token = () => `canary-${randomUUID().replaceAll("-", "")}`;
2662
+ const fileId = () => randomUUID().slice(0, 8);
2663
+ mkdirSync(storesRoot, { recursive: true });
2664
+ const memory = {
2665
+ store: "memory",
2666
+ token: token(),
2667
+ plantedAt
2668
+ };
2669
+ const memoryPath = join(storesRoot, "memory.json");
2670
+ const entries = existsSync(memoryPath) ? readJsonFile(memoryPath) : [];
2671
+ if (!Array.isArray(entries)) throw new Error(`${memoryPath} must hold a JSON array`);
2672
+ entries.push({
2673
+ id: `canary-${fileId()}`,
2674
+ text: `recorded after ${baseTime}: ${memory.token}`,
2675
+ at: plantedAt
2676
+ });
2677
+ writeJsonAtomic(memoryPath, entries);
2678
+ const pages = ["knowledge", "docs"].map((store) => {
2679
+ const canary = {
2680
+ store,
2681
+ token: token(),
2682
+ plantedAt
2683
+ };
2684
+ mkdirSync(join(storesRoot, store), { recursive: true });
2685
+ writeFileSync(join(storesRoot, store, `canary-${fileId()}.md`), `# canary\n\nRecorded after ${baseTime}. Token: ${canary.token}\n`);
2686
+ return canary;
2687
+ });
2688
+ const history = {
2689
+ store: "history",
2690
+ token: token(),
2691
+ plantedAt
2692
+ };
2693
+ appendFileSync(join(storesRoot, "history.jsonl"), `${JSON.stringify({
2694
+ actor: "builder",
2695
+ at: plantedAt,
2696
+ text: `token ${history.token}`
2697
+ })}\n`);
2698
+ return [
2699
+ memory,
2700
+ ...pages,
2701
+ history
2702
+ ];
2703
+ }
2704
+ /** What a solver is given: the prompt and every file of its repository. */
2705
+ function solverContext(prompt, solverRepo) {
2706
+ const files = [];
2707
+ const visible = [prompt];
2708
+ for (const path of walkFiles(solverRepo)) {
2709
+ const content = readFileSync(join(solverRepo, path));
2710
+ files.push([path, sha256Of(content)]);
2711
+ visible.push(`${path}\n${content.toString("utf8")}`);
2712
+ }
2713
+ return {
2714
+ prompt,
2715
+ files,
2716
+ visibleText: visible.join("\n"),
2717
+ sha256: hashCanonical({
2718
+ prompt,
2719
+ files
2720
+ })
2721
+ };
2722
+ }
2723
+ function probeCanaries(context, canaries, storesRoot) {
2724
+ const storeFiles = walkFiles(storesRoot).map((path) => readFileSync(join(storesRoot, path), "utf8"));
2725
+ return canaries.map((canary) => ({
2726
+ ...canary,
2727
+ inStore: storeFiles.some((content) => content.includes(canary.token)),
2728
+ probeQueries: storeFiles.length + 1,
2729
+ hits: context.visibleText.split(canary.token).length - 1,
2730
+ solverContextSha256: context.sha256
2731
+ }));
2732
+ }
2733
+ // src/real-work/pipeline.ts
2734
+ /**
2735
+ * The build's stages. Each reads the state the earlier stages left and extends
2736
+ * it; `command.ts` runs them in order and skips the ones already complete.
2737
+ */
2738
+ const DAY_MS = 864e5;
2739
+ /** Added lines shorter than this are too common to identify a solution. */
2740
+ const IDENTIFYING_LINE_LENGTH = 30;
2741
+ const windowEnd = (config) => config.builtAt === void 0 ? Date.now() : Date.parse(config.builtAt);
2742
+ function requireCache(ctx, repo) {
2743
+ const cache = cachePath(ctx.config.outDir, repo);
2744
+ if (!existsSync(cache)) throw new Error(`the census has not cached ${repo.name}`);
2745
+ return cache;
2746
+ }
2747
+ const solverRepoPath = (ctx, taskId) => join(ctx.workRoot, "solver-repos", taskId);
2748
+ const runPath = (ctx, name) => join(ctx.workRoot, "runs", name);
2749
+ function promptFor(task) {
2750
+ return [
2751
+ `Real-work task ${task.id} in repository ${task.repo}.`,
2752
+ `A merged change (pull request ${task.prNumber ?? "without number"}, subject: ${task.subject}) is held back.`,
2753
+ `The change touches these paths: ${task.changeFiles.map((file) => file.path).join(", ")}.`,
2754
+ `Implement the change so the repository's own gate passes when restricted to the tests the change adds or changes.`,
2755
+ "Those tests are held back and are not part of the repository you see; write the implementation the tests expect.",
2756
+ "You may run the repository gate. Do not modify held-back tests."
2757
+ ].join("\n");
2758
+ }
2759
+ /** Every first-parent merge on each default branch within the window, as a candidate. */
2760
+ function stageCensus(ctx) {
2761
+ const { config, state } = ctx;
2762
+ const until = windowEnd(config);
2763
+ const since = until - config.windowDays * DAY_MS;
2764
+ state.census = {};
2765
+ state.candidates = [];
2766
+ const seen = /* @__PURE__ */ new Map();
2767
+ for (const repo of config.repos) {
2768
+ const cache = ensureCache(config.outDir, repo);
2769
+ let count = 0;
2770
+ for (const merge of listMerges(cache, repo, {
2771
+ sinceMs: since,
2772
+ untilMs: until
2773
+ })) {
2774
+ const paths = changedFiles(cache, merge.snapshotCommit, merge.mergedCommit).map((file) => file.path);
2775
+ const baseId = candidateIdOf(repo, merge);
2776
+ const occurrence = (seen.get(baseId) ?? 0) + 1;
2777
+ seen.set(baseId, occurrence);
2778
+ state.candidates.push({
2779
+ id: occurrence === 1 ? baseId : `${baseId}-${occurrence}`,
2780
+ repo: repo.name,
2781
+ prNumber: merge.prNumber,
2782
+ mergedCommit: merge.mergedCommit,
2783
+ mergedAt: merge.mergedAt,
2784
+ snapshotCommit: merge.snapshotCommit,
2785
+ subject: merge.subject,
2786
+ branchSubject: merge.branchSubject,
2787
+ authorEmail: merge.authorEmail,
2788
+ paths,
2789
+ testPaths: paths.filter(isTestFile),
2790
+ addedLineCount: paths.reduce((sum, path) => sum + addedLines(cache, merge.snapshotCommit, merge.mergedCommit, path).length, 0),
2791
+ reason: "pending"
2792
+ });
2793
+ count++;
2794
+ }
2795
+ state.census[repo.name] = count;
2796
+ }
2797
+ saveState(ctx);
2798
+ }
2799
+ /** The reason a candidate is rejected before any environment is built, if there is one. */
2800
+ function preEnvironmentReason(candidate, config) {
2801
+ if (candidate.testPaths.length === 0) return "no-tests";
2802
+ if (candidate.addedLineCount > config.maxAddedLines || candidate.paths.length > config.maxFiles) return "too-large";
2803
+ const nonTest = candidate.paths.filter((path) => !isTestFile(path));
2804
+ const generated = (path) => config.generatedOnly.some((pattern) => path === pattern || path.startsWith(pattern));
2805
+ if (nonTest.length > 0 && nonTest.every(generated)) return "generated-only";
2806
+ return null;
2807
+ }
2808
+ /** Two clean environment builds per eligible candidate, at its snapshot, from the frozen lockfile. */
2809
+ async function stageBuildEnv(ctx) {
2810
+ const { config, state } = ctx;
2811
+ for (const repo of config.repos) {
2812
+ const cache = requireCache(ctx, repo);
2813
+ const lockfile = repo.gate?.lockfile ?? "package-lock.json";
2814
+ const gateRef = repo.gateRef ?? repo.defaultBranch;
2815
+ if (blobContent(cache, gateRef, lockfile) !== null) state.repoLockfiles[repo.name] = lockfileSha(cache, gateRef, lockfile);
2816
+ }
2817
+ for (const candidate of state.candidates) {
2818
+ if (state.environments[candidate.id]) continue;
2819
+ const repo = repoNamed(config, candidate.repo);
2820
+ const cache = requireCache(ctx, repo);
2821
+ const lockfile = repo.gate?.lockfile ?? "package-lock.json";
2822
+ const frozen = state.repoLockfiles[repo.name];
2823
+ const unbuildable = (error) => ({
2824
+ buildable: false,
2825
+ builds: [],
2826
+ lockfileSha256: null,
2827
+ error
2828
+ });
2829
+ if (!repo.gate || preEnvironmentReason(candidate, config) !== null) state.environments[candidate.id] = unbuildable(null);
2830
+ else if (frozen === void 0) state.environments[candidate.id] = unbuildable(`${lockfile} is missing at ${repo.gateRef ?? repo.defaultBranch}`);
2831
+ else if (blobContent(cache, candidate.snapshotCommit, lockfile) === null) state.environments[candidate.id] = unbuildable(`${lockfile} is missing at the snapshot`);
2832
+ else if (lockfileSha(cache, candidate.snapshotCommit, lockfile) !== frozen) state.environments[candidate.id] = unbuildable(`the snapshot's ${lockfile} differs from ${repo.gateRef ?? repo.defaultBranch}`);
2833
+ else state.environments[candidate.id] = await buildEnvironment(cache, repo, {
2834
+ snapshot: candidate.snapshotCommit,
2835
+ workRoot: join(ctx.workRoot, "env")
2836
+ });
2837
+ saveState(ctx);
2838
+ }
2839
+ }
2840
+ /** Red and green receipts for each pending candidate, in batches of `gradeBatchSize`. */
2841
+ async function stageGrade(ctx) {
2842
+ const { config, state } = ctx;
2843
+ const graded = new Set(state.tasks.map((task) => task.id));
2844
+ const seenMerged = new Set(state.tasks.map((task) => task.mergedCommit));
2845
+ let batch = 0;
2846
+ for (const candidate of state.candidates) {
2847
+ if (candidate.reason !== "pending") {
2848
+ if (candidate.reason === "task" && !graded.has(candidate.id)) throw new Error(`the checkpoint is missing graded task ${candidate.id}`);
2849
+ continue;
2850
+ }
2851
+ const buildable = state.environments[candidate.id]?.buildable === true;
2852
+ if (buildable && config.gradeBatchSize !== void 0 && batch >= config.gradeBatchSize) return { paused: true };
2853
+ if (buildable) batch++;
2854
+ const task = await gradeCandidate(ctx, candidate, seenMerged);
2855
+ if (task) state.tasks.push(task);
2856
+ saveState(ctx);
2857
+ }
2858
+ return { paused: false };
2859
+ }
2860
+ async function gradeCandidate(ctx, candidate, seenMerged) {
2861
+ const { config } = ctx;
2862
+ const reject = (reason) => {
2863
+ candidate.reason = reason;
2864
+ return null;
2865
+ };
2866
+ const repo = repoNamed(config, candidate.repo);
2867
+ if (!repo.gate) return reject("no-gate");
2868
+ const early = preEnvironmentReason(candidate, config);
2869
+ if (early) return reject(early);
2870
+ if (ctx.state.environments[candidate.id]?.buildable !== true) return reject("env-unbuildable");
2871
+ if (seenMerged.has(candidate.mergedCommit)) return reject("duplicate");
2872
+ const cache = requireCache(ctx, repo);
2873
+ const { snapshotCommit, mergedCommit } = candidate;
2874
+ const changeFiles = changedFiles(cache, snapshotCommit, mergedCommit).map((file) => {
2875
+ const content = blobContent(cache, mergedCommit, file.path);
2876
+ const before = blobContent(cache, snapshotCommit, file.path);
2877
+ const added = file.status === "D" ? [] : addedLines(cache, snapshotCommit, mergedCommit, file.path);
2878
+ return {
2879
+ path: file.path,
2880
+ status: file.status,
2881
+ content,
2882
+ snapshotSha256: before === null ? null : sha256Of(before),
2883
+ postSha256: content === null ? null : sha256Of(content),
2884
+ added,
2885
+ addedLineHashes: added.filter((line) => line.trim().length >= IDENTIFYING_LINE_LENGTH).map((line) => sha256Of(line.trim()))
2886
+ };
2887
+ });
2888
+ const grader = graderAt(cache, repo, mergedCommit, candidate.testPaths);
2889
+ const machine = receiptMachine(config);
2890
+ const red = await takeReceipt(cache, runPath(ctx, `${candidate.id}-red`), {
2891
+ repo,
2892
+ snapshot: snapshotCommit,
2893
+ applied: null,
2894
+ grader,
2895
+ machine
2896
+ });
2897
+ if (red.environmentError) return reject("env-unbuildable");
2898
+ const green = await takeReceipt(cache, runPath(ctx, `${candidate.id}-green`), {
2899
+ repo,
2900
+ snapshot: snapshotCommit,
2901
+ applied: mergedCommit,
2902
+ grader,
2903
+ machine
2904
+ });
2905
+ if (green.environmentError) return reject("env-unbuildable");
2906
+ if (green.receipt.passed + green.receipt.failed === 0) return reject("no-tests");
2907
+ if (!runsAgree(red.receipt.runs) || !runsAgree(green.receipt.runs)) return reject("tests-flaky");
2908
+ const redVerdict = receiptVerdict(red.receipt);
2909
+ if (redVerdict.passes) return reject("already-passes");
2910
+ if (!redVerdict.fails) return reject("tests-flaky");
2911
+ if (candidate.paths.every(isTestFile)) return reject("generated-only");
2912
+ if (!receiptVerdict(green.receipt).passes) return reject("merged-fails");
2913
+ const greenPassed = new Set(green.receipt.passedTests);
2914
+ if (!red.receipt.failedTests.every((name) => greenPassed.has(name))) return reject("tests-flaky");
2915
+ seenMerged.add(mergedCommit);
2916
+ candidate.reason = "task";
2917
+ const subject = candidate.branchSubject;
2918
+ const task = {
2919
+ id: candidate.id,
2920
+ repo: repo.name,
2921
+ kind: classifyKind({
2922
+ subject,
2923
+ paths: candidate.paths,
2924
+ addedLines: changeFiles.flatMap((file) => file.added)
2925
+ }, config.kinds),
2926
+ prNumber: candidate.prNumber,
2927
+ snapshotCommit,
2928
+ mergedCommit,
2929
+ mergedAt: candidate.mergedAt,
2930
+ subject,
2931
+ prompt: "",
2932
+ changeFiles,
2933
+ grader,
2934
+ testIds: [.../* @__PURE__ */ new Set([...green.receipt.passedTests, ...green.receipt.failedTests])],
2935
+ graderAuthor: {
2936
+ kind: repo.graderAuthorKind,
2937
+ ref: candidate.authorEmail
2938
+ },
2939
+ heldBackPaths: [...candidate.testPaths],
2940
+ receipts: {
2941
+ red: red.receipt,
2942
+ green: green.receipt
2943
+ },
2944
+ laterFix: null,
2945
+ hiddenGrader: null,
2946
+ solverWrites: [],
2947
+ solvers: [],
2948
+ timeCut: null,
2949
+ split: null
2950
+ };
2951
+ task.prompt = promptFor(task);
2952
+ return task;
2953
+ }
2954
+ /** Hidden graders from fixes merged within seven days that touch the same code. */
2955
+ async function stageLaterFix(ctx) {
2956
+ const { config, state } = ctx;
2957
+ const until = windowEnd(config);
2958
+ for (const repo of config.repos) {
2959
+ const cache = requireCache(ctx, repo);
2960
+ const merges = listMerges(cache, repo);
2961
+ for (const task of state.tasks.filter((candidate) => candidate.repo === repo.name)) {
2962
+ if (task.laterFix !== null) continue;
2963
+ for (const fix of findLaterFixes(cache, task, merges, until)) {
2964
+ const built = await buildLaterFix(cache, repo, task, fix, {
2965
+ workRoot: join(ctx.workRoot, "runs"),
2966
+ machine: receiptMachine(config)
2967
+ });
2968
+ if (built) {
2969
+ task.laterFix = built.laterFix;
2970
+ task.hiddenGrader = built.grader;
2971
+ saveState(ctx);
2972
+ break;
2973
+ }
2974
+ }
2975
+ }
2976
+ }
2977
+ saveState(ctx);
2978
+ }
2979
+ /** Each task's solver repository, cut at its snapshot, and canaries planted and probed. */
2980
+ function stageTimeCut(ctx) {
2981
+ const { config, state } = ctx;
2982
+ for (const task of state.tasks) {
2983
+ const repo = repoNamed(config, task.repo);
2984
+ const dest = solverRepoPath(ctx, task.id);
2985
+ removeDirectory(dest);
2986
+ const cut = cutTaskRepo(requireCache(ctx, repo), repo.defaultBranch, task.snapshotCommit, dest, task.heldBackPaths);
2987
+ const probed = probeCanaries(solverContext(task.prompt, dest), plantCanaries(config.stores.root, cut.baseTime), config.stores.root);
2988
+ const vacuous = probed.find((canary) => !canary.inStore);
2989
+ if (vacuous) throw new Error(`the ${vacuous.store} canary for ${task.id} is not in its store`);
2990
+ const leaked = probed.find((canary) => canary.hits > 0);
2991
+ if (leaked) throw new Error(`the ${leaked.store} canary reached the solver context of ${task.id}`);
2992
+ task.timeCut = {
2993
+ baseTime: cut.baseTime,
2994
+ latestObjectTime: cut.latestObjectTime,
2995
+ solverCommit: cut.runCommit,
2996
+ canaries: probed
2997
+ };
2998
+ saveState(ctx);
2999
+ }
3000
+ }
3001
+ function requireTimeCut(task) {
3002
+ if (task.timeCut === null) throw new Error(`task ${task.id} has no time cut`);
3003
+ return task.timeCut;
3004
+ }
3005
+ /** The oracle, null and middle-model cells, each graded on the solver's own checkout. */
3006
+ async function stageSolve(ctx) {
3007
+ const { config, state } = ctx;
3008
+ state.spreadCells = [];
3009
+ const middle = middleSolver(config.middleModel);
3010
+ for (const task of state.tasks) {
3011
+ const repo = repoNamed(config, task.repo);
3012
+ const timeCut = requireTimeCut(task);
3013
+ const workdir = ensureRunClone(solverRepoPath(ctx, task.id), runPath(ctx, `${task.id}-solve`));
3014
+ const guarded = /* @__PURE__ */ new Set([...task.grader.paths, ...task.hiddenGrader?.paths ?? []]);
3015
+ const writes = /* @__PURE__ */ new Set();
3016
+ try {
3017
+ for (const [name, solver] of [
3018
+ ["oracle", oracleSolver(task.changeFiles, guarded)],
3019
+ ["null", nullSolver],
3020
+ ["middle", middle]
3021
+ ]) {
3022
+ const { cell, wrote } = await runSolverCell(workdir, {
3023
+ id: task.id,
3024
+ prompt: task.prompt,
3025
+ solverSnapshot: timeCut.solverCommit
3026
+ }, {
3027
+ repo,
3028
+ grader: task.hiddenGrader ?? task.grader,
3029
+ solver,
3030
+ name
3031
+ });
3032
+ state.spreadCells.push(cell);
3033
+ for (const path of wrote) writes.add(path);
3034
+ }
3035
+ } finally {
3036
+ removeDirectory(workdir);
3037
+ }
3038
+ task.solvers = [config.middleModel.name];
3039
+ task.solverWrites = [...writes].sort(compareCodeUnits);
3040
+ saveState(ctx);
3041
+ }
3042
+ }
3043
+ /** The notes-only control on every task; a task it solves is dropped as `answer-in-notes`. */
3044
+ async function stageRetrieval(ctx) {
3045
+ const { config, state } = ctx;
3046
+ state.retrievalCells = [];
3047
+ const solver = retrievalSolver(config.retrieval, config.stores.root);
3048
+ const answered = /* @__PURE__ */ new Set();
3049
+ for (const task of state.tasks) {
3050
+ const timeCut = requireTimeCut(task);
3051
+ const workdir = ensureRunClone(solverRepoPath(ctx, task.id), runPath(ctx, `${task.id}-retrieval`));
3052
+ try {
3053
+ const { run, report } = await solverRun(workdir, {
3054
+ repo: repoNamed(config, task.repo),
3055
+ snapshot: timeCut.solverCommit,
3056
+ grader: task.grader,
3057
+ solver,
3058
+ prompt: task.prompt
3059
+ });
3060
+ const pass = run.exitCode === 0 && run.failed === 0 && run.passed >= 1;
3061
+ state.retrievalCells.push({
3062
+ task: task.id,
3063
+ pass,
3064
+ runId: randomUUID(),
3065
+ tools: report.tools ?? []
3066
+ });
3067
+ if (pass) answered.add(task.id);
3068
+ } finally {
3069
+ removeDirectory(workdir);
3070
+ }
3071
+ }
3072
+ for (const candidate of state.candidates) if (answered.has(candidate.id)) candidate.reason = "answer-in-notes";
3073
+ state.tasks = state.tasks.filter((task) => !answered.has(task.id));
3074
+ saveState(ctx);
3075
+ }
3076
+ /**
3077
+ * Red and green rerun for a sample of tasks, recorded under the configured
3078
+ * auditor. The builder cannot verify who invoked it, so a rerun is independent
3079
+ * only when the auditor runs this stage: the builder runs `seal`, the auditor
3080
+ * runs `report`.
3081
+ */
3082
+ async function stageAudit(ctx) {
3083
+ const { config, state } = ctx;
3084
+ const count = config.audit.count ?? Math.max(3, Math.ceil(state.tasks.length / 10));
3085
+ const sample = [...state.tasks].sort((a, b) => compareCodeUnits(a.id, b.id)).slice(0, count);
3086
+ state.auditReruns = [];
3087
+ for (const task of sample) {
3088
+ const repo = repoNamed(config, task.repo);
3089
+ const workdir = ensureRunClone(requireCache(ctx, repo), runPath(ctx, `${task.id}-audit`));
3090
+ try {
3091
+ const run = {
3092
+ repo,
3093
+ snapshot: task.snapshotCommit,
3094
+ grader: task.grader
3095
+ };
3096
+ const red = await gradedRun(workdir, {
3097
+ ...run,
3098
+ applied: null
3099
+ });
3100
+ const green = await gradedRun(workdir, {
3101
+ ...run,
3102
+ applied: task.mergedCommit
3103
+ });
3104
+ state.auditReruns.push({
3105
+ task: task.id,
3106
+ by: config.audit.agent,
3107
+ redExit: red.exitCode,
3108
+ greenExit: green.exitCode
3109
+ });
3110
+ } finally {
3111
+ removeDirectory(workdir);
3112
+ }
3113
+ }
3114
+ saveState(ctx);
3115
+ }
3116
+ function stageSeal(ctx) {
3117
+ const { state } = ctx;
3118
+ const sealed = sealSplits(state.tasks, ctx.config.seal);
3119
+ for (const task of state.tasks) task.split = sealed.splits.get(task.id) ?? null;
3120
+ state.seal = {
3121
+ testSetSha256: sealed.testSetSha256,
3122
+ testIds: sealed.testIds,
3123
+ sealedAt: (/* @__PURE__ */ new Date()).toISOString()
3124
+ };
3125
+ saveState(ctx);
3126
+ }
3127
+ function stageReport(ctx, builder) {
3128
+ writeReport(ctx.config, ctx.state, {
3129
+ builtAt: ctx.config.builtAt ?? (/* @__PURE__ */ new Date()).toISOString(),
3130
+ builder
3131
+ });
3132
+ }
3133
+ // src/real-work/command.ts
3134
+ /**
3135
+ * `agent-eval real-work <stage> <config.json>`: build a benchmark of real work
3136
+ * from merged changes in git history. `build` runs every stage; any other
3137
+ * stage runs the incomplete stages up to it. Progress persists in
3138
+ * `<outDir>/.work/state.json`, so an interrupted build resumes.
3139
+ */
3140
+ const PACKAGE_NAME = "@tangle-network/agent-eval";
3141
+ const BUILDER_REPO = "tangle-network/agent-eval";
3142
+ const BUILDER_PATH = "src/real-work/";
3143
+ const PIPELINE = [
3144
+ "census",
3145
+ "build-env",
3146
+ "grade",
3147
+ "laterfix",
3148
+ "timecut",
3149
+ "solve",
3150
+ "retrieval",
3151
+ "audit",
3152
+ "seal",
3153
+ "report"
3154
+ ];
3155
+ /** The stages each subcommand runs. `seal` stops before the audit, so an auditor can run `report`. */
3156
+ const SUBCOMMANDS = {
3157
+ census: PIPELINE.slice(0, 1),
3158
+ "build-env": PIPELINE.slice(0, 2),
3159
+ grade: PIPELINE.slice(0, 3),
3160
+ laterfix: PIPELINE.slice(0, 4),
3161
+ timecut: PIPELINE.slice(0, 5),
3162
+ seal: PIPELINE.filter((stage) => stage !== "audit" && stage !== "report"),
3163
+ report: PIPELINE,
3164
+ build: PIPELINE
3165
+ };
3166
+ const USAGE$1 = `usage: agent-eval real-work <${Object.keys(SUBCOMMANDS).join("|")}> <config.json>
3167
+
3168
+ Builds a benchmark of real work from merged changes: each task starts at the
3169
+ code before a merged change, holds back the tests the change added or changed,
3170
+ and is graded by them. See docs/real-work.md for the config and every page.`;
3171
+ const PROCESS_IO$1 = {
3172
+ stdout: (text) => process.stdout.write(text),
3173
+ stderr: (text) => process.stderr.write(text)
3174
+ };
3175
+ /** The directory of this package: the agent-eval checkout or the installed package. */
3176
+ function packageRoot() {
3177
+ let dir = dirname(fileURLToPath(import.meta.url));
3178
+ for (;;) {
3179
+ const manifest = join(dir, "package.json");
3180
+ if (existsSync(manifest)) try {
3181
+ if (JSON.parse(readFileSync(manifest, "utf8")).name === PACKAGE_NAME) return dir;
3182
+ } catch {}
3183
+ const parent = dirname(dir);
3184
+ if (parent === dir) return null;
3185
+ dir = parent;
3186
+ }
3187
+ }
3188
+ /**
3189
+ * The commit of the builder that ran: HEAD of the agent-eval checkout holding
3190
+ * this code. An installed package is not a checkout, so it needs
3191
+ * `builderCommit` in the config. A config commit that disagrees with the
3192
+ * checkout is refused rather than recorded.
3193
+ */
3194
+ function resolveBuilderCommit(config) {
3195
+ const root = packageRoot();
3196
+ if (root !== null) {
3197
+ const top = git(["rev-parse", "--show-toplevel"], { cwd: root });
3198
+ if (top.ok && realpathSync(top.stdout.trim()) === realpathSync(root)) {
3199
+ const head = git(["rev-parse", "HEAD"], { cwd: root });
3200
+ if (head.ok) {
3201
+ const commit = head.stdout.trim();
3202
+ if (config.builderCommit !== void 0 && config.builderCommit !== commit) throw new ConfigError(`builderCommit ${config.builderCommit} disagrees with the checkout running the builder (${commit})`);
3203
+ return commit;
3204
+ }
3205
+ }
3206
+ }
3207
+ if (config.builderCommit !== void 0) return config.builderCommit;
3208
+ throw new ConfigError("cannot resolve the builder commit: run from an agent-eval git checkout, or set builderCommit");
3209
+ }
3210
+ async function runStage(ctx, stage, builder) {
3211
+ switch (stage) {
3212
+ case "census":
3213
+ stageCensus(ctx);
3214
+ return { paused: false };
3215
+ case "build-env":
3216
+ await stageBuildEnv(ctx);
3217
+ return { paused: false };
3218
+ case "grade": return await stageGrade(ctx);
3219
+ case "laterfix":
3220
+ await stageLaterFix(ctx);
3221
+ return { paused: false };
3222
+ case "timecut":
3223
+ stageTimeCut(ctx);
3224
+ return { paused: false };
3225
+ case "solve":
3226
+ await stageSolve(ctx);
3227
+ return { paused: false };
3228
+ case "retrieval":
3229
+ await stageRetrieval(ctx);
3230
+ return { paused: false };
3231
+ case "audit":
3232
+ await stageAudit(ctx);
3233
+ return { paused: false };
3234
+ case "seal":
3235
+ stageSeal(ctx);
3236
+ return { paused: false };
3237
+ case "report":
3238
+ if (builder === null) throw new Error("the report stage needs the builder identity");
3239
+ stageReport(ctx, {
3240
+ repo: BUILDER_REPO,
3241
+ path: BUILDER_PATH,
3242
+ ...builder
3243
+ });
3244
+ return { paused: false };
3245
+ }
3246
+ }
3247
+ async function runRealWorkCommand(argv, io = PROCESS_IO$1) {
3248
+ if (argv.includes("--help") || argv.includes("-h")) {
3249
+ io.stdout(`${USAGE$1}\n`);
3250
+ return 0;
3251
+ }
3252
+ const [subcommand, configPath, ...extra] = argv;
3253
+ const stages = subcommand === void 0 ? void 0 : SUBCOMMANDS[subcommand];
3254
+ if (stages === void 0 || configPath === void 0 || extra.length > 0) {
3255
+ io.stderr(`${USAGE$1}\n`);
3256
+ return 2;
3257
+ }
3258
+ let config;
3259
+ try {
3260
+ config = loadRealWorkConfig(configPath);
3261
+ } catch (error) {
3262
+ io.stderr(`${error instanceof Error ? error.message : String(error)}\n`);
3263
+ return 2;
3264
+ }
3265
+ try {
3266
+ const ctx = openBuild(config);
3267
+ const builder = stages.includes("report") ? {
3268
+ commit: resolveBuilderCommit(config),
3269
+ command: config.builderCommand ?? `agent-eval real-work ${subcommand} ${configPath}`
3270
+ } : null;
3271
+ for (const stage of stages) {
3272
+ if (stage !== "report" && ctx.state.stagesRun.includes(stage)) {
3273
+ io.stdout(`stage ${stage} already complete\n`);
3274
+ continue;
3275
+ }
3276
+ const { paused } = await runStage(ctx, stage, builder);
3277
+ if (paused) {
3278
+ saveState(ctx);
3279
+ io.stdout(`stage ${stage} paused after ${config.gradeBatchSize} candidates\n`);
3280
+ return 0;
3281
+ }
3282
+ if (stage === "report") io.stdout(`wrote the report to ${config.outDir}: ${ctx.state.tasks.length} tasks of ${ctx.state.candidates.length} candidates\n`);
3283
+ else {
3284
+ ctx.state.stagesRun.push(stage);
3285
+ saveState(ctx);
3286
+ io.stdout(`stage ${stage} done\n`);
3287
+ }
3288
+ }
3289
+ return 0;
3290
+ } catch (error) {
3291
+ const message = error instanceof AgentEvalError || !(error instanceof Error) ? String(error instanceof Error ? error.message : error) : error.stack ?? error.message;
3292
+ io.stderr(`real-work build failed: ${message}\n`);
3293
+ return 1;
3294
+ }
3295
+ }
1184
3296
  // src/search-command.ts
1185
3297
  /**
1186
3298
  * `agent-eval search <subcommand>`: work with a search ledger from a terminal.
@@ -1806,6 +3918,7 @@ async function runSupervisorRunCommand(argv, io = PROCESS_IO) {
1806
3918
  * agent-eval search show <search-ledger.jsonl>
1807
3919
  * agent-eval skill-usage <transcripts-dir> [--since 7d]
1808
3920
  * agent-eval procedure-registry <sessions-dir> [--ledger <path>]... [--since 30d] [--outcomes <file>] [--change-ledger <file>]...
3921
+ * agent-eval real-work <stage|build> <config.json>
1809
3922
  * agent-eval openapi [--out path] # write OpenAPI spec
1810
3923
  * agent-eval version
1811
3924
  *
@@ -1889,6 +4002,11 @@ Commands:
1889
4002
  that served it, its cost and how it ended; the labeler module's default
1890
4003
  export labels turns, and without one no turn has a kind or a correction.
1891
4004
  The JSON registry goes to stdout and the table to stderr.
4005
+ real-work <census|build-env|grade|laterfix|timecut|seal|report|build> <config.json>
4006
+ Build a benchmark of real work from merged changes in git history: each
4007
+ task starts before a merged change, holds back the tests it added or
4008
+ changed, and is graded by them. 'build' runs every stage; progress
4009
+ persists under the config's outDir, so a stopped build resumes.
1892
4010
  version
1893
4011
  Print server + wire-protocol version JSON.
1894
4012
 
@@ -1904,6 +4022,7 @@ async function main() {
1904
4022
  assertKnownFlags(command, flags);
1905
4023
  if (command === "analyst-benchmark" && flags.help === "true") return await runAnalystBenchmarkCommand(process.argv.slice(3));
1906
4024
  if (command === "search") return await runSearchCommand(process.argv.slice(3));
4025
+ if (command === "real-work") return await runRealWorkCommand(process.argv.slice(3));
1907
4026
  if (flags.help === "true") {
1908
4027
  process.stdout.write(`${HELP}\n`);
1909
4028
  return 0;
@@ -1991,7 +4110,7 @@ const FLAGS_BY_COMMAND = {
1991
4110
  "": /* @__PURE__ */ new Set()
1992
4111
  };
1993
4112
  function assertKnownFlags(command, flags) {
1994
- if (command === "rollout-release" || command === "analyst-benchmark" || command === "supervisor-run" || command === "skill-usage" || command === "procedure-registry" || command === "search") return;
4113
+ if (command === "rollout-release" || command === "analyst-benchmark" || command === "supervisor-run" || command === "skill-usage" || command === "procedure-registry" || command === "real-work" || command === "search") return;
1995
4114
  const allowed = FLAGS_BY_COMMAND[command];
1996
4115
  if (!allowed) return;
1997
4116
  const unknown = Object.keys(flags).filter((flag) => !allowed.has(flag));