yats-toolkit 0.1.12 → 0.1.14

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 (39) hide show
  1. package/README.md +1 -1
  2. package/benchmark/README.md +54 -0
  3. package/benchmark/questions/csharp/Carter/01-modules.md +1 -0
  4. package/benchmark/questions/csharp/Carter/02-handlers.md +1 -0
  5. package/benchmark/questions/csharp/MediatR/01-pipeline.md +1 -0
  6. package/benchmark/questions/csharp/MediatR/02-dispatch.md +1 -0
  7. package/benchmark/questions/csharp/eShopOnWeb/01-repository.md +1 -0
  8. package/benchmark/questions/csharp/eShopOnWeb/02-architecture.md +1 -0
  9. package/benchmark/questions/go/gin/01-middleware.md +1 -0
  10. package/benchmark/questions/go/gin/02-routing.md +1 -0
  11. package/benchmark/questions/go/lab_hub/01-protocol-translation.md +1 -0
  12. package/benchmark/questions/go/lab_hub/02-bidirectional-flow.md +1 -0
  13. package/benchmark/questions/go/terraform/01-providers.md +1 -0
  14. package/benchmark/questions/go/terraform/02-graph.md +1 -0
  15. package/benchmark/questions/php/laravel/01-container.md +1 -0
  16. package/benchmark/questions/php/laravel/02-routing.md +1 -0
  17. package/benchmark/questions/php/symfony/01-dependency-injection.md +1 -0
  18. package/benchmark/questions/php/symfony/02-event-dispatcher.md +1 -0
  19. package/benchmark/questions/python/01-middleware.md +8 -0
  20. package/benchmark/questions/python/02-routing.md +9 -0
  21. package/benchmark/questions/python/django/01-middleware.md +1 -0
  22. package/benchmark/questions/python/django/01-orm.md +1 -0
  23. package/benchmark/questions/python/fastapi/01-middleware.md +1 -0
  24. package/benchmark/questions/python/fastapi/02-routing.md +1 -0
  25. package/benchmark/questions/typescript/nestjs/01-decorators.md +1 -0
  26. package/benchmark/questions/typescript/nestjs/02-modules.md +1 -0
  27. package/benchmark/questions/typescript/nextjs/01-rendering.md +1 -0
  28. package/benchmark/questions/typescript/nextjs/02-routing.md +1 -0
  29. package/benchmark/run.sh +288 -0
  30. package/benchmark/scripts/compare-codex-mcp.sh +94 -0
  31. package/benchmark/scripts/compare.py +42 -0
  32. package/benchmark/scripts/parse-copilot.sh +34 -0
  33. package/benchmark/scripts/report.py +123 -0
  34. package/benchmark/targets/repos.json +23 -0
  35. package/package.json +6 -2
  36. package/src/bridge.js +158 -75
  37. package/src/setup.js +3 -3
  38. package/src/watch.js +155 -0
  39. package/bin/setup.js +0 -80
