Repository navigation
Expand file tree
/
Copy pathrun-pilot-agent.mjs
More file actions
executable file
·1684 lines (1522 loc) · 71.1 KB
/
Copy pathrun-pilot-agent.mjs
File metadata and controls
executable file
·1684 lines (1522 loc) · 71.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
import path from "node:path";
import { createHash } from "node:crypto";
import { homedir, tmpdir } from "node:os";
import { fileURLToPath } from "node:url";
import { spawnSync } from "node:child_process";
import { executableOnPath } from "./lib/executable.mjs";
import { parseArgs } from "./lib/args.mjs";
import { run } from "./lib/process.mjs";
import { classifyCommand, subcommand, policyBlocked, taskPolicyBlocked } from "./lib/tool-policy.mjs";
import { createCommandGuards } from "./lib/command-guards.mjs";
import { SCENARIO_TASKS, loadScenario } from "./lib/scenarios.mjs";
import { runBounded } from "./lib/bounded-process.mjs";
import { normalizeAgentEvents } from "./lib/agent-events.mjs";
import { buildPerformance } from "./lib/performance.mjs";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, "..");
const DEFAULT_CODEX_MODEL = "gpt-6.1-sol";
const DEFAULT_VERSION_PINS = {git: "git version 2.44.0", but: "but 0.5.2189", jj: "jj 0.42.0"};
function loadVersionPins(profilePath) {
const overrides = profilePath ? JSON.parse(readFileSync(profilePath, "utf8")) : {};
if (!overrides || Array.isArray(overrides) || typeof overrides !== "object"
|| Object.entries(overrides).some(([key, value]) => !Object.hasOwn(DEFAULT_VERSION_PINS, key) || typeof value !== "string" || !value.trim() || value !== value.trim())) {
throw new Error("--version-pins must contain an object with only git/but/jj nonempty version strings");
}
return {profile_path: profilePath, expected: {...DEFAULT_VERSION_PINS, ...overrides}, observed: {}};
}
// Versioned model ID, not the floating `opus` alias: reruns of a published
// batch must hit the same model. Current-generation Claude models have no
// dated snapshots; the versioned ID is the pin. Override with --model.
const DEFAULT_CLAUDE_MODEL = "claude-opus-5-5";
const DEFAULT_JJ_SKILL = {
package: "onevcat/skills@onevcat-jj",
name: "onevcat-jj",
// Pinned to the last upstream commit touching the skill so runs are
// reproducible; the fetched bytes are verified against expected_sha256.
source_rev: "4955f5422d992db58ddb3652ec1c1b552405b39d",
source_url: "https://raw.githubusercontent.com/onevcat/skills/4955f5422d992db58ddb3652ec1c1b552405b39d/skills/onevcat-jj/SKILL.md",
expected_sha256: "e0364004187a1769adc0b532befe346fd4b372bb1aab2768b9ebb694f2d13687",
selection_note: "Top direct jj result from `npx skills find jj` on 2026-06-29; the skills CLI showed 279 installs.",
};
const TASK_CONFIGS = {
...Object.fromEntries(SCENARIO_TASKS.map(task => [task.id, task])),
"pilot-1-selective-validation": {
id: "pilot-1-selective-validation",
taskDir: "tasks/pilot-1-selective-validation",
createFixtureScript: "scripts/create-pilot-fixture.mjs",
applyStateScript: "scripts/apply-pilot-state.mjs",
verifyScript: "scripts/verify-pilot.mjs",
gitbutlerPrep: "setup",
},
"pilot-2-multi-amend": {
id: "pilot-2-multi-amend",
taskDir: "tasks/pilot-2-multi-amend",
createFixtureScript: "scripts/create-pilot2-fixture.mjs",
applyStateScript: "scripts/apply-pilot2-state.mjs",
verifyScript: "scripts/verify-pilot2.mjs",
gitbutlerPrep: "setup-and-apply-branch",
applyBranch: "amend-series",
},
"pilot-3-split-commit": {
id: "pilot-3-split-commit",
taskDir: "tasks/pilot-3-split-commit",
createFixtureScript: "scripts/create-pilot3-fixture.mjs",
applyStateScript: "scripts/apply-pilot3-state.mjs",
verifyScript: "scripts/verify-pilot3.mjs",
gitbutlerPrep: "setup-and-apply-branch",
applyBranch: "split-workflow",
fixtureDirty: false,
applyDirtyState: false,
},
"pilot-4-reorder-commits": {
id: "pilot-4-reorder-commits",
taskDir: "tasks/pilot-4-reorder-commits",
createFixtureScript: "scripts/create-pilot4-fixture.mjs",
verifyScript: "scripts/verify-pilot4.mjs",
gitbutlerPrep: "setup-and-apply-branch",
applyBranch: "reorder-series",
fixtureDirty: false,
applyDirtyState: false,
},
"pilot-5-squash-commits": {
id: "pilot-5-squash-commits",
taskDir: "tasks/pilot-5-squash-commits",
createFixtureScript: "scripts/create-pilot5-fixture.mjs",
verifyScript: "scripts/verify-pilot5.mjs",
gitbutlerPrep: "setup-and-apply-branch",
applyBranch: "squash-series",
fixtureDirty: false,
applyDirtyState: false,
},
"pilot-6-update-dirty-branch": {
id: "pilot-6-update-dirty-branch",
taskDir: "tasks/pilot-6-update-dirty-branch",
createFixtureScript: "scripts/create-pilot6-fixture.mjs",
applyStateScript: "scripts/apply-pilot6-state.mjs",
verifyScript: "scripts/verify-pilot6.mjs",
gitbutlerPrep: "setup-and-apply-branch",
applyBranch: "notify-retry",
},
};
let taskConfig;
let taskDir;
let scenario;
let scenarioMetadata;
function shellQuote(value) {
return `'${String(value).replaceAll("'", "'\\''")}'`;
}
function commandPath(command) {
const result = spawnSync("bash", ["-lc", `command -v ${shellQuote(command)} || true`], {
encoding: "utf8",
});
return result.stdout.trim();
}
function executablePath(value, fallbackCommand) {
const candidate = value ?? commandPath(fallbackCommand);
if (!candidate) {
throw new Error(`Could not find required executable: ${fallbackCommand}`);
}
if (!value || candidate.includes("/") || path.isAbsolute(candidate)) {
return path.resolve(candidate);
}
const found = commandPath(candidate);
if (!found) {
throw new Error(`Could not find required executable: ${candidate}`);
}
return path.resolve(found);
}
function sha256Text(text) {
return createHash("sha256").update(text).digest("hex");
}
function sha256File(filePath) {
return createHash("sha256").update(readFileSync(filePath)).digest("hex");
}
function sortedDirectoryFiles(dir) {
return readdirSync(dir)
.flatMap((entry) => {
const fullPath = path.join(dir, entry);
const stat = statSync(fullPath);
if (stat.isDirectory()) return sortedDirectoryFiles(fullPath);
if (stat.isFile()) return [fullPath];
return [];
})
.sort();
}
function sha256Directory(dir) {
const hash = createHash("sha256");
for (const filePath of sortedDirectoryFiles(dir)) {
hash.update(path.relative(dir, filePath).split(path.sep).join("/"));
hash.update("\0");
hash.update(readFileSync(filePath));
hash.update("\0");
}
return hash.digest("hex");
}
function nearestGitRoot(targetPath) {
let dir = statSync(targetPath).isDirectory() ? targetPath : path.dirname(targetPath);
while (dir !== path.dirname(dir)) {
if (existsSync(path.join(dir, ".git"))) return dir;
dir = path.dirname(dir);
}
return null;
}
function gitOutputOrNull(root, args) {
const result = spawnSync("git", ["-C", root, ...args], { encoding: "utf8" });
if (result.status !== 0) return null;
return result.stdout.trimEnd();
}
function gitSourceInfo(targetPath, { scope = "path" } = {}) {
const root = nearestGitRoot(targetPath);
if (!root) return null;
const relativePath = path.relative(root, targetPath);
if (scope === "path" && !gitOutputOrNull(root, ["ls-files", "--", relativePath])) return null;
const statusArgs = scope === "repo"
? ["status", "--short"]
: ["status", "--short", "--", relativePath];
const statusShort = gitOutputOrNull(root, statusArgs) ?? "";
return {
root,
head: gitOutputOrNull(root, ["rev-parse", "HEAD"]),
dirty: statusShort.length > 0,
status_short: statusShort,
};
}
function copyIfExists(source, dest) {
if (!existsSync(source)) return false;
cpSync(source, dest);
return true;
}
function prepareCodexHome(runDir, enabled) {
if (!enabled) return null;
const sourceHome = path.resolve(process.env.CODEX_HOME ?? path.join(process.env.HOME ?? "", ".codex"));
const codexHome = path.join(runDir, "codex-home");
mkdirSync(codexHome, { recursive: true });
return {
path: codexHome,
source_home: sourceHome,
auth_copied: copyIfExists(path.join(sourceHome, "auth.json"), path.join(codexHome, "auth.json")),
installation_id_copied: copyIfExists(path.join(sourceHome, "installation_id"), path.join(codexHome, "installation_id")),
};
}
function prepareClaudeSettings(runDir, enabled, effortLevel) {
if (!enabled) return null;
const settingsPath = path.join(runDir, "claude-settings.json");
const settings = {
permissions: {
defaultMode: "bypassPermissions",
},
enabledPlugins: {},
};
if (effortLevel) {
settings.effortLevel = effortLevel;
}
writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
return {
path: settingsPath,
settings,
};
}
function prepareClaudeConfig(enabled) {
if (!enabled) return null;
const configDir = mkdtempSync(path.join(tmpdir(), "vcb-claude-config-"));
chmodSync(configDir, 0o700);
const sourceConfigDir = process.env.CLAUDE_CONFIG_DIR ?? path.join(homedir(), ".claude");
const sourceCredentialsPath = path.join(sourceConfigDir, ".credentials.json");
let oauthToken = process.env.CLAUDE_CODE_OAUTH_TOKEN ?? null;
let authSource = oauthToken ? "environment" : null;
let credentialsJson = null;
if (!oauthToken && existsSync(sourceCredentialsPath)) {
credentialsJson = readFileSync(sourceCredentialsPath, "utf8");
authSource = "credentials-file";
} else if (!oauthToken && process.platform === "darwin") {
const keychainCredentials = run(
"security",
["find-generic-password", "-s", "Claude Code-credentials", "-w"],
{ check: false },
);
if (keychainCredentials.status === 0 && keychainCredentials.stdout.trim()) {
credentialsJson = keychainCredentials.stdout.trim();
authSource = "macos-keychain";
}
}
if (!oauthToken && credentialsJson) {
try {
oauthToken = JSON.parse(credentialsJson)?.claudeAiOauth?.accessToken ?? null;
} catch {
oauthToken = null;
}
}
if (!oauthToken) {
rmSync(configDir, { recursive: true, force: true });
throw new Error("Could not prepare isolated Claude OAuth from the environment, configured credentials file, or macOS Keychain");
}
return {
path: configDir,
auth_source: authSource,
oauth_token: oauthToken,
cleanup: () => rmSync(configDir, { recursive: true, force: true }),
};
}
function createWrappers(runDir, arm, realBut, realJj, realGit) {
return createCommandGuards(runDir, arm, {git: realGit, but: realBut, jj: realJj}, taskConfig.id);
}
function prepareShellConfig(runDir, binDir) {
const shellConfigDir = path.join(runDir, "shell-config");
mkdirSync(shellConfigDir, { recursive: true });
const prependWrapperPath = `export PATH=${shellQuote(binDir)}:"$PATH"\n`;
// Reassert wrapper PATH precedence through startup files in this ZDOTDIR.
// Other shells inherit PATH from env but get no startup-file isolation here.
// .zprofile prepends again after macOS /etc/zprofile runs path_helper for
// login shells and may reorder the inherited PATH.
writeFileSync(path.join(shellConfigDir, ".zshenv"), prependWrapperPath);
writeFileSync(path.join(shellConfigDir, ".zprofile"), prependWrapperPath);
return { path: shellConfigDir };
}
function parseSkillVersion(skillFile) {
const content = readFileSync(skillFile, "utf8");
const match = content.match(/^version:\s*"?([^"\n]+)"?\s*$/m);
return match?.[1] ?? null;
}
function parseSkillName(skillFile) {
const content = readFileSync(skillFile, "utf8");
const match = content.match(/^name:\s*"?([^"\n]+)"?\s*$/m);
return match?.[1] ?? null;
}
function renderGitButlerInstructions(workspace, realBut, codexSkillPath, claudeSkillPath, butEnv) {
const setupBlock = taskConfig.cold
? "## Version control\nUse GitButler (`but`) for version-control writes; read-only Git inspection is allowed. This existing Git project has NOT been adopted by GitButler. Perform any required adoption as part of the task. Do not use raw Git writes or jj."
: run(realBut, ["agent", "setup", "--print"], { cwd: workspace, env: butEnv }).stdout.trimEnd();
const content = `# AGENTS.md
## Benchmark boundary
Work only in the current repository and its configured local remotes. Do not inspect parent benchmark directories, hidden oracle files, reference solutions, or research documents. Temporary comparison files outside the repository are allowed.
## Local skill
The official GitButler CLI skill is installed for this benchmark trial at:
- ${codexSkillPath}
- ${claudeSkillPath}
Use the installed skill if your agent runtime loads local skills or you need GitButler command details.
${setupBlock}
`;
return {
content,
setup_block: setupBlock,
setup_block_sha256: sha256Text(setupBlock),
};
}
function renderJjInstructions(workspace, realJj, codexSkillPath, claudeSkillPath, sourceMetadata) {
const version = run(realJj, ["--version"], { cwd: workspace }).stdout.trimEnd();
const policyBlock = `## Version control
- Use Jujutsu (\`jj\`) for version-control write operations in this benchmark trial.
- ${taskConfig.cold ? "This existing Git project has NOT been adopted by jj. Perform any required adoption as part of the task." : "The repository was prepared with `jj git init --colocate`."} Git-visible refs still matter to the verifier.
- Do not use raw \`git\` writes or GitButler (\`but\`) in this benchmark trial.
- Read-only Git inspection is allowed if it helps you verify Git-visible state.
- Always pass \`--no-pager\` to jj commands that may print long output.
- Always pass \`-m\` / \`--message\` to jj commands that need descriptions; do not open an editor.
- Keep bookmarks updated for any named task branch so the final Git branch points at the requested history.
- When the task asks to leave changes uncommitted, leave them in the working-copy commit \`@\`.
`;
const content = `# AGENTS.md
## Benchmark boundary
Work only in the current repository and its configured local remotes. Do not inspect parent benchmark directories, hidden oracle files, reference solutions, or research documents. Temporary comparison files outside the repository are allowed.
## Local skill
The local Jujutsu CLI skill is installed for this benchmark trial at:
- ${codexSkillPath}
- ${claudeSkillPath}
Skill source: ${sourceMetadata.package ?? sourceMetadata.source_url ?? "external source"}.
Use the installed skill if your agent runtime loads local skills or you need Jujutsu command details.
${policyBlock}
`;
return {
content,
version,
setup_block: policyBlock.trimEnd(),
setup_block_sha256: sha256Text(policyBlock.trimEnd()),
};
}
function appendHarnessExclude(workspace) {
writeFileSync(
path.join(workspace, ".git/info/exclude"),
"\n# version-control-bench harness files\n.codex/\n.claude/\nAGENTS.md\nCLAUDE.md\n",
{ flag: "a" },
);
}
function writeAgentInstructionFiles(workspace, content) {
writeFileSync(path.join(workspace, "AGENTS.md"), content);
writeFileSync(path.join(workspace, "CLAUDE.md"), content.replace("# AGENTS.md", "# CLAUDE.md"));
}
function installPlainGitInstructions(workspace) {
writeAgentInstructionFiles(workspace, `# AGENTS.md
## Version control
- Use plain Git CLI for version-control write operations.
- Do not use GitButler CLI (\`but\`) in this benchmark trial.
- Commit only changes requested by the task.
- Do not push or open pull requests unless the user asks.
- Keep commit messages succinct: explain what changed.
`);
appendHarnessExclude(workspace);
return {
installed_codex: path.join(workspace, "AGENTS.md"),
installed_claude: path.join(workspace, "CLAUDE.md"),
};
}
function installGitButlerSkill(workspace, skillDir, realBut, butEnv) {
const skillFile = path.join(skillDir, "SKILL.md");
if (!existsSync(skillFile)) {
throw new Error(`GitButler skill file not found: ${skillFile}`);
}
const refsDir = path.join(skillDir, "references");
const installed = [];
const cliVersionOutput = run(realBut, ["--version"], { cwd: workspace, env: butEnv }).stdout.trim();
const cliVersion = /^but\s+(\S+)(?:\s|$)/.exec(cliVersionOutput)?.[1];
if (!cliVersion) {
throw new Error(`Could not parse GitButler CLI version from: ${JSON.stringify(cliVersionOutput)}`);
}
const sourceSkillContent = readFileSync(skillFile, "utf8");
const frontmatter = /^---\r?\n[\s\S]*?\r?\n---/.exec(sourceSkillContent)?.[0];
if (!frontmatter) {
throw new Error(`GitButler skill source does not contain YAML frontmatter: ${skillFile}`);
}
const sourceVersion = parseSkillVersion(skillFile);
if (!["0.0.0", cliVersion].includes(sourceVersion)) {
throw new Error(`GitButler skill version ${sourceVersion} does not match binary ${cliVersion}: ${skillFile}`);
}
const installedFrontmatter = frontmatter.replace(/^version:\s*0\.0\.0\s*$/m, `version: ${cliVersion}`);
const installedSkillContent = installedFrontmatter + sourceSkillContent.slice(frontmatter.length);
for (const root of [".codex/skills/gitbutler", ".claude/skills/gitbutler"]) {
const dest = path.join(workspace, root);
mkdirSync(dest, { recursive: true });
writeFileSync(path.join(dest, "SKILL.md"), installedSkillContent);
if (existsSync(refsDir)) {
cpSync(refsDir, path.join(dest, "references"), { recursive: true });
}
installed.push(dest);
}
const codexSkillPath = path.join(workspace, ".codex/skills/gitbutler/SKILL.md");
const claudeSkillPath = path.join(workspace, ".claude/skills/gitbutler/SKILL.md");
const instructions = renderGitButlerInstructions(workspace, realBut, codexSkillPath, claudeSkillPath, butEnv);
writeAgentInstructionFiles(workspace, instructions.content);
appendHarnessExclude(workspace);
return {
name: parseSkillName(skillFile) ?? "but",
install_name: "gitbutler",
source_dir: skillDir,
version: cliVersion,
installed,
instructions: {
installed_codex: path.join(workspace, "AGENTS.md"),
installed_claude: path.join(workspace, "CLAUDE.md"),
source_url: "https://docs.gitbutler.com/ai-agents/getting-started#add-optional-agent-instructions",
source_command: "but agent setup --print",
setup_block_sha256: instructions.setup_block_sha256,
},
};
}
function fetchJjSkillSource(runDir, sourceMetadata) {
const dest = path.join(runDir, "external-skills", sourceMetadata.name);
const skillFile = path.join(dest, "SKILL.md");
mkdirSync(dest, { recursive: true });
const fetched = run("curl", ["-fsSL", "--connect-timeout", "5", "--max-time", "15", sourceMetadata.source_url], { cwd: repoRoot, check: false });
if (fetched.status !== 0 || !fetched.stdout.trim()) {
throw new Error(`Failed to fetch jj skill from ${sourceMetadata.source_url}\n${fetched.stderr}`);
}
if (sourceMetadata.expected_sha256) {
const actual = sha256Text(fetched.stdout);
if (actual !== sourceMetadata.expected_sha256) {
throw new Error(
`jj skill integrity check failed for ${sourceMetadata.source_url}\n` +
`expected sha256 ${sourceMetadata.expected_sha256}\n` +
`actual sha256 ${actual}\n` +
`Pass --jj-skill-sha256 (or --jj-skill-sha256 none) when intentionally using different skill content.`,
);
}
}
writeFileSync(skillFile, fetched.stdout);
return {
dir: dest,
source: {
...sourceMetadata,
fetched_at: new Date().toISOString(),
},
};
}
function resolveJjSkillSource(runDir, configuredDir, sourceMetadata) {
if (configuredDir) {
return {
dir: configuredDir,
source: {
...sourceMetadata,
configured_dir: configuredDir,
},
};
}
return fetchJjSkillSource(runDir, sourceMetadata);
}
function installJjSkill(workspace, skillDir, realJj, sourceMetadata) {
const skillFile = path.join(skillDir, "SKILL.md");
if (!existsSync(skillFile)) {
throw new Error(`Jujutsu skill file not found: ${skillFile}`);
}
const refsDir = path.join(skillDir, "references");
const installed = [];
const skillName = parseSkillName(skillFile) ?? sourceMetadata.name ?? path.basename(skillDir);
for (const root of [`.codex/skills/${skillName}`, `.claude/skills/${skillName}`]) {
const dest = path.join(workspace, root);
mkdirSync(dest, { recursive: true });
cpSync(skillFile, path.join(dest, "SKILL.md"));
if (existsSync(refsDir)) {
cpSync(refsDir, path.join(dest, "references"), { recursive: true });
}
installed.push(dest);
}
const codexSkillPath = path.join(workspace, `.codex/skills/${skillName}/SKILL.md`);
const claudeSkillPath = path.join(workspace, `.claude/skills/${skillName}/SKILL.md`);
const instructions = renderJjInstructions(workspace, realJj, codexSkillPath, claudeSkillPath, sourceMetadata);
writeAgentInstructionFiles(workspace, instructions.content);
appendHarnessExclude(workspace);
return {
name: skillName,
source_dir: skillDir,
source: sourceMetadata,
version: parseSkillVersion(skillFile),
installed,
instructions: {
installed_codex: path.join(workspace, "AGENTS.md"),
installed_claude: path.join(workspace, "CLAUDE.md"),
source_package: sourceMetadata.package ?? null,
source_url: sourceMetadata.source_url ?? null,
source_command: "jj --version",
setup_block_sha256: instructions.setup_block_sha256,
tool_version: instructions.version,
},
};
}
function prepareWorkspace(runDir, arm, realBut, butSkillDir, realJj, jjSkill, butEnv) {
const workspace = path.join(runDir, "workspace");
if (scenario) {
let setup;
const install = () => {
if (setup) return;
setup = arm === "but+skill" ? installGitButlerSkill(workspace, butSkillDir, realBut, butEnv)
: arm === "jj+skill" ? installJjSkill(workspace, jjSkill.dir, realJj, jjSkill.source)
: { instructions: installPlainGitInstructions(workspace) };
const localPolicy = "\n## Local task policy\n\nDo not attempt publication with Git push/send-pack, jj git push, or But push/PR commands. "
+ (taskConfig.id === "pilot-12-integrate-topics" ? "But land/merge is allowed only against this disposable repository's configured self-remote local main.\n" : "But land/merge is outside this task.\n")
+ "Git/jj retain unrelated work through named refs/bookmarks; only But must retain any initially applied sibling branches. Harness AGENTS.md, CLAUDE.md, .codex/ and .claude/ files are excluded from project changes.\n";
for (const name of ["AGENTS.md", "CLAUDE.md"]) writeFileSync(path.join(workspace,name), localPolicy, {flag:"a"});
setup.instructions.installed_instruction_sha256 = sha256File(path.join(workspace, "AGENTS.md"));
};
scenarioMetadata = scenario.prepare({repoDir: workspace, arm, butBin: realBut, jjBin: realJj, env: butEnv,
variant: args.get("variant"), beforeTask: install, beforeMistake: install});
install();
writeFileSync(path.join(runDir, "scenario-metadata.json"), JSON.stringify(scenarioMetadata, null, 2));
return { workspace, setup };
}
const dirty = arm === "git" && taskConfig.fixtureDirty !== false;
run("node", [path.join(repoRoot, taskConfig.createFixtureScript), "--out", workspace, "--force", "true", "--dirty", String(dirty)], {
cwd: repoRoot, env: butEnv,
});
if (arm === "but+skill") {
if (taskConfig.gitbutlerPrep === "setup-and-apply-branch") {
run("git", ["switch", "main"], { cwd: workspace, stdio: "pipe" });
}
run(realBut, ["setup"], { cwd: workspace, stdio: "pipe", env: butEnv });
if (taskConfig.gitbutlerPrep === "setup-and-apply-branch") {
run(realBut, ["apply", taskConfig.applyBranch], { cwd: workspace, stdio: "pipe", env: butEnv });
}
const setup = installGitButlerSkill(workspace, butSkillDir, realBut, butEnv);
if (taskConfig.applyDirtyState !== false) {
run("node", [path.join(repoRoot, taskConfig.applyStateScript), "dirty", workspace], { cwd: repoRoot });
}
return { workspace, setup };
}
if (arm === "jj+skill") {
run(realJj, ["git", "init", "--colocate"], { cwd: workspace, stdio: "pipe" });
run(realJj, ["config", "set", "--repo", "ui.paginate", "never"], { cwd: workspace, stdio: "pipe" });
const setup = installJjSkill(workspace, jjSkill.dir, realJj, jjSkill.source);
if (taskConfig.applyDirtyState !== false) {
run("node", [path.join(repoRoot, taskConfig.applyStateScript), "dirty", workspace], { cwd: repoRoot });
}
return { workspace, setup };
}
return { workspace, setup: { instructions: installPlainGitInstructions(workspace) } };
}
function buildPrompt() {
const instruction = readFileSync(path.join(taskDir, "instruction.md"), "utf8").trim();
return [
"You are running inside a version-control benchmark sandbox.",
"All requested file changes already exist. Perform the requested review or version-control task; do not implement new application code.",
"Work only in the current repository and its configured local remotes. Do not inspect parent benchmark directories, hidden oracle files, reference solutions, or the research packet. Temporary comparison files outside the repository are allowed.",
"",
`Task: ${instruction}`,
"",
"When the requested result is complete, return any requested answer and stop.",
].join("\n");
}
function agentCliVersion(agent) {
const cmd = agent === "codex" ? "codex" : "claude";
const probe = run(cmd, ["--version"], { check: false });
if (probe.status !== 0) return null;
return `${probe.stdout}${probe.stderr}`.trim().split("\n")[0] || null;
}
async function runAgent(agent, workspace, prompt, env, model, timeoutMs) {
const start = Date.now();
let cmd;
let args;
if (agent === "codex") {
cmd = "codex";
args = [
"exec",
"--json",
"-C",
workspace,
"--dangerously-bypass-approvals-and-sandbox",
];
if (env.VCB_CODEX_CLEAN_CONFIG === "true") {
args.push("--ignore-user-config", "--ignore-rules", "--ephemeral");
if (env.VCB_CODEX_DISABLE_PLUGINS === "true") {
args.push("--disable", "plugins");
}
}
if (model) args.push("-m", model);
if (codexEffortLevel) args.push("-c", `model_reasoning_effort=${JSON.stringify(codexEffortLevel)}`);
args.push(prompt);
} else if (agent === "claude") {
cmd = "claude";
args = ["-p", "--permission-mode", "bypassPermissions", "--output-format", "stream-json", "--verbose"];
if (env.VCB_CLAUDE_CLEAN_CONFIG === "true" && env.VCB_CLAUDE_SETTINGS) {
args.push(
"--settings",
env.VCB_CLAUDE_SETTINGS,
"--setting-sources",
"project,local",
"--strict-mcp-config",
);
}
if (model) args.push("--model", model);
args.push(prompt);
} else {
throw new Error(`Unknown agent: ${agent}`);
}
const chunks = {stdout: [], stderr: []};
const result = await runBounded(cmd, args, {
cwd: workspace, env, timeoutMs, killDescendants: true, maxOutputBytes: 64 * 1024 * 1024,
onOutput: (data, stream) => chunks[stream].push(data),
});
const end = Date.now();
return {
cmd,
args: args.map((arg) => (arg === prompt ? "<prompt>" : arg)),
status: result.status,
signal: result.signal,
timed_out: result.timed_out,
start_ms: start,
end_ms: end,
duration_ms: end - start,
stdout: Buffer.concat(chunks.stdout).toString('utf8'),
stderr: Buffer.concat(chunks.stderr).toString('utf8'),
error: result.error ? String(result.error) : null,
};
}
function parseAgentModel(agentResult) {
return agentResult.stderr.match(/^model:\s*(.+)$/m)?.[1] ?? null;
}
function parseJsonObject(text) {
try {
const parsed = JSON.parse(text);
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
} catch {
return null;
}
}
function usageTokenTotal(usage) {
if (!usage || typeof usage !== "object") return 0;
return [
"inputTokens",
"outputTokens",
"cacheReadInputTokens",
"cacheCreationInputTokens",
"webSearchRequests",
].reduce((sum, key) => {
const value = usage[key];
return sum + (Number.isFinite(value) ? value : 0);
}, 0);
}
function primaryModelFromUsage(modelUsage) {
if (!modelUsage || typeof modelUsage !== "object") return null;
const entries = Object.entries(modelUsage)
.map(([model, usage]) => ({
model,
cost: Number.isFinite(usage?.costUSD) ? usage.costUSD : 0,
tokens: usageTokenTotal(usage),
}))
.sort((a, b) => (b.cost - a.cost) || (b.tokens - a.tokens) || a.model.localeCompare(b.model));
return entries[0]?.model ?? null;
}
// Codex prints a trailing "tokens used\n<n,nnn>" block on stderr.
function parseCodexTokensUsed(stderr) {
const matches = [...stderr.matchAll(/tokens used\s*[\r\n]+\s*([\d,]+)/gi)];
const value = matches.at(-1)?.[1];
return value ? Number(value.replaceAll(",", "")) : null;
}
// Totals are comparable across runs of the same agent, not across agents:
// each CLI decides for itself what counts as a used token (e.g. cache reads).
function claudeTokensUsed(parsed) {
const sumKeys = (usage, keys) =>
keys.reduce((sum, key) => sum + (Number.isFinite(usage?.[key]) ? usage[key] : 0), 0);
if (parsed.modelUsage && typeof parsed.modelUsage === "object") {
const total = Object.values(parsed.modelUsage).reduce(
(sum, usage) => sum + sumKeys(usage, ["inputTokens", "outputTokens", "cacheReadInputTokens", "cacheCreationInputTokens"]),
0,
);
if (total > 0) return total;
}
const total = sumKeys(parsed.usage, ["input_tokens", "output_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"]);
return total > 0 ? total : null;
}
function parseAgentOutput(agent, agentResult, eventData = null) {
if (agent === "reference") return {output_format: "text", observed_model: null, tokens_used_total: null, transcript_stdout: agentResult.stdout};
const stream = eventData ?? normalizeAgentEvents(agent, agentResult.stdout);
const parsed = stream.terminal;
if (agent !== "claude") {
const usage = parsed?.usage ?? null;
return {
output_format: stream.structured ? "jsonl" : "text",
observed_model: stream.observed_model ?? parseAgentModel(agentResult), observed_model_source: stream.observed_model ? "event-stream" : "stderr",
tokens_used_total: usage && Number.isFinite(usage.input_tokens) && Number.isFinite(usage.output_tokens)
? usage.input_tokens + usage.output_tokens : parseCodexTokensUsed(agentResult.stderr),
usage, parse_error: stream.parse_error,
is_error: parsed?.type === "turn.failed" || parsed?.type === "error",
transcript_stdout: stream.structured ? stream.final_text : agentResult.stdout,
};
}
if (!parsed) return {
output_format: "jsonl", parse_error: true, observed_model: null,
transcript_stdout: stream.final_text,
};
return {
output_format: stream.structured ? "jsonl" : "json", parse_error: stream.parse_error,
observed_model: primaryModelFromUsage(parsed.modelUsage) ?? parseAgentModel(agentResult),
observed_model_source: parsed.modelUsage ? "modelUsage" : "stderr",
transcript_stdout: typeof parsed.result === "string" ? parsed.result : stream.final_text,
result_text_bytes: typeof parsed.result === "string" ? Buffer.byteLength(parsed.result) : 0,
type: parsed.type ?? null, subtype: parsed.subtype ?? null, is_error: parsed.is_error ?? null,
stop_reason: parsed.stop_reason ?? null, session_id: parsed.session_id ?? null,
total_cost_usd: parsed.total_cost_usd ?? null,
num_turns: parsed.num_turns ?? null, duration_api_ms: parsed.duration_api_ms ?? null,
duration_ms: parsed.duration_ms ?? null,
tokens_used_total: claudeTokensUsed(parsed), usage: parsed.usage ?? null,
model_usage: parsed.modelUsage ?? null, errors: parsed.errors ?? null,
permission_denials: parsed.permission_denials ?? null,
};
}
function verify(workspace, response = "") {
if (scenario) return scenario.verify({repoDir: workspace, arm, butBin: realBut, jjBin: realJj, env: butEnv, metadata: scenarioMetadata, response});
const result = run("node", [path.join(repoRoot, taskConfig.verifyScript), "--repo", workspace, "--task", taskDir], {
cwd: repoRoot,
check: false,
});
try {
return JSON.parse(result.stdout);
} catch {
return {
passed: false,
failure_class: "BAD_VERIFIER_OUTPUT",
stdout: result.stdout,
stderr: result.stderr,
};
}
}
function parseTrace(tracePath) {
if (!existsSync(tracePath)) return [];
return readFileSync(tracePath, "utf8")
.split("\n")
.filter(Boolean)
.map((line) => {
if (line.startsWith("v3\t")) return { schema: "v3", ...JSON.parse(line.slice(3)) };
const parts = line.split("\t");
if (parts[0] === "v2") {
if (parts.length < 10) return null;
const [schema, startMs, endMs, durationMs, tool, status, cwd, parent, grandparent, internal] = parts;
return {
schema,
start_ms: Number(startMs),
end_ms: Number(endMs),
duration_ms: Number(durationMs),
ts: Math.floor(Number(startMs) / 1000),
tool,
status: Number(status),
cwd,
parent,
grandparent,
internal: internal === "true",
argv: parts.slice(10).join("\t"),
};
}
if (parts.length < 7) return null;
const legacy = parts.length === 7;
const [ts, tool, status, cwd, parent] = parts;
const grandparent = legacy ? "" : parts[5];
const internal = legacy ? parts[5] : parts[6];
const argv = (legacy ? parts.slice(6) : parts.slice(7)).join("\t");
return {
schema: "legacy",
start_ms: Number(ts) * 1000,
end_ms: null,
duration_ms: null,
ts: Number(ts),
tool,
status: Number(status),
cwd,
parent,
grandparent,
internal: internal === "true",
argv,
};
})
.filter(Boolean)
.sort((a, b) => {
const startDelta = (entryStartMs(a) ?? 0) - (entryStartMs(b) ?? 0);
if (startDelta !== 0) return startDelta;
return (entryEndMs(a) ?? 0) - (entryEndMs(b) ?? 0);
});
}
function commandParts(argv) {
return argv.trim().split(/\s+/).filter(Boolean);
}
function vcSubcommand(entry) {
return subcommand(entry.tool, entry.argv_array ?? commandParts(entry.argv));
}
function entryClassification(entry) {
return classifyCommand(entry.tool, entry.argv_array ?? commandParts(entry.argv));
}
function isGitInspection(entry) { return entryClassification(entry) === "inspection"; }
function isGitMutation(entry) { return entryClassification(entry) === "mutation"; }
function isButInspection(entry) { return entryClassification(entry) === "inspection"; }
function isButMutation(entry) { return entryClassification(entry) === "mutation"; }
function isJjInspection(entry) { return entryClassification(entry) === "inspection"; }
function isJjMutation(entry) { return entryClassification(entry) === "mutation"; }
function isShellParent(parent) {
if (!parent) return false;
return ["sh", "bash", "zsh", "/bin/sh", "/bin/bash", "/bin/zsh"].some((shell) => parent === shell || parent.endsWith(`/${shell}`));
}
function isVcEntry(entry) {
return entry.tool === "git" || entry.tool === "but" || entry.tool === "jj";
}
function isNumber(value) {
return Number.isFinite(value);
}
function entryStartMs(entry) {
if (!entry) return null;
if (isNumber(entry.start_ms)) return entry.start_ms;
if (isNumber(entry.ts)) return entry.ts * 1000;
return null;
}
function entryEndMs(entry) {
if (!entry) return null;
if (isNumber(entry.end_ms)) return entry.end_ms;
const startMs = entryStartMs(entry);
if (startMs !== null && isNumber(entry.duration_ms)) return startMs + entry.duration_ms;
return null;
}
function entryDurationMs(entry) {
return isNumber(entry?.duration_ms) ? entry.duration_ms : null;
}
function durationStats(entries) {
const durations = entries.map(entryDurationMs).filter((duration) => duration !== null);
const intervals = entries
.map((entry) => {
const start = entryStartMs(entry);
const end = entryEndMs(entry);
return start !== null && end !== null && end >= start ? { start, end } : null;
})
.filter(Boolean)
.sort((a, b) => a.start - b.start);
let occupied = 0;
let current = null;
for (const interval of intervals) {
if (!current) {
current = { ...interval };
continue;
}
if (interval.start <= current.end) {
current.end = Math.max(current.end, interval.end);
} else {
occupied += current.end - current.start;
current = { ...interval };
}
}
if (current) occupied += current.end - current.start;
return {
duration_ms_observed_count: durations.length,
duration_ms_sum: durations.length ? durations.reduce((sum, duration) => sum + duration, 0) : null,
duration_ms_occupied: intervals.length ? occupied : null,
duration_ms_max: durations.length ? Math.max(...durations) : null,
};
}
function isInspection(entry) {
if (entry.tool === "git") return isGitInspection(entry);
if (entry.tool === "but") return isButInspection(entry);
if (entry.tool === "jj") return isJjInspection(entry);
return false;
}
function isMutation(entry) {
if (entry.tool === "git") return isGitMutation(entry);
if (entry.tool === "but") return isButMutation(entry);
if (entry.tool === "jj") return isJjMutation(entry);
return false;
}
function isCodexPlatformProbe(entry) {
if (entry.tool !== "git") return false;
const { command, args } = vcSubcommand(entry);
const codexParent = entry.parent === "codex" || entry.parent?.endsWith("/codex") || entry.parent?.includes("/codex/");
const fsmonitorProbe = codexParent
&& command === "config"
&& args[0] === "--null"
&& args[1] === "--get"
&& args[2] === "core.fsmonitor";
const hasCodexRepoFlags = entry.argv.includes("core.hooksPath=/dev/null") || entry.argv.includes("core.fsmonitor=false");
const pluginProbe = entry.argv.includes("/.codex/.tmp/plugins")
|| (command === "ls-remote" && /^https:\/\/github\.com\//.test(args[0] ?? ""));