yats-toolkit 0.2.3 → 0.3.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.
Files changed (32) hide show
  1. package/README.md +14 -2
  2. package/benchmark/questions/go/chi/01-routing.md +1 -0
  3. package/benchmark/questions/go/chi/02-middleware.md +1 -0
  4. package/benchmark/questions/php/slim/01-routing.md +1 -0
  5. package/benchmark/questions/php/slim/02-container.md +1 -0
  6. package/benchmark/questions/python/flask/01-routing.md +1 -0
  7. package/benchmark/questions/python/flask/02-context.md +1 -0
  8. package/benchmark/questions/typescript/express/01-middleware.md +1 -0
  9. package/benchmark/questions/typescript/express/02-router.md +1 -0
  10. package/benchmark/questions/typescript/koa/01-middleware.md +1 -0
  11. package/benchmark/questions/typescript/koa/02-context.md +1 -0
  12. package/benchmark/targets/repos.json +5 -6
  13. package/package.json +1 -1
  14. package/src/benchmark.js +1352 -334
  15. package/src/bridge.js +8 -6
  16. package/src/setup.js +18 -10
  17. package/benchmark/questions/go/terraform/01-providers.md +0 -1
  18. package/benchmark/questions/go/terraform/02-graph.md +0 -1
  19. package/benchmark/questions/php/laravel/01-container.md +0 -1
  20. package/benchmark/questions/php/laravel/02-routing.md +0 -1
  21. package/benchmark/questions/php/symfony/01-dependency-injection.md +0 -1
  22. package/benchmark/questions/php/symfony/02-event-dispatcher.md +0 -1
  23. package/benchmark/questions/python/01-middleware.md +0 -8
  24. package/benchmark/questions/python/02-routing.md +0 -9
  25. package/benchmark/questions/python/django/01-middleware.md +0 -1
  26. package/benchmark/questions/python/django/01-orm.md +0 -1
  27. package/benchmark/questions/typescript/nestjs/01-decorators.md +0 -1
  28. package/benchmark/questions/typescript/nestjs/02-modules.md +0 -1
  29. package/benchmark/questions/typescript/nextjs/01-rendering.md +0 -1
  30. package/benchmark/questions/typescript/nextjs/02-routing.md +0 -1
  31. /package/benchmark/questions/go/{lab_hub → hub-lab}/01-protocol-translation.md +0 -0
  32. /package/benchmark/questions/go/{lab_hub → hub-lab}/02-bidirectional-flow.md +0 -0
package/src/benchmark.js CHANGED
@@ -2,13 +2,17 @@
2
2
  * yats benchmark — AI agent token comparison
3
3
  * Measures token usage answering codebase questions with and without YATS.
4
4
  * Uses only Node.js built-ins (zero dependencies).
5
+ *
6
+ * Interactive UI: arrow-key selection + colors when run in a TTY.
7
+ * Falls back to plain numbered prompts when stdin is piped (scriptable).
5
8
  */
6
9
  import * as fs from "node:fs";
7
10
  import * as path from "node:path";
8
11
  import { spawn, execSync } from "node:child_process";
9
12
  import * as readline from "node:readline";
13
+ import { fileURLToPath } from "node:url";
14
+ import * as os from "node:os";
10
15
 
11
- // Simple inline logger (replaces @yats/shared dependency)
12
16
  const logger = {
13
17
  info: (msg) => console.error(`[benchmark] ${msg}`),
14
18
  warn: (msg) => console.error(`[benchmark] ⚠ ${msg}`),
@@ -16,77 +20,362 @@ const logger = {
16
20
  };
17
21
 
18
22
  // ============================================================
19
- // Types (JSDoc for clarity, no TypeScript needed)
23
+ // Terminal UI (colors + arrow-key selection)
20
24
  // ============================================================
21
25
 
22
- /**
23
- * @typedef {Object} AgentConfig
24
- * @property {string} name
25
- * @property {string} cli
26
- * @property {string} checkCmd
27
- * @property {string} installHint
28
- * @property {string} needsApiKey
29
- * @property {boolean} needsSkill
30
- * @property {boolean} needsMcpConfig
31
- * @property {(prompt: string, repoDir: string, hasMcp: boolean) => string[]} runCmd
32
- */
26
+ const isTTY = Boolean(process.stdin.isTTY && process.stdout.isTTY);
33
27
 
34
- /**
35
- * @typedef {Object} RepoConfig
36
- * @property {string} name
37
- * @property {string} url
38
- * @property {string} defaultPath
39
- * @property {string} language
40
- * @property {string[]} questions
41
- */
28
+ const A = isTTY
29
+ ? {
30
+ reset: "\x1b[0m",
31
+ bold: "\x1b[1m",
32
+ dim: "\x1b[2m",
33
+ purple: "\x1b[35m",
34
+ cyan: "\x1b[36m",
35
+ green: "\x1b[32m",
36
+ red: "\x1b[31m",
37
+ yellow: "\x1b[33m",
38
+ gray: "\x1b[90m",
39
+ }
40
+ : {
41
+ reset: "", bold: "", dim: "", purple: "", cyan: "",
42
+ green: "", red: "", yellow: "", gray: "",
43
+ };
42
44
 
43
- /**
44
- * @typedef {Object} RunResult
45
- * @property {number} run
46
- * @property {boolean} withYats
47
- * @property {number} tokens
48
- * @property {number} cost
49
- * @property {number} outputTokens
50
- * @property {number} cacheRead
51
- * @property {number} cacheWrite
52
- * @property {Record<string, number>} toolCalls
53
- * @property {number} agentSpawns
54
- * @property {number} fileReads
55
- * @property {number} bashCmds
56
- * @property {number} yatsQueries
57
- * @property {number} contentChars
58
- * @property {number} duration
59
- * @property {string} [error]
60
- * @property {string} logFile
61
- */
45
+ function setRaw(on) {
46
+ if (process.stdin.isTTY && typeof process.stdin.setRawMode === "function") {
47
+ process.stdin.setRawMode(on);
48
+ }
49
+ }
50
+
51
+ function showCursor(on) {
52
+ if (isTTY) process.stdout.write(on ? "\x1b[?25h" : "\x1b[?25l");
53
+ }
54
+
55
+ function restoreTerminal() {
56
+ setRaw(false);
57
+ showCursor(true);
58
+ }
59
+
60
+ process.on("SIGINT", () => {
61
+ restoreTerminal();
62
+ console.log(`\n ${A.yellow}✖ Cancelled${A.reset}\n`);
63
+ process.exit(130);
64
+ });
65
+
66
+ // Reads a single key (raw mode). Returns "up" | "down" | "enter" | "backspace" | "ctrl-c" | "esc" | a character.
67
+ function readKey() {
68
+ return new Promise((resolve) => {
69
+ const stdin = process.stdin;
70
+ let acc = "";
71
+ const done = (k) => {
72
+ stdin.removeListener("data", onData);
73
+ resolve(k);
74
+ };
75
+ const onData = (chunk) => {
76
+ acc += chunk;
77
+ if (acc.length === 1 && acc !== "\x1b") {
78
+ const ch = acc;
79
+ if (ch === "\r" || ch === "\n") done("enter");
80
+ else if (ch === "\x03") done("ctrl-c");
81
+ else if (ch === "\x7f" || ch === "\b") done("backspace");
82
+ else done(ch);
83
+ return;
84
+ }
85
+ if (acc.startsWith("\x1b")) {
86
+ if (acc.length >= 3) {
87
+ if (acc === "\x1b[A") done("up");
88
+ else if (acc === "\x1b[B") done("down");
89
+ else done("esc");
90
+ }
91
+ // else wait for more bytes of the escape sequence
92
+ }
93
+ };
94
+ stdin.on("data", onData);
95
+ });
96
+ }
97
+
98
+ // Non-TTY line input (piped stdin) via a readline interface + queue.
99
+ const rl = !isTTY ? readline.createInterface({ input: process.stdin, output: process.stdout }) : null;
100
+ const lineQueue = [];
101
+ const lineWaiters = [];
102
+ if (rl) {
103
+ rl.on("line", (line) => {
104
+ if (lineWaiters.length) lineWaiters.shift()(line);
105
+ else lineQueue.push(line);
106
+ });
107
+ rl.on("close", () => {
108
+ while (lineWaiters.length) lineWaiters.shift()("");
109
+ });
110
+ }
111
+
112
+ // Ask for a free-text line. Works in TTY (raw line editing) and piped stdin.
113
+ async function askLine(question) {
114
+ process.stdout.write(question);
115
+ if (!isTTY) {
116
+ return new Promise((resolve) => {
117
+ if (lineQueue.length) resolve(lineQueue.shift());
118
+ else lineWaiters.push(resolve);
119
+ });
120
+ }
121
+ setRaw(true);
122
+ let line = "";
123
+ while (true) {
124
+ const key = await readKey();
125
+ if (key === "enter") {
126
+ process.stdout.write("\n");
127
+ setRaw(false);
128
+ return line;
129
+ }
130
+ if (key === "ctrl-c") {
131
+ restoreTerminal();
132
+ console.log(`\n ${A.yellow}✖ Cancelled${A.reset}\n`);
133
+ process.exit(130);
134
+ }
135
+ if (key === "backspace") {
136
+ if (line.length) {
137
+ line = line.slice(0, -1);
138
+ process.stdout.write("\b \b");
139
+ }
140
+ } else if (typeof key === "string" && key.length === 1 && key >= " ") {
141
+ line += key;
142
+ process.stdout.write(key);
143
+ }
144
+ }
145
+ }
146
+
147
+ // Interactive selector. options: [{ label, hint, value, ok?, accent? }]
148
+ async function select(title, options) {
149
+ if (!isTTY) {
150
+ console.log(`\n ${title}`);
151
+ options.forEach((o, i) => {
152
+ console.log(` ${i + 1}. ${o.label}${o.hint ? ` (${o.hint})` : ""}`);
153
+ });
154
+ const choice = await askLine(` Pick [1-${options.length}]: `);
155
+ const idx = parseInt(choice) - 1;
156
+ return idx >= 0 && idx < options.length ? options[idx].value : options[0].value;
157
+ }
158
+
159
+ let idx = 0;
160
+ const cols = process.stdout.columns || 80;
161
+ const maxLabel = Math.max(24, cols - 12);
162
+ const draw = () => {
163
+ let s = ` ${A.bold}${A.purple}${title}${A.reset}\n`;
164
+ for (let i = 0; i < options.length; i++) {
165
+ const o = options[i];
166
+ const sel = i === idx;
167
+ const cursor = sel ? `${A.purple}›${A.reset}` : " ";
168
+ let label = o.label;
169
+ if (label.length > maxLabel) label = label.slice(0, maxLabel - 1) + "…";
170
+ if (sel) label = `${A.bold}${label}${A.reset}`;
171
+ if (!sel && o.accent) label = `${A.cyan}${label}${A.reset}`;
172
+ if (sel && o.accent) label = `${A.bold}${A.cyan}${label}${A.reset}`;
173
+ let hint = "";
174
+ if (o.hint) {
175
+ const color = o.ok === false ? A.red : A.gray;
176
+ hint = ` ${A.dim}${color}${o.hint}${A.reset}`;
177
+ }
178
+ s += ` ${cursor} ${label}${hint}\n`;
179
+ }
180
+ s += `\n ${A.dim}↑/↓ move · Enter select · Ctrl+C cancel${A.reset}\n`;
181
+ return s;
182
+ };
183
+
184
+ const lineCount = options.length + 3; // title + options + blank + footer
185
+ setRaw(true);
186
+ showCursor(false);
187
+ process.stdout.write("\n" + draw());
188
+
189
+ while (true) {
190
+ const key = await readKey();
191
+ if (key === "up") idx = (idx - 1 + options.length) % options.length;
192
+ else if (key === "down") idx = (idx + 1) % options.length;
193
+ else if (key === "enter") break;
194
+ else if (key === "ctrl-c") {
195
+ restoreTerminal();
196
+ console.log(`\n ${A.yellow}✖ Cancelled${A.reset}\n`);
197
+ process.exit(130);
198
+ } else {
199
+ continue;
200
+ }
201
+ process.stdout.write(`\x1b[${lineCount}A\x1b[J`);
202
+ process.stdout.write(draw());
203
+ }
204
+
205
+ setRaw(false);
206
+ showCursor(true);
207
+ process.stdout.write("\n");
208
+ return options[idx].value;
209
+ }
62
210
 
63
211
  // ============================================================
64
- // Configuration
212
+ // Helpers
65
213
  // ============================================================
66
214
 
67
- const KNOWN_REPOS = [
68
- {
69
- name: "fastapi",
70
- url: "https://github.com/tiangolo/fastapi.git",
71
- defaultPath: path.join(process.env.HOME ?? "/tmp", "repos", "fastapi"),
72
- language: "python",
73
- questions: [
74
- "How does middleware work in FastAPI? Trace registration, ordering, and execution of the middleware stack.",
75
- "How are HTTP routes registered and dispatched in FastAPI? Find the key classes responsible for routing.",
76
- ],
77
- },
215
+ function isInstalled(cmd) {
216
+ try {
217
+ execSync(`which ${cmd}`, { stdio: "pipe" });
218
+ return true;
219
+ } catch {
220
+ return false;
221
+ }
222
+ }
223
+
224
+ function hasApiKey(envVar) {
225
+ return !envVar || !!process.env[envVar];
226
+ }
227
+
228
+ function toAbsolute(p) {
229
+ let s = String(p).trim();
230
+ if (s === "~") s = process.env.HOME ?? "/tmp";
231
+ else if (s.startsWith("~/")) s = path.join(process.env.HOME ?? "/tmp", s.slice(2));
232
+ return path.resolve(s);
233
+ }
234
+
235
+ // ============================================================
236
+ // .env loading — so spawned agents inherit API keys
237
+ // ============================================================
238
+
239
+ function loadEnvFile(filePath) {
240
+ try {
241
+ const content = fs.readFileSync(filePath, "utf8");
242
+ let count = 0;
243
+ for (const line of content.split("\n")) {
244
+ const trimmed = line.trim();
245
+ if (!trimmed || trimmed.startsWith("#")) continue;
246
+ const eq = trimmed.indexOf("=");
247
+ if (eq <= 0) continue;
248
+ const key = trimmed.slice(0, eq).trim();
249
+ let value = trimmed.slice(eq + 1).trim();
250
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
251
+ value = value.slice(1, -1);
252
+ }
253
+ if (key && !(key in process.env)) {
254
+ process.env[key] = value;
255
+ count++;
256
+ }
257
+ }
258
+ return count;
259
+ } catch {
260
+ return 0;
261
+ }
262
+ }
263
+
264
+ function loadEnv() {
265
+ const candidates = [];
266
+ // Canonical: ~/.yats/.env (setup writes embedding + benchmark keys there)
267
+ candidates.push(path.join(process.env.HOME ?? "/tmp", ".yats", ".env"));
268
+ candidates.push(path.join(process.cwd(), ".env"));
269
+
270
+ // walk up from this module (src/) to find a repo-root .env (legacy fallback)
271
+ let dir = path.dirname(fileURLToPath(import.meta.url));
272
+ for (let i = 0; i < 6; i++) {
273
+ const p = path.join(dir, ".env");
274
+ if (!candidates.includes(p)) candidates.push(p);
275
+ const parent = path.dirname(dir);
276
+ if (parent === dir) break;
277
+ dir = parent;
278
+ }
279
+
280
+ // Load ALL candidates so keys accumulate (first one wins per key).
281
+ let loaded = null;
282
+ for (const c of candidates) {
283
+ if (loadEnvFile(c) > 0 && !loaded) loaded = c;
284
+ }
285
+ return loaded;
286
+ }
287
+
288
+ const LOADED_ENV = loadEnv();
289
+ if (LOADED_ENV) logger.info(`Loaded ${LOADED_ENV}`);
290
+
291
+ let selectedModel = null;
292
+ let copilotConsent = false;
293
+ let workDir = path.join(process.cwd(), "repos");
294
+
295
+ // ============================================================
296
+ // Repos — loaded dynamically from benchmark/targets + benchmark/questions
297
+ // ============================================================
298
+
299
+ const BENCH_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "benchmark");
300
+ const CONNECT_DIR = path.join(BENCH_DIR, "..", "..", "..", "connect");
301
+ let BENCH_HOME = null;
302
+
303
+ function benchHome() {
304
+ if (!BENCH_HOME) {
305
+ BENCH_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "yats-bench-"));
306
+ }
307
+ return BENCH_HOME;
308
+ }
309
+
310
+ function readConnect(agentDir, file) {
311
+ try {
312
+ return fs.readFileSync(path.join(CONNECT_DIR, agentDir, file), "utf8");
313
+ } catch {
314
+ return null;
315
+ }
316
+ }
317
+
318
+ // Private/unknown repos (the LLM has never seen them) — the real proof.
319
+ const UNKNOWN_REPOS = [
78
320
  {
79
- name: "lab_hub",
80
- url: "https://github.com/fvinciarelli/lab_hub.git",
81
- defaultPath: path.join(process.env.HOME ?? "/tmp", "repos", "lab_hub"),
321
+ name: "hub-lab",
322
+ url: "https://github.com/fvinciarelli/hub-lab.git",
82
323
  language: "go",
83
- questions: [
84
- "How does Hub Lab translate analyzer protocols? What are the key Go packages and functions?",
85
- "How does the bidirectional flow work in Hub Lab? Trace orders and results paths.",
86
- ],
324
+ known: false,
87
325
  },
88
326
  ];