@@ -0,0 +1,123 @@
1
+ #!/usr/bin/env python3
2
+ """Aggregate benchmark metrics from Claude stream-json output."""
3
+ import json, sys
4
+
5
+ logfile = sys.argv[1]
6
+ tag = sys.argv[2] if len(sys.argv) > 2 else "?"
7
+
8
+ with open(logfile) as f:
9
+ events = [json.loads(line.strip()) for line in f if line.strip()]
10
+
11
+ results = [e for e in events if e.get("type") == "result"]
12
+ if not results:
13
+ print("NO RESULTS"); sys.exit(1)
14
+
15
+ # ── Tokens from modelUsage (session-aggregated, includes sub-agents) ──
16
+ usage_keys = ["input_tokens", "output_tokens",
17
+ "cache_creation_input_tokens", "cache_read_input_tokens"]
18
+ totals = {k: 0 for k in usage_keys}
19
+ models_seen = set()
20
+ total_cost = 0.0
21
+ turns = sum(r.get("num_turns", 0) for r in results)
22
+ errors = []
23
+ all_denials = sum(len(r.get("permission_denials", [])) for r in results)
24
+ for r in results:
25
+ for e in (r.get("errors") or []):
26
+ errors.append(e)
27
+
28
+ # modelUsage is the canonical source — same across all results (session total)
29
+ last = results[-1]
30
+ total_cost = last.get("total_cost_usd", 0)
31
+ for m, mu in last.get("modelUsage", {}).items():
32
+ models_seen.add(m)
33
+ totals["input_tokens"] += mu.get("inputTokens", 0)
34
+ totals["output_tokens"] += mu.get("outputTokens", 0)
35
+ totals["cache_creation_input_tokens"] += mu.get("cacheCreationInputTokens", 0)
36
+ totals["cache_read_input_tokens"] += mu.get("cacheReadInputTokens", 0)
37
+
38
+ # ── Tool calls ──
39
+ tool_calls = {}
40
+ for e in events:
41
+ if e.get("type") == "assistant":
42
+ for c in e.get("message", {}).get("content", []):
43
+ if c.get("type") == "tool_use":
44
+ name = c.get("name", "?")
45
+ tool_calls[name] = tool_calls.get(name, 0) + 1
46
+
47
+ yats = sum(v for k, v in tool_calls.items() if "yats" in k or "mcp__" in k)
48
+ reads = tool_calls.get("Read", 0)
49
+ bash = tool_calls.get("Bash", 0)
50
+ agents = tool_calls.get("Agent", 0) + tool_calls.get("Task", 0)
51
+ other = sum(tool_calls.values()) - yats - reads - bash - agents
52
+
53
+ # ── Content fetched ──
54
+ content_chars = 0
55
+ for e in events:
56
+ if e.get("type") == "user":
57
+ for c in e.get("message", {}).get("content", []):
58
+ if c.get("type") == "tool_result":
59
+ text = c.get("content", "")
60
+ if isinstance(text, list):
61
+ text = "".join(str(x.get("text", "")) for x in text)
62
+ content_chars += len(text)
63
+
64
+ # ── Report ──
65
+ total_tokens = sum(totals.values())
66
+ pcts = {k: (totals[k] / total_tokens * 100) if total_tokens else 0 for k in usage_keys}
67
+
68
+ lines = [
69
+ "",
70
+ f" {'='*50}",
71
+ f" {tag:^50}",
72
+ f" {'='*50}",
73
+ "",
74
+ f" TOKENS",
75
+ f" Input: {totals['input_tokens']:>12,} ({pcts['input_tokens']:5.1f}%)",
76
+ f" Output: {totals['output_tokens']:>12,} ({pcts['output_tokens']:5.1f}%)",
77
+ f" Cache read: {totals['cache_read_input_tokens']:>12,} ({pcts['cache_read_input_tokens']:5.1f}%) ← barato (0.1x)",
78
+ f" Cache write:{totals['cache_creation_input_tokens']:>12,} ({pcts['cache_creation_input_tokens']:5.1f}%) ← caro (1.25x)",
79
+ f" ─────────────────────────────",
80
+ f" TOTAL: {total_tokens:>12,}",
81
+ "",
82
+ f" COST: ${total_cost:.4f}",
83
+ "",
84
+ f" STRATEGY",
85
+ f" Turns: {turns:>8}",
86
+ f" Agent spawns: {agents:>8}",
87
+ f" YATS queries: {yats:>8} ← barato, dirigido",
88
+ f" File reads: {reads:>8} ← caro, contenido crudo",
89
+ f" Bash commands: {bash:>8} ← exploracion a ciegas" if bash > 0 else f" Bash commands: {bash:>8}",
90
+ f" Other: {other:>8}",
91
+ f" Content fetched: {content_chars:>8,} chars",
92
+ "",
93
+ f" Models: {', '.join(sorted(models_seen))}",
94
+ f" Errors: {len(errors)}, Denials: {all_denials}",
95
+ "",
96
+ ]
97
+
98
+ for line in lines:
99
+ print(line)
100
+
101
+ # ── JSON summary ──
102
+ summary = {
103
+ "tag": tag,
104
+ "tokens": totals,
105
+ "total_tokens": total_tokens,
106
+ "cost_usd": round(total_cost, 6),
107
+ "turns": turns,
108
+ "strategy": {
109
+ "agent_spawns": agents,
110
+ "yats_queries": yats,
111
+ "file_reads": reads,
112
+ "bash_commands": bash,
113
+ "other": other,
114
+ "tool_breakdown": dict(sorted(tool_calls.items(), key=lambda x: -x[1])),
115
+ },
116
+ "content_chars": content_chars,
117
+ "models": sorted(models_seen),
118
+ "errors": len(errors),
119
+ "permission_denials": all_denials,
120
+ }
121
+ json_path = logfile.replace(".jsonl", ".summary.json")
122
+ with open(json_path, "w") as f:
123
+ json.dump(summary, f, indent=2)
@@ -0,0 +1,23 @@
1
+ {
2
+ "python": [
3
+ { "name": "fastapi", "url": "https://github.com/fastapi/fastapi", "desc": "FastAPI web framework" },
4
+ { "name": "django", "url": "https://github.com/django/django", "desc": "Django web framework" }
5
+ ],
6
+ "typescript": [
7
+ { "name": "nestjs", "url": "https://github.com/nestjs/nest", "desc": "NestJS progressive Node.js framework" },
8
+ { "name": "nextjs", "url": "https://github.com/vercel/next.js", "desc": "Next.js React framework" }
9
+ ],
10
+ "go": [
11
+ { "name": "gin", "url": "https://github.com/gin-gonic/gin", "desc": "Gin HTTP web framework" },
12
+ { "name": "terraform", "url": "https://github.com/hashicorp/terraform", "desc": "Terraform IaC tool" }
13
+ ],
14
+ "csharp": [
15
+ { "name": "MediatR", "url": "https://github.com/jbogard/MediatR", "desc": "MediatR CQRS/Mediator library" },
16
+ { "name": "eShopOnWeb", "url": "https://github.com/dotnet-architecture/eShopOnWeb", "desc": "Microsoft clean architecture reference app" },
17
+ { "name": "Carter", "url": "https://github.com/CarterCommunity/Carter", "desc": "Minimal APIs framework for ASP.NET Core" }
18
+ ],
19
+ "php": [
20
+ { "name": "laravel", "url": "https://github.com/laravel/framework", "desc": "Laravel PHP framework" },
21
+ { "name": "symfony", "url": "https://github.com/symfony/symfony", "desc": "Symfony PHP framework" }
22
+ ]
23
+ }
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "yats-toolkit",
3
- "version": "0.1.12",
3
+ "version": "0.1.14",
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",
7
7
  "repository": {
8
8
  "type": "git",
9
- "url": "git+https://github.com/fvinciarelli/yats.git"
9
+ "url": "git+https://github.com/fvinciarelli/yats.ai.git"
10
10
  },
