yats-toolkit 0.4.2 → 0.5.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.
package/src/connect.js CHANGED
@@ -6,11 +6,18 @@
6
6
  * yats connect <agent> Show config for specific agent
7
7
  * yats connect --install Place files in current directory
8
8
  * yats connect --link Show GitHub links
9
+ *
10
+ * Install behavior (never breaks the user's files):
11
+ * - File does not exist → create it
12
+ * - JSON files → merge `mcpServers` (existing entries preserved)
13
+ * - TOML/Codex config → append only the `[mcp_servers.yats]` section
14
+ * - Text/Skill files → warn, show what will be added, ask, then append
9
15
  */
10
16
  import { writeFileSync, readFileSync, existsSync, mkdirSync } from "node:fs";
11
17
  import { join, dirname } from "node:path";
12
18
  import { createInterface } from "node:readline";
13
19
  import { homedir } from "node:os";
20
+ import { spawnSync } from "node:child_process";
14
21
 
15
22
  const B = "\x1b[1m";
16
23
  const D = "\x1b[2m";
@@ -28,8 +35,8 @@ const AGENTS = {
28
35
  name: "Claude Code",
29
36
  transport: "stdio bridge",
30
37
  files: [
31
- { src: "connect/claude/yats/SKILL.md", dest: ".claude/skills/yats/SKILL.md", type: "skill" },
32
- { src: "connect/claude/.mcp.json", dest: ".mcp.json", type: "json" },
38
+ { src: "connect/claude/SKILL.md", dest: ".claude/skills/yats/SKILL.md", type: "skill" },
39
+ { src: "connect/claude/mcp.json", dest: ".mcp.json", type: "json" },
33
40
  ],
34
41
  url: "https://github.com/fvinciarelli/yats.ai/tree/main/connect/claude",
35
42
  },
@@ -46,7 +53,7 @@ const AGENTS = {
46
53
  name: "GitHub Copilot",
47
54
  transport: "stdio bridge",
48
55
  files: [
49
- { src: "connect/copilot/instructions.md", dest: ".github/instructions.md", type: "text" },
56
+ { src: "connect/copilot/instructions.md", dest: ".github/copilot-instructions.md", type: "text" },
50
57
  { src: "connect/copilot/mcp.json", dest: ".copilot/mcp.json", type: "json" },
51
58
  ],
52
59
  url: "https://github.com/fvinciarelli/yats.ai/tree/main/connect/copilot",
@@ -79,6 +86,51 @@ function getYatsMcpConfig() {
79
86
  }
80
87
  }
81
88
 
89
+ function getFileContent(srcPath) {
90
+ // Templates ship inside the package (connect/ dir) — resolves from src/ → ../connect/
91
+ try {
92
+ const pkgDir = dirname(new URL(import.meta.url).pathname);
93
+ const installedPath = join(pkgDir, "..", srcPath);
94
+ if (existsSync(installedPath)) {
95
+ return readFileSync(installedPath, "utf-8");
96
+ }
97
+ } catch { /* not installed as npm package */ }
98
+ return null;
99
+ }
100
+
101
+ // ============================================================
102
+ // Render / template helpers
103
+ // ============================================================
104
+
105
+ function renderContent(srcPath) {
106
+ const content = getFileContent(srcPath);
107
+ if (content === null) {
108
+ console.log(` ${RED}✗${R} Missing template ${srcPath} — reinstall yats-toolkit`);
109
+ return null;
110
+ }
111
+ // YATS identifies repos by their full rootPath — instruct the full path,
112
+ // not the basename, so the server matches by path and never by name.
113
+ return content.replaceAll("__REPO_PATH__", process.cwd());
114
+ }
115
+
116
+ // Split YAML frontmatter from the body (only meaningful at the top of a file)
117
+ function splitFrontmatter(content) {
118
+ if (content.startsWith("---")) {
119
+ const end = content.indexOf("\n---", 3);
120
+ if (end !== -1) {
121
+ return {
122
+ frontmatter: content.slice(0, end + 4),
123
+ body: content.slice(end + 5),
124
+ };
125
+ }
126
+ }
127
+ return { frontmatter: "", body: content };
128
+ }
129
+
130
+ function appendMarker(agentKey) {
131
+ return `\n---\n\n<!-- Added by \`yats connect ${agentKey}\` — YATS code intelligence. Remove this block if you don't need it. -->\n\n`;
132
+ }
133
+
82
134
  // ============================================================
83
135
  // Install helpers
84
136
  // ============================================================
@@ -93,7 +145,60 @@ function safeMergeJson(existingPath, newEntry) {
93
145
  return JSON.stringify(obj, null, 2) + "\n";
94
146
  }
95
147
 
96
- async function installFiles(agentKey) {
148
+ // Single shared readline so piped stdin keeps working across multiple prompts
149
+ // Prompt helper that works both interactively (TTY) and with piped stdin
150
+ // (e.g. `printf 'y\n' | yats connect --install codex`). readline.question()
151
+ // hangs on a finished pipe stream, so piped input is collected upfront.
152
+ // Always call close() when done — an open readline keeps the process alive.
153
+ function makePrompter() {
154
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
155
+ if (process.stdin.isTTY) {
156
+ return {
157
+ ask: (question) => new Promise((resolve) => rl.question(question, resolve)),
158
+ close: () => rl.close(),
159
+ };
160
+ }
161
+ const all = (async () => {
162
+ const lines = [];
163
+ for await (const line of rl) lines.push(line);
164
+ return lines;
165
+ })();
166
+ let idx = 0;
167
+ return {
168
+ ask: async (question) => {
169
+ process.stdout.write(question);
170
+ const lines = await all;
171
+ return idx < lines.length ? lines[idx++] : "";
172
+ },
173
+ close: () => rl.close(),
174
+ };
175
+ }
176
+
177
+ function previewBlock(label, content) {
178
+ console.log(` ${D}${label}:${R}`);
179
+ for (const line of content.trimEnd().split("\n")) {
180
+ console.log(` ${D} │ ${line}${R}`);
181
+ }
182
+ console.log("");
183
+ }
184
+
185
+ function tomlHasMcpYats(content) {
186
+ return /\[mcp_servers\.yats\]/.test(content);
187
+ }
188
+
189
+ // Append the [mcp_servers.yats] section (+ multi_agent=false if [features] exists without it)
190
+ function tomlAppendYats(content) {
191
+ let out = content.trimEnd();
192
+ if (!/^\[features\]/m.test(out)) {
193
+ out += `\n\n[features]\nmulti_agent = false # REQUIRED: force direct MCP tool usage\n`;
194
+ } else if (!/^multi_agent\s*=/m.test(out)) {
195
+ out = out.replace(/^\[features\]/m, "[features]\nmulti_agent = false # REQUIRED: force direct MCP tool usage");
196
+ }
197
+ out += `\n\n# Added by \`yats connect codex\` — YATS MCP stdio bridge\n[mcp_servers.yats]\ncommand = "yats"\nargs = ["bridge"]\n`;
198
+ return out;
199
+ }
200
+
201
+ async function installFiles(agentKey, prompter) {
97
202
  const agent = AGENTS[agentKey];
98
203
  if (!agent) {
99
204
  console.error(`Unknown agent: ${agentKey}`);
@@ -101,17 +206,13 @@ async function installFiles(agentKey) {
101
206
  }
102
207
 
103
208
  console.log("");
104
- console.log(` ${Y}${B}⚠️ Before installing, back up your existing config files.${R}`);
105
- console.log(` ${D}This will modify or create files in your current directory.${R}`);
209
+ console.log(` ${Y}${B}⚠️ This will add YATS config files to your current directory.${R}`);
210
+ console.log(` ${D}Existing files are never overwritten — YATS content is merged or appended.${R}`);
106
211
  console.log("");
107
212
 
108
- const rl = createInterface({ input: process.stdin, output: process.stdout });
109
- const answer = await new Promise((resolve) => {
110
- rl.question(` ${B}Proceed with install for ${agent.name}? [y/N]${R} `, resolve);
111
- });
112
- rl.close();
113
-
114
- if (answer.toLowerCase() !== "y") {
213
+ const proceed = (await prompter.ask(` ${B}Proceed with install for ${agent.name}? [y/N]${R} `)).toLowerCase() === "y";
214
+ if (!proceed) {
215
+ prompter.close();
115
216
  console.log("");
116
217
  console.log(" Cancelled.");
117
218
  console.log("");
@@ -127,45 +228,69 @@ async function installFiles(agentKey) {
127
228
  const mcpConfig = getYatsMcpConfig();
128
229
 
129
230
  if (file.type === "json") {
130
- const merged = safeMergeJson(destPath, mcpConfig);
131
231
  const exists = existsSync(destPath);
232
+ const merged = safeMergeJson(destPath, mcpConfig);
132
233
  mkdirSync(dirname(destPath), { recursive: true });
133
234
  writeFileSync(destPath, merged);
134
235
  if (exists) {
135
236
  console.log(` ${Y}↻${R} Merged YATS into existing ${destPath}`);
237
+ const entry = mcpConfig.mcpServers.yats;
238
+ console.log(` ${D} Added: mcpServers.yats → ${JSON.stringify(entry)}${R}`);
239
+ console.log(` ${D} Your existing entries are preserved.${R}`);
136
240
  } else {
137
241
  console.log(` ${G}✓${R} Created ${destPath}`);
138
242
  }
139
243
  installed++;
140
- } else if (file.type === "text" || file.type === "skill") {
141
- if (existsSync(destPath)) {
142
- console.log(` ${Y}⚠${R} ${destPath} already exists — skipped (backup and remove to replace)`);
143
- skipped++;
244
+ } else if (file.type === "toml") {
245
+ const exists = existsSync(destPath);
246
+ mkdirSync(dirname(destPath), { recursive: true });
247
+ if (!exists) {
248
+ const content = renderContent(file.src);
249
+ if (content === null) { skipped++; continue; }
250
+ writeFileSync(destPath, content);
251
+ console.log(` ${G}✓${R} Created ${destPath}`);
252
+ installed++;
144
253
  } else {
145
- const content = getFileContent(file.src);
146
- if (content) {
147
- mkdirSync(dirname(destPath), { recursive: true });
148
- writeFileSync(destPath, content);
149
- console.log(` ${G}✓${R} Created ${destPath}`);
150
- installed++;
151
- } else {
152
- console.log(` ${RED}✗${R} Could not read ${file.src} — download from GitHub`);
254
+ const existing = readFileSync(destPath, "utf-8");
255
+ if (tomlHasMcpYats(existing)) {
256
+ console.log(` ${Y}✓${R} ${destPath} already has [mcp_servers.yats] — nothing to add.`);
153
257
  skipped++;
258
+ } else {
259
+ console.log(` ${Y}⚠${R} ${destPath} exists without YATS config.`);
260
+ const addition = tomlAppendYats(existing);
261
+ previewBlock("Will append", addition.replace(existing, "").trimStart());
262
+ if ((await prompter.ask(` ${B}Append YATS section to ${destPath}? [y/N]${R} `)).toLowerCase() === "y") {
263
+ writeFileSync(destPath, addition);
264
+ console.log(` ${G}✓${R} Appended YATS section to ${destPath}`);
265
+ installed++;
266
+ } else {
267
+ console.log(` ${Y}—${R} Skipped ${destPath}`);
268
+ skipped++;
269
+ }
154
270
  }
155
271
  }
156
- } else if (file.type === "toml") {
157
- if (existsSync(destPath)) {
158
- console.log(` ${Y}⚠${R} ${destPath} already exists — skipped (backup and remove to replace)`);
159
- skipped++;
272
+ } else { // text / skill
273
+ const destExists = existsSync(destPath);
274
+ mkdirSync(dirname(destPath), { recursive: true });
275
+ if (!destExists) {
276
+ const content = renderContent(file.src);
277
+ if (content === null) { skipped++; continue; }
278
+ writeFileSync(destPath, content);
279
+ console.log(` ${G}✓${R} Created ${destPath}`);
280
+ installed++;
160
281
  } else {
161
- const content = getFileContent(file.src);
162
- if (content) {
163
- mkdirSync(dirname(destPath), { recursive: true });
164
- writeFileSync(destPath, content);
165
- console.log(` ${G}✓${R} Created ${destPath}`);
282
+ console.log(` ${Y}⚠${R} ${destPath} already exists — your content is preserved.`);
283
+ const content = renderContent(file.src);
284
+ if (content === null) { skipped++; continue; }
285
+ // Skills have YAML frontmatter that only makes sense at the top → append the body only
286
+ const block = file.type === "skill" ? splitFrontmatter(content).body : content;
287
+ previewBlock("Will append", appendMarker(agentKey) + "\n" + block.trimStart());
288
+ if ((await prompter.ask(` ${B}Append YATS block to ${destPath}? [y/N]${R} `)).toLowerCase() === "y") {
289
+ writeFileSync(destPath, readFileSync(destPath, "utf-8").trimEnd() + "\n" + appendMarker(agentKey) + block.trimStart() + "\n");
290
+ console.log(` ${G}✓${R} Appended YATS block to ${destPath}`);
166
291
  installed++;
167
292
  } else {
168
- console.log(` ${RED}✗${R} Could not read ${file.src} — download from GitHub`);
293
+ console.log(` ${Y}—${R} Skipped ${destPath}`);
169
294
  skipped++;
170
295
  }
171
296
  }
@@ -178,16 +303,53 @@ async function installFiles(agentKey) {
178
303
  console.log("");
179
304
  }
180
305
 
181
- function getFileContent(srcPath) {
182
- // Try from node_modules first (when installed via npm)
183
- try {
184
- const pkgDir = dirname(new URL(import.meta.url).pathname);
185
- const installedPath = join(pkgDir, "..", srcPath);
186
- if (existsSync(installedPath)) {
187
- return readFileSync(installedPath, "utf-8");
188
- }
189
- } catch { /* not installed as npm package */ }
190
- return null;
306
+ // ============================================================
307
+ // Claude Code MCP activation
308
+ // ============================================================
309
+
310
+ /**
311
+ * After installing Claude config files, ask how to activate the YATS MCP
312
+ * server. Claude Code doesn't load project-scoped servers (.mcp.json)
313
+ * without explicit approval, so offer the two no-approval scopes (local /
314
+ * user) or leaving activation to the user (/mcp or session restart).
315
+ */
316
+ async function claudeMcpActivation(prompter) {
317
+ const mcpConfig = getYatsMcpConfig();
318
+ const yatsUrl = mcpConfig?.mcpServers?.yats?.url;
319
+ if (!yatsUrl) return;
320
+
321
+ console.log("");
322
+ console.log(` ${Y}${B}⚠️ Claude Code doesn't load project MCP servers without approval.${R}`);
323
+ console.log(` ${D}Activate the YATS MCP server now (local/user scopes need no approval):${R}`);
324
+ console.log("");
325
+ console.log(` ${B}1${R}. This project only (--scope local)`);
326
+ console.log(` ${B}2${R}. All your projects (--scope user)`);
327
+ console.log(` ${B}3${R}. Do nothing (activate later with /mcp or by restarting the session)`);
328
+ console.log("");
329
+ const choice = await prompter.ask(` ${B}Pick [1-3]:${R} `);
330
+
331
+ const scope = choice === "1" ? "local" : choice === "2" ? "user" : null;
332
+ if (!scope) {
333
+ console.log("");
334
+ console.log(` ${Y}—${R} Skipped. Remember: restart the Claude session and approve yats (${D}/mcp${R}) to load YATS tools.`);
335
+ return;
336
+ }
337
+
338
+ const args = ["mcp", "add", "--scope", scope, "--transport", "sse", "yats", yatsUrl];
339
+ console.log(` ${D}Running: claude ${args.join(" ")}${R}`);
340
+ console.log("");
341
+ const res = spawnSync("claude", args, { stdio: "inherit" });
342
+ if (res.error) {
343
+ console.error(` ${RED}✗${R} Could not run 'claude' (${res.error.message}).`);
344
+ } else if (res.status !== 0) {
345
+ console.error(` ${RED}✗${R} 'claude mcp add' failed (exit ${res.status}).`);
346
+ } else {
347
+ console.log(` ${G}✓${R} YATS MCP activated with scope '${scope}'. Restart the Claude session to load it.`);
348
+ }
349
+ if (res.error || res.status !== 0) {
350
+ console.error(` ${RED} Run it manually: claude mcp add --scope ${scope} --transport sse yats ${yatsUrl}${R}`);
351
+ }
352
+ console.log("");
191
353
  }
192
354
 
193
355
  // ============================================================
@@ -214,12 +376,12 @@ function showConfig(agentKey) {
214
376
  if (file.type === "json") {
215
377
  console.log(` ${D}${safeMergeJson("", mcpConfig).replace(/\n/g, "\n ")}${R}`);
216
378
  } else {
217
- const content = getFileContent(file.src);
379
+ const content = renderContent(file.src);
218
380
  if (content) {
219
381
  const preview = content.split("\n").slice(0, 8).join("\n");
220
382
  console.log(` ${D}${preview}${D}...${R}`);
221
383
  } else {
222
- console.log(` ${D}(download from GitHub)${R}`);
384
+ console.log(` ${RED}(missing template)${R}`);
223
385
  }
224
386
  }
225
387
  console.log("");
@@ -243,9 +405,9 @@ function showLink(agentKey) {
243
405
  }
244
406
 
245
407
  async function ask(question) {
246
- const rl = createInterface({ input: process.stdin, output: process.stdout });
247
- const answer = await new Promise((resolve) => rl.question(question, resolve));
248
- rl.close();
408
+ const prompter = makePrompter();
409
+ const answer = await prompter.ask(question);
410
+ prompter.close();
249
411
  return answer;
250
412
  }
251
413
 
@@ -284,7 +446,12 @@ export default async function connect(args) {
284
446
  console.error(` Agents: ${Object.keys(AGENTS).join(", ")}`);
285
447
  process.exit(1);
286
448
  }
287
- await installFiles(agentKey);
449
+ const prompter = makePrompter();
450
+ await installFiles(agentKey, prompter);
451
+ if (agentKey === "claude") {
452
+ await claudeMcpActivation(prompter);
453
+ }
454
+ prompter.close();
288
455
  return;
289
456
  }
290
457
 
package/src/indexer.js CHANGED
@@ -1,25 +1,64 @@
1
1
  /**
2
- * yats index <path> — Index a repository by sending files to YATS server.
2
+ * yats index <path> [--skip-docs] — Index a repository by sending files to YATS server.
3
3
  * Reads each file from the host and POSTs it via HTTP.
4
+ *
5
+ * --skip-docs: skip documentation files (DOC_EXTENSIONS, default .md/.mdx/.rst/
6
+ * .txt/.adoc/.org/.wiki/.readme) instead of only .md files.
4
7
  */
5
8
  import { readFileSync, statSync, readdirSync } from "node:fs";
6
- import { join, relative, basename } from "node:path";
9
+ import { join, relative } from "node:path";
10
+ import { homedir } from "node:os";
7
11
 
8
12
  const YATS_URL = process.env.YATS_URL || "http://localhost:5555";
9
13
 
10
- const IGNORED = new Set([
14
+ export const IGNORED = new Set([
11
15
  "node_modules", ".git", "dist", "build", ".next", "__pycache__",
12
16
  "vendor", "target", "bin", "obj", ".venv", "venv", ".yarn", ".pnpm",
13
17
  ]);
14
18
 
15
- async function walk(dir) {
19
+ export const DEFAULT_DOC_EXTENSIONS = ".md,.mdx,.rst,.txt,.adoc,.org,.wiki,.readme";
20
+
21
+ /**
22
+ * Read the YATS config written by `yats setup` (~/.yats/.env), so the CLI
23
+ * filters files consistently with the server (DOC_EXTENSIONS, SKIP_EXTENSIONS,
24
+ * IGNORED_DIRS). Accepts an explicit path for tests.
25
+ */
26
+ export function loadYatsEnv(envPath = null) {
27
+ const file = envPath ?? join(homedir(), ".yats", ".env");
28
+ const env = {};
29
+ try {
30
+ for (const line of readFileSync(file, "utf-8").split("\n")) {
31
+ if (!line.trim() || line.trim().startsWith("#")) continue;
32
+ const m = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/);
33
+ if (m) env[m[1]] = m[2];
34
+ }
35
+ } catch {
36
+ // No .env — use built-in defaults.
37
+ }
38
+ return env;
39
+ }
40
+
41
+ /**
42
+ * Decide whether a repository-relative path must be skipped client-side.
43
+ * Pure helper (exported for tests):
44
+ * - skipDocs: drop files whose extension is in docExtensions
45
+ * - skipExtensions: drop files ending with any of these suffixes
46
+ */
47
+ export function shouldSkipFile(relPath, { skipDocs = false, docExtensions = [], skipExtensions = [] } = {}) {
48
+ const lower = relPath.toLowerCase();
49
+ if (skipDocs && docExtensions.some((e) => lower.endsWith(e))) return true;
50
+ if (skipExtensions.some((e) => lower.endsWith(e))) return true;
51
+ return false;
52
+ }
53
+
54
+ async function walk(dir, ignored) {
16
55
  const files = [];
17
56
  const entries = readdirSync(dir, { withFileTypes: true });
18
57
  for (const e of entries) {
19
- if (IGNORED.has(e.name) || e.name.startsWith(".")) continue;
58
+ if (ignored.has(e.name) || e.name.startsWith(".")) continue;
20
59
  const full = join(dir, e.name);
21
60
  if (e.isDirectory()) {
22
- files.push(...await walk(full));
61
+ files.push(...await walk(full, ignored));
23
62
  } else if (e.isFile()) {
24
63
  files.push(full);
25
64
  }
@@ -31,17 +70,38 @@ export default async function indexRepo(args, options = {}) {
31
70
  const skipDocs = options.skipDocs || false;
32
71
  const repoPath = args[0];
33
72
  if (!repoPath) {
34
- console.error("Usage: npx yats index <path>");
73
+ console.error("Usage: npx yats index <path> [--skip-docs]");
35
74
  process.exit(1);
36
75
  }
37
76
 
38
- const repoName = basename(repoPath);
39
- const stat = statSync(repoPath);
77
+ // The repository identity is its full path (two clones of the same repo are
78
+ // two distinct indexes) — never the basename.
79
+ const repoName = repoPath;
80
+ let stat;
81
+ try {
82
+ stat = statSync(repoPath);
83
+ } catch {
84
+ console.error(`Path not found: ${repoPath}`);
85
+ process.exit(1);
86
+ }
40
87
  if (!stat.isDirectory()) {
41
88
  console.error(`Not a directory: ${repoPath}`);
42
89
  process.exit(1);
43
90
  }
44
91
 
92
+ // P4 — read the YATS config from ~/.yats/.env so the CLI filters files
93
+ // consistently with the server.
94
+ const yatsEnv = loadYatsEnv();
95
+ const ignoredDirs = new Set(IGNORED);
96
+ for (const d of (yatsEnv.IGNORED_DIRS ?? "").split(",")) {
97
+ const t = d.trim();
98
+ if (t) ignoredDirs.add(t);
99
+ }
100
+ const docExtensions = (yatsEnv.DOC_EXTENSIONS ?? DEFAULT_DOC_EXTENSIONS)
101
+ .split(",").map((e) => e.trim().toLowerCase()).filter(Boolean);
102
+ const skipExtensions = (yatsEnv.SKIP_EXTENSIONS ?? "")
103
+ .split(",").map((e) => e.trim().toLowerCase()).filter(Boolean);
104
+
45
105
  // Register repo
46
106
  try {
47
107
  await fetch(`${YATS_URL}/index`, {
@@ -56,14 +116,14 @@ export default async function indexRepo(args, options = {}) {
56
116
 
57
117
  // Walk and send files
58
118
  console.log(`Indexing ${repoPath}...`);
59
- const files = await walk(repoPath);
119
+ const files = await walk(repoPath, ignoredDirs);
60
120
  // Send files concurrently in batches
61
121
  const CONCURRENCY = 10;
62
122
  const batch = [];
63
-
123
+
64
124
  for (const file of files) {
65
125
  const relPath = relative(repoPath, file);
66
- if (skipDocs && relPath.endsWith(".md")) continue;
126
+ if (shouldSkipFile(relPath, { skipDocs, docExtensions, skipExtensions })) continue;
67
127
  batch.push(file);
68
128
  }
69
129
 
@@ -108,10 +168,55 @@ export default async function indexRepo(args, options = {}) {
108
168
  });
109
169
  const data = await res.json();
110
170
  if (res.ok) {
111
- console.log(` ✓ Graph finalized: ${data.stored} relationships (${data.rewritten} cross-file resolved)`);
171
+ console.log(` ✓ Graph finalized (${data.stored} relationships in final flush)`);
112
172
  }
113
173
  } catch {
114
174
  // Non-fatal — the server flushes on its own debounce timer.
115
175
  }
176
+
177
+ // Record the indexed commit so `yats watch` knows where to start diffing
178
+ // from (P1: the index reflects the last commit, not the last save).
179
+ try {
180
+ const { execSync } = await import("node:child_process");
181
+ const commit = execSync("git rev-parse HEAD", {
182
+ cwd: repoPath,
183
+ encoding: "utf-8",
184
+ stdio: "pipe",
185
+ }).trim();
186
+ if (commit) {
187
+ await fetch(`${YATS_URL}/index/commit`, {
188
+ method: "POST",
189
+ headers: { "Content-Type": "application/json" },
190
+ body: JSON.stringify({ repository: repoName, commit }),
191
+ });
192
+ console.log(` ✓ Indexed commit recorded: ${commit.slice(0, 8)}`);
193
+ }
194
+ } catch {
195
+ // Not a git repo (or server unreachable) — watch will handle it.
196
+ }
197
+
198
+ // Report the real totals from the graph. The server flushes incrementally
199
+ // while files stream in, so the final flush above may report 0 even though
200
+ // thousands of relationships are already stored.
201
+ try {
202
+ const res = await fetch(`${YATS_URL}/mcp`, {
203
+ method: "POST",
204
+ headers: { "Content-Type": "application/json" },
205
+ body: JSON.stringify({
206
+ jsonrpc: "2.0",
207
+ id: 1,
208
+ method: "tools/call",
209
+ params: { name: "repository_summary", arguments: { path: repoName } },
210
+ }),
211
+ });
212
+ const data = await res.json();
213
+ const text = data?.result?.content?.[0]?.text;
214
+ if (text) {
215
+ const summary = JSON.parse(text);
216
+ console.log(` ✓ Indexed ${summary.totalSymbols} symbols, ${summary.totalRelationships} relationships`);
217
+ }
218
+ } catch {
219
+ // Non-fatal — summary is informational.
220
+ }
116
221
  console.log(``);
117
222
  }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Tests — P4: CLI-side config respect (indexer.js helpers).
3
+ */
4
+
5
+ import { describe, it, before, after } from "node:test";
6
+ import assert from "node:assert/strict";
7
+ import { writeFileSync, mkdirSync, rmSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { tmpdir } from "node:os";
10
+
11
+ import { loadYatsEnv, shouldSkipFile, DEFAULT_DOC_EXTENSIONS } from "./indexer.js";
12
+
13
+ describe("loadYatsEnv", () => {
14
+ let dir;
15
+ let envPath;
16
+
17
+ before(() => {
18
+ dir = join(tmpdir(), `yats-env-test-${Date.now()}`);
19
+ mkdirSync(dir, { recursive: true });
20
+ envPath = join(dir, ".env");
21
+ writeFileSync(
22
+ envPath,
23
+ "# comment line\n" +
24
+ "DOC_EXTENSIONS=.md,.rst\n" +
25
+ "IGNORED_DIRS=node_modules,dist,vendor\n" +
26
+ "SKIP_EXTENSIONS=.min.js,.lock\n" +
27
+ "EMPTY_VALUE=\n" +
28
+ "NO_EQUALS_SIGN\n",
29
+ );
30
+ });
31
+
32
+ after(() => {
33
+ try { rmSync(dir, { recursive: true }); } catch {}
34
+ });
35
+
36
+ it("parses KEY=VALUE lines and ignores comments and malformed lines", () => {
37
+ const env = loadYatsEnv(envPath);
38
+ assert.equal(env.DOC_EXTENSIONS, ".md,.rst");
39
+ assert.equal(env.IGNORED_DIRS, "node_modules,dist,vendor");
40
+ assert.equal(env.SKIP_EXTENSIONS, ".min.js,.lock");
41
+ assert.equal(env.EMPTY_VALUE, "");
42
+ assert.equal(env.NO_EQUALS_SIGN, undefined);
43
+ });
44
+
45
+ it("returns an empty object when the file is missing", () => {
46
+ const env = loadYatsEnv(join(dir, "does-not-exist.env"));
47
+ assert.deepEqual(env, {});
48
+ });
49
+ });
50
+
51
+ describe("shouldSkipFile", () => {
52
+ const docExtensions = DEFAULT_DOC_EXTENSIONS
53
+ .split(",").map((e) => e.trim().toLowerCase()).filter(Boolean);
54
+
55
+ it("skips only .md when skipDocs is false", () => {
56
+ assert.equal(shouldSkipFile("README.md", { skipDocs: false, docExtensions }), false);
57
+ });
58
+
59
+ it("skips every DOC_EXTENSIONS file with --skip-docs, not only .md (P4)", () => {
60
+ for (const ext of docExtensions) {
61
+ assert.equal(
62
+ shouldSkipFile(`docs/guide${ext}`, { skipDocs: true, docExtensions }),
63
+ true,
64
+ `docs/guide${ext} should be skipped`,
65
+ );
66
+ }
67
+ assert.equal(
68
+ shouldSkipFile("src/code.py", { skipDocs: true, docExtensions }),
69
+ false,
70
+ "code files are never skipped by --skip-docs",
71
+ );
72
+ });
73
+
74
+ it("skips SKIP_EXTENSIONS suffixes including compound ones like .min.js", () => {
75
+ const skipExtensions = [".min.js", ".lock"];
76
+ assert.equal(shouldSkipFile("app.min.js", { skipExtensions }), true);
77
+ assert.equal(shouldSkipFile("yarn.lock", { skipExtensions }), true);
78
+ assert.equal(shouldSkipFile("app.js", { skipExtensions }), false);
79
+ });
80
+
81
+ it("is case-insensitive", () => {
82
+ assert.equal(
83
+ shouldSkipFile("README.MD", { skipDocs: true, docExtensions }),
84
+ true,
85
+ );
86
+ });
87
+ });