89
327
 
328
+ function loadQuestions(lang, repo) {
329
+ const dir = path.join(BENCH_DIR, "questions", lang, repo);
330
+ if (!fs.existsSync(dir)) return [];
331
+ try {
332
+ return fs
333
+ .readdirSync(dir)
334
+ .filter((f) => f.endsWith(".md"))
335
+ .sort()
336
+ .map((f) => fs.readFileSync(path.join(dir, f), "utf8").trim())
337
+ .filter(Boolean);
338
+ } catch {
339
+ return [];
340
+ }
341
+ }
342
+
343
+ function loadRepos() {
344
+ const repos = [];
345
+ for (const r of UNKNOWN_REPOS) {
346
+ repos.push({
347
+ ...r,
348
+ defaultPath: path.join(process.env.HOME ?? "/tmp", "repos", r.name),
349
+ questions: loadQuestions(r.language, r.name),
350
+ });
351
+ }
352
+ try {
353
+ const data = JSON.parse(
354
+ fs.readFileSync(path.join(BENCH_DIR, "targets", "repos.json"), "utf8"),
355
+ );
356
+ for (const [lang, entries] of Object.entries(data)) {
357
+ for (const e of entries) {
358
+ repos.push({
359
+ name: e.name,
360
+ url: e.url,
361
+ language: lang,
362
+ known: true,
363
+ defaultPath: path.join(process.env.HOME ?? "/tmp", "repos", e.name),
364
+ questions: loadQuestions(lang, e.name),
365
+ });
366
+ }
367
+ }
368
+ } catch (err) {
369
+ logger.warn(`Could not load repos.json: ${err.message}`);
370
+ }
371
+ return repos.filter((r) => r.questions.length > 0);
372
+ }
373
+
374
+ const KNOWN_REPOS = loadRepos();
375
+
376
+ /**
377
+ * Each agent: how to run it, how to check it's installed, and how to wire YATS MCP.
378
+ */
90
379
  const KNOWN_AGENTS = [
91
380
  {
92
381
  name: "claude",
@@ -94,207 +383,611 @@ const KNOWN_AGENTS = [
94
383
  checkCmd: "which claude",
95
384
  installHint: "npm install -g @anthropic-ai/claude-code",
96
385
  needsApiKey: "ANTHROPIC_API_KEY",
386
+ defaultModel: process.env.YATS_BENCH_MODEL ?? "haiku",
387
+ models: [
388
+ { name: "haiku", hint: "fastest & cheapest" },
389
+ { name: "sonnet", hint: "balanced" },
390
+ { name: "opus", hint: "most powerful" },
391
+ ],
392
+ authLabel: "ANTHROPIC_API_KEY (in ~/.yats/.env)",
97
393
  needsSkill: true,
98
- needsMcpConfig: true,
99
- runCmd: (prompt, repoDir, hasMcp) => {
100
- return [
101
- "-p", prompt,
102
- "--model", process.env.YATS_BENCH_MODEL ?? "haiku",
103
- "--output-format", "stream-json",
104
- "--verbose",
105
- "--dangerously-skip-permissions",
106
- ...(hasMcp ? ["--mcp-config", "/tmp/yats-bench-mcp.json"] : []),
107
- ];
108
- },
394
+ mcpKind: "stdio",
395
+ runCmd: (prompt, repoDir, hasMcp, model) => [
396
+ "-p", prompt,
397
+ "--model", model,
398
+ "--output-format", "stream-json",
399
+ "--verbose",
400
+ "--dangerously-skip-permissions",
401
+ ...(hasMcp ? ["--mcp-config", "/tmp/yats-bench-mcp.json"] : []),
402
+ ],
109
403
  },
110
404
  {
111
405
  name: "codex",
112
406
  cli: "codex",
113
407
  checkCmd: "which codex",
114
- installHint: "Install VS Code ChatGPT extension",
408
+ installHint: "npm install -g @openai/codex",
115
409
  needsApiKey: "OPENAI_API_KEY",
410
+ defaultModel: "gpt-4.1-mini",
411
+ models: [
412
+ { name: "gpt-4.1-mini", hint: "fastest & cheapest" },
413
+ { name: "gpt-4.1", hint: "balanced" },
414
+ { name: "gpt-5.4", hint: "most powerful" },
415
+ ],
416
+ authLabel: "OPENAI_API_KEY (in ~/.yats/.env)",
116
417
  needsSkill: false,
117
- needsMcpConfig: false,
118
- runCmd: (prompt, repoDir, hasMcp) => {
119
- return [
120
- "exec", "--json",
121
- ...(hasMcp ? [] : ["-c", "mcp_servers.yats.enabled=false"]),
122
- prompt,
123
- ];
124
- },
418
+ mcpKind: "codex-config",
419
+ runCmd: (prompt, repoDir, hasMcp, model) => ["exec", "--json", "--skip-git-repo-check", "--dangerously-bypass-approvals-and-sandbox", prompt],
420
+ },
421
+ {
422
+ name: "copilot",
423
+ cli: "copilot",
424
+ checkCmd: "which copilot",
425
+ installHint: "npm install -g @github/copilot",
426
+ needsApiKey: "",
427
+ defaultModel: "default",
428
+ models: [
429
+ { name: "default", hint: "Copilot-managed model" },
430
+ ],
431
+ authLabel: "copilot auth (consent asked at start)",
432
+ needsSkill: false,
433
+ mcpKind: "copilot-config",
434
+ runCmd: (prompt, repoDir, hasMcp, model) => [
435
+ "-p", prompt,
436
+ "--output-format", "json",
437
+ "--allow-all",
438
+ ...(hasMcp ? ["--additional-mcp-config", "@/tmp/copilot-mcp.json"] : []),
439
+ ],
440
+ },
441
+ {
442
+ name: "cursor",
443
+ cli: "cursor-agent",
444
+ checkCmd: "which cursor-agent",
445
+ installHint: "https://cursor.com/docs/cli — install the cursor-agent CLI",
446
+ needsApiKey: "",
447
+ defaultModel: "claude-sonnet-5",
448
+ models: [
449
+ { name: "claude-sonnet-5", hint: "balanced" },
450
+ { name: "claude-haiku-5", hint: "fast & cheap" },
451
+ ],
452
+ authLabel: "cursor-agent login",
453
+ needsSkill: false,
454
+ mcpKind: "cursor-config",
455
+ runCmd: (prompt, repoDir, hasMcp, model) => [
456
+ "-p", prompt,
457
+ "--output-format", "stream-json",
458
+ "--force",
459
+ "--model", model,
460
+ ],
461
+ },
462
+ {
463
+ name: "gemini",
464
+ cli: "gemini",
465
+ checkCmd: "which gemini",
466
+ installHint: "npm install -g @google/gemini-cli",
467
+ needsApiKey: "GEMINI_API_KEY",
468
+ defaultModel: process.env.YATS_BENCH_GEMINI_MODEL ?? "gemini-flash-latest",
469
+ models: [
470
+ { name: "gemini-flash-latest", hint: "fastest & cheapest" },
471
+ { name: "gemini-2.5-pro", hint: "most powerful" },
472
+ { name: "gemini-pro-latest", hint: "balanced" },
473
+ ],
474
+ authLabel: "GEMINI_API_KEY (in ~/.yats/.env)",
475
+ needsSkill: false,
476
+ mcpKind: "gemini-config",
477
+ runCmd: (prompt, repoDir, hasMcp, model) => [
478
+ "-p", prompt,
479
+ "--model", model,
480
+ "--output-format", "stream-json",
481
+ "--yolo",
482
+ ],
125
483
  },
126
484
  ];
127
485
 
128
486
  // ============================================================
129
- // Interactive wizard
487
+ // Wizard steps (modern UI)
130
488
  // ============================================================
131
489
 
132
- const ask = (rl, question) => new Promise((resolve) => rl.question(question, resolve));
490
+ async function selectAgent() {
491
+ const opts = KNOWN_AGENTS.map((a) => {
492
+ const installed = isInstalled(a.cli);
493
+ const hasKey = !a.needsApiKey || hasApiKey(a.needsApiKey);
494
+ let hint = installed ? "installed" : "not installed";
495
+ if (installed && a.needsApiKey && !hasKey) hint = `missing ${a.needsApiKey} in ~/.yats/.env`;
496
+ return { label: a.name, hint, ok: installed && hasKey, value: a };
497
+ });
498
+ return select("Select your AI agent", opts);
499
+ }
133
500
 
134
- async function selectAgent(rl) {
135
- console.log("\n Available agents:");
136
- KNOWN_AGENTS.forEach((a, i) => console.log(` ${i + 1}. ${a.name}`));
137
- const choice = await ask(rl, "\n Pick agent [1-2]: ");
138
- const idx = parseInt(choice) - 1;
139
- if (isNaN(idx) || idx < 0 || idx >= KNOWN_AGENTS.length) {
140
- console.log(" Invalid. Defaulting to claude.");
141
- return KNOWN_AGENTS[0];
501
+ async function selectModel(agent) {
502
+ if (agent.models.length <= 1) {
503
+ selectedModel = agent.models[0].name;
504
+ return;
142
505
  }
143
- return KNOWN_AGENTS[idx];
506
+ const opts = agent.models.map((m) => ({
507
+ label: m.name,
508
+ hint: m.hint,
509
+ value: m.name,
510
+ }));
511
+ selectedModel = await select(`Model for ${agent.name}`, opts);
512
+ console.log(` ${A.green}✓${A.reset} Model: ${A.bold}${selectedModel}${A.reset}`);
144
513
  }
145
514
 
146
- async function selectRepo(rl) {
147
- console.log("\n Available repos:");
148
- KNOWN_REPOS.forEach((r, i) => {
149
- const exists = fs.existsSync(r.defaultPath);
150
- console.log(` ${i + 1}. ${r.name} (${r.language}) ${exists ? "[cloned]" : "[will clone]"}`);
151
- });
152
- const choice = await ask(rl, "\n Pick repo [1-2]: ");
153
- const idx = parseInt(choice) - 1;
154
- if (isNaN(idx) || idx < 0 || idx >= KNOWN_REPOS.length) {
155
- console.log(" Invalid. Defaulting to lab_hub.");
156
- return KNOWN_REPOS[1];
515
+ async function selectWorkDir() {
516
+ const def = path.join(process.cwd(), "repos");
517
+ const input = (await askLine(`\n Where to download repos? [${def}]: `)).trim();
518
+ workDir = toAbsolute(input || def);
519
+ for (const r of KNOWN_REPOS) {
520
+ r.defaultPath = path.join(workDir, r.name);
157
521
  }
158
- return KNOWN_REPOS[idx];
522
+ console.log(` ${A.green}✓${A.reset} Repos will be saved to ${workDir}`);
159
523
  }
160
524
 
161
- async function selectQuestion(rl, repo) {
162
- console.log("\n Questions:");
163
- repo.questions.forEach((q, i) => {
164
- console.log(` ${i + 1}. ${q.slice(0, 80)}...`);
525
+ async function selectRepo() {
526
+ const opts = KNOWN_REPOS.map((r) => {
527
+ const exists = fs.existsSync(r.defaultPath) && fs.existsSync(path.join(r.defaultPath, ".git"));
528
+ return {
529
+ label: r.name,
530
+ hint: r.known
531
+ ? `${r.language}${exists ? "" : " · will clone"}`
532
+ : `${r.language} · unknown — proposed by YATS.AI`,
533
+ accent: !r.known,
534
+ value: r,
535
+ };
536
+ });
537
+ opts.push({
538
+ label: "Custom repo",
539
+ hint: "your own — local path or git URL",
540
+ accent: true,
541
+ value: "__custom__",
165
542
  });
166
- const choice = await ask(rl, "\n Pick question [1]: ");
167
- const idx = parseInt(choice || "1") - 1;
168
- if (isNaN(idx) || idx < 0 || idx >= repo.questions.length) {
169
- return repo.questions[0];
543
+ return select("Select a repository", opts);
544
+ }
545
+
546
+ async function selectCustomRepo() {
547
+ console.log(`\n ${A.bold}${A.purple}Custom repo${A.reset}\n`);
548
+ const loc = (await askLine(" Local path or git URL: ")).trim();
549
+ if (!loc) {
550
+ console.log(` ${A.red}✖ Empty location. Aborting.${A.reset}`);
551
+ process.exit(1);
552
+ }
553
+
554
+ const isUrl = /^(https?:\/\/|git@|ssh:\/\/)/i.test(loc);
555
+ let name, url, defaultPath;
556
+ if (isUrl) {
557
+ name = loc.split("/").pop().replace(/\.git$/, "") || "custom";
558
+ url = loc;
559
+ defaultPath = path.join(workDir, name);
560
+ } else {
561
+ defaultPath = toAbsolute(loc);
562
+ name = path.basename(defaultPath);
563
+ url = null;
170
564
  }
171
- return repo.questions[idx];
565
+
566
+ const lang = (await askLine(" Language [auto]: ")).trim() || "auto";
567
+
568
+ console.log(`\n ${A.dim}Question (Enter for a default architecture question):${A.reset}`);
569
+ const q = (await askLine(" > ")).trim();
570
+ const question = q || "Explain the architecture of this codebase: the key components, how they connect, and the main data flow.";
571
+
572
+ return {
573
+ name,
574
+ url,
575
+ language: lang,
576
+ known: false,
577
+ defaultPath,
578
+ questions: [question],
579
+ custom: true,
580
+ };
581
+ }
582
+
583
+ async function selectQuestion(repo) {
584
+ const opts = repo.questions.map((q) => ({
585
+ label: q.length > 76 ? q.slice(0, 76) + "…" : q,
586
+ hint: null,
587
+ value: q,
588
+ }));
589
+ return select("Pick a question", opts);
172
590
  }
173
591
 
174
- async function selectRuns(rl) {
175
- const choice = await ask(rl, "\n Number of runs per condition [1]: ");
176
- const n = parseInt(choice || "1");
177
- return isNaN(n) || n < 1 ? 1 : Math.min(n, 5);
592
+ async function selectRuns() {
593
+ const opts = [1, 2, 3].map((n) => ({
594
+ label: `${n} run${n > 1 ? "s" : ""}`,
595
+ hint: n === 1 ? "recommended" : null,
596
+ value: n,
597
+ }));
598
+ return select("Runs per condition", opts);
178
599
  }
179
600
 
180
601
  // ============================================================
181
602
  // Setup
182
603
  // ============================================================
183
604
 
184
- function ensureRepo(repo) {
185
- const repoPath = repo.defaultPath;
186
- if (!fs.existsSync(repoPath)) {
187
- console.log(`\n Cloning ${repo.name} from ${repo.url}...`);
605
+ async function ensureRepo(repo) {
606
+ const repoPath = path.resolve(repo.defaultPath);
607
+ const gitDir = path.join(repoPath, ".git");
608
+ if (fs.existsSync(repoPath) && fs.existsSync(gitDir)) {
609
+ console.log(` ${A.green}✓${A.reset} Repo at ${repoPath}`);
610
+ return repoPath;
611
+ }
612
+ if (repo.url) {
613
+ if (fs.existsSync(repoPath)) {
614
+ console.log(` ${A.yellow}⚠${A.reset} Removing incomplete clone at ${repoPath}...`);
615
+ fs.rmSync(repoPath, { recursive: true, force: true });
616
+ }
188
617
  const parent = path.dirname(repoPath);
189
618
  fs.mkdirSync(parent, { recursive: true });
190
- execSync(`git clone --depth 1 ${repo.url} ${repoPath}`, {
191
- stdio: "inherit",
192
- timeout: 120_000,
619
+ await runWithSpinner(`Cloning ${repo.name}...`, () => new Promise((resolve, reject) => {
620
+ const proc = spawn("git", ["clone", "--depth", "1", repo.url, repoPath], { stdio: ["ignore", "pipe", "pipe"] });
621
+ proc.on("close", (code) => (code === 0 ? resolve() : reject(new Error(`git clone exited with code ${code}`))));
622
+ proc.on("error", reject);
623
+ }));
624
+ console.log(` ${A.green}✓${A.reset} Cloned to ${repoPath}`);
625
+ return repoPath;
626
+ }
627
+ logger.error(`Path not found: ${repoPath}`);
628
+ process.exit(1);
629
+ }
630
+
631
+ const IGNORE_DIRS = new Set(["node_modules", ".git", "dist", "build", ".next", "__pycache__", "vendor", "target", "bin", "obj", ".venv", "venv", ".yarn", ".pnpm"]);
632
+
633
+ function countFiles(dir) {
634
+ let n = 0;
635
+ try {
636
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
637
+ if (e.name.startsWith(".")) continue;
638
+ if (IGNORE_DIRS.has(e.name)) continue;
639
+ const full = path.join(dir, e.name);
640
+ if (e.isDirectory()) n += countFiles(full);
641
+ else if (e.isFile()) n++;
642
+ }
643
+ } catch {
644
+ /* ignore unreadable dirs */
645
+ }
646
+ return n;
647
+ }
648
+
649
+ function getRepoSummary(repoName) {
650
+ try {
651
+ const out = execSync(`yats summary "${repoName}"`, { encoding: "utf8", stdio: "pipe", timeout: 30_000 });
652
+ return JSON.parse(out);
653
+ } catch {
654
+ return null;
655
+ }
656
+ }
657
+
658
+ function isIndexedAtPath(repoPath) {
659
+ try {
660
+ const out = execSync("yats list", { encoding: "utf8", stdio: "pipe" });
661
+ // yats list prints " <name> → <rootPath>". YATS identifies repos by
662
+ // rootPath, so compare exact paths (not substring — avoids hub-lab matching hub-lab-2).
663
+ return out.split("\n").some((line) => {
664
+ const arrow = line.lastIndexOf("→");
665
+ if (arrow === -1) return false;
666
+ return line.slice(arrow + 1).trim() === repoPath;
193
667
  });
194
- console.log(` ✓ Cloned to ${repoPath}`);
668
+ } catch {
669
+ /* not indexed yet */
670
+ return false;
671
+ }
672
+ }
673
+
674
+ async function ensureIndexed(repo, repoPath) {
675
+ console.log(`\n ${A.dim}Checking if ${repo.name} is indexed...${A.reset}`);
676
+ const already = isIndexedAtPath(repoPath);
677
+
678
+ if (!already) {
679
+ await runWithSpinner(`Indexing ${repo.name}...`, () => new Promise((resolve, reject) => {
680
+ const proc = spawn("yats", ["index", repoPath], { stdio: ["ignore", "pipe", "pipe"] });
681
+ proc.on("close", (code) => (code === 0 ? resolve() : reject(new Error(`yats index exited with code ${code}`))));
682
+ proc.on("error", reject);
683
+ }));
684
+ console.log(` ${A.green}✓${A.reset} Indexed`);
195
685
  } else {
196
- console.log(` ✓ Repo already at ${repoPath}`);
686
+ console.log(` ${A.green}✓${A.reset} Already indexed`);
197
687
  }
198
- return repoPath;
688
+
689
+ const summary = getRepoSummary(repo.name);
690
+ const files = countFiles(repoPath);
691
+ const rows = [
692
+ ["Files", files.toLocaleString()],
693
+ ["Symbols", (summary?.totalSymbols ?? 0).toLocaleString()],
694
+ ["Relationships", (summary?.totalRelationships ?? 0).toLocaleString()],
695
+ ["Languages", (summary?.languages || []).join(", ") || "—"],
696
+ ];
697
+ const w1 = Math.max(...rows.map((r) => r[0].length));
698
+ const w2 = Math.max(...rows.map((r) => r[1].length));
699
+ const border = (l, m, r) => " " + l + "─".repeat(w1 + 2) + m + "─".repeat(w2 + 2) + r;
700
+ const row = (a, b) => ` │ ${a.padEnd(w1)} │ ${b.padEnd(w2)} │`;
701
+ console.log(border("┌", "┬", "┐"));
702
+ for (const [a, b] of rows) console.log(row(a, b));
703
+ console.log(border("└", "┴", "┘"));
199
704
  }
200
705
 
201
- function setupAgent(agent, repoPath, withYats) {
202
- // Skill for Claude
203
- if (agent.needsSkill && withYats) {
204
- const skillDir = path.join(repoPath, ".claude", "skills", "yats");
205
- fs.mkdirSync(skillDir, { recursive: true });
206
- fs.writeFileSync(path.join(skillDir, "SKILL.md"), `---
706
+ function writeSkill(repoPath, withYats) {
707
+ const skillDir = path.join(repoPath, ".claude", "skills", "yats");
708
+ if (withYats) {
709
+ const content = readConnect("claude", "SKILL.md") ?? `---
207
710
  name: yats
208
- description: YATS has this codebase indexed. Use when asked about the code — how something works, architecture, call chains, where something is defined.
209
- when_to_use: "How does X work?, Where is X defined?, What calls X?, architecture, trace, find routes, find config"
711
+ description: YATS has this codebase indexed. Use when asked about the code.
210
712
  ---
211
713
 
212
714
  # YATS Code Intelligence
213
- This repo is indexed by YATS (mcp__yats__* tools). Every symbol, call, and relationship is in a knowledge graph.
214
-
215
- ## Golden rule
216
- **YATS first, Read second.** MCP tools return in ms for ~100 tokens. Reading files costs thousands.
217
-
218
- ## Workflow
219
- 1. search_code — natural language query
220
- 2. find_symbol on hits
221
- 3. find_callers / find_callees to trace
222
- 4. Only then Read files at the line YATS gave you
223
- `);
224
- } else if (!withYats) {
225
- const skillDir = path.join(repoPath, ".claude", "skills", "yats");
226
- if (fs.existsSync(skillDir)) {
227
- fs.rmSync(skillDir, { recursive: true });
228
- }
715
+ Use YATS MCP tools first, file reads second.
716
+ `;
717
+ fs.mkdirSync(skillDir, { recursive: true });
718
+ fs.writeFileSync(path.join(skillDir, "SKILL.md"), content);
719
+ } else {
720
+ fs.rmSync(skillDir, { recursive: true, force: true });
229
721
  }
722
+ }
230
723
 
231
- // MCP config for Claude
232
- if (agent.needsMcpConfig && withYats) {
233
- const mcpConfig = {
234
- mcpServers: {
235
- yats: { url: "http://localhost:5555/mcp" },
236
- },
237
- };
238
- fs.writeFileSync("/tmp/yats-bench-mcp.json", JSON.stringify(mcpConfig));
239
-
240
- const claudeJson = {
241
- env: { API_TIMEOUT_MS: "3000000" },
242
- permissions: { defaultMode: "default" },
243
- projects: {
244
- [repoPath]: {
245
- mcpServers: {
246
- yats: { type: "sse", url: "http://localhost:5555/mcp/sse" },
247
- },
248
- },
249
- },
250
- };
251
- const claudeJsonPath = path.join(process.env.HOME ?? "/tmp", ".claude.json");
252
- fs.writeFileSync(claudeJsonPath, JSON.stringify(claudeJson));
253
- } else if (agent.name === "claude") {
254
- const claudeJsonPath = path.join(process.env.HOME ?? "/tmp", ".claude.json");
255
- fs.writeFileSync(claudeJsonPath, JSON.stringify({
256
- env: { API_TIMEOUT_MS: "3000000" },
257
- permissions: { defaultMode: "default" },
258
- projects: {},
259
- }));
724
+ function setupAgent(agent, repoPath, withYats) {
725
+ const home = path.join(benchHome(), agent.name);
726
+ fs.mkdirSync(home, { recursive: true });
727
+
728
+ switch (agent.mcpKind) {
729
+ case "stdio": { // Claude
730
+ process.env.CLAUDE_CONFIG_DIR = home;
731
+ if (agent.needsSkill) writeSkill(repoPath, withYats);
732
+ if (withYats) {
733
+ const mcp = readConnect("claude", "mcp.json")
734
+ ?? JSON.stringify({ mcpServers: { yats: { command: "yats", args: ["bridge"] } } });
735
+ fs.writeFileSync("/tmp/yats-bench-mcp.json", mcp);
736
+ }
737
+ break;
738
+ }
739
+
740
+ case "codex-config": { // Codex
741
+ process.env.CODEX_HOME = home;
742
+ if (process.env.OPENAI_API_KEY) {
743
+ fs.writeFileSync(path.join(home, "auth.json"), JSON.stringify({ OPENAI_API_KEY: process.env.OPENAI_API_KEY }));
744
+ }
745
+ fs.rmSync(path.join(repoPath, ".codex", "config.toml"), { force: true });
746
+ const model = selectedModel ?? agent.defaultModel;
747
+ const base = readConnect("codex", "config.toml")
748
+ ?? `model = "gpt-4.1-mini"\nsandbox_mode = "danger-full-access"\napproval_policy = "never"\n\n[features]\nmulti_agent = false\n`;
749
+ let config = base.replace(/^model\s*=.*$/m, `model = "${model}"`);
750
+ if (withYats) {
751
+ if (!/\[mcp_servers\.yats\]/.test(config)) {
752
+ config += `\n[mcp_servers.yats]\ncommand = "yats"\nargs = ["bridge"]\n`;
753
+ }
754
+ } else {
755
+ config = config.replace(/\n\[mcp_servers\.yats\][\s\S]*$/, "");
756
+ }
757
+ fs.writeFileSync(path.join(home, "config.toml"), config);
758
+ if (withYats) {
759
+ const ag = readConnect("codex", "AGENTS.md");
760
+ if (ag) fs.writeFileSync(path.join(repoPath, "AGENTS.md"), ag.replaceAll("__REPO_NAME__", path.basename(repoPath)));
761
+ } else {
762
+ fs.rmSync(path.join(repoPath, "AGENTS.md"), { force: true });
763
+ }
764
+ break;
765
+ }
766
+
767
+ case "copilot-config": { // Copilot
768
+ process.env.COPILOT_HOME = home;
769
+ // Only copy the user's auth metadata if they explicitly consented in checkAgent().
770
+ if (copilotConsent) {
771
+ const realConfig = path.join(os.homedir(), ".copilot", "config.json");
772
+ if (fs.existsSync(realConfig)) {
773
+ fs.copyFileSync(realConfig, path.join(home, "config.json"));
774
+ }
775
+ }
776
+ if (withYats) {
777
+ const bridge = path.join(BENCH_DIR, "adapters", "mcp-bridge-stdio.cjs");
778
+ const mcp = JSON.stringify({
779
+ mcpServers: { yats: { type: "local", command: "node", args: [bridge, "--stdio"] } },
780
+ });
781
+ fs.writeFileSync("/tmp/copilot-mcp.json", mcp);
782
+ const instr = readConnect("copilot", "instructions.md");
783
+ if (instr) {
784
+ const ghDir = path.join(repoPath, ".github");
785
+ fs.mkdirSync(ghDir, { recursive: true });
786
+ fs.writeFileSync(path.join(ghDir, "copilot-instructions.md"), instr);
787
+ }
788
+ } else {
789
+ fs.rmSync(path.join(repoPath, ".github", "copilot-instructions.md"), { force: true });
790
+ }
791
+ break;
792
+ }
793
+
794
+ case "cursor-config": { // Cursor
795
+ if (withYats) {
796
+ const mcp = readConnect("cursor", "mcp.json")
797
+ ?? JSON.stringify({ mcpServers: { yats: { url: "http://localhost:5555/mcp" } } });
798
+ fs.writeFileSync("/tmp/cursor-mcp.json", mcp);
799
+ process.env.CURSOR_MCP_CONFIG = "/tmp/cursor-mcp.json";
800
+ const rules = readConnect("cursor", "rules.mdc");
801
+ if (rules) {
802
+ const rulesDir = path.join(repoPath, ".cursor", "rules");
803
+ fs.mkdirSync(rulesDir, { recursive: true });
804
+ fs.writeFileSync(path.join(rulesDir, "yats.mdc"), rules);
805
+ }
806
+ } else {
807
+ delete process.env.CURSOR_MCP_CONFIG;
808
+ fs.rmSync(path.join(repoPath, ".cursor", "rules", "yats.mdc"), { force: true });
809
+ }
810
+ break;
811
+ }
812
+
813
+ case "gemini-config": { // Gemini
814
+ process.env.GEMINI_CLI_HOME = home;
815
+ process.env.GEMINI_CLI_TRUST_WORKSPACE = "true";
816
+ fs.rmSync(path.join(repoPath, ".gemini", "settings.json"), { force: true });
817
+ if (withYats) {
818
+ const mcp = readConnect("gemini", "mcp.json")
819
+ ?? JSON.stringify({ mcpServers: { yats: { command: "yats", args: ["bridge"], trust: true } } });
820
+ const settingsDir = path.join(home, ".gemini");
821
+ fs.mkdirSync(settingsDir, { recursive: true });
822
+ fs.writeFileSync(path.join(settingsDir, "settings.json"), mcp);
823
+ const gmd = readConnect("gemini", "GEMINI.md");
824
+ if (gmd) fs.writeFileSync(path.join(repoPath, "GEMINI.md"), gmd);
825
+ } else {
826
+ fs.rmSync(path.join(home, ".gemini", "settings.json"), { force: true });
827
+ fs.rmSync(path.join(repoPath, "GEMINI.md"), { force: true });
828
+ }
829
+ break;
830
+ }
260
831
  }
261
832
  }
262
833
 
263
- function checkAgent(agent) {
264
- try {
265
- execSync(agent.checkCmd, { stdio: "pipe" });
266
- console.log(` ✓ ${agent.name} CLI found`);
267
- } catch {
268
- console.log(` ⚠ ${agent.name} CLI not found. Install: ${agent.installHint}`);
834
+ async function checkAgent(agent) {
835
+ console.log(`\n ${A.dim}Checking ${agent.name}...${A.reset}`);
836
+ if (!isInstalled(agent.cli)) {
837
+ console.log(` ${A.red}✖ ${agent.cli} is not installed.${A.reset}`);
838
+ console.log(` Install: ${agent.installHint}`);
839
+ return false;
269
840
  }
841
+ console.log(` ${A.green}✓${A.reset} ${agent.cli} found`);
270
842
 
271
- if (!process.env[agent.needsApiKey]) {
272
- console.log(` ⚠ ${agent.needsApiKey} not set. Set it in .env or export it.`);
273
- console.log(` Required for ${agent.name}. See benchmark/.env.example`);
274
- } else {
275
- console.log(` ✓ ${agent.needsApiKey} is set`);
843
+ // API-key agents (claude/codex/gemini) read keys from ~/.yats/.env
844
+ if (agent.needsApiKey) {
845
+ if (!hasApiKey(agent.needsApiKey)) {
846
+ console.log(` ${A.red}✖ ${agent.needsApiKey} not set.${A.reset}`);
847
+ console.log(` Add it to ${A.bold}~/.yats/.env${A.reset} to use ${agent.name}.`);
848
+ return false;
849
+ }
850
+ console.log(` ${A.green}✓${A.reset} ${agent.needsApiKey} found in ~/.yats/.env`);
851
+ return true;
276
852
  }
853
+
854
+ // copilot / cursor use their own OAuth login (no API key in .env)
855
+ if (agent.name === "copilot") {
856
+ const realConfig = path.join(os.homedir(), ".copilot", "config.json");
857
+ if (fs.existsSync(realConfig)) {
858
+ const use = await select("Copilot login", [
859
+ { label: "Use my existing Copilot login (copy ~/.copilot/config.json)", value: true },
860
+ { label: "No — cancel", value: false },
861
+ ]);
862
+ if (!use) {
863
+ console.log(` ${A.yellow}✖ Cancelled${A.reset}`);
864
+ return false;
865
+ }
866
+ copilotConsent = true;
867
+ console.log(` ${A.green}✓${A.reset} Will use your existing Copilot login`);
868
+ } else {
869
+ console.log(` ${A.red}✖ No ~/.copilot/config.json found.${A.reset}`);
870
+ console.log(` Run ${A.bold}copilot auth${A.reset} first.`);
871
+ return false;
872
+ }
873
+ return true;
874
+ }
875
+
876
+ console.log(` ${A.dim}Auth: ${agent.authLabel}${A.reset}`);
877
+ return true;
277
878
  }
278
879
 
279
880
  // ============================================================
280
881
  // Run
281
882
  // ============================================================
282
883
 
283
- function runAgent(agent, prompt, repoPath, withYats, logFile, timeoutSec = 180) {
284
- const args = agent.runCmd(prompt, repoPath, withYats);
884
+ let agentActivity = "";
885
+
886
+ // Generic activity extractor — tails the agent's JSONL log and shows the most
887
+ // recent meaningful event (a tool call, or the event type). No per-agent parsing.
888
+ function tailAgentActivity(logFile) {
889
+ try {
890
+ const size = fs.statSync(logFile).size;
891
+ if (size === 0) { agentActivity = ""; return; }
892
+ const fd = fs.openSync(logFile, "r");
893
+ const len = Math.min(size, 32 * 1024);
894
+ const buf = Buffer.alloc(len);
895
+ fs.readSync(fd, buf, 0, len, size - len);
896
+ fs.closeSync(fd);
897
+
898
+ const events = [];
899
+ for (const line of buf.toString("utf8").split("\n")) {
900
+ const l = line.trim();
901
+ if (!l) continue;
902
+ try {
903
+ const e = JSON.parse(l);
904
+ if (e && typeof e === "object") events.push(e);
905
+ } catch { /* partial line */ }
906
+ }
907
+
908
+ const toolName = (e) => {
909
+ const name =
910
+ (typeof e.name === "string" && e.name) ||
911
+ e.tool_name ||
912
+ e.tool_call?.name ||
913
+ e.tool_use?.name ||
914
+ e.tool?.name ||
915
+ (Array.isArray(e.message?.content) &&
916
+ e.message.content.find((c) => c && c.type === "tool_use")?.name);
917
+ return typeof name === "string" && name ? name : null;
918
+ };
919
+
920
+ // Prefer the most recent tool call in the tail
921
+ for (let i = events.length - 1; i >= 0; i--) {
922
+ const name = toolName(events[i]);
923
+ if (!name) continue;
924
+ const e = events[i];
925
+ const input =
926
+ e.input || e.arguments || e.tool_call?.input || e.tool_call?.arguments ||
927
+ e.tool_use?.input ||
928
+ (Array.isArray(e.message?.content) &&
929
+ e.message.content.find((c) => c && c.type === "tool_use")?.input);
930
+ let detail = input?.file_path ?? input?.query ?? input?.pattern ?? input?.command ?? input?.url ?? "";
931
+ if (!detail && input && typeof input === "object") {
932
+ detail = Object.values(input).find((v) => typeof v === "string") ?? "";
933
+ }
934
+ agentActivity = `${name}${detail ? " " + String(detail).slice(0, 48) : ""}`;
935
+ return;
936
+ }
937
+
938
+ // Fallback: most recent event type
939
+ const last = events[events.length - 1];
940
+ if (last && typeof last.type === "string") {
941
+ agentActivity = `${last.type}${last.subtype ? ":" + last.subtype : ""}`;
942
+ }
943
+ } catch {
944
+ /* file not ready yet */
945
+ }
946
+ }
947
+
948
+ async function runWithSpinner(label, fn) {
949
+ if (!isTTY) {
950
+ console.log(` ${A.dim}${label}...${A.reset}`);
951
+ return fn();
952
+ }
953
+ agentActivity = "";
954
+ const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
955
+ let i = 0;
956
+ const start = Date.now();
957
+ const id = setInterval(() => {
958
+ const secs = Math.floor((Date.now() - start) / 1000);
959
+ process.stdout.write(`\r ${A.cyan}${frames[i % frames.length]}${A.reset} ${A.dim}${label}${A.reset} ${A.gray}${secs}s${A.reset} ${A.dim}${agentActivity}${A.reset} `);
960
+ i++;
961
+ }, 80);
962
+ try {
963
+ return await fn();
964
+ } finally {
965
+ clearInterval(id);
966
+ process.stdout.write("\r\x1b[2K");
967
+ }
968
+ }
969
+
970
+ function runAgent(agent, prompt, repoPath, withYats, logFile, timeoutSec = 600) {
971
+ const model = selectedModel ?? agent.defaultModel;
972
+ const constrained = `Answer the following question about this codebase. Reply concisely in plain text in your final message only. Do NOT create, write, edit, or delete any files, and do not run commands that modify the repo.\n\nQuestion:\n${prompt}`;
973
+ const args = agent.runCmd(constrained, repoPath, withYats, model);
285
974
 
286
975
  return new Promise((resolve) => {
287
976
  const proc = spawn(agent.cli, args, {
288
977
  cwd: repoPath,
289
- stdio: ["pipe", fs.openSync(logFile, "w"), "pipe"],
978
+ stdio: ["ignore", fs.openSync(logFile, "w"), "ignore"],
290
979
  timeout: timeoutSec * 1000,
291
980
  });
292
981
 
982
+ const watcher = setInterval(() => tailAgentActivity(logFile), 400);
983
+
293
984
  proc.on("close", (code, signal) => {
985
+ clearInterval(watcher);
294
986
  resolve({ exitCode: code ?? -1, signal });
295
987
  });
296
988
 
297
989
  proc.on("error", (err) => {
990
+ clearInterval(watcher);
298
991
  fs.appendFileSync(logFile, `\nSPAWN_ERROR: ${err.message}\n`);
299
992
  resolve({ exitCode: -1, signal: null });
300
993
  });
@@ -308,54 +1001,145 @@ function runAgent(agent, prompt, repoPath, withYats, logFile, timeoutSec = 180)
308
1001
  function parseResult(logFile) {
309
1002
  try {
310
1003
  const content = fs.readFileSync(logFile, "utf-8");
311
- const lines = content.trim().split("\n");
312
- const events = lines
313
- .map((l) => {
314
- try { return JSON.parse(l); } catch { return null; }
315
- })
316
- .filter(Boolean);
317
-
318
- const results = events.filter((e) => e.type === "result");
319
- if (!results.length) return { error: "No result events found", logFile };
320
-
321
- const last = results[results.length - 1];
322
- const modelUsage = last.modelUsage ?? {};
1004
+ const events = [];
1005
+ for (const line of content.split("\n")) {
1006
+ const l = line.trim();
1007
+ if (!l) continue;
1008
+ try {
1009
+ const j = JSON.parse(l);
1010
+ if (j && typeof j === "object") events.push(j);
1011
+ } catch {
1012
+ /* skip non-JSON lines */
1013
+ }
1014
+ }
323
1015
 
324
1016
  let tokens = 0;
325
1017
  let outputTokens = 0;
326
1018
  let cacheRead = 0;
327
1019
  let cacheWrite = 0;
328
- for (const mu of Object.values(modelUsage)) {
329
- tokens += (mu.inputTokens ?? 0) + (mu.outputTokens ?? 0) +
330
- (mu.cacheReadInputTokens ?? 0) + (mu.cacheCreationInputTokens ?? 0);
331
- outputTokens += mu.outputTokens ?? 0;
332
- cacheRead += mu.cacheReadInputTokens ?? 0;
333
- cacheWrite += mu.cacheCreationInputTokens ?? 0;
1020
+ let cost = 0;
1021
+ let duration = 0;
1022
+ let errorMsg = null;
1023
+
1024
+ // Claude / Cursor: "result" events with modelUsage
1025
+ const results = events.filter((e) => e.type === "result");
1026
+ if (results.length) {
1027
+ const last = results[results.length - 1];
1028
+ if (last.is_error || last.is_api_error_message) {
1029
+ errorMsg = last.result || last.error || "agent reported an error";
1030
+ }
1031
+ if (last.status === "error") {
1032
+ errorMsg = last.error?.message || last.result || "agent reported an error";
1033
+ }
1034
+ const mu = last.modelUsage ?? {};
1035
+ for (const k of Object.keys(mu)) {
1036
+ tokens += (mu[k].inputTokens ?? 0) + (mu[k].outputTokens ?? 0) +
1037
+ (mu[k].cacheReadInputTokens ?? 0) + (mu[k].cacheCreationInputTokens ?? 0);
1038
+ outputTokens += mu[k].outputTokens ?? 0;
1039
+ cacheRead += mu[k].cacheReadInputTokens ?? 0;
1040
+ cacheWrite += mu[k].cacheCreationInputTokens ?? 0;
1041
+ }
1042
+ cost = last.total_cost_usd ?? cost;
1043
+ duration = last.duration_ms ?? duration;
1044
+ }
1045
+
1046
+ // Codex: "turn.failed" or "error" events
1047
+ if (!errorMsg) {
1048
+ for (const e of events) {
1049
+ if (e.type === "turn.failed" && e.error?.message) {
1050
+ errorMsg = e.error.message;
1051
+ break;
1052
+ }
1053
+ if (e.type === "error" && e.message) {
1054
+ errorMsg = e.message;
1055
+ break;
1056
+ }
1057
+ }
1058
+ }
1059
+
1060
+ // Codex: "turn.completed" events with usage
1061
+ for (const e of events) {
1062
+ if (e.type === "turn.completed" && e.usage) {
1063
+ const u = e.usage;
1064
+ tokens += (u.input_tokens ?? 0) + (u.output_tokens ?? 0) + (u.reasoning_output_tokens ?? 0);
1065
+ outputTokens += u.output_tokens ?? 0;
1066
+ cacheRead += u.cached_input_tokens ?? 0;
1067
+ }
1068
+ }
1069
+
1070
+ // Copilot (legacy): "assistant.usage" events
1071
+ for (const e of events) {
1072
+ if (e.type === "assistant.usage") {
1073
+ tokens += (e.inputTokens ?? 0) + (e.outputTokens ?? 0) + (e.cacheReadTokens ?? 0);
1074
+ outputTokens += e.outputTokens ?? 0;
1075
+ cacheRead += e.cacheReadTokens ?? 0;
1076
+ }
1077
+ }
1078
+
1079
+ // Copilot 1.x: "assistant.message" carries outputTokens. Input tokens are NOT
1080
+ // exposed in the JSON stream, so for Copilot `tokens` == output tokens only.
1081
+ for (const e of events) {
1082
+ if (e.type === "assistant.message" && e.data && typeof e.data.outputTokens === "number") {
1083
+ outputTokens += e.data.outputTokens;
1084
+ tokens += e.data.outputTokens;
1085
+ }
1086
+ }
1087
+
1088
+ // Copilot 1.x credits (nano AI units) — the only full-cost signal available.
1089
+ let nanoAiu = 0;
1090
+ for (const e of events) {
1091
+ if (e.type === "session.usage_checkpoint" && e.data && typeof e.data.totalNanoAiu === "number") {
1092
+ nanoAiu = e.data.totalNanoAiu;
1093
+ }
1094
+ }
1095
+
1096
+ // Gemini: "result" events with stats
1097
+ for (const e of events) {
1098
+ if (e.type === "result" && e.stats) {
1099
+ tokens += (e.stats.input_tokens ?? 0) + (e.stats.output_tokens ?? 0);
1100
+ outputTokens += e.stats.output_tokens ?? 0;
1101
+ }
334
1102
  }
335
1103
 
336
1104
  // Tool calls
337
1105
  const toolCalls = {};
338
1106
  for (const e of events) {
339
- if (e.type === "assistant") {
340
- for (const c of e.message?.content ?? []) {
341
- if (c.type === "tool_use") {
342
- toolCalls[c.name] = (toolCalls[c.name] ?? 0) + 1;
343
- }
1107
+ if (e.type === "assistant" && e.message?.content) {
1108
+ for (const c of e.message.content) {
1109
+ if (c.type === "tool_use") toolCalls[c.name] = (toolCalls[c.name] ?? 0) + 1;
1110
+ }
1111
+ }
1112
+ if (e.type === "item.completed" && e.item) {
1113
+ const it = e.item;
1114
+ if (it.type !== "agent_message" && it.type !== "message") {
1115
+ const name = it.tool || it.name || it.type;
1116
+ if (name) toolCalls[name] = (toolCalls[name] ?? 0) + 1;
344
1117
  }
345
1118
  }
1119
+ if (e.type === "tool_use" && e.tool_name) {
1120
+ toolCalls[e.tool_name] = (toolCalls[e.tool_name] ?? 0) + 1;
1121
+ }
346
1122
  }
347
1123
 
1124
+ const YATS_TOOLS = new Set([
1125
+ "search_code", "search_documentation", "search_similar",
1126
+ "find_symbol", "find_references", "find_callers", "find_callees",
1127
+ "find_implementations", "find_inheritors", "find_tests",
1128
+ "find_routes", "find_configuration", "expand_graph", "related_symbols",
1129
+ "list_symbols", "list_repositories", "repository_summary",
1130
+ "architecture_summary", "index_repository", "delete_repository",
1131
+ "reindex", "index_file", "remove_file",
1132
+ ]);
348
1133
  const yatsQueries = Object.entries(toolCalls)
349
- .filter(([k]) => k.includes("yats") || k.includes("mcp__"))
1134
+ .filter(([k]) => /yats|mcp__/i.test(k) || YATS_TOOLS.has(k))
350
1135
  .reduce((sum, [, v]) => sum + v, 0);
351
- const fileReads = toolCalls["Read"] ?? 0;
352
- const bashCmds = toolCalls["Bash"] ?? 0;
353
- const agentSpawns = (toolCalls["Agent"] ?? 0) + (toolCalls["Task"] ?? 0);
1136
+ const fileReads = (toolCalls["Read"] ?? 0) + (toolCalls["read_file"] ?? 0);
1137
+ const bashCmds = (toolCalls["Bash"] ?? 0) + (toolCalls["bash"] ?? 0) + (toolCalls["command_execution"] ?? 0);
354
1138
 
355
1139
  let contentChars = 0;
356
1140
  for (const e of events) {
357
- if (e.type === "user") {
358
- for (const c of e.message?.content ?? []) {
1141
+ if (e.type === "user" && e.message?.content) {
1142
+ for (const c of e.message.content) {
359
1143
  if (c.type === "tool_result") {
360
1144
  let t = c.content ?? "";
361
1145
  if (Array.isArray(t)) t = t.map((x) => x.text ?? "").join("");
@@ -366,19 +1150,9 @@ function parseResult(logFile) {
366
1150
  }
367
1151
 
368
1152
  return {
369
- tokens,
370
- cost: last.total_cost_usd ?? 0,
371
- outputTokens,
372
- cacheRead,
373
- cacheWrite,
374
- toolCalls,
375
- agentSpawns,
376
- fileReads,
377
- bashCmds,
378
- yatsQueries,
379
- contentChars,
380
- duration: last.duration_ms ?? 0,
381
- logFile,
1153
+ tokens, cost, outputTokens, cacheRead, cacheWrite, toolCalls,
1154
+ fileReads, bashCmds, yatsQueries, contentChars, nanoAiu, duration,
1155
+ error: errorMsg, logFile,
382
1156
  };
383
1157
  } catch (err) {
384
1158
  return { error: err.message, logFile };
@@ -389,33 +1163,119 @@ function parseResult(logFile) {
389
1163
  // Output
390
1164
  // ============================================================
391
1165
 
1166
+ function fmtDuration(ms) {
1167
+ const s = Math.round(ms / 1000);
1168
+ if (s < 60) return `${s}s`;
1169
+ const m = Math.floor(s / 60);
1170
+ return `${m}m ${s % 60}s`;
1171
+ }
1172
+
392
1173
  function printTable(title, runs, withYats) {
393
1174
  const label = withYats ? "With YATS" : "Baseline";
394
- console.log(`\n ${title} — ${label}`);
395
- console.log(" ┌──────┬──────────┬────────┬───────┬──────┬──────┬──────┬──────────┐");
396
- console.log(" │ Run │ Tokens │ Cost │ Output│ Reads│ Bash │ YATS │ Result │");
397
- console.log(" ├──────┼──────────┼────────┼───────┼──────┼──────┼──────┼──────────┤");
1175
+ const cols = [
1176
+ { h: "Run", w: 5, right: false },
1177
+ { h: "Tokens", w: 10, right: true },
1178
+ { h: "Cost", w: 8, right: true },
1179
+ { h: "Output", w: 7, right: true },
1180
+ { h: "Reads", w: 6, right: true },
1181
+ { h: "Bash", w: 5, right: true },
1182
+ { h: "YATS", w: 5, right: true },
1183
+ { h: "Time", w: 8, right: true },
1184
+ { h: "Result", w: 8, right: false },
1185
+ ];
1186
+ const cell = (txt, w, right) => {
1187
+ const s = String(txt);
1188
+ return right ? s.padStart(w) : s.padEnd(w);
1189
+ };
1190
+ const row = (vals) => " │" + vals.map((v, i) => " " + cell(v, cols[i].w, cols[i].right) + " ").join("│") + "│";
1191
+ const border = (l, m, r) => " " + l + cols.map((c) => "─".repeat(c.w + 2)).join(m) + r;
1192
+
1193
+ console.log(`\n ${A.bold}${title} — ${label}${A.reset}`);
1194
+ console.log(border("┌", "┬", "┐"));
1195
+ console.log(row(cols.map((c) => c.h)));
1196
+ console.log(border("├", "┼", "┤"));
398
1197
  for (const r of runs) {
399
1198
  const status = r.error ? "ERROR" : "OK";
400
- console.log(
401
- ` │ ${String(r.run).padEnd(4)} │ ${String(r.tokens).padStart(8)} │ $${r.cost.toFixed(3).padStart(4)} │ ${String(r.outputTokens).padStart(5)} │ ${String(r.fileReads).padStart(4)} │ ${String(r.bashCmds).padStart(4)} │ ${String(r.yatsQueries).padStart(4)} │ ${status.padEnd(8)} │`,
402
- );
1199
+ console.log(row([
1200
+ String(r.run),
1201
+ r.tokens.toLocaleString(),
1202
+ "$" + r.cost.toFixed(3),
1203
+ String(r.outputTokens),
1204
+ String(r.fileReads),
1205
+ String(r.bashCmds),
1206
+ String(r.yatsQueries),
1207
+ fmtDuration(r.duration ?? 0),
1208
+ status,
1209
+ ]));
403
1210
  }
404
- const avg = (arr) => arr.length ? arr.reduce((a, b) => a + b, 0) / arr.length : 0;
1211
+ const avg = (arr) => (arr.length ? arr.reduce((a, b) => a + b, 0) / arr.length : 0);
405
1212
  const good = runs.filter((r) => !r.error);
406
1213
  if (good.length) {
407
- console.log(" ├──────┼──────────┼────────┼───────┼──────┼──────┼──────┼──────────┤");
408
- console.log(
409
- ` │ AVG │ ${String(Math.round(avg(good.map((r) => r.tokens)))).padStart(8)} │ $${avg(good.map((r) => r.cost)).toFixed(3).padStart(4)} │ ${String(Math.round(avg(good.map((r) => r.outputTokens)))).padStart(5)} │ ${String(Math.round(avg(good.map((r) => r.fileReads)))).padStart(4)} │ ${String(Math.round(avg(good.map((r) => r.bashCmds)))).padStart(4)} │ ${String(Math.round(avg(good.map((r) => r.yatsQueries)))).padStart(4)} │ │`,
410
- );
1214
+ console.log(border("├", "┼", "┤"));
1215
+ console.log(row([
1216
+ "AVG",
1217
+ Math.round(avg(good.map((r) => r.tokens))).toLocaleString(),
1218
+ "$" + avg(good.map((r) => r.cost)).toFixed(3),
1219
+ String(Math.round(avg(good.map((r) => r.outputTokens)))),
1220
+ String(Math.round(avg(good.map((r) => r.fileReads)))),
1221
+ String(Math.round(avg(good.map((r) => r.bashCmds)))),
1222
+ String(Math.round(avg(good.map((r) => r.yatsQueries)))),
1223
+ fmtDuration(avg(good.map((r) => r.duration ?? 0))),
1224
+ "",
1225
+ ]));
411
1226
  }
412
- console.log(" └──────┴──────────┴────────┴───────┴──────┴──────┴──────┴──────────┘");
1227
+ console.log(border("└", "┴", "┘"));
1228
+ }
1229
+
1230
+ function printCopilotTable(title, runs, withYats) {
1231
+ const label = withYats ? "With YATS" : "Baseline";
1232
+ const cols = [
1233
+ { h: "Run", w: 5, right: false },
1234
+ { h: "AIU (cost)", w: 12, right: true },
1235
+ { h: "Time", w: 8, right: true },
1236
+ { h: "Result", w: 8, right: false },
1237
+ ];
1238
+ const cell = (txt, w, right) => {
1239
+ const s = String(txt);
1240
+ return right ? s.padStart(w) : s.padEnd(w);
1241
+ };
1242
+ const row = (vals) => " │" + vals.map((v, i) => " " + cell(v, cols[i].w, cols[i].right) + " ").join("│") + "│";
1243
+ const border = (l, m, r) => " " + l + cols.map((c) => "─".repeat(c.w + 2)).join(m) + r;
1244
+
1245
+ console.log(`\n ${A.bold}${title} — ${label}${A.reset}`);
1246
+ console.log(border("┌", "┬", "┐"));
1247
+ console.log(row(cols.map((c) => c.h)));
1248
+ console.log(border("├", "┼", "┤"));
1249
+ for (const r of runs) {
1250
+ const status = r.error ? "ERROR" : "OK";
1251
+ console.log(row([
1252
+ String(r.run),
1253
+ ((r.nanoAiu ?? 0) / 1e9).toFixed(3),
1254
+ fmtDuration(r.duration ?? 0),
1255
+ status,
1256
+ ]));
1257
+ }
1258
+ const good = runs.filter((r) => !r.error);
1259
+ if (good.length) {
1260
+ const avg = (arr, f) => arr.reduce((a, b) => a + f(b), 0) / arr.length;
1261
+ console.log(border("├", "┼", "┤"));
1262
+ console.log(row([
1263
+ "AVG",
1264
+ (avg(good, (r) => r.nanoAiu ?? 0) / 1e9).toFixed(3),
1265
+ fmtDuration(avg(good, (r) => r.duration ?? 0)),
1266
+ "",
1267
+ ]));
1268
+ }
1269
+ console.log(border("└", "┴", "┘"));
413
1270
  }
414
1271
 
415
1272
  function printComparison(baseline, yats) {
416
1273
  const goodB = baseline.filter((r) => !r.error);
417
1274
  const goodY = yats.filter((r) => !r.error);
418
- if (!goodB.length || !goodY.length) return;
1275
+ if (!goodB.length || !goodY.length) {
1276
+ console.log(`\n ${A.yellow}⚠ No valid results to compare.${A.reset}`);
1277
+ return;
1278
+ }
419
1279
 
420
1280
  const avg = (arr) => arr.reduce((a, b) => a + b, 0) / arr.length;
421
1281
  const tB = avg(goodB.map((r) => r.tokens));
@@ -426,132 +1286,290 @@ function printComparison(baseline, yats) {
426
1286
  const rY = avg(goodY.map((r) => r.fileReads));
427
1287
  const bB = avg(goodB.map((r) => r.bashCmds));
428
1288
  const bY = avg(goodY.map((r) => r.bashCmds));
1289
+ const dB = avg(goodB.map((r) => r.duration ?? 0));
1290
+ const dY = avg(goodY.map((r) => r.duration ?? 0));
1291
+
1292
+ if (tB <= 0) {
1293
+ console.log(`\n ${A.yellow}⚠ Baseline returned 0 tokens — the agent likely failed (check credits/auth).${A.reset}`);
1294
+ return;
1295
+ }
1296
+
1297
+ const W = 46;
1298
+ const n = (x) => Math.round(x).toLocaleString();
1299
+ const pct = (a, b) => ((a - b) / a * 100);
1300
+ const strip = (s) => s.replace(/\x1b\[[0-9;]*m/g, "");
1301
+ const pad = (s) => s + " ".repeat(Math.max(0, W - strip(s).length));
1302
+ const line = (txt) => " ║ " + pad(txt) + " ║";
1303
+
1304
+ const sign = (p) => {
1305
+ if (p > 0) return `${A.green}↓ ${Math.abs(p).toFixed(1).padStart(5)}%${A.reset}`;
1306
+ if (p < 0) return `${A.red}↑ ${Math.abs(p).toFixed(1).padStart(5)}%${A.reset}`;
1307
+ return `${A.dim}· 0.0%${A.reset}`;
1308
+ };
429
1309
 
430
- const tokenSave = ((tB - tY) / tB * 100);
431
- const costSave = ((cB - cY) / cB * 100);
432
- const readSave = rB ? ((rB - rY) / rB * 100) : 0;
433
- const bashSave = bB ? ((bB - bY) / bB * 100) : 0;
1310
+ const tokenSave = pct(tB, tY);
1311
+ const costSave = cB > 0 ? pct(cB, cY) : null;
1312
+ const readSave = rB ? pct(rB, rY) : 0;
1313
+ const bashSave = bB ? pct(bB, bY) : 0;
1314
+ const timeSave = dB ? pct(dB, dY) : 0;
434
1315
 
435
- console.log("\n ╔══════════════════════════════════════════════════╗");
436
- console.log(" ║" + " SAVINGS (YATS vs Baseline)".padEnd(49) + "║");
437
- console.log(" ╠══════════════════════════════════════════════════╣");
438
- console.log(` ║ Tokens: ${String(Math.round(tB)).padStart(8)} → ${String(Math.round(tY)).padStart(8)} ${tokenSave > 0 ? "↓" : "↑"} ${Math.abs(tokenSave).toFixed(1).padStart(5)}%`.padEnd(49) + "║");
439
- console.log(` ║ Cost: $${cB.toFixed(3)} → $${cY.toFixed(3)} ${costSave > 0 ? "↓" : "↑"} ${Math.abs(costSave).toFixed(1).padStart(5)}%`.padEnd(49) + "║");
440
- console.log(` ║ File reads: ${String(Math.round(rB)).padStart(5)} → ${String(Math.round(rY)).padStart(5)} ${readSave > 0 ? "↓" : "↑"} ${Math.abs(readSave).toFixed(1).padStart(5)}%`.padEnd(49) + "║");
441
- console.log(` ║ Bash cmds: ${String(Math.round(bB)).padStart(5)} → ${String(Math.round(bY)).padStart(5)} ${bashSave > 0 ? "↓" : "↑"} ${Math.abs(bashSave).toFixed(1).padStart(5)}%`.padEnd(49) + "║");
442
- console.log(" ╚══════════════════════════════════════════════════╝");
1316
+ const costCell = cB > 0 ? `$${cB.toFixed(3)} → $${cY.toFixed(3)}` : `${A.dim}n/a${A.reset}`;
1317
+
1318
+ console.log(" ╔" + "═".repeat(W + 2) + "╗");
1319
+ console.log(" ║ " + "SAVINGS (YATS vs Baseline)".padEnd(W) + " ║");
1320
+ console.log(" ╠" + "═".repeat(W + 2) + "╣");
1321
+ console.log(line(`Tokens: ${n(tB).padStart(8)} → ${n(tY).padStart(8)} ${sign(tokenSave)}`));
1322
+ console.log(line(`Cost: ${costCell} ${costSave === null ? `${A.dim}n/a${A.reset}` : sign(costSave)}`));
1323
+ console.log(line(`File reads: ${n(rB).padStart(5)} → ${n(rY).padStart(5)} ${sign(readSave)}`));
1324
+ console.log(line(`Bash cmds: ${n(bB).padStart(5)} → ${n(bY).padStart(5)} ${sign(bashSave)}`));
1325
+ console.log(line(`Time: ${fmtDuration(dB).padStart(8)} → ${fmtDuration(dY).padStart(8)} ${sign(timeSave)}`));
1326
+ console.log(" ╚" + "═".repeat(W + 2) + "╝");
1327
+ }
1328
+
1329
+ function printCopilotComparison(baseline, yats) {
1330
+ const goodB = baseline.filter((r) => !r.error);
1331
+ const goodY = yats.filter((r) => !r.error);
1332
+ if (!goodB.length || !goodY.length) {
1333
+ console.log(`\n ${A.yellow}⚠ No valid results to compare.${A.reset}`);
1334
+ return;
1335
+ }
1336
+
1337
+ const avg = (arr, f) => arr.reduce((a, b) => a + f(b), 0) / arr.length;
1338
+ const aB = avg(goodB, (r) => r.nanoAiu ?? 0);
1339
+ const aY = avg(goodY, (r) => r.nanoAiu ?? 0);
1340
+ const dB = avg(goodB, (r) => r.duration ?? 0);
1341
+ const dY = avg(goodY, (r) => r.duration ?? 0);
1342
+
1343
+ if (aB <= 0) {
1344
+ console.log(`\n ${A.yellow}⚠ Baseline used 0 AIU — the agent likely failed (check credits/auth).${A.reset}`);
1345
+ return;
1346
+ }
1347
+
1348
+ const W = 46;
1349
+ const pct = (a, b) => ((a - b) / a * 100);
1350
+ const strip = (s) => s.replace(/\x1b\[[0-9;]*m/g, "");
1351
+ const pad = (s) => s + " ".repeat(Math.max(0, W - strip(s).length));
1352
+ const line = (txt) => " ║ " + pad(txt) + " ║";
1353
+ const sign = (p) => {
1354
+ if (p > 0) return `${A.green}↓ ${Math.abs(p).toFixed(1).padStart(5)}%${A.reset}`;
1355
+ if (p < 0) return `${A.red}↑ ${Math.abs(p).toFixed(1).padStart(5)}%${A.reset}`;
1356
+ return `${A.dim}· 0.0%${A.reset}`;
1357
+ };
1358
+ const aiu = (x) => (x / 1e9).toFixed(3);
1359
+
1360
+ console.log(" ╔" + "═".repeat(W + 2) + "╗");
1361
+ console.log(" ║ " + "SAVINGS (YATS vs Baseline)".padEnd(W) + " ║");
1362
+ console.log(" ╠" + "═".repeat(W + 2) + "╣");
1363
+ console.log(line(`AIU (cost): ${aiu(aB).padStart(7)} → ${aiu(aY).padStart(7)} ${sign(pct(aB, aY))}`));
1364
+ console.log(line(`Time: ${fmtDuration(dB).padStart(8)} → ${fmtDuration(dY).padStart(8)} ${sign(pct(dB, dY))}`));
1365
+ console.log(" ╚" + "═".repeat(W + 2) + "╝");
1366
+ }
1367
+
1368
+ function saveResult(entry) {
1369
+ const file = path.join(BENCH_DIR, "results.json");
1370
+ let data = { runs: [] };
1371
+ try {
1372
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
1373
+ if (Array.isArray(parsed.runs)) data = parsed;
1374
+ } catch {
1375
+ /* start fresh */
1376
+ }
1377
+ data.runs.push(entry);
1378
+ fs.writeFileSync(file, JSON.stringify(data, null, 2) + "\n");
443
1379
  }
444
1380
 
445
1381
  // ============================================================
446
1382
  // Main entry
447
1383
  // ============================================================
448
1384
 
449
- export async function runBenchmark() {
450
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1385
+ function printIntro() {
1386
+ console.log(`\n ${A.bold}${A.purple}YATS Benchmark${A.reset}`);
1387
+ console.log(` ${A.dim}Measure token savings: the same question, answered with vs without YATS.${A.reset}\n`);
1388
+ console.log(` ${A.yellow}💡 Tip:${A.reset} ${A.dim}Pick an ${A.reset}${A.cyan}unknown${A.reset}${A.dim} or your own repo — the model can't answer it from memory, so that's where YATS shows its real value.${A.reset}`);
1389
+ }
451
1390
 
452
- console.log("\n ╔══════════════════════════════════════════════════╗");
453
- console.log(" ║" + " YATS BENCHMARK".padEnd(49) + "║");
454
- console.log(" ╚══════════════════════════════════════════════════╝");
1391
+ async function runOnce() {
1392
+ printIntro();
1393
+ selectedModel = null;
455
1394
 
456
- // 1. Select agent
457
- const agent = await selectAgent(rl);
458
- checkAgent(agent);
1395
+ // 1. Agent
1396
+ const agent = await selectAgent();
1397
+ if (!(await checkAgent(agent))) {
1398
+ restoreTerminal();
1399
+ process.exit(1);
1400
+ }
459
1401
 
460
- // 2. Select repo
461
- const repo = await selectRepo(rl);
1402
+ // 2. Model
1403
+ await selectModel(agent);
462
1404
 
463
- // 3. Ensure repo cloned
464
- const repoPath = ensureRepo(repo);
1405
+ // 3. Workdir
1406
+ await selectWorkDir();
1407
+
1408
+ // 4. Repo
1409
+ let repo = await selectRepo();
1410
+ if (repo === "__custom__") {
1411
+ repo = await selectCustomRepo();
1412
+ }
465
1413
 
466
- // 4. Select question
467
- const question = await selectQuestion(rl, repo);
1414
+ // 3. Clone + index
1415
+ const repoPath = await ensureRepo(repo);
1416
+ await ensureIndexed(repo, repoPath);
1417
+ process.env.YATS_DEFAULT_REPO = repoPath;
468
1418
 
469
- // 5. Number of runs
470
- const numRuns = await selectRuns(rl);
1419
+ // 4. Question
1420
+ const question = await selectQuestion(repo);
471
1421
 
472
- rl.close();
1422
+ // 5. Runs
1423
+ const numRuns = await selectRuns();
473
1424
 
474
- // 6. Ensure repo is indexed
475
- console.log(`\n Checking if ${repo.name} is indexed...`);
1425
+ restoreTerminal();
476
1426
 
477
- const resultsDir = path.join(process.cwd(), "benchmark", "results");
1427
+ const resultsDir = path.join(BENCH_DIR, "results");
478
1428
  fs.mkdirSync(resultsDir, { recursive: true });
479
- const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
1429
+ const model = selectedModel ?? agent.defaultModel;
1430
+ const date = new Date().toISOString().slice(0, 10);
1431
+ const baseName = `${repo.name}__${agent.name}__${model}__${date}`;
480
1432
 
481
- // 7. Run baseline
482
- console.log(`\n ═══════ BASELINE (${numRuns} runs) ═══════`);
1433
+ // 6. Baseline
1434
+ console.log(`\n ${A.bold}═══════ BASELINE (${numRuns} run${numRuns > 1 ? "s" : ""}) ═══════${A.reset}`);
483
1435
  const baselineResults = [];
484
1436
  for (let i = 1; i <= numRuns; i++) {
485
- console.log(`\n ▶ Run ${i}/${numRuns} — BASELINE...`);
486
1437
  setupAgent(agent, repoPath, false);
487
- const logFile = path.join(resultsDir, `${repo.name}_baseline_${timestamp}_run${i}.jsonl`);
488
- await runAgent(agent, question, repoPath, false, logFile);
1438
+ const logFile = path.join(resultsDir, `${baseName}__baseline.jsonl`);
1439
+ const t0 = Date.now();
1440
+ await runWithSpinner(`Baseline ${i}/${numRuns} — ${agent.name} is reading files to answer`, () =>
1441
+ runAgent(agent, question, repoPath, false, logFile));
1442
+ const elapsedMs = Date.now() - t0;
489
1443
  const result = parseResult(logFile);
490
1444
  baselineResults.push({
491
- run: i,
492
- withYats: false,
493
- tokens: result.tokens ?? 0,
494
- cost: result.cost ?? 0,
1445
+ run: i, withYats: false,
1446
+ tokens: result.tokens ?? 0, cost: result.cost ?? 0,
495
1447
  outputTokens: result.outputTokens ?? 0,
496
- cacheRead: result.cacheRead ?? 0,
497
- cacheWrite: result.cacheWrite ?? 0,
1448
+ cacheRead: result.cacheRead ?? 0, cacheWrite: result.cacheWrite ?? 0,
498
1449
  toolCalls: result.toolCalls ?? {},
499
- agentSpawns: result.agentSpawns ?? 0,
500
- fileReads: result.fileReads ?? 0,
501
- bashCmds: result.bashCmds ?? 0,
502
- yatsQueries: result.yatsQueries ?? 0,
503
- contentChars: result.contentChars ?? 0,
504
- duration: result.duration ?? 0,
505
- error: result.error,
506
- logFile,
1450
+ fileReads: result.fileReads ?? 0, bashCmds: result.bashCmds ?? 0,
1451
+ yatsQueries: result.yatsQueries ?? 0, contentChars: result.contentChars ?? 0,
1452
+ nanoAiu: result.nanoAiu ?? 0,
1453
+ duration: elapsedMs, error: result.error, logFile,
507
1454
  });
508
1455
  const r = baselineResults[baselineResults.length - 1];
509
- if (r.error) {
510
- console.log(` ❌ Error: ${r.error}`);
511
- } else {
512
- console.log(` ✓ ${r.tokens.toLocaleString()} tokens, $${r.cost.toFixed(4)}, ${r.fileReads} reads, ${r.bashCmds} bash`);
513
- }
1456
+ if (r.error) console.log(` ${A.red}✖ ${r.error}${A.reset}`);
1457
+ else console.log(` ${A.green}✓${A.reset} ${r.tokens.toLocaleString()} tokens${r.nanoAiu ? `, ${(r.nanoAiu / 1e9).toFixed(3)} AIU` : ""}, $${r.cost.toFixed(4)}, ${r.fileReads} reads, ${r.bashCmds} bash, ${fmtDuration(elapsedMs)}`);
1458
+ }
1459
+
1460
+ // 6.5 — Ask before continuing to the with-YATS runs
1461
+ console.log(`\n ${A.dim}Baseline finished. Next up: the same question answered ${A.bold}with YATS${A.reset}${A.dim}.${A.reset}`);
1462
+ const proceed = await select("Continue with the YATS runs?", [
1463
+ { label: "Yes, run with YATS", value: true },
1464
+ { label: "No, stop here", value: false },
1465
+ ]);
1466
+ if (!proceed) {
1467
+ console.log(`\n ${A.yellow}✖ Stopped before the YATS runs${A.reset}\n`);
1468
+ return;
514
1469
  }
515
1470
 
516
- // 8. Run YATS
517
- console.log(`\n ═══════ WITH YATS (${numRuns} runs) ═══════`);
1471
+ // 7. YATS
1472
+ console.log(`\n ${A.bold}═══════ WITH YATS (${numRuns} run${numRuns > 1 ? "s" : ""}) ═══════${A.reset}`);
518
1473
  const yatsResults = [];
519
1474
  for (let i = 1; i <= numRuns; i++) {
520
- console.log(`\n ▶ Run ${i}/${numRuns} — YATS...`);
521
1475
  setupAgent(agent, repoPath, true);
522
- const logFile = path.join(resultsDir, `${repo.name}_yats_${timestamp}_run${i}.jsonl`);
523
- await runAgent(agent, question, repoPath, true, logFile);
1476
+ const logFile = path.join(resultsDir, `${baseName}__yats.jsonl`);
1477
+ const t0 = Date.now();
1478
+ await runWithSpinner(`With YATS ${i}/${numRuns} — ${agent.name} is querying the knowledge graph`, () =>
1479
+ runAgent(agent, question, repoPath, true, logFile));
1480
+ const elapsedMs = Date.now() - t0;
524
1481
  const result = parseResult(logFile);
525
1482
  yatsResults.push({
526
- run: i,
527
- withYats: true,
528
- tokens: result.tokens ?? 0,
529
- cost: result.cost ?? 0,
1483
+ run: i, withYats: true,
1484
+ tokens: result.tokens ?? 0, cost: result.cost ?? 0,
530
1485
  outputTokens: result.outputTokens ?? 0,
531
- cacheRead: result.cacheRead ?? 0,
532
- cacheWrite: result.cacheWrite ?? 0,
1486
+ cacheRead: result.cacheRead ?? 0, cacheWrite: result.cacheWrite ?? 0,
533
1487
  toolCalls: result.toolCalls ?? {},
534
- agentSpawns: result.agentSpawns ?? 0,
535
- fileReads: result.fileReads ?? 0,
536
- bashCmds: result.bashCmds ?? 0,
537
- yatsQueries: result.yatsQueries ?? 0,
538
- contentChars: result.contentChars ?? 0,
539
- duration: result.duration ?? 0,
540
- error: result.error,
541
- logFile,
1488
+ fileReads: result.fileReads ?? 0, bashCmds: result.bashCmds ?? 0,
1489
+ yatsQueries: result.yatsQueries ?? 0, contentChars: result.contentChars ?? 0,
1490
+ nanoAiu: result.nanoAiu ?? 0,
1491
+ duration: elapsedMs, error: result.error, logFile,
542
1492
  });
543
1493
  const r = yatsResults[yatsResults.length - 1];
544
- if (r.error) {
545
- console.log(` ❌ Error: ${r.error}`);
546
- } else {
547
- console.log(` ✓ ${r.tokens.toLocaleString()} tokens, $${r.cost.toFixed(4)}, ${r.yatsQueries} yats, ${r.fileReads} reads`);
548
- }
1494
+ if (r.error) console.log(` ${A.red}✖ ${r.error}${A.reset}`);
1495
+ else console.log(` ${A.green}✓${A.reset} ${r.tokens.toLocaleString()} tokens${r.nanoAiu ? `, ${(r.nanoAiu / 1e9).toFixed(3)} AIU` : ""}, $${r.cost.toFixed(4)}, ${r.yatsQueries} yats, ${r.fileReads} reads, ${fmtDuration(elapsedMs)}`);
549
1496
  }
550
1497
 
551
- // 9. Show results
552
- printTable(repo.name, baselineResults, false);
553
- printTable(repo.name, yatsResults, true);
554
- printComparison(baselineResults, yatsResults);
1498
+ // 8. Results
1499
+ const isCopilot = agent.name === "copilot";
1500
+ if (isCopilot) {
1501
+ console.log(`\n ${A.yellow}⚠ ${A.bold}Copilot CLI doesn't expose Input Tokens${A.reset}${A.yellow} — comparing ${A.bold}AIU (cost)${A.reset}${A.yellow} & time instead.${A.reset}`);
1502
+ printCopilotTable(repo.name, baselineResults, false);
1503
+ printCopilotTable(repo.name, yatsResults, true);
1504
+ printCopilotComparison(baselineResults, yatsResults);
1505
+ } else {
1506
+ printTable(repo.name, baselineResults, false);
1507
+ printTable(repo.name, yatsResults, true);
1508
+ printComparison(baselineResults, yatsResults);
1509
+ }
555
1510
 
556
- console.log(`\n Logs saved to: ${resultsDir}\n`);
1511
+ // Persist a summary entry to results.json
1512
+ const avgField = (arr, f) => {
1513
+ const good = arr.filter((r) => !r.error);
1514
+ return good.length ? good.reduce((s, r) => s + f(r), 0) / good.length : 0;
1515
+ };
1516
+ const entry = {
1517
+ agent: agent.name,
1518
+ model: selectedModel ?? agent.defaultModel,
1519
+ repo: repo.name,
1520
+ date: new Date().toISOString().slice(0, 10),
1521
+ question,
1522
+ time_ms: {
1523
+ without: Math.round(avgField(baselineResults, (r) => r.duration ?? 0)),
1524
+ with: Math.round(avgField(yatsResults, (r) => r.duration ?? 0)),
1525
+ },
1526
+ };
1527
+ if (isCopilot) {
1528
+ const aB = avgField(baselineResults, (r) => r.nanoAiu ?? 0);
1529
+ const aY = avgField(yatsResults, (r) => r.nanoAiu ?? 0);
1530
+ entry.aiu = {
1531
+ without: Math.round((aB / 1e9) * 1e6) / 1e6,
1532
+ with: Math.round((aY / 1e9) * 1e6) / 1e6,
1533
+ };
1534
+ entry.savings_pct = aB > 0 ? Math.round(((aB - aY) / aB * 100) * 10) / 10 : null;
1535
+ } else {
1536
+ const tB = avgField(baselineResults, (r) => r.tokens);
1537
+ const tY = avgField(yatsResults, (r) => r.tokens);
1538
+ entry.tokens = { without: Math.round(tB), with: Math.round(tY) };
1539
+ entry.cost = {
1540
+ without: Math.round(avgField(baselineResults, (r) => r.cost) * 1000) / 1000,
1541
+ with: Math.round(avgField(yatsResults, (r) => r.cost) * 1000) / 1000,
1542
+ };
1543
+ entry.file_reads = {
1544
+ without: Math.round(avgField(baselineResults, (r) => r.fileReads)),
1545
+ with: Math.round(avgField(yatsResults, (r) => r.fileReads)),
1546
+ };
1547
+ entry.bash_cmds = {
1548
+ without: Math.round(avgField(baselineResults, (r) => r.bashCmds)),
1549
+ with: Math.round(avgField(yatsResults, (r) => r.bashCmds)),
1550
+ };
1551
+ entry.yats_queries = {
1552
+ without: Math.round(avgField(baselineResults, (r) => r.yatsQueries)),
1553
+ with: Math.round(avgField(yatsResults, (r) => r.yatsQueries)),
1554
+ };
1555
+ entry.savings_pct = tB > 0 ? Math.round(((tB - tY) / tB * 100) * 10) / 10 : null;
1556
+ }
1557
+ saveResult(entry);
1558
+
1559
+ console.log(`\n ${A.dim}Logs saved to: ${resultsDir}${A.reset}\n`);
1560
+ }
1561
+
1562
+ export async function runBenchmark() {
1563
+ while (true) {
1564
+ await runOnce();
1565
+ const again = await select("What's next?", [
1566
+ { label: "Run another benchmark", value: true },
1567
+ { label: "Exit", value: false },
1568
+ ]);
1569
+ if (!again) break;
1570
+ }
1571
+ console.log(`\n ${A.dim}Bye 👋${A.reset}\n`);
1572
+ restoreTerminal();
1573
+ if (rl) rl.close();
1574
+ process.exit(0);
557
1575
  }