yats-toolkit 0.2.2 → 0.3.0

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