yats-toolkit 0.8.0 → 0.8.2

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.
@@ -0,0 +1,21 @@
1
+ {
2
+ "version": "2.0.0",
3
+ "tasks": [
4
+ {
5
+ "label": "YATS: watch",
6
+ "detail": "Keeps the YATS index in sync with the files on disk (live mode).",
7
+ "type": "shell",
8
+ "command": "yats",
9
+ "args": ["watch", ".", "--live"],
10
+ "runOptions": {
11
+ "runOn": "folderOpen"
12
+ },
13
+ "presentation": {
14
+ "reveal": "never",
15
+ "panel": "dedicated",
16
+ "showReuseMessage": false
17
+ },
18
+ "problemMatcher": []
19
+ }
20
+ ]
21
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "yats-toolkit",
3
- "version": "0.8.0",
3
+ "version": "0.8.2",
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",
package/src/connect.js CHANGED
@@ -67,6 +67,9 @@ const AGENTS = {
67
67
  files: [
68
68
  // Native VS Code workspace MCP config (servers format).
69
69
  { src: "connect/vscode/mcp.json", dest: ".vscode/mcp.json", type: "json" },
70
+ // Keeps the index in sync with the working tree: `yats watch . --live`
71
+ // runs on folder open (VS Code asks once for "Allow Automatic Tasks").
72
+ { src: "connect/vscode/tasks.json", dest: ".vscode/tasks.json", type: "json", merge: "tasks" },
70
73
  ],
71
74
  url: "https://github.com/fvinciarelli/yats.ai/tree/main/connect/vscode",
72
75
  },
@@ -187,6 +190,27 @@ export function mergeServerConfig(existing, template) {
187
190
  return out;
188
191
  }
189
192
 
193
+ /**
194
+ * Merge an editor tasks file (`.vscode/tasks.json`) without clobbering the
195
+ * user's tasks: existing entries are kept in order and a task whose label is
196
+ * already present is never duplicated (re-running `yats connect --install` is
197
+ * a no-op).
198
+ */
199
+ export function mergeTasksConfig(existing, template) {
200
+ const out = { ...existing };
201
+ for (const key of Object.keys(template)) {
202
+ if (key === "tasks") continue;
203
+ out[key] = template[key];
204
+ }
205
+
206
+ const current = Array.isArray(existing.tasks) ? existing.tasks : [];
207
+ const labels = new Set(current.map((t) => t && t.label).filter(Boolean));
208
+ const added = (template.tasks ?? []).filter((t) => t && !labels.has(t.label));
209
+
210
+ out.tasks = [...current, ...added];
211
+ return out;
212
+ }
213
+
190
214
  /**
191
215
  * Install one agent's JSON config file from its template.
192
216
  * The template is the source of truth (correct format + transport per
@@ -218,7 +242,9 @@ function installJsonFile(file) {
218
242
  console.log(` ${Y}⚠${R} ${destPath} exists but is not valid JSON — left untouched.`);
219
243
  return false;
220
244
  }
221
- merged = mergeServerConfig(existing, templateObj);
245
+ merged = file.merge === "tasks"
246
+ ? mergeTasksConfig(existing, templateObj)
247
+ : mergeServerConfig(existing, templateObj);
222
248
  }
223
249
 
224
250
  mkdirSync(dirname(destPath), { recursive: true });
@@ -462,7 +488,11 @@ function showConfig(agentKey) {
462
488
  try {
463
489
  const tpl = JSON.parse(templateContent);
464
490
  const existing = existsSync(file.dest) ? readJsonObject(file.dest) : null;
465
- const preview = existing ? mergeServerConfig(existing, tpl) : tpl;
491
+ const preview = existing
492
+ ? (file.merge === "tasks"
493
+ ? mergeTasksConfig(existing, tpl)
494
+ : mergeServerConfig(existing, tpl))
495
+ : tpl;
466
496
  console.log(` ${D}${JSON.stringify(preview, null, 2).replace(/\n/g, "\n ")}${R}`);
467
497
  } catch {
468
498
  console.log(` ${D}${templateContent.replace(/\n/g, "\n ")}${R}`);
@@ -10,7 +10,7 @@
10
10
  import { describe, it } from "node:test";
11
11
  import assert from "node:assert/strict";
12
12
 
13
- import { mergeServerConfig, renderContent } from "./connect.js";
13
+ import { mergeServerConfig, mergeTasksConfig, renderContent } from "./connect.js";
14
14
 
15
15
  describe("mergeServerConfig", () => {
16
16
  it("merges mcpServers entries, preserving existing servers", () => {
@@ -83,4 +83,56 @@ describe("agent templates (shipped in the package)", () => {
83
83
  // hardcoded (CI runs from a different path).
84
84
  assert.ok(content.includes(`yats index ${process.cwd()}`));
85
85
  });
86
+
87
+ it("vscode tasks template runs `yats watch . --live` on folder open", () => {
88
+ const content = renderContent("connect/vscode/tasks.json");
89
+ assert.ok(content, "tasks template must resolve");
90
+ const tpl = JSON.parse(content);
91
+ const task = tpl.tasks.find((t) => t.label === "YATS: watch");
92
+ assert.ok(task, "task must be present");
93
+ assert.equal(task.command, "yats");
94
+ assert.deepEqual(task.args, ["watch", ".", "--live"]);
95
+ assert.equal(task.runOptions.runOn, "folderOpen");
96
+ assert.equal(task.presentation.reveal, "never");
97
+ });
98
+ });
99
+
100
+ describe("mergeTasksConfig — .vscode/tasks.json is never clobbered", () => {
101
+ const yatsTask = {
102
+ label: "YATS: watch",
103
+ type: "shell",
104
+ command: "yats",
105
+ args: ["watch", ".", "--live"],
106
+ runOptions: { runOn: "folderOpen" },
107
+ };
108
+
109
+ it("preserves the user's tasks and appends the YATS one", () => {
110
+ const existing = {
111
+ version: "2.0.0",
112
+ tasks: [{ label: "build", type: "shell", command: "make" }],
113
+ };
114
+
115
+ const merged = mergeTasksConfig(existing, { version: "2.0.0", tasks: [yatsTask] });
116
+
117
+ assert.deepEqual(merged.tasks.map((t) => t.label), ["build", "YATS: watch"]);
118
+ assert.deepEqual(merged.tasks[0], existing.tasks[0]);
119
+ assert.equal(merged.version, "2.0.0");
120
+ });
121
+
122
+ it("does not duplicate the YATS task on re-install", () => {
123
+ const once = mergeTasksConfig({}, { version: "2.0.0", tasks: [yatsTask] });
124
+ const twice = mergeTasksConfig(once, { version: "2.0.0", tasks: [yatsTask] });
125
+
126
+ assert.equal(twice.tasks.length, 1);
127
+ assert.equal(twice.tasks[0].label, "YATS: watch");
128
+ });
129
+
130
+ it("keeps the user's version and keys when the template lacks them", () => {
131
+ const existing = { version: "2.0.0", inputs: [{ id: "x" }], tasks: [] };
132
+ const merged = mergeTasksConfig(existing, { tasks: [yatsTask] });
133
+
134
+ assert.equal(merged.version, "2.0.0");
135
+ assert.deepEqual(merged.inputs, [{ id: "x" }]);
136
+ assert.equal(merged.tasks.length, 1);
137
+ });
86
138
  });
package/src/indexer.js CHANGED
@@ -22,6 +22,7 @@ import { join, relative } from "node:path";
22
22
  import { homedir } from "node:os";
23
23
  import { spawnSync } from "node:child_process";
24
24
  import { createHash } from "node:crypto";
25
+ import { canonicalRepoPath } from "./repo-path.js";
25
26
 
26
27
  const YATS_URL = process.env.YATS_URL || "http://localhost:5555";
27
28
 
@@ -288,15 +289,17 @@ export default async function indexRepo(args, options = {}) {
288
289
  const skipDocsFlag = options.skipDocs || false;
289
290
  const noConfig = options.noConfig || false;
290
291
  const force = options.force === true;
291
- const repoPath = args[0];
292
- if (!repoPath) {
292
+ const rawPath = args[0];
293
+ if (!rawPath) {
293
294
  console.error("Usage: npx yats index <path> [--skip-docs] [--no-config]");
294
295
  process.exit(1);
295
296
  }
296
297
 
297
- // The repository identity is its full path (two clones of the same repo are
298
- // two distinct indexes) — never the basename.
299
- const repoName = repoPath;
298
+ // The repository identity is its canonical full path
299
+ // (`C:\Repo\`, `C:/Repo` and `/c/Repo` are the same repo) — never the
300
+ // basename, and never the raw string the user typed: `yats index .` used to
301
+ // register a repo literally named ".", which split the index in two.
302
+ const repoPath = canonicalRepoPath(rawPath);
300
303
  let stat;
301
304
  try {
302
305
  stat = statSync(repoPath);
@@ -317,13 +320,33 @@ export default async function indexRepo(args, options = {}) {
317
320
  const skipDocs = skipDocsFlag || effective.indexDocs === false;
318
321
  const ignoredDirs = new Set([...IGNORED, ...effective.ignoredDirs]);
319
322
 
320
- // Register repo
323
+ // Register repo. The server owns the identity: it canonicalizes the path and
324
+ // answers with the rootPath already stored for this folder. That keeps a
325
+ // legacy index (indexed under another spelling) working instead of creating
326
+ // a duplicate, and `yats index .` / `yats watch .` agree on the same repo.
327
+ //
328
+ // Older servers answer with the *basename* instead of the full rootPath, so
329
+ // only trust the field when it looks like an absolute path (a CLI upgrade can
330
+ // land before the server image does).
331
+ let repoName = repoPath;
321
332
  try {
322
- await fetch(`${YATS_URL}/index`, {
333
+ const res = await fetch(`${YATS_URL}/index`, {
323
334
  method: "POST",
324
335
  headers: { "Content-Type": "application/json" },
325
336
  body: JSON.stringify({ path: repoPath }),
326
337
  });
338
+ const data = await res.json().catch(() => null);
339
+ if (!res.ok) {
340
+ console.error(
341
+ `Cannot register repository: ${data?.error ?? `HTTP ${res.status}`}`,
342
+ );
343
+ process.exit(1);
344
+ }
345
+ if (data?.warning) console.warn(`\n ⚠ ${data.warning}\n`);
346
+ const answered = typeof data?.repository === "string" ? data.repository : "";
347
+ if (answered && (answered.includes("/") || answered.includes("\\"))) {
348
+ repoName = answered;
349
+ }
327
350
  } catch {
328
351
  console.error(`Cannot reach YATS at ${YATS_URL}. Is it running?`);
329
352
  process.exit(1);
package/src/remove.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * Wraps the MCP delete_repository tool, accepting a directory path
4
4
  * instead of requiring the exact repo name.
5
5
  */
6
- import { resolve } from "node:path";
6
+ import { canonicalRepoPath } from "./repo-path.js";
7
7
 
8
8
  const YATS_URL = process.env.YATS_URL || "http://localhost:5555";
9
9
 
@@ -29,7 +29,7 @@ export default async function remove(args) {
29
29
  process.exit(1);
30
30
  }
31
31
 
32
- const repoPath = resolve(rawPath);
32
+ const repoPath = canonicalRepoPath(rawPath);
33
33
 
34
34
  try {
35
35
  // Step 1: ask for confirmation (using path, server resolves to repo)
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Repository path canonicalization — mirrors
3
+ * `packages/shared/src/utils/repo-path.ts` (the package is published on its own
4
+ * and must stay dependency-free, so the logic is duplicated here).
5
+ *
6
+ * Both copies are covered by the same table of assertions
7
+ * (`src/repo-path.test.js` and `packages/shared/src/utils/repo-path.test.ts`);
8
+ * if you change one, change the other.
9
+ */
10
+
11
+ import { posix, win32 } from "node:path";
12
+
13
+ const WINDOWS_DRIVE = /^[A-Za-z]:[\\/]/;
14
+ const WINDOWS_UNC = /^\\\\[^\\]/;
15
+
16
+ /** True when the string is written as a Windows path (drive or UNC). */
17
+ export function isWindowsPath(value) {
18
+ return WINDOWS_DRIVE.test(value) || WINDOWS_UNC.test(value);
19
+ }
20
+
21
+ function stripDevicePrefix(value) {
22
+ return value
23
+ .replace(/^\\\\\?\\/, "")
24
+ .replace(/^\/\/\?\//, "")
25
+ .replace(/^\\\\\.\\/, "")
26
+ .replace(/^\/\/\.\//, "");
27
+ }
28
+
29
+ /**
30
+ * Canonical repository path: absolute, forward slashes, uppercase drive
31
+ * letter, no trailing slash (except filesystem roots). Case is preserved.
32
+ *
33
+ * @param {string} input
34
+ * @param {{platform?: string, cwd?: string}} [options]
35
+ */
36
+ export function canonicalRepoPath(input, options = {}) {
37
+ const platform = options.platform ?? process.platform;
38
+ let value = (input ?? "").trim();
39
+ if (!value) return "";
40
+
41
+ value = stripDevicePrefix(value);
42
+
43
+ // MSYS/Cygwin drive spelling (Git Bash): "/c/Users/..." is "C:/Users/...".
44
+ // Only translate on Windows hosts: on Linux "/c/foo" is a real directory.
45
+ if (platform === "win32") {
46
+ value = value.replace(/^\/([A-Za-z])(?=\/)/, (_m, drive) => `${drive.toUpperCase()}:`);
47
+ }
48
+
49
+ value = value.replace(/\\/g, "/");
50
+
51
+ const isWindows = platform === "win32" || isWindowsPath(value);
52
+ const p = isWindows ? win32 : posix;
53
+
54
+ const hostMatchesStyle = isWindows === (process.platform === "win32");
55
+ const cwd = options.cwd ?? (hostMatchesStyle ? process.cwd() : undefined);
56
+ if (cwd && !p.isAbsolute(value)) {
57
+ value = p.resolve(cwd.replace(/\\/g, "/"), value);
58
+ }
59
+
60
+ let out = p.normalize(value).replace(/\\/g, "/");
61
+
62
+ if (!out.startsWith("//")) {
63
+ out = out.replace(/^([a-z]):/, (_m, drive) => `${drive.toUpperCase()}:`);
64
+ }
65
+
66
+ if (out.length > 1 && !/^[A-Za-z]:\/$/.test(out) && out !== "//") {
67
+ out = out.replace(/\/+$/, "");
68
+ }
69
+
70
+ return out;
71
+ }
72
+
73
+ /**
74
+ * Identity key: case-folded on case-insensitive filesystems (Windows/macOS)
75
+ * and for Windows-style paths. POSIX paths keep their case.
76
+ */
77
+ export function repoPathKey(input, options = {}) {
78
+ const canonical = canonicalRepoPath(input, options);
79
+ const platform = options.platform ?? process.platform;
80
+ const caseInsensitive =
81
+ platform === "win32" || platform === "darwin" || isWindowsPath(canonical);
82
+ return caseInsensitive ? canonical.toLowerCase() : canonical;
83
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Tests — repository path canonicalization (mirror of the shared TS util).
3
+ *
4
+ * YATS identifies repos by the string of their root path, so every spelling of
5
+ * the same folder must produce the same identity: backslashes, Git Bash
6
+ * `/c/...`, trailing slashes, `\\?\` prefixes and relative `.`.
7
+ */
8
+
9
+ import { describe, it } from "node:test";
10
+ import assert from "node:assert/strict";
11
+
12
+ import { canonicalRepoPath, isWindowsPath, repoPathKey } from "./repo-path.js";
13
+
14
+ describe("canonicalRepoPath — Windows spellings collapse to one identity", () => {
15
+ const win = { platform: "win32" };
16
+
17
+ it("normalizes drive, separators and trailing slash", () => {
18
+ assert.equal(canonicalRepoPath("C:\\Users\\me\\repo\\", win), "C:/Users/me/repo");
19
+ assert.equal(canonicalRepoPath("c:/users/me/repo", win), "C:/users/me/repo");
20
+ assert.equal(canonicalRepoPath("C:/Users/me/repo/.", win), "C:/Users/me/repo");
21
+ assert.equal(canonicalRepoPath("C:\\Users\\me\\repo\\\\sub\\..", win), "C:/Users/me/repo");
22
+ });
23
+
24
+ it("translates the Git Bash (MSYS) drive form", () => {
25
+ assert.equal(canonicalRepoPath("/c/Users/me/repo", win), "C:/Users/me/repo");
26
+ assert.equal(canonicalRepoPath("/C/Users/me/repo/", win), "C:/Users/me/repo");
27
+ });
28
+
29
+ it("strips \\\\?\\ extended-length prefixes", () => {
30
+ assert.equal(canonicalRepoPath("\\\\?\\C:\\Users\\me\\repo", win), "C:/Users/me/repo");
31
+ });
32
+
33
+ it("resolves relative paths against the given cwd", () => {
34
+ assert.equal(canonicalRepoPath(".", { ...win, cwd: "C:\\repo" }), "C:/repo");
35
+ assert.equal(canonicalRepoPath("..", { ...win, cwd: "C:\\repo\\sub" }), "C:/repo");
36
+ });
37
+
38
+ it("keeps UNC shares with a single leading double slash", () => {
39
+ assert.equal(canonicalRepoPath("\\\\server\\share\\repo", win), "//server/share/repo");
40
+ });
41
+
42
+ it("keeps the drive root without a trailing slash", () => {
43
+ assert.equal(canonicalRepoPath("C:\\", win), "C:/");
44
+ });
45
+
46
+ it("does not rewrite the case of path components", () => {
47
+ assert.equal(canonicalRepoPath("C:\\Users\\Franco\\MiRepo", win), "C:/Users/Franco/MiRepo");
48
+ });
49
+ });
50
+
51
+ describe("canonicalRepoPath — POSIX paths", () => {
52
+ const linux = { platform: "linux" };
53
+
54
+ it("resolves relatives and drops the trailing slash", () => {
55
+ assert.equal(canonicalRepoPath("/home/me/repo/", linux), "/home/me/repo");
56
+ assert.equal(canonicalRepoPath("/home/me/repo/../repo", linux), "/home/me/repo");
57
+ assert.equal(canonicalRepoPath(".", { ...linux, cwd: "/home/me/repo" }), "/home/me/repo");
58
+ });
59
+
60
+ it("does not treat /c/... as a Windows drive on Linux", () => {
61
+ assert.equal(canonicalRepoPath("/c/foo", linux), "/c/foo");
62
+ });
63
+
64
+ it("is idempotent", () => {
65
+ for (const input of ["/home/me/repo", "C:\\Users\\me\\repo\\", "/c/Users/me/repo"]) {
66
+ const platform = input.startsWith("/c/") ? "win32" : "linux";
67
+ const once = canonicalRepoPath(input, { platform });
68
+ const twice = canonicalRepoPath(once, { platform });
69
+ assert.equal(twice, once);
70
+ }
71
+ });
72
+ });
73
+
74
+ describe("repoPathKey — case-insensitive identity", () => {
75
+ it("folds case so Windows spellings of the same folder match", () => {
76
+ const a = repoPathKey("C:\\Users\\Franco\\MiRepo", { platform: "win32" });
77
+ const b = repoPathKey("/c/users/franco/mirepo", { platform: "win32" });
78
+ assert.equal(a, b);
79
+ });
80
+
81
+ it("keeps POSIX paths distinct when they differ in case", () => {
82
+ assert.notEqual(
83
+ repoPathKey("/home/me/Repo", { platform: "linux" }),
84
+ repoPathKey("/home/me/repo", { platform: "linux" }),
85
+ );
86
+ });
87
+ });
88
+
89
+ describe("isWindowsPath", () => {
90
+ it("detects drives and UNC, not POSIX paths", () => {
91
+ assert.equal(isWindowsPath("C:\\Users"), true);
92
+ assert.equal(isWindowsPath("C:/Users"), true);
93
+ assert.equal(isWindowsPath("\\\\server\\share"), true);
94
+ assert.equal(isWindowsPath("/home/me"), false);
95
+ assert.equal(isWindowsPath("./relative"), false);
96
+ });
97
+ });
package/src/watch.js CHANGED
@@ -24,9 +24,19 @@
24
24
  * may live in a container without git).
25
25
  */
26
26
 
27
- import { watch as fsWatch, statSync, readFileSync } from "node:fs";
28
- import { resolve, relative } from "node:path";
27
+ import {
28
+ watch as fsWatch,
29
+ statSync,
30
+ readFileSync,
31
+ writeFileSync,
32
+ unlinkSync,
33
+ existsSync,
34
+ mkdirSync,
35
+ } from "node:fs";
36
+ import { resolve, relative, join, dirname } from "node:path";
29
37
  import { execSync } from "node:child_process";
38
+ import { createHash } from "node:crypto";
39
+ import { homedir } from "node:os";
30
40
  import indexRepo, {
31
41
  IGNORED,
32
42
  loadYatsEnv,
@@ -34,6 +44,7 @@ import indexRepo, {
34
44
  resolveRepoConfig,
35
45
  shouldSkipFile,
36
46
  } from "./indexer.js";
47
+ import { canonicalRepoPath } from "./repo-path.js";
37
48
 
38
49
  // ============================================================
39
50
  // Config
@@ -52,6 +63,79 @@ const SKIP_PATTERNS = [
52
63
  /\.yarn\//,
53
64
  ];
54
65
 
66
+ // ============================================================
67
+ // Single-instance lock — one watcher per repo
68
+ // ============================================================
69
+
70
+ /** Root of YATS host state (`YATS_HOME` overrides it, used by tests). */
71
+ function yatsHome() {
72
+ return process.env.YATS_HOME ?? join(homedir(), ".yats");
73
+ }
74
+
75
+ /**
76
+ * Lock file for a repo. Keyed by the resolved path so `yats watch .`,
77
+ * `yats watch /abs/path` and an IDE task pointing at the same folder share it.
78
+ */
79
+ export function watchLockPath(repoPath) {
80
+ const key = createHash("sha1").update(resolve(repoPath)).digest("hex").slice(0, 12);
81
+ return join(yatsHome(), "run", `watch-${key}.json`);
82
+ }
83
+
84
+ /** True when `pid` is a live process (EPERM means it exists but isn't ours). */
85
+ function pidAlive(pid) {
86
+ if (!Number.isInteger(pid) || pid <= 0) return false;
87
+ try {
88
+ process.kill(pid, 0);
89
+ return true;
90
+ } catch (err) {
91
+ return err.code === "EPERM";
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Take the per-repo watcher lock.
97
+ *
98
+ * Any number of triggers (IDE folderOpen task, terminal command, git hook)
99
+ * may launch `yats watch` for the same folder; only the first one wins and the
100
+ * rest exit as a no-op. Locks left behind by a dead PID are replaced.
101
+ */
102
+ export function acquireWatchLock(repoPath) {
103
+ const lockPath = watchLockPath(repoPath);
104
+ mkdirSync(dirname(lockPath), { recursive: true });
105
+
106
+ if (existsSync(lockPath)) {
107
+ try {
108
+ const held = JSON.parse(readFileSync(lockPath, "utf-8"));
109
+ if (pidAlive(held.pid)) {
110
+ return { acquired: false, pid: held.pid, repoPath: held.repoPath ?? repoPath, lockPath };
111
+ }
112
+ } catch {
113
+ /* corrupt or unreadable lock — treat it as stale */
114
+ }
115
+ }
116
+
117
+ writeFileSync(
118
+ lockPath,
119
+ JSON.stringify(
120
+ { pid: process.pid, repoPath: resolve(repoPath), startedAt: new Date().toISOString() },
121
+ null,
122
+ 2,
123
+ ) + "\n",
124
+ );
125
+ return { acquired: true, lockPath };
126
+ }
127
+
128
+ /** Release the lock, but only when this process owns it. */
129
+ export function releaseWatchLock(repoPath) {
130
+ const lockPath = watchLockPath(repoPath);
131
+ try {
132
+ const held = JSON.parse(readFileSync(lockPath, "utf-8"));
133
+ if (held.pid === process.pid) unlinkSync(lockPath);
134
+ } catch {
135
+ /* nothing to release */
136
+ }
137
+ }
138
+
55
139
  // ============================================================
56
140
  // git helpers (host side — the server container has no git)
57
141
  // ============================================================
@@ -120,11 +204,6 @@ function post(baseUrl, path, body) {
120
204
  });
121
205
  }
122
206
 
123
- /** The repository identity is its full path — never the basename. */
124
- function repoNameFor(repoPath) {
125
- return repoPath;
126
- }
127
-
128
207
  async function getRecordedCommit(baseUrl, repoName) {
129
208
  const res = await fetch(
130
209
  `${baseUrl}/index/commit?repository=${encodeURIComponent(repoName)}`,
@@ -303,7 +382,10 @@ export default async function watchRepo(args = []) {
303
382
  const baseUrl = process.env.YATS_URL ?? DEFAULT_URL;
304
383
  const cleanArgs = args.filter((a) => a !== "--live" && a !== "--repo" && a !== "--no-config");
305
384
 
306
- const repoPath = resolve(cleanArgs[0] ?? process.cwd());
385
+ // Canonical path (`C:\Repo\`, `C:/Repo`, `/c/Repo`, `.` all collapse to one
386
+ // identity) so `yats index` and `yats watch` — and the IDE task — agree on
387
+ // the same repo.
388
+ const repoPath = canonicalRepoPath(cleanArgs[0] ?? process.cwd());
307
389
 
308
390
  if (!cleanArgs[0] || cleanArgs[0] === "--help" || cleanArgs[0] === "-h") {
309
391
  console.log("Usage: yats watch <path> [--live] [--no-config]");
@@ -320,7 +402,23 @@ export default async function watchRepo(args = []) {
320
402
  process.exit(1);
321
403
  }
322
404
 
323
- const repoName = repoNameFor(repoPath);
405
+ // One watcher per repo: IDE tasks, terminals and hooks may all try to start
406
+ // this, but a second process would re-index the same files (double embeddings
407
+ // cost) and race on the same files.
408
+ const lock = acquireWatchLock(repoPath);
409
+ if (!lock.acquired) {
410
+ console.log(`👀 Already watching: ${repoPath}`);
411
+ console.log(` PID ${lock.pid} owns this repo — this invocation is a no-op.`);
412
+ return;
413
+ }
414
+ const releaseLock = () => releaseWatchLock(repoPath);
415
+ process.on("exit", releaseLock);
416
+ for (const signal of ["SIGINT", "SIGTERM"]) {
417
+ process.on(signal, () => {
418
+ releaseLock();
419
+ process.exit(0);
420
+ });
421
+ }
324
422
 
325
423
  // Server reachability
326
424
  try {
@@ -330,6 +428,30 @@ export default async function watchRepo(args = []) {
330
428
  process.exit(1);
331
429
  }
332
430
 
431
+ // Register before watching: the server owns the identity and answers with the
432
+ // rootPath already stored for this folder, so a legacy index keeps working
433
+ // (and gets a warning) instead of being duplicated under a new spelling.
434
+ let repoName = repoPath;
435
+ try {
436
+ const res = await post(baseUrl, "/index", { path: repoPath });
437
+ const data = await res.json().catch(() => null);
438
+ if (!res.ok) {
439
+ // Never watch a repo the server could not register: files would be
440
+ // indexed without a Repository node and queries would not find them.
441
+ console.error(`Cannot register repository: ${data?.error ?? `HTTP ${res.status}`}`);
442
+ releaseLock();
443
+ process.exit(1);
444
+ }
445
+ if (data?.warning) console.log(`\n ⚠ ${data.warning}\n`);
446
+ // Older servers answer with the basename — only trust full paths.
447
+ const answered = typeof data?.repository === "string" ? data.repository : "";
448
+ if (answered && (answered.includes("/") || answered.includes("\\"))) {
449
+ repoName = answered;
450
+ }
451
+ } catch {
452
+ /* non-fatal: watching still works, it just re-registers on the next run */
453
+ }
454
+
333
455
  // P6 — same config resolution as `yats index`: a malformed
334
456
  // .yats/config.json stops the run instead of watching with wrong filters.
335
457
  const repoConfig = resolveRepoConfig(repoPath, noConfig);
@@ -344,12 +466,6 @@ export default async function watchRepo(args = []) {
344
466
  const gitOk = isGitRepo(repoPath);
345
467
 
346
468
  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
469
  startLiveWatch(repoPath, repoName, baseUrl, effective);
354
470
  }
355
471
 
package/src/watch.test.js CHANGED
@@ -10,11 +10,11 @@ import { describe, it, before, after } from "node:test";
10
10
  import assert from "node:assert/strict";
11
11
  import { createServer } from "node:http";
12
12
  import { join } from "node:path";
13
- import { writeFileSync, mkdirSync, rmSync } from "node:fs";
13
+ import { writeFileSync, mkdirSync, rmSync, existsSync, mkdtempSync } from "node:fs";
14
14
  import { execSync } from "node:child_process";
15
15
  import { tmpdir } from "node:os";
16
16
 
17
- import { parseNameStatus, applyDiff } from "./watch.js";
17
+ import { parseNameStatus, applyDiff, acquireWatchLock, releaseWatchLock, watchLockPath } from "./watch.js";
18
18
  import { mergeRepoConfig } from "./indexer.js";
19
19
 
20
20
  function git(cwd, cmd) {
@@ -195,3 +195,65 @@ describe("applyDiff — commit-based sync (P1)", () => {
195
195
  assert.deepEqual(sentPaths, ["docs/api.md"], "only docs matching the whitelist are sent");
196
196
  });
197
197
  });
198
+
199
+ describe("watch lock — one watcher per repo", () => {
200
+ const originalHome = process.env.YATS_HOME;
201
+ let home;
202
+
203
+ before(() => {
204
+ home = mkdtempSync(join(tmpdir(), "yats-lock-"));
205
+ process.env.YATS_HOME = home;
206
+ });
207
+
208
+ after(() => {
209
+ if (originalHome === undefined) delete process.env.YATS_HOME;
210
+ else process.env.YATS_HOME = originalHome;
211
+ rmSync(home, { recursive: true, force: true });
212
+ });
213
+
214
+ it("keyes the lock by resolved path and creates the run dir", () => {
215
+ const a = watchLockPath("/tmp/some/repo");
216
+ const b = watchLockPath("/tmp/some/repo/");
217
+ assert.equal(a, b);
218
+ assert.ok(a.startsWith(join(home, "run")));
219
+ });
220
+
221
+ it("first caller acquires, second one is a no-op that reports the owner", () => {
222
+ const repo = join(home, "repo-a");
223
+
224
+ const first = acquireWatchLock(repo);
225
+ assert.equal(first.acquired, true);
226
+ assert.ok(existsSync(watchLockPath(repo)));
227
+
228
+ const second = acquireWatchLock(repo);
229
+ assert.equal(second.acquired, false);
230
+ assert.equal(second.pid, process.pid);
231
+
232
+ releaseWatchLock(repo);
233
+ assert.ok(!existsSync(watchLockPath(repo)), "release removes the lock");
234
+ });
235
+
236
+ it("replaces a stale lock left behind by a dead PID", () => {
237
+ const repo = join(home, "repo-b");
238
+ mkdirSync(join(home, "run"), { recursive: true });
239
+ writeFileSync(
240
+ watchLockPath(repo),
241
+ JSON.stringify({ pid: 999999999, repoPath: repo, startedAt: new Date().toISOString() }),
242
+ );
243
+
244
+ const acquired = acquireWatchLock(repo);
245
+ assert.equal(acquired.acquired, true, "dead PID must not block the watcher");
246
+
247
+ releaseWatchLock(repo);
248
+ });
249
+
250
+ it("does not release a lock owned by another process", () => {
251
+ const repo = join(home, "repo-c");
252
+ mkdirSync(join(home, "run"), { recursive: true });
253
+ const lockPath = watchLockPath(repo);
254
+ writeFileSync(lockPath, JSON.stringify({ pid: process.pid + 1, repoPath: repo }));
255
+
256
+ releaseWatchLock(repo);
257
+ assert.ok(existsSync(lockPath), "another PID's lock must survive");
258
+ });
259
+ });