yats-toolkit 0.1.10 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -97,9 +97,14 @@ Add this to your AI agent's MCP config:
97
97
  ```bash
98
98
  yats setup # Run the setup wizard
99
99
  yats index <path> # Index a repository
100
+ yats search <query> # Search indexed code
101
+ yats list # List indexed repositories
102
+ yats summary <repo> # Show repository summary
103
+ yats clear <repo> # Delete indexed data (needs confirmation)
100
104
  yats status # Check what's indexed
101
105
  yats stop # Stop all YATS services
102
106
  yats bridge # MCP stdio ↔ HTTP proxy (for CLI-only agents)
107
+ yats benchmark # AI agent token comparison
103
108
  ```
104
109
 
105
110
  ## Requirements
@@ -143,6 +148,33 @@ yats bridge
143
148
  ```
144
149
  Starts an MCP stdio ↔ HTTP proxy. Useful for AI agents that only support stdio transport (Copilot, Claude Desktop). Connects to the YATS server at `localhost:5555` by default.
145
150
 
151
+ ```bash
152
+ yats search <query> [--repo=<name>] [--limit=<n>]
153
+ ```
154
+ Searches indexed code using natural language. Uses the `search_code` MCP tool. Results include symbol name, kind, file, line, score, and snippet.
155
+
156
+ ```bash
157
+ yats list
158
+ ```
159
+ Lists all indexed repositories with their root paths. Calls `list_repositories` MCP tool.
160
+
161
+ ```bash
162
+ yats summary <repository>
163
+ ```
164
+ Shows a detailed summary: symbol counts by kind, relationship counts, and languages. Calls `repository_summary` MCP tool.
165
+
166
+ ```bash
167
+ yats clear <repository>
168
+ ```
169
+ Deletes all indexed data for a repository (symbols, relationships, vectors). Uses two-step confirmation via the `delete_repository` MCP tool. Source code files are NOT affected.
170
+
171
+ ```bash
172
+ yats benchmark
173
+ ```
174
+ Runs an interactive AI agent benchmark. Compares token usage answering the same
175
+ codebase questions with and without YATS. Supports Claude CLI and Codex.
176
+ Automatically clones test repos, indexes them, and saves results with averages.
177
+
146
178
  ## License
147
179
 
148
180
  MIT © Franco Vinciarelli
package/bin/setup.js CHANGED
@@ -1,13 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
3
  * YATS Toolkit — Code intelligence for AI agents.
4
- *
4
+ *
5
5
  * Usage:
6
6
  * yats setup # One-time setup wizard
7
7
  * yats index <path> # Index a repository
8
+ * yats search <query> # Search indexed code
9
+ * yats list # List indexed repositories
10
+ * yats summary <repo> # Show repository summary
11
+ * yats clear <repo> # Delete indexed data
8
12
  * yats status # Check indexed repos
9
13
  * yats stop # Stop all YATS services
10
14
  * yats bridge # MCP stdio ↔ HTTP proxy (for Copilot, Claude)
15
+ * yats benchmark # AI agent token comparison
11
16
  */
12
17
 
13
18
  const cmd = process.argv[2] || "setup";
@@ -24,6 +29,18 @@ switch (cmd) {
24
29
  import("../src/indexer.js").then(m => m.default(cleanArgs, { skipDocs }));
25
30
  break;
26
31
  }
32
+ case "search":
33
+ import("../src/search.js").then(m => m.default(args));
34
+ break;
35
+ case "list":
36
+ import("../src/list.js").then(m => m.default());
37
+ break;
38
+ case "summary":
39
+ import("../src/summary.js").then(m => m.default(args));
40
+ break;
41
+ case "clear":
42
+ import("../src/clear.js").then(m => m.default(args));
43
+ break;
27
44
  case "status":
28
45
  import("../src/status.js").then(m => m.default());
29
46
  break;
@@ -33,17 +50,31 @@ switch (cmd) {
33
50
  case "bridge":
34
51
  import("../src/bridge.js");
35
52
  break;
53
+ case "benchmark":
54
+ import("../src/benchmark.js").then(m => m.runBenchmark());
55
+ break;
36
56
  case "--version":
37
57
  case "-v":
38
- console.log("yats v0.1.0");
58
+ try {
59
+ const { readFileSync } = await import("node:fs");
60
+ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf-8"));
61
+ console.log(`yats v${pkg.version}`);
62
+ } catch {
63
+ console.log("yats v0.1.10");
64
+ }
39
65
  break;
40
66
  default:
41
67
  console.log(`YATS Toolkit — Code intelligence for AI agents`);
42
68
  console.log(``);
43
69
  console.log(` yats setup Setup wizard`);
44
70
  console.log(` yats index <path> Index a repository`);
71
+ console.log(` yats search <query> Search indexed code`);
72
+ console.log(` yats list List indexed repositories`);
73
+ console.log(` yats summary <repo> Show repository summary`);
74
+ console.log(` yats clear <repo> Delete indexed data`);
45
75
  console.log(` yats status Check indexed repos`);
46
76
  console.log(` yats stop Stop YATS services`);
47
77
  console.log(` yats bridge Stdio proxy for Copilot/Claude`);
78
+ console.log(` yats benchmark AI agent token comparison`);
48
79
  break;
49
80
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "yats-toolkit",
3
- "version": "0.1.10",
3
+ "version": "0.1.11",
4
4
  "description": "YATS — Yet Another Token Saver. One-command MCP server that indexes your codebase into a knowledge graph so AI agents (Claude, Cursor, Copilot) can search and navigate it without burning tokens.",
5
5
  "author": "Franco Vinciarelli <vinciarellifranco@gmail.com>",
6
6
  "license": "SEE LICENSE IN LICENSE",
@@ -0,0 +1,557 @@
1
+ /**
2
+ * yats benchmark — AI agent token comparison
3
+ * Measures token usage answering codebase questions with and without YATS.
4
+ * Uses only Node.js built-ins (zero dependencies).
5
+ */
6
+ import * as fs from "node:fs";
7
+ import * as path from "node:path";
8
+ import { spawn, execSync } from "node:child_process";
9
+ import * as readline from "node:readline";
10
+
11
+ // Simple inline logger (replaces @yats/shared dependency)
12
+ const logger = {
13
+ info: (msg) => console.error(`[benchmark] ${msg}`),
14
+ warn: (msg) => console.error(`[benchmark] ⚠ ${msg}`),
15
+ error: (msg) => console.error(`[benchmark] ❌ ${msg}`),
16
+ };
17
+
18
+ // ============================================================
19
+ // Types (JSDoc for clarity, no TypeScript needed)
20
+ // ============================================================
21
+
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
+ */
33
+
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
+ */
42
+
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
+ */
62
+
63
+ // ============================================================
64
+ // Configuration
65
+ // ============================================================
66
+
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
+ },
78
+ {
79
+ name: "lab_hub",
80
+ url: "https://github.com/fvinciarelli/lab_hub.git",
81
+ defaultPath: path.join(process.env.HOME ?? "/tmp", "repos", "lab_hub"),
82
+ 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
+ ],
87
+ },
88
+ ];
89
+
90
+ const KNOWN_AGENTS = [
91
+ {
92
+ name: "claude",
93
+ cli: "claude",
94
+ checkCmd: "which claude",
95
+ installHint: "npm install -g @anthropic-ai/claude-code",
96
+ needsApiKey: "ANTHROPIC_API_KEY",
97
+ 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
+ },
109
+ },
110
+ {
111
+ name: "codex",
112
+ cli: "codex",
113
+ checkCmd: "which codex",
114
+ installHint: "Install VS Code ChatGPT extension",
115
+ needsApiKey: "OPENAI_API_KEY",
116
+ 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
+ },
125
+ },
126
+ ];
127
+
128
+ // ============================================================
129
+ // Interactive wizard
130
+ // ============================================================
131
+
132
+ const ask = (rl, question) => new Promise((resolve) => rl.question(question, resolve));
133
+
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];
142
+ }
143
+ return KNOWN_AGENTS[idx];
144
+ }
145
+
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];
157
+ }
158
+ return KNOWN_REPOS[idx];
159
+ }
160
+
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)}...`);
165
+ });
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];
170
+ }
171
+ return repo.questions[idx];
172
+ }
173
+
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);
178
+ }
179
+
180
+ // ============================================================
181
+ // Setup
182
+ // ============================================================
183
+
184
+ function ensureRepo(repo) {
185
+ const repoPath = repo.defaultPath;
186
+ if (!fs.existsSync(repoPath)) {
187
+ console.log(`\n Cloning ${repo.name} from ${repo.url}...`);
188
+ const parent = path.dirname(repoPath);
189
+ fs.mkdirSync(parent, { recursive: true });
190
+ execSync(`git clone --depth 1 ${repo.url} ${repoPath}`, {
191
+ stdio: "inherit",
192
+ timeout: 120_000,
193
+ });
194
+ console.log(` ✓ Cloned to ${repoPath}`);
195
+ } else {
196
+ console.log(` ✓ Repo already at ${repoPath}`);
197
+ }
198
+ return repoPath;
199
+ }
200
+
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"), `---
207
+ 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"
210
+ ---
211
+
212
+ # 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
+ }
229
+ }
230
+
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
+ }));
260
+ }
261
+ }
262
+
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}`);
269
+ }
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`);
276
+ }
277
+ }
278
+
279
+ // ============================================================
280
+ // Run
281
+ // ============================================================
282
+
283
+ function runAgent(agent, prompt, repoPath, withYats, logFile, timeoutSec = 180) {
284
+ const args = agent.runCmd(prompt, repoPath, withYats);
285
+
286
+ return new Promise((resolve) => {
287
+ const proc = spawn(agent.cli, args, {
288
+ cwd: repoPath,
289
+ stdio: ["pipe", fs.openSync(logFile, "w"), "pipe"],
290
+ timeout: timeoutSec * 1000,
291
+ });
292
+
293
+ proc.on("close", (code, signal) => {
294
+ resolve({ exitCode: code ?? -1, signal });
295
+ });
296
+
297
+ proc.on("error", (err) => {
298
+ fs.appendFileSync(logFile, `\nSPAWN_ERROR: ${err.message}\n`);
299
+ resolve({ exitCode: -1, signal: null });
300
+ });
301
+ });
302
+ }
303
+
304
+ // ============================================================
305
+ // Parse results
306
+ // ============================================================
307
+
308
+ function parseResult(logFile) {
309
+ try {
310
+ 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 ?? {};
323
+
324
+ let tokens = 0;
325
+ let outputTokens = 0;
326
+ let cacheRead = 0;
327
+ 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;
334
+ }
335
+
336
+ // Tool calls
337
+ const toolCalls = {};
338
+ 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
+ }
344
+ }
345
+ }
346
+ }
347
+
348
+ const yatsQueries = Object.entries(toolCalls)
349
+ .filter(([k]) => k.includes("yats") || k.includes("mcp__"))
350
+ .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);
354
+
355
+ let contentChars = 0;
356
+ for (const e of events) {
357
+ if (e.type === "user") {
358
+ for (const c of e.message?.content ?? []) {
359
+ if (c.type === "tool_result") {
360
+ let t = c.content ?? "";
361
+ if (Array.isArray(t)) t = t.map((x) => x.text ?? "").join("");
362
+ contentChars += String(t).length;
363
+ }
364
+ }
365
+ }
366
+ }
367
+
368
+ 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,
382
+ };
383
+ } catch (err) {
384
+ return { error: err.message, logFile };
385
+ }
386
+ }
387
+
388
+ // ============================================================
389
+ // Output
390
+ // ============================================================
391
+
392
+ function printTable(title, runs, withYats) {
393
+ 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(" ├──────┼──────────┼────────┼───────┼──────┼──────┼──────┼──────────┤");
398
+ for (const r of runs) {
399
+ 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
+ );
403
+ }
404
+ const avg = (arr) => arr.length ? arr.reduce((a, b) => a + b, 0) / arr.length : 0;
405
+ const good = runs.filter((r) => !r.error);
406
+ 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
+ );
411
+ }
412
+ console.log(" └──────┴──────────┴────────┴───────┴──────┴──────┴──────┴──────────┘");
413
+ }
414
+
415
+ function printComparison(baseline, yats) {
416
+ const goodB = baseline.filter((r) => !r.error);
417
+ const goodY = yats.filter((r) => !r.error);
418
+ if (!goodB.length || !goodY.length) return;
419
+
420
+ const avg = (arr) => arr.reduce((a, b) => a + b, 0) / arr.length;
421
+ const tB = avg(goodB.map((r) => r.tokens));
422
+ const tY = avg(goodY.map((r) => r.tokens));
423
+ const cB = avg(goodB.map((r) => r.cost));
424
+ const cY = avg(goodY.map((r) => r.cost));
425
+ const rB = avg(goodB.map((r) => r.fileReads));
426
+ const rY = avg(goodY.map((r) => r.fileReads));
427
+ const bB = avg(goodB.map((r) => r.bashCmds));
428
+ const bY = avg(goodY.map((r) => r.bashCmds));
429
+
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;
434
+
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(" ╚══════════════════════════════════════════════════╝");
443
+ }
444
+
445
+ // ============================================================
446
+ // Main entry
447
+ // ============================================================
448
+
449
+ export async function runBenchmark() {
450
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
451
+
452
+ console.log("\n ╔══════════════════════════════════════════════════╗");
453
+ console.log(" ║" + " YATS BENCHMARK".padEnd(49) + "║");
454
+ console.log(" ╚══════════════════════════════════════════════════╝");
455
+
456
+ // 1. Select agent
457
+ const agent = await selectAgent(rl);
458
+ checkAgent(agent);
459
+
460
+ // 2. Select repo
461
+ const repo = await selectRepo(rl);
462
+
463
+ // 3. Ensure repo cloned
464
+ const repoPath = ensureRepo(repo);
465
+
466
+ // 4. Select question
467
+ const question = await selectQuestion(rl, repo);
468
+
469
+ // 5. Number of runs
470
+ const numRuns = await selectRuns(rl);
471
+
472
+ rl.close();
473
+
474
+ // 6. Ensure repo is indexed
475
+ console.log(`\n Checking if ${repo.name} is indexed...`);
476
+
477
+ const resultsDir = path.join(process.cwd(), "benchmark", "results");
478
+ fs.mkdirSync(resultsDir, { recursive: true });
479
+ const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
480
+
481
+ // 7. Run baseline
482
+ console.log(`\n ═══════ BASELINE (${numRuns} runs) ═══════`);
483
+ const baselineResults = [];
484
+ for (let i = 1; i <= numRuns; i++) {
485
+ console.log(`\n ▶ Run ${i}/${numRuns} — BASELINE...`);
486
+ 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);
489
+ const result = parseResult(logFile);
490
+ baselineResults.push({
491
+ run: i,
492
+ withYats: false,
493
+ tokens: result.tokens ?? 0,
494
+ cost: result.cost ?? 0,
495
+ outputTokens: result.outputTokens ?? 0,
496
+ cacheRead: result.cacheRead ?? 0,
497
+ cacheWrite: result.cacheWrite ?? 0,
498
+ 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,
507
+ });
508
+ 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
+ }
514
+ }
515
+
516
+ // 8. Run YATS
517
+ console.log(`\n ═══════ WITH YATS (${numRuns} runs) ═══════`);
518
+ const yatsResults = [];
519
+ for (let i = 1; i <= numRuns; i++) {
520
+ console.log(`\n ▶ Run ${i}/${numRuns} — YATS...`);
521
+ 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);
524
+ const result = parseResult(logFile);
525
+ yatsResults.push({
526
+ run: i,
527
+ withYats: true,
528
+ tokens: result.tokens ?? 0,
529
+ cost: result.cost ?? 0,
530
+ outputTokens: result.outputTokens ?? 0,
531
+ cacheRead: result.cacheRead ?? 0,
532
+ cacheWrite: result.cacheWrite ?? 0,
533
+ 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,
542
+ });
543
+ 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
+ }
549
+ }
550
+
551
+ // 9. Show results
552
+ printTable(repo.name, baselineResults, false);
553
+ printTable(repo.name, yatsResults, true);
554
+ printComparison(baselineResults, yatsResults);
555
+
556
+ console.log(`\n Logs saved to: ${resultsDir}\n`);
557
+ }
package/src/clear.js ADDED
@@ -0,0 +1,57 @@
1
+ /**
2
+ * yats clear <repository> — Delete indexed data via MCP
3
+ * Thin HTTP client that calls delete_repository on the YATS MCP server.
4
+ * Uses two-step confirmation flow.
5
+ */
6
+ const YATS_URL = process.env.YATS_URL || "http://localhost:5555";
7
+
8
+ async function mcpCall(tool, args = {}) {
9
+ const res = await fetch(`${YATS_URL}/mcp`, {
10
+ method: "POST",
11
+ headers: { "Content-Type": "application/json" },
12
+ body: JSON.stringify({
13
+ jsonrpc: "2.0",
14
+ id: 1,
15
+ method: "tools/call",
16
+ params: { name: tool, arguments: args },
17
+ }),
18
+ });
19
+ const data = await res.json();
20
+ return data?.result?.content?.[0]?.text;
21
+ }
22
+
23
+ export default async function clear(args) {
24
+ const repo = args[0];
25
+ if (!repo) {
26
+ console.error("Usage: yats clear <repository>");
27
+ process.exit(1);
28
+ }
29
+
30
+ try {
31
+ // Step 1: ask for confirmation
32
+ console.log(`Fetching info for "${repo}"...`);
33
+ const warning = await mcpCall("delete_repository", { repository: repo });
34
+ console.log(warning);
35
+ console.log("");
36
+
37
+ // Step 2: confirm via stdin
38
+ const readline = await import("node:readline");
39
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
40
+ const answer = await new Promise((resolve) => rl.question(" Confirm deletion? [y/N] ", resolve));
41
+ rl.close();
42
+
43
+ if (answer.toLowerCase() !== "y") {
44
+ console.log("Cancelled.");
45
+ process.exit(0);
46
+ }
47
+
48
+ // Step 3: execute
49
+ console.log("Deleting...");
50
+ const result = await mcpCall("delete_repository", { repository: repo, confirm: true });
51
+ console.log(result);
52
+ console.log("");
53
+ } catch (err) {
54
+ console.error(`Cannot reach YATS at ${YATS_URL}. Is it running?`);
55
+ process.exit(1);
56
+ }
57
+ }
package/src/indexer.js CHANGED
@@ -57,34 +57,43 @@ export default async function indexRepo(args, options = {}) {
57
57
  // Walk and send files
58
58
  console.log(`Indexing ${repoPath}...`);
59
59
  const files = await walk(repoPath);
60
- let sent = 0;
61
- let errors = 0;
62
-
60
+ // Send files concurrently in batches
61
+ const CONCURRENCY = 10;
62
+ const batch = [];
63
+
63
64
  for (const file of files) {
64
65
  const relPath = relative(repoPath, file);
65
-
66
- // Skip docs if requested
67
66
  if (skipDocs && relPath.endsWith(".md")) continue;
67
+ batch.push(file);
68
+ }
68
69
 
69
- try {
70
- const content = readFileSync(file, "utf-8");
71
- // Skip binary/large files
72
- if (content.includes("\0") || content.length > 1_000_000) continue;
70
+ let sent = 0;
71
+ let errors = 0;
72
+ const total = batch.length;
73
73
 
74
- const res = await fetch(`${YATS_URL}/index/file`, {
75
- method: "POST",
76
- headers: { "Content-Type": "application/json" },
77
- body: JSON.stringify({ repoName, filePath: relPath, content }),
78
- });
79
- if (res.ok) {
80
- sent++;
81
- process.stdout.write(`\r ${sent}/${files.length} files`);
82
- } else {
83
- errors++;
74
+ for (let i = 0; i < batch.length; i += CONCURRENCY) {
75
+ const chunk = batch.slice(i, i + CONCURRENCY);
76
+ const results = await Promise.all(chunk.map(async (file) => {
77
+ const relPath = relative(repoPath, file);
78
+ try {
79
+ const content = readFileSync(file, "utf-8");
80
+ if (content.includes("\0") || content.length > 1_000_000) return { ok: true, skipped: true };
81
+ const res = await fetch(`${YATS_URL}/index/file`, {
82
+ method: "POST",
83
+ headers: { "Content-Type": "application/json" },
84
+ body: JSON.stringify({ repoName, filePath: relPath, content }),
85
+ });
86
+ return { ok: res.ok, skipped: false };
87
+ } catch {
88
+ return { ok: false, skipped: false };
84
89
  }
85
- } catch {
86
- errors++;
90
+ }));
91
+
92
+ for (const r of results) {
93
+ if (r.ok) sent++;
94
+ else if (!r.skipped) errors++;
87
95
  }
96
+ process.stdout.write(`\r ${sent + errors}/${total} files`);
88
97
  }
89
98
  console.log(`\r ✓ ${sent} files indexed${errors > 0 ? `, ${errors} skipped` : ""}`);
90
99
  console.log(``);
package/src/list.js ADDED
@@ -0,0 +1,37 @@
1
+ /**
2
+ * yats list — List all indexed repositories via MCP
3
+ * Thin HTTP client that calls list_repositories on the YATS MCP server.
4
+ */
5
+ const YATS_URL = process.env.YATS_URL || "http://localhost:5555";
6
+
7
+ export default async function list() {
8
+ try {
9
+ const res = await fetch(`${YATS_URL}/mcp`, {
10
+ method: "POST",
11
+ headers: { "Content-Type": "application/json" },
12
+ body: JSON.stringify({
13
+ jsonrpc: "2.0",
14
+ id: 1,
15
+ method: "tools/call",
16
+ params: { name: "list_repositories", arguments: {} },
17
+ }),
18
+ });
19
+ const data = await res.json();
20
+ const text = data?.result?.content?.[0]?.text;
21
+ if (text) {
22
+ const repos = JSON.parse(text);
23
+ if (repos.length === 0) {
24
+ console.log("No indexed repositories found.");
25
+ } else {
26
+ for (const r of repos) {
27
+ console.log(` ${r.name} → ${r.rootPath}`);
28
+ }
29
+ }
30
+ } else {
31
+ console.log("No indexed repositories found.");
32
+ }
33
+ } catch (err) {
34
+ console.error(`Cannot reach YATS at ${YATS_URL}. Is it running?`);
35
+ process.exit(1);
36
+ }
37
+ }
package/src/search.js ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * yats search <query> — Search code via MCP
3
+ * Thin HTTP client that calls search_code on the YATS MCP server.
4
+ */
5
+ const YATS_URL = process.env.YATS_URL || "http://localhost:5555";
6
+
7
+ export default async function search(args) {
8
+ const repo = args.find(a => a.startsWith("--repo="))?.split("=")[1] || "";
9
+ const limit = parseInt(args.find(a => a.startsWith("--limit="))?.split("=")[1] || "10", 10);
10
+ const cleanArgs = args.filter(a => !a.startsWith("--"));
11
+ const query = cleanArgs.join(" ");
12
+
13
+ if (!query) {
14
+ console.error("Usage: yats search <query> [--repo=<name>] [--limit=<n>]");
15
+ process.exit(1);
16
+ }
17
+
18
+ try {
19
+ const res = await fetch(`${YATS_URL}/mcp`, {
20
+ method: "POST",
21
+ headers: { "Content-Type": "application/json" },
22
+ body: JSON.stringify({
23
+ jsonrpc: "2.0",
24
+ id: 1,
25
+ method: "tools/call",
26
+ params: {
27
+ name: "search_code",
28
+ arguments: { query, repository: repo || undefined, limit },
29
+ },
30
+ }),
31
+ });
32
+ const data = await res.json();
33
+ const text = data?.result?.content?.[0]?.text;
34
+ if (text) {
35
+ const results = JSON.parse(text);
36
+ if (Array.isArray(results) && results.length > 0) {
37
+ console.log(`Found ${results.length} results:\n`);
38
+ for (const r of results) {
39
+ console.log(` ${r.kind?.toUpperCase() ?? "?"} ${r.name}`);
40
+ console.log(` File: ${r.file}:${r.line}`);
41
+ console.log(` Score: ${(r.score ?? 0).toFixed(2)} (${r.source ?? "vector"})`);
42
+ if (r.reason) console.log(` Reason: ${r.reason}`);
43
+ if (r.snippet) console.log(` ${r.snippet.slice(0, 200)}`);
44
+ console.log("");
45
+ }
46
+ } else {
47
+ console.log("No results found.");
48
+ }
49
+ } else {
50
+ console.log("No results found.");
51
+ }
52
+ } catch (err) {
53
+ console.error(`Cannot reach YATS at ${YATS_URL}. Is it running?`);
54
+ process.exit(1);
55
+ }
56
+ }
package/src/summary.js ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * yats summary <repository> — Show repository summary via MCP
3
+ * Thin HTTP client that calls repository_summary on the YATS MCP server.
4
+ */
5
+ const YATS_URL = process.env.YATS_URL || "http://localhost:5555";
6
+
7
+ export default async function summary(args) {
8
+ const repo = args[0];
9
+ if (!repo) {
10
+ console.error("Usage: yats summary <repository>");
11
+ process.exit(1);
12
+ }
13
+
14
+ try {
15
+ const res = await fetch(`${YATS_URL}/mcp`, {
16
+ method: "POST",
17
+ headers: { "Content-Type": "application/json" },
18
+ body: JSON.stringify({
19
+ jsonrpc: "2.0",
20
+ id: 1,
21
+ method: "tools/call",
22
+ params: {
23
+ name: "repository_summary",
24
+ arguments: { repository: repo },
25
+ },
26
+ }),
27
+ });
28
+ const data = await res.json();
29
+ const text = data?.result?.content?.[0]?.text;
30
+ if (text) {
31
+ console.log(text);
32
+ } else {
33
+ console.log(`No summary available for "${repo}".`);
34
+ }
35
+ } catch (err) {
36
+ console.error(`Cannot reach YATS at ${YATS_URL}. Is it running?`);
37
+ process.exit(1);
38
+ }
39
+ }