yats-toolkit 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/setup.js CHANGED
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * Usage:
6
6
  * yats setup # One-time setup wizard
7
- * yats index <path> # Index a repository (--skip-docs: skip docs)
7
+ * yats index <path> # Index a repo (--skip-docs, --no-config)
8
8
  * yats search <query> # Search indexed code
9
9
  * yats list # List indexed repositories
10
10
  * yats summary <repo> # Show repository summary
@@ -47,8 +47,9 @@ switch (cmd) {
47
47
  case "index":
48
48
  case "add": {
49
49
  const skipDocs = args.includes("--skip-docs");
50
- const cleanArgs = args.filter(a => a !== "--skip-docs");
51
- import("../src/indexer.js").then(m => m.default(cleanArgs, { skipDocs }));
50
+ const noConfig = args.includes("--no-config");
51
+ const cleanArgs = args.filter((a) => a !== "--skip-docs" && a !== "--no-config");
52
+ import("../src/indexer.js").then(m => m.default(cleanArgs, { skipDocs, noConfig }));
52
53
  break;
53
54
  }
54
55
  case "reindex":
@@ -110,7 +111,7 @@ switch (cmd) {
110
111
  console.log(`YATS Toolkit — Code intelligence for AI agents`);
111
112
  console.log(``);
112
113
  console.log(` yats setup Setup wizard`);
113
- console.log(` yats index <path> Index a repository (--skip-docs: skip docs)`);
114
+ console.log(` yats index <path> Index a repo (--skip-docs, --no-config)`);
114
115
  console.log(` yats search <query> Search indexed code`);
115
116
  console.log(` yats list List indexed repositories`);
116
117
  console.log(` yats summary <repo> Show repository summary`);
@@ -123,7 +124,7 @@ switch (cmd) {
123
124
  console.log(` yats update-base Update Docker images`);
124
125
  console.log(` yats bridge Stdio proxy for Copilot/Claude`);
125
126
  console.log(` yats benchmark AI agent token comparison`);
126
- console.log(` yats watch <path> Sync index with git commits (--live: on save)`);
127
+ console.log(` yats watch <path> Sync index with git commits (--live, --no-config)`);
127
128
  console.log(` yats connect [agent] Show agent setup config`);
128
129
  break;
129
130
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "yats-toolkit",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
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",
@@ -49,7 +49,7 @@
49
49
  ],
50
50
  "scripts": {
51
51
  "start": "node bin/setup.js",
52
- "test": "node --test src/*.test.js"
52
+ "test": "node --test --test-concurrency=1 src/*.test.js"
53
53
  },
54
54
  "dependencies": {},
55
55
  "engines": {
package/src/indexer.js CHANGED
@@ -1,16 +1,37 @@
1
1
  /**
2
- * yats index <path> [--skip-docs] — Index a repository by sending files to YATS server.
3
- * Reads each file from the host and POSTs it via HTTP.
2
+ * yats index <path> [--skip-docs] [--no-config] — Index a repository by
3
+ * sending files to YATS server. Reads each file from the host and POSTs it
4
+ * via HTTP.
4
5
  *
5
- * --skip-docs: skip documentation files (DOC_EXTENSIONS, default .md/.mdx/.rst/
6
- * .txt/.adoc/.org/.wiki/.readme) instead of only .md files.
6
+ * --skip-docs: skip documentation files (DOC_EXTENSIONS, default .md/.mdx/
7
+ * .rst/.txt/.adoc/.org/.wiki/.readme) instead of only .md files.
8
+ * --no-config: ignore the repo's .yats/config.json and use machine defaults.
9
+ *
10
+ * Per-repo config (`.yats/config.json`, all keys optional):
11
+ *
12
+ * {
13
+ * "indexDocs": false, // skip ALL docs for this repo
14
+ * "docExtensions": [".md"], // REPLACES the machine's DOC_EXTENSIONS
15
+ * "docPatterns": ["docs/", "README.md"], // whitelist: only these doc files are sent
16
+ * "ignoredDirs": ["sandbox"], // ADDED to the machine's IGNORED_DIRS
17
+ * "skipExtensions": [".snap"] // ADDED to the machine's SKIP_EXTENSIONS
18
+ * }
7
19
  */
8
- import { readFileSync, statSync, readdirSync } from "node:fs";
20
+ import { readFileSync, statSync, readdirSync, readSync } from "node:fs";
9
21
  import { join, relative } from "node:path";
10
22
  import { homedir } from "node:os";
23
+ import { spawnSync } from "node:child_process";
11
24
 
12
25
  const YATS_URL = process.env.YATS_URL || "http://localhost:5555";
13
26
 
27
+ const CONFIG_SCHEMA_HINT = `{
28
+ "indexDocs": false,
29
+ "docExtensions": [".md"],
30
+ "docPatterns": ["docs/", "README.md"],
31
+ "ignoredDirs": ["sandbox"],
32
+ "skipExtensions": [".snap"]
33
+ }`;
34
+
14
35
  export const IGNORED = new Set([
15
36
  "node_modules", ".git", "dist", "build", ".next", "__pycache__",
16
37
  "vendor", "target", "bin", "obj", ".venv", "venv", ".yarn", ".pnpm",
@@ -43,14 +64,171 @@ export function loadYatsEnv(envPath = null) {
43
64
  * Pure helper (exported for tests):
44
65
  * - skipDocs: drop files whose extension is in docExtensions
45
66
  * - skipExtensions: drop files ending with any of these suffixes
67
+ * - docPatterns (prefix whitelist): when set, doc files are only sent if
68
+ * their path starts with one of the prefixes (code files always sent)
46
69
  */
47
- export function shouldSkipFile(relPath, { skipDocs = false, docExtensions = [], skipExtensions = [] } = {}) {
70
+ export function shouldSkipFile(
71
+ relPath,
72
+ { skipDocs = false, docExtensions = [], skipExtensions = [], docPatterns = null } = {},
73
+ ) {
48
74
  const lower = relPath.toLowerCase();
49
- if (skipDocs && docExtensions.some((e) => lower.endsWith(e))) return true;
75
+ const isDoc = docExtensions.some((e) => lower.endsWith(e));
76
+ if (isDoc) {
77
+ if (skipDocs) return true;
78
+ if (docPatterns && !docPatterns.some((p) => relPath.startsWith(p))) return true;
79
+ }
50
80
  if (skipExtensions.some((e) => lower.endsWith(e))) return true;
51
81
  return false;
52
82
  }
53
83
 
84
+ // ============================================================
85
+ // Per-repo config — .yats/config.json (P6)
86
+ // ============================================================
87
+
88
+ /** Validate a parsed repo config. Returns {ok:false,error} with a human
89
+ * (and AI-agent) readable explanation of what is wrong. */
90
+ export function validateRepoConfig(raw) {
91
+ let data;
92
+ try {
93
+ data = JSON.parse(raw);
94
+ } catch (err) {
95
+ return { ok: false, error: `not valid JSON: ${err.message}` };
96
+ }
97
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
98
+ return { ok: false, error: "must be a JSON object (not an array or a plain value)" };
99
+ }
100
+ const errors = [];
101
+ if (data.indexDocs !== undefined && typeof data.indexDocs !== "boolean") {
102
+ errors.push('"indexDocs" must be true or false');
103
+ }
104
+ for (const key of ["docExtensions", "docPatterns", "ignoredDirs", "skipExtensions"]) {
105
+ if (data[key] !== undefined && (!Array.isArray(data[key]) || !data[key].every((v) => typeof v === "string"))) {
106
+ errors.push(`"${key}" must be an array of strings`);
107
+ }
108
+ }
109
+ if (errors.length > 0) return { ok: false, error: errors.join("; ") };
110
+ return { ok: true, config: data };
111
+ }
112
+
113
+ /**
114
+ * Load and validate the repo's .yats/config.json.
115
+ * Returns { ok:true, config, path, exists } or { ok:false, error, path, exists }.
116
+ * A missing file is NOT an error — machine defaults apply.
117
+ */
118
+ export function loadRepoConfig(repoPath) {
119
+ const configPath = join(repoPath, ".yats", "config.json");
120
+ let raw;
121
+ try {
122
+ raw = readFileSync(configPath, "utf-8");
123
+ } catch {
124
+ return { ok: true, config: {}, path: configPath, exists: false };
125
+ }
126
+ const result = validateRepoConfig(raw);
127
+ return { ...result, path: configPath, exists: true };
128
+ }
129
+
130
+ /**
131
+ * Merge the machine config (~/.yats/.env) with the repo config.
132
+ * Rule: a repo can only NARROW what the machine allows — ignoredDirs and
133
+ * skipExtensions are UNIONs, docExtensions REPLACES the global list, and
134
+ * indexDocs=false can only turn docs off (never on, if the machine forbids).
135
+ */
136
+ export function mergeRepoConfig(globalEnv, repoConfig) {
137
+ const toList = (v) => v.split(",").map((e) => e.trim().toLowerCase()).filter(Boolean);
138
+
139
+ const docExtensions = Array.isArray(repoConfig.docExtensions)
140
+ ? repoConfig.docExtensions.map((e) => e.trim().toLowerCase()).filter(Boolean)
141
+ : toList(globalEnv.DOC_EXTENSIONS ?? DEFAULT_DOC_EXTENSIONS);
142
+
143
+ return {
144
+ docExtensions,
145
+ skipExtensions: [
146
+ ...toList(globalEnv.SKIP_EXTENSIONS ?? ""),
147
+ ...(Array.isArray(repoConfig.skipExtensions) ? repoConfig.skipExtensions : []),
148
+ ],
149
+ ignoredDirs: [
150
+ ...toList(globalEnv.IGNORED_DIRS ?? ""),
151
+ ...(Array.isArray(repoConfig.ignoredDirs) ? repoConfig.ignoredDirs : []),
152
+ ],
153
+ docPatterns: Array.isArray(repoConfig.docPatterns) ? repoConfig.docPatterns : null,
154
+ indexDocs: repoConfig.indexDocs !== false,
155
+ };
156
+ }
157
+
158
+ /**
159
+ * The message printed when .yats/config.json is invalid. Written for BOTH
160
+ * humans and AI agents running `yats index`: it explains what is wrong, why
161
+ * indexing stopped (a broken filter could index something huge), and the
162
+ * three ways out (fix + re-run, delete the file, or --no-config).
163
+ */
164
+ export function configErrorText(repoPath, configPath, error) {
165
+ return [
166
+ `✗ Invalid repo config: ${configPath}`,
167
+ ``,
168
+ ` ${error}`,
169
+ ``,
170
+ ` Indexing stopped before reading any file. A broken config could mean`,
171
+ ` wrong filters (e.g. indexing a huge folder that was meant to be ignored).`,
172
+ ``,
173
+ ` How to fix — pick ONE:`,
174
+ ``,
175
+ ` 1. Correct ${configPath} (valid JSON, schema below) and re-run:`,
176
+ ``,
177
+ ` yats index ${repoPath}`,
178
+ ``,
179
+ ` 2. Delete the file to fall back to the machine defaults (~/.yats/.env).`,
180
+ ``,
181
+ ` 3. Re-run with --no-config to ignore the file for this run only:`,
182
+ ``,
183
+ ` yats index ${repoPath} --no-config`,
184
+ ``,
185
+ ` Valid schema (every key is optional):`,
186
+ ``,
187
+ ...CONFIG_SCHEMA_HINT.split("\n").map((l) => ` ${l}`),
188
+ ``,
189
+ ` Semantics: ignoredDirs/skipExtensions ADD to the machine config;`,
190
+ ` docExtensions REPLACES it; docPatterns whitelists which doc files are`,
191
+ ` sent (prefix match); indexDocs=false skips all docs for this repo.`,
192
+ ].join("\n");
193
+ }
194
+
195
+ function promptYesNo(question) {
196
+ process.stdout.write(question);
197
+ try {
198
+ const buf = Buffer.alloc(16);
199
+ const n = readSync(0, buf, 0, 16);
200
+ return buf.toString("utf-8", 0, n).trim().toLowerCase() === "y";
201
+ } catch {
202
+ return false;
203
+ }
204
+ }
205
+
206
+ /**
207
+ * Resolve the repo config, stopping the run on a malformed file.
208
+ * - Non-TTY (the normal case — an AI agent runs yats): exit 1 with the
209
+ * configErrorText so the agent can fix the file and re-run.
210
+ * - TTY (a human): ask whether to open $EDITOR to fix it, re-validate and
211
+ * retry in a loop until valid or declined.
212
+ */
213
+ export function resolveRepoConfig(repoPath, noConfig = false) {
214
+ if (noConfig) return {};
215
+ for (;;) {
216
+ const res = loadRepoConfig(repoPath);
217
+ if (res.ok) return res.config;
218
+
219
+ console.error(configErrorText(repoPath, res.path, res.error));
220
+
221
+ if (!process.stdin.isTTY) process.exit(1);
222
+
223
+ const editor = process.env.EDITOR || process.env.VISUAL || "vi";
224
+ const answer = promptYesNo(`\n Open ${editor} to fix it and retry? [y/N] `);
225
+ if (!answer) process.exit(1);
226
+ spawnSync(editor, [res.path], { stdio: "inherit" });
227
+ console.log(" Re-reading the config...");
228
+ }
229
+ }
230
+
231
+
54
232
  async function walk(dir, ignored) {
55
233
  const files = [];
56
234
  const entries = readdirSync(dir, { withFileTypes: true });
@@ -67,10 +245,11 @@ async function walk(dir, ignored) {
67
245
  }
68
246
 
69
247
  export default async function indexRepo(args, options = {}) {
70
- const skipDocs = options.skipDocs || false;
248
+ const skipDocsFlag = options.skipDocs || false;
249
+ const noConfig = options.noConfig || false;
71
250
  const repoPath = args[0];
72
251
  if (!repoPath) {
73
- console.error("Usage: npx yats index <path> [--skip-docs]");
252
+ console.error("Usage: npx yats index <path> [--skip-docs] [--no-config]");
74
253
  process.exit(1);
75
254
  }
76
255
 
@@ -89,18 +268,13 @@ export default async function indexRepo(args, options = {}) {
89
268
  process.exit(1);
90
269
  }
91
270
 
92
- // P4 — read the YATS config from ~/.yats/.env so the CLI filters files
93
- // consistently with the server.
271
+ // P4/P6 — machine config (~/.yats/.env) + repo config (.yats/config.json).
272
+ // A malformed repo config STOPS the run (never index with broken filters).
94
273
  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);
274
+ const repoConfig = resolveRepoConfig(repoPath, noConfig);
275
+ const effective = mergeRepoConfig(yatsEnv, repoConfig);
276
+ const skipDocs = skipDocsFlag || effective.indexDocs === false;
277
+ const ignoredDirs = new Set([...IGNORED, ...effective.ignoredDirs]);
104
278
 
105
279
  // Register repo
106
280
  try {
@@ -123,7 +297,12 @@ export default async function indexRepo(args, options = {}) {
123
297
 
124
298
  for (const file of files) {
125
299
  const relPath = relative(repoPath, file);
126
- if (shouldSkipFile(relPath, { skipDocs, docExtensions, skipExtensions })) continue;
300
+ if (shouldSkipFile(relPath, {
301
+ skipDocs,
302
+ docExtensions: effective.docExtensions,
303
+ skipExtensions: effective.skipExtensions,
304
+ docPatterns: effective.docPatterns,
305
+ })) continue;
127
306
  batch.push(file);
128
307
  }
129
308
 
@@ -7,8 +7,21 @@ import assert from "node:assert/strict";
7
7
  import { writeFileSync, mkdirSync, rmSync } from "node:fs";
8
8
  import { join } from "node:path";
9
9
  import { tmpdir } from "node:os";
10
+ import { execFileSync } from "node:child_process";
11
+ import { fileURLToPath } from "node:url";
10
12
 
11
- import { loadYatsEnv, shouldSkipFile, DEFAULT_DOC_EXTENSIONS } from "./indexer.js";
13
+ import {
14
+ loadYatsEnv,
15
+ shouldSkipFile,
16
+ loadRepoConfig,
17
+ validateRepoConfig,
18
+ mergeRepoConfig,
19
+ configErrorText,
20
+ DEFAULT_DOC_EXTENSIONS,
21
+ } from "./indexer.js";
22
+
23
+ const __dirname = fileURLToPath(new URL(".", import.meta.url));
24
+ const SETUP_JS = join(__dirname, "..", "bin", "setup.js");
12
25
 
13
26
  describe("loadYatsEnv", () => {
14
27
  let dir;
@@ -85,3 +98,177 @@ describe("shouldSkipFile", () => {
85
98
  );
86
99
  });
87
100
  });
101
+
102
+ describe(".yats/config.json — repo config (P6)", () => {
103
+ let repo;
104
+
105
+ before(() => {
106
+ repo = join(tmpdir(), `yats-repo-config-test-${Date.now()}`);
107
+ mkdirSync(join(repo, ".yats"), { recursive: true });
108
+ });
109
+
110
+ after(() => {
111
+ try { rmSync(repo, { recursive: true }); } catch {}
112
+ });
113
+
114
+ function writeConfig(content) {
115
+ writeFileSync(join(repo, ".yats", "config.json"), content);
116
+ }
117
+
118
+ it("returns defaults when the file does not exist", () => {
119
+ const res = loadRepoConfig(repo);
120
+ assert.equal(res.ok, true);
121
+ assert.equal(res.exists, false);
122
+ assert.deepEqual(res.config, {});
123
+ });
124
+
125
+ it("loads a valid config", () => {
126
+ writeConfig(JSON.stringify({
127
+ indexDocs: false,
128
+ docExtensions: [".md"],
129
+ docPatterns: ["docs/", "README.md"],
130
+ ignoredDirs: ["sandbox"],
131
+ skipExtensions: [".snap"],
132
+ }));
133
+ const res = loadRepoConfig(repo);
134
+ assert.equal(res.ok, true);
135
+ assert.equal(res.exists, true);
136
+ assert.equal(res.config.indexDocs, false);
137
+ assert.deepEqual(res.config.docPatterns, ["docs/", "README.md"]);
138
+ });
139
+
140
+ it("rejects malformed JSON with a clear error", () => {
141
+ writeConfig("{ not json");
142
+ const res = loadRepoConfig(repo);
143
+ assert.equal(res.ok, false);
144
+ assert.ok(res.error.includes("not valid JSON"), `error should mention JSON: ${res.error}`);
145
+ });
146
+
147
+ it("rejects wrong types with a clear error", () => {
148
+ writeConfig(JSON.stringify({ indexDocs: "no", ignoredDirs: "sandbox", docPatterns: [1] }));
149
+ const res = loadRepoConfig(repo);
150
+ assert.equal(res.ok, false);
151
+ assert.ok(res.error.includes("indexDocs"), `error should mention indexDocs: ${res.error}`);
152
+ assert.ok(res.error.includes("ignoredDirs"), `error should mention ignoredDirs: ${res.error}`);
153
+ assert.ok(res.error.includes("docPatterns"), `error should mention docPatterns: ${res.error}`);
154
+ });
155
+
156
+ it("rejects non-object roots", () => {
157
+ writeConfig("[1,2,3]");
158
+ const res = validateRepoConfig("[1,2,3]");
159
+ assert.equal(res.ok, false);
160
+ assert.ok(res.error.includes("object"));
161
+ });
162
+
163
+ it("configErrorText tells the AI client how to fix and retry", () => {
164
+ const text = configErrorText("/repo", "/repo/.yats/config.json", "not valid JSON: Unexpected token");
165
+ assert.ok(text.includes("Invalid repo config"), "names the problem");
166
+ assert.ok(text.includes("not valid JSON"), "includes the specific error");
167
+ assert.ok(text.includes("yats index /repo"), "gives the exact re-run command");
168
+ assert.ok(text.includes("--no-config"), "offers the bypass flag");
169
+ assert.ok(text.includes("Delete the file"), "offers falling back to defaults");
170
+ assert.ok(text.includes('"docPatterns"'), "shows the schema");
171
+ });
172
+ });
173
+
174
+ describe("mergeRepoConfig — machine vs repo (P6)", () => {
175
+ const globalEnv = {
176
+ DOC_EXTENSIONS: ".md,.rst",
177
+ SKIP_EXTENSIONS: ".lock,.min.js",
178
+ IGNORED_DIRS: "vendor,dist",
179
+ };
180
+
181
+ it("unions ignoredDirs and skipExtensions", () => {
182
+ const m = mergeRepoConfig(globalEnv, {
183
+ ignoredDirs: ["sandbox"],
184
+ skipExtensions: [".snap"],
185
+ });
186
+ assert.deepEqual(m.ignoredDirs, ["vendor", "dist", "sandbox"]);
187
+ assert.deepEqual(m.skipExtensions, [".lock", ".min.js", ".snap"]);
188
+ });
189
+
190
+ it("replaces docExtensions when the repo sets them (even empty)", () => {
191
+ const replaced = mergeRepoConfig(globalEnv, { docExtensions: [".mdx"] });
192
+ assert.deepEqual(replaced.docExtensions, [".mdx"]);
193
+
194
+ const emptied = mergeRepoConfig(globalEnv, { docExtensions: [] });
195
+ assert.deepEqual(emptied.docExtensions, [], "empty array disables docs for the repo");
196
+ });
197
+
198
+ it("keeps global docExtensions when the repo does not set them", () => {
199
+ const m = mergeRepoConfig(globalEnv, {});
200
+ assert.deepEqual(m.docExtensions, [".md", ".rst"]);
201
+ assert.equal(m.docPatterns, null);
202
+ assert.equal(m.indexDocs, true);
203
+ });
204
+
205
+ it("repo indexDocs:false turns docs off", () => {
206
+ const m = mergeRepoConfig(globalEnv, { indexDocs: false });
207
+ assert.equal(m.indexDocs, false);
208
+ });
209
+ });
210
+
211
+ describe("shouldSkipFile — docPatterns whitelist (P6)", () => {
212
+ const docExtensions = [".md"];
213
+
214
+ it("only sends doc files matching a pattern (code files always sent)", () => {
215
+ const opts = { docExtensions, docPatterns: ["docs/", "README.md"] };
216
+ assert.equal(shouldSkipFile("docs/guide.md", opts), false, "docs/ matches");
217
+ assert.equal(shouldSkipFile("README.md", opts), false, "README.md matches");
218
+ assert.equal(shouldSkipFile("notes.md", opts), true, "notes.md is outside the whitelist");
219
+ assert.equal(shouldSkipFile("src/main.ts", opts), false, "code is never filtered by docPatterns");
220
+ });
221
+
222
+ it("without patterns every doc file is sent", () => {
223
+ assert.equal(shouldSkipFile("notes.md", { docExtensions, docPatterns: null }), false);
224
+ });
225
+ });
226
+
227
+ describe("indexRepo — malformed config stops the run (P6)", () => {
228
+ let repo;
229
+
230
+ before(() => {
231
+ repo = join(tmpdir(), `yats-broken-config-test-${Date.now()}`);
232
+ mkdirSync(join(repo, ".yats"), { recursive: true });
233
+ });
234
+
235
+ after(() => {
236
+ try { rmSync(repo, { recursive: true }); } catch {}
237
+ });
238
+
239
+ it("exits 1 with fix instructions before indexing anything", () => {
240
+ writeFileSync(join(repo, ".yats", "config.json"), "{ broken json");
241
+ try {
242
+ execFileSync(process.execPath, [SETUP_JS, "index", repo], {
243
+ encoding: "utf-8",
244
+ stdio: "pipe",
245
+ });
246
+ assert.fail("should have exited non-zero");
247
+ } catch (err) {
248
+ assert.equal(err.status, 1);
249
+ const out = `${err.stdout ?? ""}\n${err.stderr ?? ""}`;
250
+ assert.ok(out.includes("Invalid repo config"), out);
251
+ assert.ok(out.includes("yats index"), out);
252
+ assert.ok(out.includes("--no-config"), out);
253
+ // It must NOT even try to reach the server — config is checked first.
254
+ assert.ok(!out.includes("Cannot reach YATS"), out);
255
+ }
256
+ });
257
+
258
+ it("a valid config proceeds (fails later on the unreachable server)", () => {
259
+ writeFileSync(join(repo, ".yats", "config.json"), JSON.stringify({ indexDocs: false }));
260
+ try {
261
+ execFileSync(process.execPath, [SETUP_JS, "index", repo], {
262
+ encoding: "utf-8",
263
+ stdio: "pipe",
264
+ env: { ...process.env, YATS_URL: "http://127.0.0.1:1" },
265
+ });
266
+ assert.fail("should have exited non-zero");
267
+ } catch (err) {
268
+ assert.equal(err.status, 1);
269
+ const out = `${err.stdout ?? ""}\n${err.stderr ?? ""}`;
270
+ assert.ok(!out.includes("Invalid repo config"), out);
271
+ assert.ok(out.includes("Cannot reach YATS"), out);
272
+ }
273
+ });
274
+ });
package/src/setup.js CHANGED
@@ -133,9 +133,9 @@ const EMBEDDED_COMPOSE = `services:
133
133
  - VOYAGE_MODEL=\${EMBEDDING_VOYAGE_MODEL:-voyage-code-2}
134
134
  - REPOSITORIES_PATH=/repos
135
135
  - YATS_PORT=__MCP_PORT__
136
- - EMBEDDING_BATCH_SIZE=__BATCH_SIZE__
137
- - INDEX_DOCS=__INDEX_DOCS__
138
- - DOC_MAX_FILES=__DOC_MAX__
136
+ - EMBEDDING_BATCH_SIZE=\${EMBEDDING_BATCH_SIZE:-__BATCH_SIZE__}
137
+ - INDEX_DOCS=\${INDEX_DOCS:-__INDEX_DOCS__}
138
+ - DOC_MAX_FILES=\${DOC_MAX_FILES:-__DOC_MAX__}
139
139
  - DOC_EXTENSIONS=\${DOC_EXTENSIONS:-__DOC_EXTENSIONS__}
140
140
  - SKIP_EXTENSIONS=\${SKIP_EXTENSIONS:-__SKIP_EXTENSIONS__}
141
141
  - IGNORED_DIRS=\${IGNORED_DIRS:-__IGNORED_DIRS__}
package/src/watch.js CHANGED
@@ -27,7 +27,13 @@
27
27
  import { watch as fsWatch, statSync, readFileSync } from "node:fs";
28
28
  import { resolve, relative } from "node:path";
29
29
  import { execSync } from "node:child_process";
30
- import indexRepo, { IGNORED } from "./indexer.js";
30
+ import indexRepo, {
31
+ IGNORED,
32
+ loadYatsEnv,
33
+ mergeRepoConfig,
34
+ resolveRepoConfig,
35
+ shouldSkipFile,
36
+ } from "./indexer.js";
31
37
 
32
38
  // ============================================================
33
39
  // Config
@@ -132,14 +138,31 @@ async function getRecordedCommit(baseUrl, repoName) {
132
138
  }
133
139
  }
134
140
 
135
- function shouldSkipPath(relPath) {
141
+ function shouldSkipPath(relPath, extraIgnoredDirs = []) {
136
142
  if (!relPath || relPath.startsWith(".")) return true;
137
143
  const segments = relPath.split("/");
138
- return segments.some((seg) => IGNORED.has(seg)) || SKIP_PATTERNS.some((p) => p.test(relPath));
144
+ return (
145
+ segments.some((seg) => IGNORED.has(seg) || extraIgnoredDirs.includes(seg)) ||
146
+ SKIP_PATTERNS.some((p) => p.test(relPath))
147
+ );
139
148
  }
140
149
 
141
- async function indexFile(baseUrl, repoPath, repoName, relPath) {
142
- if (shouldSkipPath(relPath)) return;
150
+ /**
151
+ * Build the per-file filter from the effective config (machine + repo).
152
+ * Doc/code filtering is delegated to indexer.shouldSkipFile (P4/P6) so
153
+ * `yats watch` and `yats index` behave identically.
154
+ */
155
+ function makeFileFilter(effective) {
156
+ return (relPath) =>
157
+ shouldSkipPath(relPath, effective.ignoredDirs ?? []) ||
158
+ shouldSkipFile(relPath, {
159
+ ...effective,
160
+ skipDocs: effective.indexDocs === false,
161
+ });
162
+ }
163
+
164
+ async function indexFile(baseUrl, repoPath, repoName, relPath, skipFn) {
165
+ if (skipFn(relPath)) return;
143
166
  const fullPath = resolve(repoPath, relPath);
144
167
  let content;
145
168
  try {
@@ -163,8 +186,8 @@ async function indexFile(baseUrl, repoPath, repoName, relPath) {
163
186
  }
164
187
  }
165
188
 
166
- async function removeFile(baseUrl, repoName, relPath) {
167
- if (shouldSkipPath(relPath)) return;
189
+ async function removeFile(baseUrl, repoName, relPath, skipFn) {
190
+ if (skipFn(relPath)) return;
168
191
  console.log(` ↻ Removing from index: ${relPath}`);
169
192
  try {
170
193
  const res = await post(baseUrl, "/index/remove", {
@@ -184,9 +207,9 @@ async function removeFile(baseUrl, repoName, relPath) {
184
207
 
185
208
  /**
186
209
  * Bring the index from `from` to `to` by streaming only the changed files.
187
- * Exported for tests (baseUrl is injectable).
210
+ * Exported for tests (baseUrl and the effective config are injectable).
188
211
  */
189
- export async function applyDiff(repoPath, repoName, from, to, baseUrl = DEFAULT_URL) {
212
+ export async function applyDiff(repoPath, repoName, from, to, baseUrl = DEFAULT_URL, effective = {}) {
190
213
  let output;
191
214
  try {
192
215
  output = git(repoPath, `diff --name-status ${from}..${to}`);
@@ -198,6 +221,7 @@ export async function applyDiff(repoPath, repoName, from, to, baseUrl = DEFAULT_
198
221
  return;
199
222
  }
200
223
 
224
+ const skipFn = makeFileFilter(effective);
201
225
  const changes = parseNameStatus(output);
202
226
  const total =
203
227
  changes.added.length + changes.modified.length +
@@ -208,13 +232,13 @@ export async function applyDiff(repoPath, repoName, from, to, baseUrl = DEFAULT_
208
232
  `⟲${changes.renamed.length}`,
209
233
  );
210
234
 
211
- for (const p of changes.deleted) await removeFile(baseUrl, repoName, p);
212
- for (const r of changes.renamed) await removeFile(baseUrl, repoName, r.from);
235
+ for (const p of changes.deleted) await removeFile(baseUrl, repoName, p, skipFn);
236
+ for (const r of changes.renamed) await removeFile(baseUrl, repoName, r.from, skipFn);
213
237
  for (const p of [...changes.added, ...changes.modified]) {
214
- await indexFile(baseUrl, repoPath, repoName, p);
238
+ await indexFile(baseUrl, repoPath, repoName, p, skipFn);
215
239
  }
216
240
  for (const r of changes.renamed) {
217
- await indexFile(baseUrl, repoPath, repoName, r.to);
241
+ await indexFile(baseUrl, repoPath, repoName, r.to, skipFn);
218
242
  }
219
243
 
220
244
  // Flush cross-file relationships and record the new commit. Both are
@@ -237,8 +261,9 @@ export async function applyDiff(repoPath, repoName, from, to, baseUrl = DEFAULT_
237
261
  // Live mode — save-based indexing (fs.watch + debounce)
238
262
  // ============================================================
239
263
 
240
- function startLiveWatch(repoPath, repoName, baseUrl) {
264
+ function startLiveWatch(repoPath, repoName, baseUrl, effective) {
241
265
  const pending = new Map();
266
+ const skipFn = makeFileFilter(effective);
242
267
 
243
268
  fsWatch(repoPath, { recursive: true }, (_eventType, filename) => {
244
269
  if (!filename || SKIP_PATTERNS.some((p) => p.test(filename))) return;
@@ -257,9 +282,9 @@ function startLiveWatch(repoPath, repoName, baseUrl) {
257
282
  pending.delete(fullPath);
258
283
  try {
259
284
  statSync(fullPath);
260
- await indexFile(baseUrl, repoPath, repoName, relPath);
285
+ await indexFile(baseUrl, repoPath, repoName, relPath, skipFn);
261
286
  } catch {
262
- await removeFile(baseUrl, repoName, relPath);
287
+ await removeFile(baseUrl, repoName, relPath, skipFn);
263
288
  }
264
289
  }, DEBOUNCE_MS),
265
290
  );
@@ -274,19 +299,21 @@ function startLiveWatch(repoPath, repoName, baseUrl) {
274
299
 
275
300
  export default async function watchRepo(args = []) {
276
301
  const live = args.includes("--live");
302
+ const noConfig = args.includes("--no-config");
277
303
  const baseUrl = process.env.YATS_URL ?? DEFAULT_URL;
278
- const cleanArgs = args.filter((a) => a !== "--live" && a !== "--repo");
304
+ const cleanArgs = args.filter((a) => a !== "--live" && a !== "--repo" && a !== "--no-config");
279
305
 
280
306
  const repoPath = resolve(cleanArgs[0] ?? process.cwd());
281
307
 
282
308
  if (!cleanArgs[0] || cleanArgs[0] === "--help" || cleanArgs[0] === "-h") {
283
- console.log("Usage: yats watch <path> [--live]");
309
+ console.log("Usage: yats watch <path> [--live] [--no-config]");
284
310
  console.log("");
285
311
  console.log("Keeps the YATS index in sync with the repository's commits.");
286
312
  console.log("Saving files without committing does NOT touch the index —");
287
313
  console.log("the graph always reflects the last commit.");
288
314
  console.log("");
289
- console.log(" --live also re-index on every file save (uncommitted code)");
315
+ console.log(" --live also re-index on every file save (uncommitted code)");
316
+ console.log(" --no-config ignore the repo's .yats/config.json");
290
317
  console.log("");
291
318
  console.log(" yats watch ~/my-project");
292
319
  console.log(" yats watch ~/my-project --live");
@@ -303,6 +330,11 @@ export default async function watchRepo(args = []) {
303
330
  process.exit(1);
304
331
  }
305
332
 
333
+ // P6 — same config resolution as `yats index`: a malformed
334
+ // .yats/config.json stops the run instead of watching with wrong filters.
335
+ const repoConfig = resolveRepoConfig(repoPath, noConfig);
336
+ const effective = mergeRepoConfig(loadYatsEnv(), repoConfig);
337
+
306
338
  console.log(`👀 Watching: ${repoPath}`);
307
339
  console.log(` Repo: ${repoName}`);
308
340
  console.log(` Server: ${baseUrl}`);
@@ -318,7 +350,7 @@ export default async function watchRepo(args = []) {
318
350
  } catch {
319
351
  /* non-fatal */
320
352
  }
321
- startLiveWatch(repoPath, repoName, baseUrl);
353
+ startLiveWatch(repoPath, repoName, baseUrl, effective);
322
354
  }
323
355
 
324
356
  if (!gitOk) {
@@ -358,7 +390,7 @@ export default async function watchRepo(args = []) {
358
390
  console.log(
359
391
  ` Indexed commit ${recorded.slice(0, 8)} ≠ HEAD ${head.slice(0, 8)} — syncing...`,
360
392
  );
361
- await applyDiff(repoPath, repoName, recorded, head, baseUrl);
393
+ await applyDiff(repoPath, repoName, recorded, head, baseUrl, effective);
362
394
  recorded = head;
363
395
  }
364
396
 
@@ -375,7 +407,7 @@ export default async function watchRepo(args = []) {
375
407
 
376
408
  console.log(`\n ⬆ HEAD moved ${recorded ? recorded.slice(0, 8) + " → " : ""}${head.slice(0, 8)}`);
377
409
  if (recorded) {
378
- await applyDiff(repoPath, repoName, recorded, head, baseUrl);
410
+ await applyDiff(repoPath, repoName, recorded, head, baseUrl, effective);
379
411
  } else {
380
412
  // First commit after an unborn HEAD — nothing to diff from: full index.
381
413
  await indexRepo([repoPath]);
package/src/watch.test.js CHANGED
@@ -15,6 +15,7 @@ import { execSync } from "node:child_process";
15
15
  import { tmpdir } from "node:os";
16
16
 
17
17
  import { parseNameStatus, applyDiff } from "./watch.js";
18
+ import { mergeRepoConfig } from "./indexer.js";
18
19
 
19
20
  function git(cwd, cmd) {
20
21
  return execSync(`git ${cmd}`, { cwd, encoding: "utf-8", stdio: "pipe" }).trim();
@@ -150,4 +151,47 @@ describe("applyDiff — commit-based sync (P1)", () => {
150
151
  // The commit is still recorded (idempotent sync)
151
152
  assert.equal(requests.filter((r) => r.url === "/index/commit").length, 1);
152
153
  });
154
+
155
+ it("applies the repo config: docs skipped when indexDocs=false (P6)", async () => {
156
+ // New commit adding a doc file and a code file
157
+ writeFileSync(join(workDir, "guide.md"), "# Guide\n");
158
+ writeFileSync(join(workDir, "extra.txt"), "plain text\n");
159
+ git(workDir, "add -A");
160
+ git(workDir, "commit -m 'v3: add docs + code'");
161
+ const v3 = git(workDir, "rev-parse HEAD");
162
+
163
+ requests = [];
164
+ const effective = mergeRepoConfig({}, { indexDocs: false, docExtensions: [".md"] });
165
+ await applyDiff(workDir, repoName, v2, v3, baseUrl, effective);
166
+
167
+ const sentPaths = requests
168
+ .filter((r) => r.url === "/index/file")
169
+ .map((r) => r.body.filePath)
170
+ .sort();
171
+ assert.deepEqual(
172
+ sentPaths,
173
+ ["extra.txt"],
174
+ "doc files (.md) are skipped, code/plain files are sent",
175
+ );
176
+ });
177
+
178
+ it("applies docPatterns: only whitelisted docs are sent (P6)", async () => {
179
+ const v3 = git(workDir, "rev-parse HEAD");
180
+ mkdirSync(join(workDir, "docs"), { recursive: true });
181
+ writeFileSync(join(workDir, "docs", "api.md"), "# API\n");
182
+ writeFileSync(join(workDir, "notes.md"), "# Notes\n");
183
+ git(workDir, "add -A");
184
+ git(workDir, "commit -m 'v4: more docs'");
185
+ const v4 = git(workDir, "rev-parse HEAD");
186
+
187
+ requests = [];
188
+ const effective = mergeRepoConfig({}, { docExtensions: [".md"], docPatterns: ["docs/"] });
189
+ await applyDiff(workDir, repoName, v3, v4, baseUrl, effective);
190
+
191
+ const sentPaths = requests
192
+ .filter((r) => r.url === "/index/file")
193
+ .map((r) => r.body.filePath)
194
+ .sort();
195
+ assert.deepEqual(sentPaths, ["docs/api.md"], "only docs matching the whitelist are sent");
196
+ });
153
197
  });