cue-ai 0.11.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cue-ai",
3
- "version": "0.11.0",
3
+ "version": "0.11.1",
4
4
  "description": "Per-project profile manager for Claude Code, Codex, and 8 other AI coding agents — scopes which skills and MCP servers load, per directory.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -340,6 +340,10 @@ export const COMMANDS = {
340
340
  summary: "Measure profile efficiency: tokens, skill usage, cost",
341
341
  load: () => import("./benchmark"),
342
342
  },
343
+ "community-eval": {
344
+ summary: "Run and optionally share a synthetic CodeGraph A/B benchmark",
345
+ load: () => import("./community-eval"),
346
+ },
343
347
  brief: {
344
348
  summary: "Show this directory's verified facts as handed to the agent; --write persists them",
345
349
  load: () => import("./brief"),
@@ -0,0 +1,99 @@
1
+ import { afterEach, expect, test } from "bun:test";
2
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import type { CommunityReport } from "../lib/community-eval/result";
6
+ import { run } from "./community-eval";
7
+
8
+ const roots: string[] = [];
9
+ afterEach(() => {
10
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
11
+ });
12
+
13
+ const arm = { score: 2, durationMs: 500, inputTokens: 900, cachedInputTokens: 100, outputTokens: 80, codegraphUsed: false };
14
+ const pair = { off: arm, on: { ...arm, codegraphUsed: true } };
15
+ const report: CommunityReport = {
16
+ version: 1, benchmark: "codegraph-v1", model: "gpt-5.4",
17
+ codexVersion: "0.172.0", codegraphVersion: "1.6.4", pairs: [pair, pair],
18
+ };
19
+
20
+ function fixture() {
21
+ const root = mkdtempSync(join(tmpdir(), "cue-benchmark-test-"));
22
+ roots.push(root);
23
+ const stdout: string[] = [];
24
+ const stderr: string[] = [];
25
+ const requests: { url: string; init: RequestInit }[] = [];
26
+ const calls: string[] = [];
27
+ const deps = {
28
+ measure: async (model: string) => { calls.push(model); return report; },
29
+ credentials: () => ({ token: "test-token", apiUrl: "https://cuecards.cc" }),
30
+ request: async (url: string, init: RequestInit) => {
31
+ requests.push({ url, init });
32
+ return Response.json({ ok: true, data: { accepted: true } });
33
+ },
34
+ stdout: (text: string) => { stdout.push(text); },
35
+ stderr: (text: string) => { stderr.push(text); },
36
+ };
37
+ return { path: join(root, "report.json"), deps, calls, requests, stdout, stderr };
38
+ }
39
+
40
+ test("run previews the named budget and does not spend or upload without separate consent", async () => {
41
+ const { path, deps, calls, requests, stdout } = fixture();
42
+ const args = ["run", "--model", "gpt-5.4", "--out", path];
43
+ expect(await run(args, deps)).toBe(0);
44
+ expect(stdout.join("")).toContain("4 Codex runs");
45
+ expect(calls).toEqual([]);
46
+ expect(await run([...args, "--yes"], deps)).toBe(0);
47
+ expect(calls).toEqual(["gpt-5.4"]);
48
+ expect(JSON.parse(readFileSync(path, "utf8"))).toEqual(report);
49
+ expect(stdout.join("")).toContain("Correct answers: without CodeGraph 4/6, with CodeGraph 4/6");
50
+ expect(requests).toEqual([]);
51
+ expect(await run([...args, "--yes"], deps)).toBe(1);
52
+ expect(await run(["run", "--model", "gpt-5.4", "--out", join(path, "missing.json"), "--yes"], deps)).toBe(1);
53
+ expect(calls).toHaveLength(1);
54
+ });
55
+
56
+ test("run explains unsupported setup without printing arbitrary runner output", async () => {
57
+ const { path, deps, stderr } = fixture();
58
+ const args = ["run", "--model", "gpt-5.4", "--yes", "--out", path];
59
+ for (const reason of ["BENCHMARK_CHATGPT_LOGIN_REQUIRED", "private provider output"]) {
60
+ expect(await run(args, { ...deps, measure: async () => { throw new Error(reason); } })).toBe(1);
61
+ }
62
+ expect(stderr.join("")).toContain("BENCHMARK_CHATGPT_LOGIN_REQUIRED");
63
+ expect(stderr.join("")).toContain("BENCHMARK_RUN_FAILED");
64
+ expect(stderr.join("")).not.toContain("private provider output");
65
+ expect(() => readFileSync(path)).toThrow();
66
+ });
67
+
68
+ test("submit previews exact payload and destination; only explicit consent can POST it", async () => {
69
+ const { path, deps, calls, requests, stdout } = fixture();
70
+ writeFileSync(path, JSON.stringify(report));
71
+ const args = ["submit", path];
72
+ expect(await run(args, { ...deps, credentials: () => { throw new Error("must not read auth in preview"); } })).toBe(0);
73
+ expect(stdout.join("")).toContain("https://cuecards.cc/api/v1/benchmarks");
74
+ expect(stdout.join("")).toContain(JSON.stringify(report, null, 2));
75
+ expect(requests).toHaveLength(0);
76
+ expect(await run([...args, "--yes"], deps)).toBe(0);
77
+ expect(requests).toHaveLength(1);
78
+ expect(requests[0]?.init).toMatchObject({ method: "POST", redirect: "error", body: JSON.stringify(report) });
79
+ expect(calls).toHaveLength(0);
80
+ expect(await run([...args, "--yes"], {
81
+ ...deps,
82
+ request: async () => Response.json({ ok: true, data: { accepted: false } }),
83
+ })).toBe(0);
84
+ expect(stdout.join("")).toContain("Already contributed");
85
+ });
86
+
87
+ test("submit rejects private data, oversized files and credentials for other origins before network", async () => {
88
+ const { path, deps, requests, stderr } = fixture();
89
+ const args = ["submit", path, "--yes"];
90
+ for (const value of [{ ...report, transcript: "private" }, "x".repeat(4096)]) {
91
+ writeFileSync(path, JSON.stringify(value));
92
+ expect(await run(args, deps)).toBe(1);
93
+ }
94
+ writeFileSync(path, JSON.stringify(report));
95
+ expect(await run(args, { ...deps, credentials: () => ({ apiUrl: "https://other.invalid", token: "never-send" }) })).toBe(1);
96
+ expect(requests).toHaveLength(0);
97
+ expect(stderr.join("")).not.toContain("private");
98
+ expect(stderr.join("")).not.toContain("never-send");
99
+ });
@@ -0,0 +1,155 @@
1
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { DEFAULT_API_URL, loadCredentials } from "../lib/cue-credentials";
3
+ import {
4
+ COMMUNITY_MODELS, COMMUNITY_PAIR_COUNT, COMMUNITY_REPORT_BYTES, COMMUNITY_SCORE_MAX, isCommunityModel, parseCommunityReport,
5
+ type CommunityModel, type CommunityReport,
6
+ } from "../lib/community-eval/result";
7
+
8
+ const endpoint = DEFAULT_API_URL + "/api/v1/benchmarks";
9
+ const usage = [
10
+ "cue community-eval run --model <" + COMMUNITY_MODELS.join("|") + "> [--out report.json] [--yes]",
11
+ "cue community-eval submit <report.json> [--yes]",
12
+ "Without --yes, each command previews its action; no models are called and no data is sent.",
13
+ ].join("\n") + "\n";
14
+
15
+ type Dependencies = {
16
+ measure: (model: CommunityModel) => Promise<CommunityReport>;
17
+ credentials: typeof loadCredentials;
18
+ request: (url: string, init: RequestInit) => Promise<Response>;
19
+ stdout: (text: string) => void;
20
+ stderr: (text: string) => void;
21
+ };
22
+
23
+ const defaults: Dependencies = {
24
+ measure: async (model) => (await import("../lib/community-eval/runner")).runCommunityEval(model),
25
+ credentials: loadCredentials,
26
+ request: (url, init) => fetch(url, init),
27
+ stdout: (text) => { process.stdout.write(text); },
28
+ stderr: (text) => { process.stderr.write(text); },
29
+ };
30
+
31
+ function readReport(path: string): CommunityReport {
32
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK);
33
+ try {
34
+ const file = fstatSync(fd);
35
+ if (!file.isFile() || file.size > COMMUNITY_REPORT_BYTES) throw new Error("Invalid report file");
36
+ const data = Buffer.alloc(COMMUNITY_REPORT_BYTES + 1);
37
+ const size = readSync(fd, data, 0, data.length, 0);
38
+ if (size > COMMUNITY_REPORT_BYTES) throw new Error("Report file is too large");
39
+ return parseCommunityReport(JSON.parse(data.toString("utf8", 0, size)));
40
+ } finally {
41
+ closeSync(fd);
42
+ }
43
+ }
44
+
45
+ async function measure(args: string[], io: Dependencies): Promise<number> {
46
+ let model: string | undefined;
47
+ let out: string | undefined;
48
+ let yes = false;
49
+ for (let i = 0; i < args.length; i++) {
50
+ const arg = args[i];
51
+ if (arg === "--yes" && !yes) yes = true;
52
+ else if (arg === "--model" && model === undefined && args[i + 1] && !args[i + 1]?.startsWith("-")) model = args[++i];
53
+ else if (arg === "--out" && out === undefined && args[i + 1] && !args[i + 1]?.startsWith("-")) out = args[++i];
54
+ else { io.stderr(usage); return 2; }
55
+ }
56
+ if (!isCommunityModel(model)) { io.stderr(usage); return 2; }
57
+ out ??= "cue-codegraph-v1.json";
58
+ io.stdout(`Plan: ${COMMUNITY_PAIR_COUNT * 2} Codex runs with ${model} using your Codex login. Runs make model requests and may consume subscription quota. Synthetic code only; no Cuecards upload.\n`);
59
+ if (!yes) { io.stdout("Re-run with --yes to start.\n"); return 0; }
60
+ let fd: number;
61
+ try {
62
+ fd = openSync(out, "wx", 0o600);
63
+ } catch {
64
+ io.stderr("BENCHMARK_OUTPUT_UNAVAILABLE: choose a writable, unused --out path.\n");
65
+ return 1;
66
+ }
67
+
68
+ let report: CommunityReport;
69
+ let saved = false;
70
+ try {
71
+ try {
72
+ report = parseCommunityReport(await io.measure(model));
73
+ if (report.model !== model) throw new Error("Model mismatch");
74
+ } catch (error) {
75
+ const code = error instanceof Error && /^BENCHMARK_[A-Z_]{1,40}$/.test(error.message)
76
+ ? error.message : "BENCHMARK_RUN_FAILED";
77
+ io.stderr(`${code}: no report saved. Check your Codex login, supported Codex and CodeGraph versions, and sandbox availability.\n`);
78
+ return 1;
79
+ }
80
+ try {
81
+ writeFileSync(fd, JSON.stringify(report, null, 2) + "\n");
82
+ saved = true;
83
+ } catch {
84
+ io.stderr("BENCHMARK_SAVE_FAILED: check the output filesystem.\n");
85
+ return 1;
86
+ }
87
+ } finally {
88
+ try {
89
+ if (!saved) {
90
+ const reserved = fstatSync(fd);
91
+ const current = lstatSync(out, { throwIfNoEntry: false });
92
+ if (current?.ino === reserved.ino && current.dev === reserved.dev) unlinkSync(out);
93
+ }
94
+ } catch {
95
+ // Best effort: never clear a different file or mask the run failure.
96
+ } finally {
97
+ closeSync(fd);
98
+ }
99
+ }
100
+ io.stdout(`Saved local report: ${out}\nPreview optional contribution with cue community-eval submit <report.json>.\n`);
101
+ const maxScore = COMMUNITY_SCORE_MAX * report.pairs.length;
102
+ const offScore = report.pairs.reduce((total, pair) => total + pair.off.score, 0);
103
+ const onScore = report.pairs.reduce((total, pair) => total + pair.on.score, 0);
104
+ io.stdout(`Correct answers: without CodeGraph ${offScore}/${maxScore}, with CodeGraph ${onScore}/${maxScore}\n`);
105
+ return 0;
106
+ }
107
+
108
+ async function submit(args: string[], io: Dependencies): Promise<number> {
109
+ const [path, confirm] = args;
110
+ if (!path || path.startsWith("-") || args.length > 2 || (confirm !== undefined && confirm !== "--yes")) {
111
+ io.stderr(usage);
112
+ return 2;
113
+ }
114
+ let report: CommunityReport;
115
+ try { report = readReport(path); } catch {
116
+ io.stderr("BENCHMARK_INVALID_REPORT: expected one bounded, complete benchmark report.\n");
117
+ return 1;
118
+ }
119
+ io.stdout(`Destination: ${endpoint}\nThe server uses your Cuecards account to prevent duplicate submissions. No individual reports are public.\n${JSON.stringify(report, null, 2)}\n`);
120
+ if (confirm !== "--yes") { io.stdout("Nothing sent. Re-run with --yes to submit.\n"); return 0; }
121
+ let accepted: boolean;
122
+ try {
123
+ const credentials = io.credentials();
124
+ // Never forward credentials saved for a self-hosted origin.
125
+ if (!credentials || new URL(credentials.apiUrl).origin !== DEFAULT_API_URL) {
126
+ io.stderr("BENCHMARK_LOGIN_REQUIRED: sign in to the official Cuecards service before sharing.\n");
127
+ return 1;
128
+ }
129
+ const response = await io.request(endpoint, {
130
+ method: "POST",
131
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${credentials.token}` },
132
+ body: JSON.stringify(report),
133
+ redirect: "error",
134
+ signal: AbortSignal.timeout(15_000),
135
+ });
136
+ if (!response.ok) throw new Error("Collector rejected report");
137
+ const result = await response.json() as { ok?: unknown; data?: { accepted?: unknown } } | null;
138
+ if (result?.ok !== true || typeof result.data?.accepted !== "boolean") throw new Error("Invalid collector response");
139
+ accepted = result.data.accepted;
140
+ } catch {
141
+ io.stderr("BENCHMARK_SUBMIT_FAILED: contribution was not confirmed; the local report remains.\n");
142
+ return 1;
143
+ }
144
+ io.stdout(accepted ? "Contribution accepted.\n" : "Already contributed; only the first report counts.\n");
145
+ return 0;
146
+ }
147
+
148
+ export async function run(args: string[], io: Dependencies = defaults): Promise<number> {
149
+ const [sub, ...rest] = args;
150
+ if (sub === "run") return measure(rest, io);
151
+ if (sub === "submit") return submit(rest, io);
152
+ if (!sub || sub === "--help" || sub === "-h") { io.stdout(usage); return 0; }
153
+ io.stderr(usage);
154
+ return 2;
155
+ }
@@ -0,0 +1,27 @@
1
+ import { expect, test } from "bun:test";
2
+ import { parseCommunityReport } from "./result";
3
+
4
+ const arm = { score: 2, durationMs: 1234, inputTokens: 400, cachedInputTokens: 100, outputTokens: 50, codegraphUsed: false };
5
+ const pair = { off: arm, on: { ...arm, codegraphUsed: true } };
6
+ const report = { version: 1, benchmark: "codegraph-v1", model: "gpt-5.4", codexVersion: "0.172.0", codegraphVersion: "1.6.4", pairs: [pair, pair] };
7
+
8
+ test("accepts exactly the versioned measurements and preserves missing usage", () => {
9
+ expect(parseCommunityReport(report)).toEqual(report);
10
+ const missing = { ...arm, inputTokens: null, cachedInputTokens: null, outputTokens: null };
11
+ expect(parseCommunityReport({ ...report, pairs: [pair, { ...pair, on: missing }] }).pairs[1]?.on.inputTokens).toBeNull();
12
+ });
13
+
14
+ test("rejects private fields, invalid cohorts, incomplete pairs, and invalid metrics", () => {
15
+ for (const bad of [
16
+ { ...report, cwd: "/private/project" },
17
+ { ...report, model: "personal-model-id" },
18
+ { ...report, codexVersion: "private-build" },
19
+ { ...report, pairs: [pair] },
20
+ { ...report, pairs: [pair, { ...pair, transcript: "private" }] },
21
+ ...[
22
+ { prompt: "private" }, { score: 4 }, { durationMs: Infinity }, { durationMs: 300_001 },
23
+ { cachedInputTokens: 401 }, { outputTokens: null }, { inputTokens: -1 },
24
+ { inputTokens: 10_000_001 }, { codegraphUsed: true },
25
+ ].map((fields) => ({ ...report, pairs: [pair, { ...pair, off: { ...arm, ...fields } }] })),
26
+ ]) expect(() => parseCommunityReport(bad)).toThrow("BENCHMARK_INVALID_REPORT");
27
+ });
@@ -0,0 +1,80 @@
1
+ /** The only data allowed out of a community benchmark. Shared by the CLI and collector. */
2
+ export const COMMUNITY_MODELS = ["gpt-5.4", "gpt-5.6-sol"] as const;
3
+ export const COMMUNITY_BENCHMARK = "codegraph-v1";
4
+ export const COMMUNITY_REPORT_BYTES = 4096;
5
+ export const COMMUNITY_PAIR_COUNT = 2;
6
+ export const COMMUNITY_SCORE_MAX = 3;
7
+
8
+ export type CommunityModel = (typeof COMMUNITY_MODELS)[number];
9
+ export type CommunityArm = {
10
+ score: number;
11
+ durationMs: number;
12
+ inputTokens: number | null;
13
+ cachedInputTokens: number | null;
14
+ outputTokens: number | null;
15
+ codegraphUsed: boolean;
16
+ };
17
+ export type CommunityReport = {
18
+ version: 1;
19
+ benchmark: typeof COMMUNITY_BENCHMARK;
20
+ model: CommunityModel;
21
+ codexVersion: string;
22
+ codegraphVersion: string;
23
+ pairs: { off: CommunityArm; on: CommunityArm }[];
24
+ };
25
+
26
+ function invalid(): never {
27
+ throw new Error("BENCHMARK_INVALID_REPORT");
28
+ }
29
+
30
+ function exactRecord(value: unknown, keys: readonly string[]): Record<string, unknown> {
31
+ if (!value || typeof value !== "object" || Array.isArray(value)
32
+ || Object.keys(value).length !== keys.length || !keys.every((key) => Object.hasOwn(value, key))) invalid();
33
+ return value as Record<string, unknown>;
34
+ }
35
+
36
+ function integer(value: unknown, min: number, max: number): number {
37
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= min && value <= max ? value : invalid();
38
+ }
39
+
40
+ function version(value: unknown): string {
41
+ return typeof value === "string" && /^\d{1,4}\.\d{1,4}\.\d{1,4}$/.test(value) ? value : invalid();
42
+ }
43
+
44
+ export function isCommunityModel(value: unknown): value is CommunityModel {
45
+ return COMMUNITY_MODELS.some((model) => model === value);
46
+ }
47
+
48
+ function parseArm(value: unknown, available: boolean): CommunityArm {
49
+ const arm = exactRecord(value, ["score", "durationMs", "inputTokens", "cachedInputTokens", "outputTokens", "codegraphUsed"]);
50
+ const { inputTokens: input, cachedInputTokens: cached, outputTokens: output, codegraphUsed } = arm;
51
+ if (typeof codegraphUsed !== "boolean" || (!available && codegraphUsed)) invalid();
52
+ const missing = input === null && cached === null && output === null;
53
+ const inputTokens = missing ? null : integer(input, 0, 10_000_000);
54
+ return {
55
+ score: integer(arm.score, 0, COMMUNITY_SCORE_MAX),
56
+ durationMs: integer(arm.durationMs, 1, 300_000),
57
+ inputTokens,
58
+ cachedInputTokens: missing ? null : integer(cached, 0, inputTokens!),
59
+ outputTokens: missing ? null : integer(output, 0, 10_000_000),
60
+ codegraphUsed,
61
+ };
62
+ }
63
+
64
+ export function parseCommunityReport(value: unknown): CommunityReport {
65
+ const report = exactRecord(value, ["version", "benchmark", "model", "codexVersion", "codegraphVersion", "pairs"]);
66
+ if (report.version !== 1 || report.benchmark !== COMMUNITY_BENCHMARK
67
+ || !isCommunityModel(report.model) || !Array.isArray(report.pairs)
68
+ || report.pairs.length !== COMMUNITY_PAIR_COUNT) invalid();
69
+ return {
70
+ version: 1,
71
+ benchmark: COMMUNITY_BENCHMARK,
72
+ model: report.model,
73
+ codexVersion: version(report.codexVersion),
74
+ codegraphVersion: version(report.codegraphVersion),
75
+ pairs: Array.from(report.pairs, (value: unknown) => {
76
+ const pair = exactRecord(value, ["off", "on"]);
77
+ return { off: parseArm(pair.off, false), on: parseArm(pair.on, true) };
78
+ }),
79
+ };
80
+ }
@@ -0,0 +1,133 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { existsSync, readFileSync, readdirSync, readlinkSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { type CommunityCommand, runCommunityEval } from "./runner";
5
+
6
+ function jsonl(codegraphUsed: boolean, usage = true, correct = true): string {
7
+ return [
8
+ { type: "thread.started", thread_id: "not-in-report" },
9
+ ...(codegraphUsed
10
+ ? [{type: "item.completed", item: {type: "mcp_tool_call", server: "codegraph", tool: "codegraph_explore", status: "completed", error: null}}]
11
+ : []),
12
+ { type: "item.completed", item: { type: "agent_message", text: JSON.stringify({
13
+ entry: "src/pricing/quote.ts",
14
+ rule: correct ? "seasonalCredit" : "not-in-report",
15
+ boundary: "src/http/quote-input.ts",
16
+ }) }},
17
+ { type: "turn.completed", usage: usage ? { input_tokens: 500, cached_input_tokens: 100, output_tokens: 75 } : {} },
18
+ ].map((event) => JSON.stringify(event)).join("\n");
19
+ }
20
+
21
+ const tools = { codex: "/test/bin/codex", codegraph: "/test/codegraph/bin/codegraph", codegraphRoot: "/test/codegraph" };
22
+
23
+ function fakeCommand(override?: (args: readonly string[]) => string | undefined) {
24
+ const calls: {args: readonly string[]; cwd: string; env: NodeJS.ProcessEnv}[] = [];
25
+ const command: CommunityCommand = (bin, args, options) => {
26
+ calls.push({ args, cwd: options.cwd, env: options.env });
27
+ const stdout = override?.(args);
28
+ if (stdout !== undefined) return { stdout, stderr: "", ok: true };
29
+ if (args[0] === "--version") {
30
+ return { stdout: bin === tools.codex ? "codex-cli 0.172.0\n" : "codegraph 1.6.2\n", stderr: "", ok: true };
31
+ }
32
+ if (args[0] === "login") return { stdout: "", stderr: "Logged in using ChatGPT", ok: true };
33
+ if (args[0] === "sandbox") return { stdout: "", stderr: "", ok: true };
34
+ expect(args[0]).toBe("exec");
35
+ expect(readdirSync(options.cwd)).toEqual(["src"]);
36
+ expect(existsSync(join(options.cwd, ".codegraph"))).toBe(false);
37
+ expect(readFileSync(join(options.cwd, "src/pricing/quote.ts"), "utf8")).toContain("seasonalCredit");
38
+ const on = args.some((arg) => arg.startsWith("mcp_servers={codegraph="));
39
+ return { stdout: jsonl(on), stderr: "", ok: true };
40
+ };
41
+ return { command, calls };
42
+ }
43
+
44
+ describe("community CodeGraph runner", () => {
45
+ test("holds model, questions, working tree and shell settings constant; alternates arm order; returns metrics only", async () => {
46
+ const { command, calls } = fakeCommand();
47
+ const report = await runCommunityEval("gpt-5.4", {
48
+ platform: "linux", tools, authHome: "/private/codex", now: () => 20,
49
+ command: (bin, args, options) => {
50
+ if (args[0] === "login" || args[0] === "exec") {
51
+ expect(readdirSync(options.env.CODEX_HOME!)).toEqual(["auth.json"]);
52
+ expect(readlinkSync(join(options.env.CODEX_HOME!, "auth.json"))).toBe("/private/codex/auth.json");
53
+ }
54
+ return command(bin, args, options);
55
+ },
56
+ });
57
+ expect(report).toEqual({
58
+ version: 1, benchmark: "codegraph-v1", model: "gpt-5.4", codexVersion: "0.172.0", codegraphVersion: "1.6.2",
59
+ pairs: Array.from({length: 2}, () => ({
60
+ off: { score: 3, durationMs: 1, inputTokens: 500, cachedInputTokens: 100, outputTokens: 75, codegraphUsed: false },
61
+ on: { score: 3, durationMs: 1, inputTokens: 500, cachedInputTokens: 100, outputTokens: 75, codegraphUsed: true },
62
+ })),
63
+ });
64
+ const execs = calls.filter(({args}) => args[0] === "exec");
65
+ expect(execs.map(({args}) => args.some((arg) => arg.startsWith("mcp_servers={codegraph=")))).toEqual([false, true, true, false]);
66
+ expect(new Set(execs.map(({cwd}) => cwd)).size).toBe(1);
67
+ expect(execs[0].args.filter((arg) => !arg.startsWith("mcp_servers="))).toEqual(
68
+ execs[1].args.filter((arg) => !arg.startsWith("mcp_servers=")),
69
+ );
70
+ expect(execs[0].args).toContain("gpt-5.4");
71
+ expect(execs[0].args).toContain("--ignore-user-config");
72
+ expect(execs[0].args).toContain("--ignore-rules");
73
+ expect(execs[0].args).toContain("--ephemeral");
74
+ expect(execs[0].args).toContain("features.hooks=false");
75
+ expect(execs[0].args).toContain("permissions.cue-benchmark.network.enabled=false");
76
+ expect(execs[1].args.join(" ")).toContain('enabled_tools=["codegraph_explore"]');
77
+ expect(execs[1].args.join(" ")).toContain("required=true");
78
+ expect(execs[1].args.join(" ")).toContain("CODEGRAPH_TELEMETRY");
79
+ const mcpRules = execs[1].args.join(" ").replaceAll('\\"', '"');
80
+ expect(mcpRules).toContain('/.codegraph"="write"');
81
+ expect(mcpRules).toContain('/index"="read"');
82
+ expect(execs[1].args.join(" ")).not.toContain("/private/codex");
83
+ expect(execs[0].env.CODEX_HOME).not.toBe("/private/codex");
84
+ expect(execs[0].env.OPENAI_API_KEY).toBeUndefined();
85
+ expect(execs[0].env.GITHUB_TOKEN).toBeUndefined();
86
+ expect(existsSync(execs[0].cwd)).toBe(false);
87
+ });
88
+
89
+ test("distinguishes a wrong answer from missing token accounting", async () => {
90
+ const { command } = fakeCommand((args) => args[0] === "exec" ? jsonl(false, false, false) : undefined);
91
+ const { pairs } = await runCommunityEval("gpt-5.4", { platform: "linux", tools, command });
92
+ expect(pairs[0].on).toMatchObject({score: 2, inputTokens: null, cachedInputTokens: null, outputTokens: null, codegraphUsed: false});
93
+ });
94
+
95
+ test("counts malformed answers as wrong and grades a partial answer per question", async () => {
96
+ const { command } = fakeCommand((args) => {
97
+ if (args[0] !== "exec") return undefined;
98
+ const on = args.some((arg) => arg.startsWith("mcp_servers={codegraph="));
99
+ const text = on ? '{"entry":"src/pricing/quote.ts"}' : 'not JSON';
100
+ return jsonl(false).split("\n").map((line) => {
101
+ const event = JSON.parse(line);
102
+ if (event.type === "item.completed") event.item.text = text;
103
+ return JSON.stringify(event);
104
+ }).join("\n");
105
+ });
106
+ const { pairs } = await runCommunityEval("gpt-5.4", { platform: "linux", tools, command });
107
+ expect(pairs.map(({ off, on }) => [off.score, on.score])).toEqual([[0, 1], [0, 1]]);
108
+ });
109
+
110
+ test("stops after first protocol error and does not leak its text", async () => {
111
+ const { command, calls } = fakeCommand((args) => args[0] === "exec" ? '{"type":"turn.failed","error":{"message":"private-path"}}' : undefined);
112
+ await expect(runCommunityEval("gpt-5.4", { platform: "linux", tools, command }))
113
+ .rejects.toThrow("BENCHMARK_CODEX_FAILED");
114
+ expect(calls.filter(({args}) => args[0] === "exec")).toHaveLength(1);
115
+ expect(existsSync(calls.at(-1)!.cwd)).toBe(false);
116
+ });
117
+
118
+ test("does not make model requests with an unsupported sandbox or release", async () => {
119
+ const { command, calls } = fakeCommand((args) => args[0] === "--version" ? "codex-cli 0.171.0" : undefined);
120
+ await expect(runCommunityEval("gpt-5.4", { platform: "darwin", tools, command }))
121
+ .rejects.toThrow("BENCHMARK_UNSUPPORTED_PLATFORM");
122
+ await expect(runCommunityEval("gpt-5.4", { platform: "linux", tools, command }))
123
+ .rejects.toThrow("BENCHMARK_UNSUPPORTED_CODEX");
124
+ expect(calls.some(({args}) => args[0] === "exec")).toBe(false);
125
+ });
126
+
127
+ test("does not start Codex with a system configuration that can change the benchmark", async () => {
128
+ const { command, calls } = fakeCommand();
129
+ await expect(runCommunityEval("gpt-5.4", { platform: "linux", tools, command, hasSystemConfig: () => true }))
130
+ .rejects.toThrow("BENCHMARK_SYSTEM_CONFIG_UNSUPPORTED");
131
+ expect(calls).toEqual([]);
132
+ });
133
+ });