yats-toolkit 0.4.2 → 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/src/watch.js CHANGED
@@ -1,134 +1,278 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * yats watch — file watcher that keeps the YATS index in sync with live edits.
3
+ * yats watch <path> [--live] — keeps the YATS index in sync with the
4
+ * repository's *commits*, not the working tree (P1).
4
5
  *
5
6
  * Usage:
6
- * yats watch <path> [--repo <name>]
7
+ * yats watch <path> # commit-based (default)
8
+ * yats watch <path> --live # also index on every file save
7
9
  *
8
- * Zero dependencies — uses Node.js built-in fs.watch and http.
10
+ * Commit-based mode:
11
+ * - Polls `git rev-parse HEAD` every YATS_WATCH_POLL_MS (default 2000ms).
12
+ * - When HEAD changes (new commit OR branch checkout), diffs
13
+ * <lastIndexedCommit>..HEAD and streams only the changed files.
14
+ * - Saving files WITHOUT committing does NOT touch the index — the graph
15
+ * always reflects the last commit.
16
+ * - On startup, if the repo has no recorded indexed commit, it runs a full
17
+ * `yats index` first so it never starts from a half-indexed state.
18
+ *
19
+ * --live mode restores save-based indexing (fs.watch + debounce) on top of
20
+ * the commit loop, for agents working on uncommitted code. Without a git
21
+ * repository, --live is the only mode available.
22
+ *
23
+ * Zero dependencies — Node built-ins only. git runs on the host (the server
24
+ * may live in a container without git).
25
+ */
26
+
27
+ import { watch as fsWatch, statSync, readFileSync } from "node:fs";
28
+ import { resolve, relative } from "node:path";
29
+ import { execSync } from "node:child_process";
30
+ import indexRepo, {
31
+ IGNORED,
32
+ loadYatsEnv,
33
+ mergeRepoConfig,
34
+ resolveRepoConfig,
35
+ shouldSkipFile,
36
+ } from "./indexer.js";
37
+
38
+ // ============================================================
39
+ // Config
40
+ // ============================================================
41
+
42
+ const DEFAULT_URL = "http://localhost:5555";
43
+ const POLL_MS = parseInt(process.env.YATS_WATCH_POLL_MS ?? "2000", 10);
44
+ const DEBOUNCE_MS = parseInt(process.env.YATS_WATCH_DEBOUNCE_MS ?? "500", 10);
45
+ const SKIP_PATTERNS = [
46
+ /node_modules/,
47
+ /\.git\//,
48
+ /vendor\//,
49
+ /__pycache__/,
50
+ /\.next\//,
51
+ /dist\//,
52
+ /\.yarn\//,
53
+ ];
54
+
55
+ // ============================================================
56
+ // git helpers (host side — the server container has no git)
57
+ // ============================================================
58
+
59
+ function git(cwd, cmd) {
60
+ return execSync(`git ${cmd}`, { cwd, encoding: "utf-8", stdio: "pipe" }).trim();
61
+ }
62
+
63
+ function isGitRepo(repoPath) {
64
+ try {
65
+ git(repoPath, "rev-parse --git-dir");
66
+ return true;
67
+ } catch {
68
+ return false;
69
+ }
70
+ }
71
+
72
+ /** Current HEAD, or null for an unborn branch (no commits yet). */
73
+ function headCommit(repoPath) {
74
+ try {
75
+ return git(repoPath, "rev-parse HEAD");
76
+ } catch {
77
+ return null;
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Parse `git diff --name-status` output.
83
+ * Handles the rename format (`R100\told\tnew`) and quoted paths.
9
84
  */
85
+ export function parseNameStatus(output) {
86
+ const changes = { added: [], modified: [], deleted: [], renamed: [] };
10
87
 
11
- import { watch, statSync, readFileSync } from "node:fs";
12
- import { resolve, basename, relative } from "node:path";
13
- import { request } from "node:http";
88
+ for (const rawLine of output.split("\n")) {
89
+ const line = rawLine.trim();
90
+ if (!line) continue;
91
+ const [status, ...rest] = line.split("\t");
92
+ if (!status) continue;
93
+
94
+ const unquote = (p) =>
95
+ p && p.startsWith('"') && p.endsWith('"') ? p.slice(1, -1) : p;
96
+
97
+ if (status.startsWith("R") && rest.length >= 2) {
98
+ changes.renamed.push({ from: unquote(rest[0]), to: unquote(rest[1]) });
99
+ } else if (status.startsWith("A")) {
100
+ changes.added.push(unquote(rest[0]));
101
+ } else if (status.startsWith("M")) {
102
+ changes.modified.push(unquote(rest[0]));
103
+ } else if (status.startsWith("D")) {
104
+ changes.deleted.push(unquote(rest[0]));
105
+ }
106
+ }
107
+
108
+ return changes;
109
+ }
14
110
 
15
111
  // ============================================================
16
112
  // HTTP helpers
17
113
  // ============================================================
18
114
 
19
115
  function post(baseUrl, path, body) {
20
- return new Promise((resolve, reject) => {
21
- const data = JSON.stringify(body);
22
- const url = new URL(path, baseUrl);
23
- const req = request(
24
- {
25
- hostname: url.hostname,
26
- port: url.port,
27
- path: url.pathname,
28
- method: "POST",
29
- headers: {
30
- "Content-Type": "application/json",
31
- "Content-Length": Buffer.byteLength(data),
32
- },
33
- },
34
- (res) => {
35
- let body = "";
36
- res.on("data", (chunk) => (body += chunk));
37
- res.on("end", () => {
38
- if (res.statusCode === 200) {
39
- resolve(body);
40
- } else {
41
- reject(new Error(`HTTP ${res.statusCode}: ${body}`));
42
- }
43
- });
44
- },
45
- );
46
- req.on("error", reject);
47
- req.write(data);
48
- req.end();
116
+ return fetch(`${baseUrl}${path}`, {
117
+ method: "POST",
118
+ headers: { "Content-Type": "application/json" },
119
+ body: JSON.stringify(body),
49
120
  });
50
121
  }
51
122
 
52
- export default async function watchRepo(args = []) {
53
- // ============================================================
54
- // Config
55
- // ============================================================
123
+ /** The repository identity is its full path — never the basename. */
124
+ function repoNameFor(repoPath) {
125
+ return repoPath;
126
+ }
56
127
 
57
- const YATS_URL = process.env.YATS_URL ?? "http://localhost:5555";
58
- const DEBOUNCE_MS = parseInt(process.env.YATS_WATCH_DEBOUNCE ?? "500", 10);
128
+ async function getRecordedCommit(baseUrl, repoName) {
129
+ const res = await fetch(
130
+ `${baseUrl}/index/commit?repository=${encodeURIComponent(repoName)}`,
131
+ );
132
+ if (!res.ok) return null;
133
+ try {
134
+ const data = await res.json();
135
+ return data.commit ?? null;
136
+ } catch {
137
+ return null;
138
+ }
139
+ }
59
140
 
60
- const repoPath = resolve(args[0] ?? process.cwd());
61
- const repoArgIdx = args.indexOf("--repo");
62
- const repoName = repoArgIdx >= 0 ? args[repoArgIdx + 1] : basename(repoPath);
141
+ function shouldSkipPath(relPath, extraIgnoredDirs = []) {
142
+ if (!relPath || relPath.startsWith(".")) return true;
143
+ const segments = relPath.split("/");
144
+ return (
145
+ segments.some((seg) => IGNORED.has(seg) || extraIgnoredDirs.includes(seg)) ||
146
+ SKIP_PATTERNS.some((p) => p.test(relPath))
147
+ );
148
+ }
63
149
 
64
- if (!args[0] || args[0] === "--help" || args[0] === "-h") {
65
- console.log("Usage: yats watch <path> [--repo <name>]");
66
- console.log("");
67
- console.log("Watches a directory and keeps the YATS index in sync.");
68
- console.log("When files change, it tells the YATS server to re-index them.");
69
- console.log("");
70
- console.log(" yats watch ~/my-project");
71
- console.log(" yats watch ~/my-project --repo my-api");
72
- process.exit(1);
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;
166
+ const fullPath = resolve(repoPath, relPath);
167
+ let content;
168
+ try {
169
+ content = readFileSync(fullPath, "utf-8");
170
+ } catch {
171
+ return; // deleted between diff and read — next commit will catch it
73
172
  }
173
+ if (content.includes("\0") || content.length > 1_000_000) return; // binary/huge
74
174
 
75
- async function indexFile(filePath) {
76
- const rel = relative(repoPath, filePath);
77
- console.log(` ↻ Indexing: ${rel}`);
78
- try {
79
- const content = readFileSync(filePath, "utf-8");
80
- // Send the RELATIVE path — symbol IDs must match the ones from `yats index`
81
- // (the server scopes symbol IDs to the repository-relative path).
82
- await post(YATS_URL, "/index/file", { filePath: rel, content, repository: repoName });
83
- console.log(` ✓ Done: ${rel}`);
84
- } catch (err) {
85
- console.error(` ✗ Failed: ${rel} — ${err.message}`);
86
- }
175
+ console.log(` ↻ Indexing: ${relPath}`);
176
+ try {
177
+ const res = await post(baseUrl, "/index/file", {
178
+ repoName,
179
+ filePath: relPath,
180
+ content,
181
+ });
182
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
183
+ console.log(` ✓ Done: ${relPath}`);
184
+ } catch (err) {
185
+ console.error(` ✗ Failed: ${relPath} — ${err.message}`);
87
186
  }
187
+ }
88
188
 
89
- async function removeFile(filePath) {
90
- const rel = relative(repoPath, filePath);
91
- console.log(` ↻ Removing from index: ${rel}`);
92
- try {
93
- await post(YATS_URL, "/index/remove", { path: rel, repository: repoName });
94
- console.log(` ✓ Removed: ${rel}`);
95
- } catch (err) {
96
- console.error(` ✗ Failed: ${rel} — ${err.message}`);
97
- }
189
+ async function removeFile(baseUrl, repoName, relPath, skipFn) {
190
+ if (skipFn(relPath)) return;
191
+ console.log(` ↻ Removing from index: ${relPath}`);
192
+ try {
193
+ const res = await post(baseUrl, "/index/remove", {
194
+ repository: repoName,
195
+ path: relPath,
196
+ });
197
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
198
+ console.log(` ✓ Removed: ${relPath}`);
199
+ } catch (err) {
200
+ console.error(` ✗ Failed: ${relPath} — ${err.message}`);
98
201
  }
202
+ }
99
203
 
100
- // ============================================================
101
- // Debounced watcher
102
- // ============================================================
204
+ // ============================================================
205
+ // Commit diff application
206
+ // ============================================================
103
207
 
104
- const pending = new Map();
105
- const SKIP_PATTERNS = [
106
- /node_modules/,
107
- /\.git\//,
108
- /vendor\//,
109
- /__pycache__/,
110
- /\.next\//,
111
- /dist\//,
112
- /\.yarn\//,
113
- ];
208
+ /**
209
+ * Bring the index from `from` to `to` by streaming only the changed files.
210
+ * Exported for tests (baseUrl and the effective config are injectable).
211
+ */
212
+ export async function applyDiff(repoPath, repoName, from, to, baseUrl = DEFAULT_URL, effective = {}) {
213
+ let output;
214
+ try {
215
+ output = git(repoPath, `diff --name-status ${from}..${to}`);
216
+ } catch (err) {
217
+ // E.g. the recorded commit was garbage-collected — full re-index is the
218
+ // only safe path.
219
+ console.log(` ⚠ Cannot diff ${from.slice(0, 8)}..${to.slice(0, 8)} — full re-index...`);
220
+ await indexRepo([repoPath]);
221
+ return;
222
+ }
114
223
 
115
- function shouldSkip(filename) {
116
- if (!filename || filename.startsWith(".")) return true;
117
- return SKIP_PATTERNS.some((p) => p.test(filename));
224
+ const skipFn = makeFileFilter(effective);
225
+ const changes = parseNameStatus(output);
226
+ const total =
227
+ changes.added.length + changes.modified.length +
228
+ changes.deleted.length + changes.renamed.length;
229
+ console.log(
230
+ ` ${total} changed file(s): +${changes.added.length} ` +
231
+ `~${changes.modified.length} -${changes.deleted.length} ` +
232
+ `⟲${changes.renamed.length}`,
233
+ );
234
+
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);
237
+ for (const p of [...changes.added, ...changes.modified]) {
238
+ await indexFile(baseUrl, repoPath, repoName, p, skipFn);
239
+ }
240
+ for (const r of changes.renamed) {
241
+ await indexFile(baseUrl, repoPath, repoName, r.to, skipFn);
118
242
  }
119
243
 
120
- console.log(`👀 Watching: ${repoPath}`);
121
- console.log(` Repo: ${repoName}`);
122
- console.log(` Server: ${YATS_URL}`);
123
- console.log(` (debounce: ${DEBOUNCE_MS}ms)`);
124
- console.log("");
244
+ // Flush cross-file relationships and record the new commit. Both are
245
+ // non-fatal: the server also flushes on its debounce timer, and watch
246
+ // re-syncs on the next poll if the commit was not recorded.
247
+ try {
248
+ await post(baseUrl, "/index/complete", { repository: repoName });
249
+ } catch {
250
+ /* non-fatal */
251
+ }
252
+ try {
253
+ await post(baseUrl, "/index/commit", { repository: repoName, commit: to });
254
+ } catch {
255
+ /* non-fatal */
256
+ }
257
+ console.log(` ✓ Index synced to commit ${to.slice(0, 8)}`);
258
+ }
125
259
 
126
- watch(repoPath, { recursive: true }, (eventType, filename) => {
127
- if (!filename || shouldSkip(filename)) return;
260
+ // ============================================================
261
+ // Live mode — save-based indexing (fs.watch + debounce)
262
+ // ============================================================
263
+
264
+ function startLiveWatch(repoPath, repoName, baseUrl, effective) {
265
+ const pending = new Map();
266
+ const skipFn = makeFileFilter(effective);
267
+
268
+ fsWatch(repoPath, { recursive: true }, (_eventType, filename) => {
269
+ if (!filename || SKIP_PATTERNS.some((p) => p.test(filename))) return;
270
+ if (filename.startsWith(".")) return;
128
271
 
129
272
  const fullPath = resolve(repoPath, filename);
273
+ const relPath = relative(repoPath, fullPath);
274
+ if (shouldSkipPath(relPath)) return;
130
275
 
131
- // Debounce: group rapid changes to the same file
132
276
  const existing = pending.get(fullPath);
133
277
  if (existing) clearTimeout(existing);
134
278
 
@@ -136,24 +280,139 @@ export default async function watchRepo(args = []) {
136
280
  fullPath,
137
281
  setTimeout(async () => {
138
282
  pending.delete(fullPath);
139
-
140
- // Check if file still exists (or was deleted)
141
283
  try {
142
284
  statSync(fullPath);
143
- await indexFile(fullPath);
285
+ await indexFile(baseUrl, repoPath, repoName, relPath, skipFn);
144
286
  } catch {
145
- await removeFile(fullPath);
287
+ await removeFile(baseUrl, repoName, relPath, skipFn);
146
288
  }
147
289
  }, DEBOUNCE_MS),
148
290
  );
149
291
  });
150
292
 
151
- // Keep the process alive
152
- process.stdin.resume();
293
+ console.log(` (live saves: every save re-indexes the file, debounced ${DEBOUNCE_MS}ms)`);
294
+ }
153
295
 
154
- // Clean shutdown
155
- process.on("SIGINT", () => {
156
- console.log("\n👋 Stopped watching.");
157
- process.exit(0);
158
- });
296
+ // ============================================================
297
+ // Main
298
+ // ============================================================
299
+
300
+ export default async function watchRepo(args = []) {
301
+ const live = args.includes("--live");
302
+ const noConfig = args.includes("--no-config");
303
+ const baseUrl = process.env.YATS_URL ?? DEFAULT_URL;
304
+ const cleanArgs = args.filter((a) => a !== "--live" && a !== "--repo" && a !== "--no-config");
305
+
306
+ const repoPath = resolve(cleanArgs[0] ?? process.cwd());
307
+
308
+ if (!cleanArgs[0] || cleanArgs[0] === "--help" || cleanArgs[0] === "-h") {
309
+ console.log("Usage: yats watch <path> [--live] [--no-config]");
310
+ console.log("");
311
+ console.log("Keeps the YATS index in sync with the repository's commits.");
312
+ console.log("Saving files without committing does NOT touch the index —");
313
+ console.log("the graph always reflects the last commit.");
314
+ console.log("");
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");
317
+ console.log("");
318
+ console.log(" yats watch ~/my-project");
319
+ console.log(" yats watch ~/my-project --live");
320
+ process.exit(1);
321
+ }
322
+
323
+ const repoName = repoNameFor(repoPath);
324
+
325
+ // Server reachability
326
+ try {
327
+ await fetch(`${baseUrl}/health`);
328
+ } catch {
329
+ console.error(`Cannot reach YATS at ${baseUrl}. Is it running?`);
330
+ process.exit(1);
331
+ }
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
+
338
+ console.log(`👀 Watching: ${repoPath}`);
339
+ console.log(` Repo: ${repoName}`);
340
+ console.log(` Server: ${baseUrl}`);
341
+ console.log(` Mode: ${live ? "commits + live saves" : "commits only"}`);
342
+ console.log("");
343
+
344
+ const gitOk = isGitRepo(repoPath);
345
+
346
+ if (live) {
347
+ // Ensure metadata registration so the repo shows up in list_repositories
348
+ try {
349
+ await post(baseUrl, "/index", { path: repoPath });
350
+ } catch {
351
+ /* non-fatal */
352
+ }
353
+ startLiveWatch(repoPath, repoName, baseUrl, effective);
354
+ }
355
+
356
+ if (!gitOk) {
357
+ if (live) {
358
+ console.log(" (not a git repository — live saves only)");
359
+ process.stdin.resume();
360
+ process.on("SIGINT", () => {
361
+ console.log("\n👋 Stopped watching.");
362
+ process.exit(0);
363
+ });
364
+ return;
365
+ }
366
+ console.error(
367
+ "Not a git repository — commit-based watch requires git.\n" +
368
+ "Use `yats watch <path> --live` to index on every save instead.",
369
+ );
370
+ process.exit(1);
371
+ }
372
+
373
+ // ============================================================
374
+ // Commit-based loop
375
+ // ============================================================
376
+
377
+ let recorded = await getRecordedCommit(baseUrl, repoName);
378
+ let head = headCommit(repoPath);
379
+
380
+ if (recorded == null || recorded.length === 0) {
381
+ if (head) {
382
+ console.log(" No recorded index commit — running a full index first...");
383
+ await indexRepo([repoPath]);
384
+ recorded = headCommit(repoPath);
385
+ } else {
386
+ console.log(" Repo has no commits yet — waiting for the first commit...");
387
+ recorded = null;
388
+ }
389
+ } else if (head && recorded !== head) {
390
+ console.log(
391
+ ` Indexed commit ${recorded.slice(0, 8)} ≠ HEAD ${head.slice(0, 8)} — syncing...`,
392
+ );
393
+ await applyDiff(repoPath, repoName, recorded, head, baseUrl, effective);
394
+ recorded = head;
395
+ }
396
+
397
+ if (recorded) {
398
+ console.log(` ✓ In sync with commit ${recorded.slice(0, 8)}`);
399
+ }
400
+ console.log(` (polling HEAD every ${POLL_MS}ms — commits trigger re-index)`);
401
+ console.log("");
402
+
403
+ while (true) {
404
+ await new Promise((r) => setTimeout(r, POLL_MS));
405
+ head = headCommit(repoPath);
406
+ if (!head || head === recorded) continue;
407
+
408
+ console.log(`\n ⬆ HEAD moved ${recorded ? recorded.slice(0, 8) + " → " : ""}${head.slice(0, 8)}`);
409
+ if (recorded) {
410
+ await applyDiff(repoPath, repoName, recorded, head, baseUrl, effective);
411
+ } else {
412
+ // First commit after an unborn HEAD — nothing to diff from: full index.
413
+ await indexRepo([repoPath]);
414
+ }
415
+ recorded = head;
416
+ console.log("");
417
+ }
159
418
  }