11
11
  "keywords": [
12
12
  "mcp",
@@ -40,6 +40,10 @@
40
40
  "files": [
41
41
  "bin/",
42
42
  "src/",
43
+ "benchmark/questions/",
44
+ "benchmark/targets/",
45
+ "benchmark/scripts/",
46
+ "benchmark/run.sh",
43
47
  "README.md"
44
48
  ],
45
49
  "scripts": {
package/src/bridge.js CHANGED
@@ -1,101 +1,184 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * YATS Bridge — MCP stdio ↔ HTTP proxy
3
+ * YATS Bridge — MCP stdio ↔ YATS HTTP proxy
4
+ *
5
+ * Acts as a local MCP server over stdio that wraps YATS MCP tools.
6
+ * Used by AI agents (Copilot, Gemini, Codex, Claude) to connect to YATS.
4
7
  *
5
8
  * Usage:
6
- * npx yats-bridge # defaults to localhost:5555
7
- * npx yats-bridge --port 5555
8
- * npx yats-bridge --url http://my-server:5555
9
+ * yats bridge # default: localhost:5555
10
+ * yats bridge --port 5555
11
+ * yats bridge --url http://my-server:5555
12
+ *
13
+ * Agent configs:
14
+ * Copilot: { "type": "local", "command": "node", "args": ["bridge.cjs", "--stdio"] }
15
+ * Gemini: { "command": "node", "args": ["bridge.cjs", "--stdio"], "trust": true }
16
+ * Codex: command = "node", args = ["bridge.cjs", "--stdio"]
17
+ * Claude: { "command": "node", "args": ["bridge.cjs", "--stdio"] }
9
18
  */
10
19
 
11
- const YATS_URL = process.env.YATS_URL || "http://localhost:5555";
20
+ import http from "node:http";
21
+ import https from "node:https";
22
+ import { createInterface } from "node:readline";
23
+ import { basename } from "node:path";
24
+
25
+ // ── Config ──────────────────────────────────────────────
26
+ let yatsUrl = process.env.YATS_URL || "http://localhost:5555";
12
27
 
13
28
  // Parse CLI args
14
29
  const args = process.argv.slice(2);
15
- let baseUrl = YATS_URL;
16
30
  for (let i = 0; i < args.length; i++) {
17
- if (args[i] === "--port" && args[i + 1]) baseUrl = `http://localhost:${args[++i]}`;
18
- if (args[i] === "--url" && args[i + 1]) baseUrl = args[++i];
31
+ if (args[i] === "--port" && args[i + 1]) {
32
+ yatsUrl = `http://localhost:${args[++i]}`;
33
+ } else if (args[i] === "--url" && args[i + 1]) {
34
+ yatsUrl = args[++i];
35
+ }
19
36
  }
20
37
 
21
- let sessionId = null;
22
- let sseBuffer = "";
23
-
24
- async function getSession() {
25
- const res = await fetch(`${baseUrl}/mcp/sse`);
26
- const reader = res.body.getReader();
27
- const decoder = new TextDecoder();
28
-
29
- // Read first SSE event to get the session endpoint
30
- while (true) {
31
- const { done, value } = await reader.read();
32
- if (done) break;
33
- sseBuffer += decoder.decode(value, { stream: true });
34
-
35
- const match = sseBuffer.match(/event: endpoint\ndata: (.+)/);
36
- if (match) {
37
- const endpoint = match[1];
38
- sessionId = new URL(endpoint, baseUrl).searchParams.get("sessionId");
39
- sseBuffer = sseBuffer.slice(match.index + match[0].length);
40
- break;
41
- }
42
- }
38
+ const YATS_MCP_URL = yatsUrl.endsWith("/mcp") ? yatsUrl : yatsUrl + "/mcp";
43
39
 
44
- if (!sessionId) throw new Error("Failed to get SSE session");
40
+ // Default repo: env var > cwd basename
41
+ const DEFAULT_REPO = process.env.YATS_DEFAULT_REPO || basename(process.cwd());
45
42
 
46
- // Keep reading SSE in background — forward messages to stdout
47
- (async () => {
48
- while (true) {
49
- const { done, value } = await reader.read();
50
- if (done) break;
51
- sseBuffer += decoder.decode(value, { stream: true });
43
+ // Tools that require a repository parameter
44
+ const REPO_TOOLS = new Set([
45
+ "search_code", "find_symbol", "find_callers", "find_callees",
46
+ "find_references", "find_implementations", "find_inheritors", "find_routes",
47
+ "find_configuration", "expand_graph", "related_symbols", "list_symbols",
48
+ "repository_summary", "architecture_summary", "search_similar",
49
+ ]);
52
50
 
53
- // Extract "message" events
54
- const parts = sseBuffer.split("\n\n");
55
- sseBuffer = parts.pop() || "";
51
+ // ── Logger ───────────────────────────────────────────────
52
+ const log = (msg) => process.stderr.write(`[yats-bridge] ${msg}\n`);
56
53
 
57
- for (const part of parts) {
58
- const msgMatch = part.match(/^event: message\ndata: (.+)$/m);
59
- if (msgMatch) {
60
- process.stdout.write(msgMatch[1].trim() + "\n");
61
- }
62
- }
63
- }
64
- })();
54
+ // ── HTTP helpers ─────────────────────────────────────────
55
+ function post(url, body) {
56
+ return new Promise((resolve, reject) => {
57
+ const u = new URL(url);
58
+ const transport = u.protocol === "https:" ? https : http;
59
+ const req = transport.request({
60
+ hostname: u.hostname,
61
+ port: u.port || (u.protocol === "https:" ? 443 : 80),
62
+ path: u.pathname,
63
+ method: "POST",
64
+ headers: { "Content-Type": "application/json", "Accept": "application/json" },
65
+ }, (res) => {
66
+ let data = "";
67
+ res.on("data", (c) => data += c);
68
+ res.on("end", () => {
69
+ try { resolve(JSON.parse(data)); }
70
+ catch (e) { reject(new Error(`Parse error: ${e.message}`)); }
71
+ });
72
+ });
73
+ req.on("error", reject);
74
+ req.setTimeout(30_000, () => { req.destroy(); reject(new Error("Timeout")); });
75
+ req.write(JSON.stringify(body));
76
+ req.end();
77
+ });
65
78
  }
66
79
 
67
- async function sendRequest(jsonLine) {
68
- if (!sessionId) await getSession();
69
- if (!sessionId) return;
80
+ // ── MCP operations ───────────────────────────────────────
81
+ async function fetchTools() {
82
+ const r = await post(YATS_MCP_URL, { jsonrpc: "2.0", id: 1, method: "tools/list", params: {} });
83
+ return r.result?.tools || [];
84
+ }
70
85
 
71
- await fetch(`${baseUrl}/mcp/message?sessionId=${sessionId}`, {
72
- method: "POST",
73
- headers: { "Content-Type": "application/json" },
74
- body: jsonLine,
86
+ async function callTool(name, args) {
87
+ const r = await post(YATS_MCP_URL, {
88
+ jsonrpc: "2.0", id: Date.now(), method: "tools/call",
89
+ params: { name, arguments: args },
75
90
  });
91
+ return r.result?.content || [{ type: "text", text: JSON.stringify(r) }];
76
92
  }
77
93
 
78
- // Read JSON-RPC from stdin
79
- let stdinBuffer = "";
80
- process.stdin.setEncoding("utf-8");
81
- process.stdin.on("data", async (chunk) => {
82
- stdinBuffer += chunk;
83
- const lines = stdinBuffer.split("\n");
84
- stdinBuffer = lines.pop() || "";
85
-
86
- for (const line of lines) {
87
- const trimmed = line.trim();
88
- if (!trimmed) continue;
94
+ // ── stdio MCP server ─────────────────────────────────────
95
+ async function start() {
96
+ log(`Connecting to ${YATS_MCP_URL}...`);
97
+ const tools = await fetchTools();
98
+ log(`Fetched ${tools.length} tools — default repo: "${DEFAULT_REPO}"`);
99
+
100
+ const rl = createInterface({ input: process.stdin, terminal: false });
101
+ let pending = 0;
102
+ let stdinClosed = false;
103
+
104
+ const checkDone = () => {
105
+ if (stdinClosed && pending === 0) {
106
+ log("All done, exiting.");
107
+ process.exit(0);
108
+ }
109
+ };
110
+
111
+ rl.on("line", (line) => {
112
+ line = line.trim();
113
+ if (!line) return;
114
+ pending++;
115
+
116
+ handleLine(line).finally(() => {
117
+ pending--;
118
+ checkDone();
119
+ });
120
+ });
121
+
122
+ async function handleLine(line) {
123
+ let request;
124
+ try { request = JSON.parse(line); }
125
+ catch { return; }
126
+
127
+ const { id, method, params } = request;
128
+
89
129
  try {
90
- JSON.parse(trimmed); // validate JSON
91
- await sendRequest(trimmed);
92
- } catch {
93
- process.stderr.write(`Bridge: invalid JSON: ${trimmed.slice(0, 100)}\n`);
130
+ if (method === "initialize") {
131
+ respond({ jsonrpc: "2.0", id, result: {
132
+ protocolVersion: "2025-03-26",
133
+ capabilities: { tools: {} },
134
+ serverInfo: { name: "yats-bridge", version: "1.0.0" },
135
+ }});
136
+ } else if (method === "notifications/initialized") {
137
+ // No response needed
138
+ } else if (method === "tools/list") {
139
+ respond({ jsonrpc: "2.0", id, result: { tools } });
140
+ } else if (method === "tools/call") {
141
+ const toolName = params?.name;
142
+ const toolArgs = params?.arguments || {};
143
+
144
+ // Auto-inject repository if missing
145
+ if (REPO_TOOLS.has(toolName) && !toolArgs.repository && !toolArgs.path) {
146
+ toolArgs.repository = DEFAULT_REPO;
147
+ }
148
+
149
+ log(`call: ${toolName}(${JSON.stringify(toolArgs).slice(0, 200)})`);
150
+ const content = await callTool(toolName, toolArgs);
151
+ const text = content.map((c) => c.text || "").join("\n");
152
+
153
+ // structuredContent fixes Gemini CLI compatibility
154
+ respond({ jsonrpc: "2.0", id, result: {
155
+ content,
156
+ structuredContent: { result: text },
157
+ }});
158
+ } else if (method === "shutdown") {
159
+ respond({ jsonrpc: "2.0", id, result: {} });
160
+ stdinClosed = true;
161
+ checkDone();
162
+ } else {
163
+ respond({ jsonrpc: "2.0", id, error: { code: -32601, message: `Unknown: ${method}` } });
164
+ }
165
+ } catch (e) {
166
+ log(`error: ${e.message}`);
167
+ respond({ jsonrpc: "2.0", id, error: { code: -32603, message: e.message } });
94
168
  }
95
169
  }
96
- });
97
170
 
98
- process.stdin.on("end", () => {
99
- // Keep process alive briefly for pending SSE responses
100
- setTimeout(() => process.exit(0), 2000);
101
- });
171
+ process.stdin.on("end", () => {
172
+ stdinClosed = true;
173
+ checkDone();
174
+ });
175
+
176
+ log("Ready — waiting for MCP client on stdio");
177
+ }
178
+
179
+ function respond(obj) {
180
+ process.stdout.write(JSON.stringify(obj) + "\n");
181
+ }
182
+
183
+ // ── Main ─────────────────────────────────────────────────
184
+ start().catch((e) => { log(`FATAL: ${e.message}`); process.exit(1); });
package/src/setup.js CHANGED
@@ -31,7 +31,7 @@ const COMPOSE_FILE = join(YATS_DIR, "docker-compose.yml");
31
31
  const MCP_CONFIG_FILE = join(YATS_DIR, "mcp-config.json");
32
32
 
33
33
  const GITHUB_COMPOSE_URL =
34
- "https://raw.githubusercontent.com/fvinciarelli/yats/main/docker/docker-compose.yml";
34
+ "https://raw.githubusercontent.com/fvinciarelli/yats.ai/main/docker/docker-compose.yml";
35
35
 
36
36
  const B = "\x1b[1m";
37
37
  const D = "\x1b[2m";
@@ -81,7 +81,7 @@ const EMBEDDED_COMPOSE = `services:
81
81
  restart: unless-stopped
82
82
  __OLLAMA_PLACEHOLDER__
83
83
  yats:
84
- image: ghcr.io/fvinciarelli/yats:latest
84
+ image: ghcr.io/fvinciarelli/yats.ai:latest
85
85
  ports: ["__MCP_PORT__:__MCP_PORT__"]
86
86
  environment:
87
87
  - NEO4J_URI=bolt://neo4j:7687
@@ -588,7 +588,7 @@ async function main() {
588
588
  // Pull the YATS Docker image from GitHub Container Registry
589
589
  const sPull = spinner("Pulling YATS image from registry...");
590
590
  try {
591
- await runCmd("docker", ["pull", "ghcr.io/fvinciarelli/yats:latest"]);
591
+ await runCmd("docker", ["pull", "ghcr.io/fvinciarelli/yats.ai:latest"]);
592
592
  sPull.done(true);
593
593
  } catch {
594
594
  sPull.done(false);
package/src/watch.js ADDED
@@ -0,0 +1,155 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * yats watch — file watcher that keeps the YATS index in sync with live edits.
4
+ *
5
+ * Usage:
6
+ * yats watch <path> [--repo <name>]
7
+ *
8
+ * Zero dependencies — uses Node.js built-in fs.watch and http.
9
+ */
10
+
11
+ import { watch, statSync, readFileSync } from "node:fs";
12
+ import { resolve, basename, relative } from "node:path";
13
+ import { request } from "node:http";
14
+
15
+ // ============================================================
16
+ // Config
17
+ // ============================================================
18
+
19
+ const YATS_URL = process.env.YATS_URL ?? "http://localhost:5555";
20
+ const DEBOUNCE_MS = parseInt(process.env.YATS_WATCH_DEBOUNCE ?? "500", 10);
21
+
22
+ const repoPath = resolve(process.argv[2] ?? process.cwd());
23
+ const repoArgIdx = process.argv.indexOf("--repo");
24
+ const repoName = repoArgIdx >= 0 ? process.argv[repoArgIdx + 1] : basename(repoPath);
25
+
26
+ if (!process.argv[2]) {
27
+ console.log("Usage: yats watch <path> [--repo <name>]");
28
+ console.log("");
29
+ console.log("Watches a directory and keeps the YATS index in sync.");
30
+ console.log("When files change, it tells the YATS server to re-index them.");
31
+ console.log("");
32
+ console.log(" yats watch ~/my-project");
33
+ console.log(" yats watch ~/my-project --repo my-api");
34
+ process.exit(1);
35
+ }
36
+
37
+ // ============================================================
38
+ // HTTP helpers
39
+ // ============================================================
40
+
41
+ function post(path, body) {
42
+ return new Promise((resolve, reject) => {
43
+ const data = JSON.stringify(body);
44
+ const url = new URL(path, YATS_URL);
45
+ const req = request(
46
+ {
47
+ hostname: url.hostname,
48
+ port: url.port,
49
+ path: url.pathname,
50
+ method: "POST",
51
+ headers: {
52
+ "Content-Type": "application/json",
53
+ "Content-Length": Buffer.byteLength(data),
54
+ },
55
+ },
56
+ (res) => {
57
+ let body = "";
58
+ res.on("data", (chunk) => (body += chunk));
59
+ res.on("end", () => {
60
+ if (res.statusCode === 200) {
61
+ resolve(body);
62
+ } else {
63
+ reject(new Error(`HTTP ${res.statusCode}: ${body}`));
64
+ }
65
+ });
66
+ },
67
+ );
68
+ req.on("error", reject);
69
+ req.write(data);
70
+ req.end();
71
+ });
72
+ }
73
+
74
+ async function indexFile(filePath) {
75
+ const rel = relative(repoPath, filePath);
76
+ console.log(` ↻ Indexing: ${rel}`);
77
+ try {
78
+ const content = readFileSync(filePath, "utf-8");
79
+ await post("/index/file", { path: filePath, content, repository: repoName });
80
+ console.log(` ✓ Done: ${rel}`);
81
+ } catch (err) {
82
+ console.error(` ✗ Failed: ${rel} — ${err.message}`);
83
+ }
84
+ }
85
+
86
+ async function removeFile(filePath) {
87
+ const rel = relative(repoPath, filePath);
88
+ console.log(` ↻ Removing from index: ${rel}`);
89
+ try {
90
+ await post("/index/remove", { path: filePath, repository: repoName });
91
+ console.log(` ✓ Removed: ${rel}`);
92
+ } catch (err) {
93
+ console.error(` ✗ Failed: ${rel} — ${err.message}`);
94
+ }
95
+ }
96
+
97
+ // ============================================================
98
+ // Debounced watcher
99
+ // ============================================================
100
+
101
+ const pending = new Map();
102
+ const SKIP_PATTERNS = [
103
+ /node_modules/,
104
+ /\.git\//,
105
+ /vendor\//,
106
+ /__pycache__/,
107
+ /\.next\//,
108
+ /dist\//,
109
+ /\.yarn\//,
110
+ ];
111
+
112
+ function shouldSkip(filename) {
113
+ if (!filename || filename.startsWith(".")) return true;
114
+ return SKIP_PATTERNS.some((p) => p.test(filename));
115
+ }
116
+
117
+ console.log(`👀 Watching: ${repoPath}`);
118
+ console.log(` Repo: ${repoName}`);
119
+ console.log(` Server: ${YATS_URL}`);
120
+ console.log(` (debounce: ${DEBOUNCE_MS}ms)`);
121
+ console.log("");
122
+
123
+ watch(repoPath, { recursive: true }, (eventType, filename) => {
124
+ if (!filename || shouldSkip(filename)) return;
125
+
126
+ const fullPath = resolve(repoPath, filename);
127
+
128
+ // Debounce: group rapid changes to the same file
129
+ const existing = pending.get(fullPath);
130
+ if (existing) clearTimeout(existing);
131
+
132
+ pending.set(
133
+ fullPath,
134
+ setTimeout(async () => {
135
+ pending.delete(fullPath);
136
+
137
+ // Check if file still exists (or was deleted)
138
+ try {
139
+ statSync(fullPath);
140
+ await indexFile(fullPath);
141
+ } catch {
142
+ await removeFile(fullPath);
143
+ }
144
+ }, DEBOUNCE_MS),
145
+ );
146
+ });
147
+
148
+ // Keep the process alive
149
+ process.stdin.resume();
150
+
151
+ // Clean shutdown
152
+ process.on("SIGINT", () => {
153
+ console.log("\n👋 Stopped watching.");
154
+ process.exit(0);
155
+ });