vexp-mcp 3.3.8 → 3.4.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.
@@ -19,6 +19,9 @@ import { parseEngineVersion, replaceOlderDaemon } from "./daemon-upgrade.js";
19
19
  * - `until` has passed — the quota reset.
20
20
  * - a license file is newer than the marker — the user upgraded mid-day, and
21
21
  * must not stay locked out until midnight over a stale free-tier marker.
22
+ *
23
+ * Lockstep with vexp-core daily_usage::daily_limit_until, which the server
24
+ * Codex runs reads before it starts a daemon.
22
25
  */
23
26
  export function readDailyLimitMarker(workspaceRoot) {
24
27
  const markerPath = path.join(workspaceRoot, ".vexp", "daily-limit.json");
@@ -102,16 +105,26 @@ export class DaemonClient {
102
105
  * can resurrect the daemon repeatedly when VS Code is closed and the daemon
103
106
  * exits — not only on the first connection of its lifetime. */
104
107
  lastSpawnAttemptMs = 0;
108
+ // The 4 s cap on a start (maybeSpawnDaemon), these retries and the
109
+ // cooldown are what the server Codex runs does at a tool call that finds
110
+ // no daemon, in lockstep: vexp-core mcp_stdio START_WAIT_AT_A_CALL,
111
+ // CALL_RETRIES, CALL_RETRY_DELAY and START_COOLDOWN.
105
112
  static MAX_RETRIES = 3;
106
113
  static RETRY_DELAY_MS = 1500;
107
114
  static SPAWN_COOLDOWN_MS = 10_000;
108
115
  static RETRYABLE_CODES = ["ENOENT", "ECONNREFUSED", "ECONNRESET", "EPIPE"];
116
+ /** The daemon of the multi-repo workspace this connected repo belongs to,
117
+ * once it has said it serves the repo. Dropped at the first failure. */
118
+ workspaceDaemonSocket;
109
119
  /** Workspace root used to (re)spawn the daemon and, when no socket is
110
120
  * resolvable, to compute the expected socket/pipe path. Set by the HTTP
111
121
  * transport so a per-workspace request can resurrect *its* daemon even when
112
122
  * VEXP_WORKSPACE is not in the supervisor's env. */
113
123
  spawnWorkspaceRoot;
114
- constructor(socketPath, sessionId, spawnWorkspaceRoot) {
124
+ /** The OS the start rules are applied for: this process's, or the one a
125
+ * test names (the Windows rules are tested on every OS). */
126
+ platform;
127
+ constructor(socketPath, sessionId, spawnWorkspaceRoot, platform = process.platform) {
115
128
  // When a caller passes an explicit path we honor it for the client's
116
129
  // lifetime (back-compat for tests and one-shot CLI usage). When omitted,
117
130
  // we re-resolve via the registry on every connect so a long-lived HTTP
@@ -119,6 +132,7 @@ export class DaemonClient {
119
132
  this.explicitSocketPath = socketPath;
120
133
  this.sessionId = sessionId ?? randomUUID();
121
134
  this.spawnWorkspaceRoot = spawnWorkspaceRoot;
135
+ this.platform = platform;
122
136
  }
123
137
  /**
124
138
  * On a connection failure, attempt to start the daemon (idempotent lato
@@ -127,7 +141,8 @@ export class DaemonClient {
127
141
  * fails re-spawns it (after SPAWN_COOLDOWN_MS). Silent: success = next retry
128
142
  * connects; failure = the ordinary retry/error path surfaces a clear error
129
143
  * with the registry candidates and the daemon log tail. Disable via
130
- * VEXP_NO_AUTOSTART=1.
144
+ * VEXP_NO_AUTOSTART=1. The rules for when it may start one are in lockstep
145
+ * with vexp-core mcp_stdio::why_no_daemon_start, the server Codex runs.
131
146
  */
132
147
  async maybeSpawnDaemon() {
133
148
  const now = Date.now();
@@ -136,7 +151,11 @@ export class DaemonClient {
136
151
  this.lastSpawnAttemptMs = now;
137
152
  if (process.env.VEXP_NO_AUTOSTART === "1")
138
153
  return;
139
- const workspaceRoot = resolveWorkspaceRoot(this.spawnWorkspaceRoot);
154
+ // A subfolder of a fresh linked worktree starts that worktree's daemon
155
+ // (daemonStartRoot): the consent, the quota marker and the start below
156
+ // all belong to the worktree root, which the registry then routes the
157
+ // subfolder to.
158
+ const workspaceRoot = daemonStartRoot(resolveWorkspaceRoot(this.spawnWorkspaceRoot));
140
159
  // Never resurrect a daemon that stopped on purpose: it would re-exit on its
141
160
  // first quota check. `call()` already answers this case before reaching us;
142
161
  // the guard keeps the contract true for any other caller.
@@ -149,12 +168,17 @@ export class DaemonClient {
149
168
  // `git worktree remove` (git unregisters the worktree and leaves the
150
169
  // folder behind; reproduced on Windows 11, 2026-09-30).
151
170
  if (!setUpForVexp(workspaceRoot) &&
152
- !(process.platform !== "win32" && worktreeConsentSource(workspaceRoot)))
171
+ !(this.platform !== "win32" && worktreeConsentSource(workspaceRoot)))
153
172
  return;
154
173
  // The daemon refuses the home directory itself; not asking spares the
155
174
  // spawn and the "daemon did not start" it would answer with.
156
175
  if (isVexpStateHome(workspaceRoot))
157
176
  return;
177
+ // Found by walking up from a git repository of its own, nobody set this
178
+ // session's folder up: a stale .vexp above it gets no daemon, which would
179
+ // index all of that folder. Lockstep with vexp-core cmd_mcp.
180
+ if (!this.spawnWorkspaceRoot && resolveWorkspaceWithSource().source === "cwd-discovery" && gitRepoBelow(workspaceRoot, process.cwd()))
181
+ return;
158
182
  const binary = resolveVexpCoreBinary();
159
183
  if (!binary)
160
184
  return;
@@ -164,6 +188,9 @@ export class DaemonClient {
164
188
  // unrelated cwd / a stripped env (e.g. the detached HTTP supervisor).
165
189
  const env = binaryEnvFor(binary);
166
190
  env.VEXP_WORKSPACE = workspaceRoot;
191
+ // Started for an agent's session: unused, it stops by itself and frees
192
+ // its slot of the plan's daemon cap (vexp-core idle.rs, every agent alike).
193
+ env.VEXP_DAEMON_OWNER = "agent";
167
194
  // `detached` stays (DETACHED_PROCESS on Windows): a non-detached child
168
195
  // would sit in libuv's kill-on-close job object and go down with this
169
196
  // server. The daemon this starts has no console either; its git
@@ -247,6 +274,10 @@ export class DaemonClient {
247
274
  // ignored next to it.
248
275
  const env = binaryEnvFor(binary);
249
276
  env.VEXP_WORKSPACE = workspaceRoot;
277
+ // The owner it had: an upgrade does not put a daemon started by hand on
278
+ // the agent's idle stop. (On Windows a held lock cannot be read: no owner.)
279
+ if (startedForAgent(workspaceRoot))
280
+ env.VEXP_DAEMON_OWNER = "agent";
250
281
  const child = spawn(binary, ["daemon-cmd", "restart"], {
251
282
  cwd: workspaceRoot,
252
283
  stdio: "ignore",
@@ -290,6 +321,8 @@ export class DaemonClient {
290
321
  get socketPath() {
291
322
  if (this.explicitSocketPath)
292
323
  return this.explicitSocketPath;
324
+ if (this.workspaceDaemonSocket)
325
+ return this.workspaceDaemonSocket;
293
326
  // HTTP per-workspace client: target this workspace's deterministic socket
294
327
  // so a freshly respawned daemon is reconnected even if the registry was
295
328
  // stale/missing when the request arrived.
@@ -334,6 +367,17 @@ export class DaemonClient {
334
367
  }
335
368
  catch (err) {
336
369
  lastError = err instanceof Error ? err : new Error(String(err));
370
+ // A connected repo has no daemon of its own while its workspace's is
371
+ // up (the engine's parent-workspace guard): the start below did
372
+ // nothing, and three retries failed on a socket nobody would bind.
373
+ if (attempt === 0 && DaemonClient.isRetryableError(lastError) && !this.explicitSocketPath) {
374
+ this.workspaceDaemonSocket = undefined;
375
+ const found = await this.findWorkspaceDaemon();
376
+ if (found === "serves")
377
+ continue;
378
+ if (found)
379
+ throw new Error(found);
380
+ }
337
381
  // An unreachable daemon may be down BY DESIGN (free-tier quota spent).
338
382
  // Answer that in words and stop here: retrying would respawn a daemon
339
383
  // that re-exits on its next quota check, and the agent would only ever
@@ -343,6 +387,16 @@ export class DaemonClient {
343
387
  if (quota)
344
388
  throw dailyLimitError(quota);
345
389
  }
390
+ // A fresh git worktree on Windows: no daemon of its own, and
391
+ // maybeSpawnDaemon starts none there. The registry no longer hands it
392
+ // the main checkout's daemon (that index leaves the worktree out), so
393
+ // the retries below could only end in a raw `connect ENOENT` on the
394
+ // worktree's pipe. Say what is going on and what to do, once.
395
+ if (attempt === 0 && DaemonClient.isRetryableError(lastError) && !this.explicitSocketPath) {
396
+ const worktree = windowsWorktreeWithoutDaemon(resolveWorkspaceRoot(this.spawnWorkspaceRoot), this.platform);
397
+ if (worktree)
398
+ throw new Error(worktree);
399
+ }
346
400
  if (attempt < DaemonClient.MAX_RETRIES && DaemonClient.isRetryableError(lastError)) {
347
401
  // On the first failure, (re)start the daemon (cooldown-gated so a
348
402
  // long-lived supervisor can resurrect it whenever it dies).
@@ -360,6 +414,33 @@ export class DaemonClient {
360
414
  }
361
415
  throw this.augmentDaemonError(lastError);
362
416
  }
417
+ /** For a connected repo whose workspace daemon answers: "serves", with the
418
+ * socket kept for this client, or the words for a repo the plan left out of
419
+ * it. Null when this is no connected repo or that daemon is not up, and the
420
+ * ordinary start applies. Lockstep with vexp-core main.rs workspace_daemon. */
421
+ async findWorkspaceDaemon() {
422
+ const repoRoot = resolveWorkspaceRoot(this.spawnWorkspaceRoot);
423
+ const parentRoot = parentWorkspaceOf(repoRoot);
424
+ if (!parentRoot)
425
+ return null;
426
+ const socket = socketPathForWorkspace(parentRoot);
427
+ let status;
428
+ try {
429
+ const asked = new DaemonClient(socket, this.sessionId).callOnce("index_status", {});
430
+ const cap = new Promise((r) => setTimeout(() => r("no answer"), 3_000).unref());
431
+ status = await Promise.race([asked, cap]);
432
+ }
433
+ catch {
434
+ return null;
435
+ }
436
+ if (status !== "no answer" && !statusServesRepo(status, repoRoot)) {
437
+ return (`${repoRoot} is a connected repo of the workspace at ${parentRoot}, whose daemon does not ` +
438
+ `serve it: the plan's repo limit left it out (see \`vexp doctor\`). AGENT INSTRUCTION: this ` +
439
+ `repository has no vexp index available here; continue with your own tools and tell the user.`);
440
+ }
441
+ this.workspaceDaemonSocket = socket;
442
+ return "serves";
443
+ }
363
444
  /** What we say when the daemon took the request and then went away.
364
445
  *
365
446
  * The lockstep twin of `daemon_gone_message` in
@@ -602,6 +683,27 @@ export class DaemonClient {
602
683
  });
603
684
  });
604
685
  }
686
+ /**
687
+ * The workspace whose index answers this client when it is not the
688
+ * target's and cannot hold the target ({@link foreignIndexRoot}), with
689
+ * the target, or null. For run_pipeline's header, read after the call so it
690
+ * names the daemon that answered. Only for a client that resolves its
691
+ * target from the env, the cwd and the registry: one given its socket, an
692
+ * HTTP client pinned to its workspace and a connected repo talking to its
693
+ * workspace's daemon reach what they were sent to.
694
+ */
695
+ foreignIndex() {
696
+ if (this.explicitSocketPath || this.spawnWorkspaceRoot || this.workspaceDaemonSocket)
697
+ return null;
698
+ try {
699
+ const t = resolveTargeting();
700
+ const served = foreignIndexRoot(t);
701
+ return served ? { served, target: t.workspaceRoot } : null;
702
+ }
703
+ catch {
704
+ return null;
705
+ }
706
+ }
605
707
  /**
606
708
  * Verifica se il daemon è raggiungibile
607
709
  */
@@ -720,9 +822,10 @@ export function isVexpStateHome(dir) {
720
822
  * commit vexp.toml instead, and a fresh clone still starts vexp at an
721
823
  * agent's first call (field report, 2026-10-23).
722
824
  *
723
- * Never a bare .vexp/: vexp-core creates one wherever it computes a socket
724
- * path. Never .vexp/.gitignore: the daemon writes it at every start, and
725
- * personal mode commits one to keep vexp to the person who set it up.
825
+ * Never a bare .vexp/: vexp-core created one wherever it computed a socket
826
+ * path, and those are still about. Never .vexp/.gitignore: the daemon
827
+ * writes it at every start, and personal mode commits one to keep vexp to
828
+ * the person who set it up.
726
829
  *
727
830
  * LOCAL_INDEX counts too: index.db is never committed, so it says vexp was
728
831
  * run in this folder on this machine, and Codex's own server (vexp-core
@@ -749,6 +852,63 @@ export function setUpForVexp(dir) {
749
852
  * git_project_root.
750
853
  */
751
854
  export function worktreeConsentSource(dir) {
855
+ const main = linkedWorktreeMain(dir);
856
+ if (!main || isVexpStateHome(main))
857
+ return null;
858
+ const vexp = path.join(main, ".vexp");
859
+ return fs.existsSync(path.join(vexp, "manifest.json")) || fs.existsSync(path.join(vexp, "index.db"))
860
+ ? main
861
+ : null;
862
+ }
863
+ /**
864
+ * Why no agent session starts a daemon for the git worktree `worktree` of
865
+ * `main` on Windows: a daemon holds the worktree's index open past the
866
+ * session, and Windows then refuses `git worktree remove` (git unregisters
867
+ * the worktree and leaves the folder behind; reproduced on Windows 11,
868
+ * 2026-09-30). ASCII, word for word vexp-core's
869
+ * mcp_stdio::worktree_no_daemon_on_windows (a test reads both).
870
+ */
871
+ export function worktreeNoDaemonOnWindows(worktree, main) {
872
+ return `${worktree} is a git worktree of ${main}, and on Windows vexp starts no daemon for it from an agent session: a running daemon would keep the worktree's index open, and Windows would then refuse 'git worktree remove'`;
873
+ }
874
+ /**
875
+ * What an agent reads when its session is in a git worktree that has no
876
+ * daemon of its own, on Windows (`platform`), where this server starts
877
+ * none for it (maybeSpawnDaemon): the worktree, why, and the one remedy, in
878
+ * one line. null anywhere else: a worktree set up on its own
879
+ * (setUpForVexp, a window's "vexp: Start Indexing" leaves its index.db),
880
+ * any other OS, a folder that is no worktree of a set-up checkout.
881
+ *
882
+ * Without it the session got `connect ENOENT \\.\pipe\vexp-<hash>` and a
883
+ * targeting dump; before 3.4 it was answered from the main checkout's index,
884
+ * which leaves the worktree's files out. vexp-core's own server serves such
885
+ * a worktree in-process instead (cmd_mcp), so only this one says it.
886
+ */
887
+ export function windowsWorktreeWithoutDaemon(target, platform = process.platform) {
888
+ if (platform !== "win32")
889
+ return null;
890
+ // A subfolder of the worktree names the worktree, the folder to open in VS
891
+ // Code (daemonStartRoot, the root maybeSpawnDaemon would start).
892
+ const workspaceRoot = daemonStartRoot(target);
893
+ if (setUpForVexp(workspaceRoot))
894
+ return null;
895
+ const main = worktreeConsentSource(workspaceRoot);
896
+ if (!main)
897
+ return null;
898
+ return (`${worktreeNoDaemonOnWindows(workspaceRoot, main)}. To index this worktree, open ${workspaceRoot} in VS Code ` +
899
+ `and run "vexp: Start Indexing". AGENT INSTRUCTION: do not retry; continue with your own tools and tell the user.`);
900
+ }
901
+ /**
902
+ * The main checkout of the linked git worktree whose root is `dir`, read
903
+ * from its `.git` FILE (`gitdir: <main>/.git/worktrees/<name>`; git 2.48's
904
+ * relative form resolves against `dir`), or null: a `.git` folder (the main
905
+ * checkout, a nested clone), a submodule (`.git/modules/`, or
906
+ * `.git/worktrees/<wt>/modules/` for one checked out inside a linked
907
+ * worktree), no `.git`.
908
+ * Decided by the file's content, never by where the folder sits. Lockstep
909
+ * with vexp-core utils::git_project_root / is_linked_worktree.
910
+ */
911
+ export function linkedWorktreeMain(dir) {
752
912
  let content;
753
913
  try {
754
914
  if (!fs.statSync(path.join(dir, ".git")).isFile())
@@ -768,53 +928,120 @@ export function worktreeConsentSource(dir) {
768
928
  const at = gitdir ? gitdir.indexOf("/.git/worktrees/") : -1;
769
929
  if (!gitdir || at <= 0)
770
930
  return null;
771
- const main = path.resolve(dir, gitdir.slice(0, at));
772
- if (isVexpStateHome(main))
931
+ // A worktree's admin dir is one folder, <common>/.git/worktrees/<name>. A
932
+ // submodule checked out inside a linked worktree has its git dir under
933
+ // that admin dir (<main>/.git/worktrees/<wt>/modules/<path>): it is its
934
+ // own project, as a submodule of the main checkout is, and reading it as
935
+ // a worktree of <main> lent it <main>'s consent and a daemon. Lockstep
936
+ // with vexp-core utils::git_project_root.
937
+ const name = gitdir.slice(at + "/.git/worktrees/".length).replace(/\/+$/, "");
938
+ if (!name || name.includes("/"))
773
939
  return null;
774
- const vexp = path.join(main, ".vexp");
775
- return fs.existsSync(path.join(vexp, "manifest.json")) || fs.existsSync(path.join(vexp, "index.db"))
776
- ? main
777
- : null;
940
+ const main = path.resolve(dir, gitdir.slice(0, at));
941
+ // A gitdir naming the folder itself links to no other checkout (vexp-core:
942
+ // git_project_root(dir) == dir is no worktree).
943
+ return main === path.resolve(dir) ? null : main;
778
944
  }
779
945
  /**
780
- * Walk up from cwd looking for .vexp/ or .git/ to find the workspace root.
781
- * Used when VEXP_WORKSPACE is not set (e.g., agent spawns MCP server
782
- * without passing the workspace path).
946
+ * The nearest folder at or above `start` that is the root of a linked git
947
+ * worktree, or null.
948
+ *
949
+ * Every worktree is a full checkout of its own, and the index of a folder
950
+ * above it never holds its files: the walk and the watcher prune any nested
951
+ * `.git` (vexp-core is_nested_git_checkout). So a worktree root is a wall
952
+ * for every search that walks up from inside it: discovery stops there, and
953
+ * the daemon registry never hands out a socket registered above it. Agent
954
+ * harnesses put worktrees inside the main checkout (`.worktrees/x`,
955
+ * `.claude/worktrees/agent-*`), and a fresh one was answered from the main
956
+ * checkout's index, with the main checkout's files (field report, devcontainer
957
+ * with `.worktrees/` under the repository, 2026-11).
783
958
  */
784
- function discoverWorkspaceRoot() {
785
- const cwd = process.cwd();
959
+ export function linkedWorktreeRootOf(start) {
960
+ let current = path.resolve(start);
961
+ while (true) {
962
+ if (linkedWorktreeMain(current))
963
+ return current;
964
+ const parent = path.dirname(current);
965
+ if (parent === current)
966
+ return null;
967
+ current = parent;
968
+ }
969
+ }
970
+ /**
971
+ * The folder a daemon is started for when a session's workspace is `dir`:
972
+ * `dir` itself, unless `dir` is not set up on its own and sits inside a
973
+ * linked git worktree with no other checkout between them, where it is that
974
+ * worktree's root.
975
+ *
976
+ * A session opened on a subfolder of a fresh worktree (Claude Code started
977
+ * in <wt>/src sets CLAUDE_PROJECT_DIR there) got no daemon at all: the
978
+ * registry no longer hands it the main checkout's daemon (that index leaves
979
+ * the worktree out), and the consent check read the subfolder, which has no
980
+ * .git of its own and so no inherited consent. The worktree's daemon, once
981
+ * started, answers the subfolder through the registry's prefix match.
982
+ *
983
+ * The walk stops at the first `.git`: a nested clone or a submodule between
984
+ * the subfolder and the worktree is a project of its own and keeps today's
985
+ * rule, and so does any normal checkout (its nearest `.git` is a folder).
986
+ */
987
+ export function daemonStartRoot(dir) {
988
+ if (setUpForVexp(dir))
989
+ return dir;
990
+ let current = path.resolve(dir);
991
+ while (true) {
992
+ if (fs.existsSync(path.join(current, ".git")))
993
+ return linkedWorktreeMain(current) ? current : dir;
994
+ const parent = path.dirname(current);
995
+ if (parent === current)
996
+ return dir;
997
+ current = parent;
998
+ }
999
+ }
1000
+ /**
1001
+ * Walk up from `start` (the cwd) looking for .vexp/ or .git/ to find the
1002
+ * workspace root. Used when VEXP_WORKSPACE is not set (e.g., agent spawns
1003
+ * MCP server without passing the workspace path).
1004
+ *
1005
+ * Passes 1 and 2 never climb past the root of a linked git worktree
1006
+ * ({@link linkedWorktreeRootOf}): inside one, the worktree itself is the
1007
+ * root (pass 3), with no .vexp/ yet if it is fresh, and the main checkout
1008
+ * above it only lends its consent (worktreeConsentSource). An ancestor's
1009
+ * .vexp/ never answers for it. A nested clone (a `.git` folder) and a
1010
+ * submodule keep the rule they had. Lockstep with vexp-core
1011
+ * utils::discover_workspace_root, which walks the same folders.
1012
+ */
1013
+ function discoverWorkspaceRoot(start = process.cwd()) {
1014
+ const cwd = path.resolve(start);
1015
+ const boundary = linkedWorktreeRootOf(cwd);
1016
+ const up = (dir) => {
1017
+ if (dir === boundary)
1018
+ return null;
1019
+ const parent = path.dirname(dir);
1020
+ return parent === dir ? null : parent;
1021
+ };
786
1022
  // Pass 1: nearest ancestor with an INITIALIZED .vexp/ (manifest.json or
787
1023
  // index.db) — a real indexed workspace, not a stray/empty .vexp/ dir. The
788
1024
  // home directory never qualifies (isVexpStateHome).
789
1025
  // MUST stay in lockstep with vexp-core/src/utils.rs::discover_workspace_root.
790
- let current = cwd;
791
- while (true) {
1026
+ for (let current = cwd; current; current = up(current)) {
792
1027
  const vexp = path.join(current, ".vexp");
793
1028
  if ((fs.existsSync(path.join(vexp, "manifest.json")) || fs.existsSync(path.join(vexp, "index.db"))) &&
794
1029
  !isVexpStateHome(current)) {
795
1030
  return current;
796
1031
  }
797
- const parent = path.dirname(current);
798
- if (parent === current)
799
- break;
800
- current = parent;
801
1032
  }
802
1033
  // Pass 2: nearest ancestor with a bare .vexp/ (workspace mid-first-index)
803
1034
  // — except the home/VEXP_HOME directory, whose .vexp is vexp's own STATE
804
1035
  // dir: treating it as a workspace let an agent that spawns servers from
805
1036
  // the home dir target the whole home (field report, 2026-09-02). Lockstep
806
1037
  // with vexp-core utils::discover_workspace_root.
807
- current = cwd;
808
- while (true) {
1038
+ for (let current = cwd; current; current = up(current)) {
809
1039
  if (fs.existsSync(path.join(current, ".vexp")) && !isVexpStateHome(current))
810
1040
  return current;
811
- const parent = path.dirname(current);
812
- if (parent === current)
813
- break;
814
- current = parent;
815
1041
  }
816
- // Pass 3: .git/ fallback.
817
- current = cwd;
1042
+ // Pass 3: .git/ fallback. Within a linked worktree this is the worktree
1043
+ // itself, or a nested repository between it and the cwd.
1044
+ let current = cwd;
818
1045
  while (true) {
819
1046
  const gitDir = path.join(current, ".git");
820
1047
  if (fs.existsSync(gitDir))
@@ -836,6 +1063,23 @@ function warnOnce(msg) {
836
1063
  _warnedOnce.add(msg);
837
1064
  console.error(msg);
838
1065
  }
1066
+ /**
1067
+ * The value of a workspace variable, or undefined when it is unset, empty,
1068
+ * blank, or still holds an editor variable (`${workspaceFolder}`, anything
1069
+ * with `${`). vexp writes `"VEXP_WORKSPACE": "${workspaceFolder}"` into
1070
+ * .vscode/mcp.json so a committed file names no checkout; every VS Code that
1071
+ * reads that file (1.99+) expands it before it starts the server, or does
1072
+ * not start it. The literal text arrives from a .mcp.json entry (VS Code
1073
+ * 1.142+ expands only `${NAME}` from its own environment there) or a client
1074
+ * that expands nothing. Unset, the next signal decides: CLAUDE_PROJECT_DIR,
1075
+ * then the cwd, which VS Code sets to the folder that holds the file
1076
+ * (1.101.1+, and for .mcp.json). Lockstep
1077
+ * with vexp-core utils::workspace_env_value, which cmd_mcp reads them with.
1078
+ */
1079
+ export function workspaceEnv(name) {
1080
+ const value = process.env[name];
1081
+ return value && value.trim() !== "" && !value.includes("${") ? value : undefined;
1082
+ }
839
1083
  /**
840
1084
  * Decide the workspace root AND which signal chose it. Single source of truth
841
1085
  * for {@link resolveWorkspaceRoot} and {@link resolveTargeting} so they cannot
@@ -862,8 +1106,8 @@ function warnOnce(msg) {
862
1106
  function resolveWorkspaceWithSource(explicit) {
863
1107
  if (explicit)
864
1108
  return { root: explicit, source: "VEXP_WORKSPACE" };
865
- const vw = process.env["VEXP_WORKSPACE"];
866
- const cpd = process.env["CLAUDE_PROJECT_DIR"];
1109
+ const vw = workspaceEnv("VEXP_WORKSPACE");
1110
+ const cpd = workspaceEnv("CLAUDE_PROJECT_DIR");
867
1111
  if (vw && cpd && canonicalWorkspaceRoot(path.resolve(vw)).toLowerCase() !== canonicalWorkspaceRoot(path.resolve(cpd)).toLowerCase()) {
868
1112
  warnOnce(`[vexp-mcp] VEXP_WORKSPACE=${vw} disagrees with this session's ` +
869
1113
  `CLAUDE_PROJECT_DIR=${cpd}; using CLAUDE_PROJECT_DIR for per-session ` +
@@ -894,7 +1138,13 @@ export function resolveWorkspaceRoot(explicit) {
894
1138
  * Selection policy:
895
1139
  * 1. Exact workspace match
896
1140
  * 2. Longest workspace that is a prefix of `workspaceHint` (handles
897
- * submodule / nested-directory cwd pointing at a parent daemon)
1141
+ * submodule / nested-directory cwd pointing at a parent daemon), never
1142
+ * one above the root of a linked git worktree the hint sits in
1143
+ * ({@link linkedWorktreeRootOf}): that daemon's index leaves the
1144
+ * worktree out, and answering from it served the main checkout's files
1145
+ * to a session pinned to the worktree whenever the main checkout's
1146
+ * daemon happened to be up. With no daemon of its own, the worktree's is
1147
+ * started (maybeSpawnDaemon, with the main checkout's consent).
898
1148
  * 3. Otherwise `null` (caller surfaces a clear "no daemon for this workspace"
899
1149
  * error and/or respawns the right one).
900
1150
  *
@@ -905,6 +1155,11 @@ export function resolveWorkspaceRoot(explicit) {
905
1155
  * / spawn path, never to an unrelated repo.
906
1156
  */
907
1157
  function pickFromDaemonRegistry(workspaceHint) {
1158
+ return pickRegistryEntry(workspaceHint)?.[1] ?? null;
1159
+ }
1160
+ /** {@link pickFromDaemonRegistry}, with the workspace the picked daemon
1161
+ * registered: `[workspace, socket]`. */
1162
+ function pickRegistryEntry(workspaceHint) {
908
1163
  const home = process.env.HOME ?? process.env.USERPROFILE ?? "";
909
1164
  if (!home)
910
1165
  return null;
@@ -936,22 +1191,32 @@ function pickFromDaemonRegistry(workspaceHint) {
936
1191
  const hintNorm = canonicalWorkspaceRoot(workspaceHint).toLowerCase();
937
1192
  for (const [ws, sock] of entries) {
938
1193
  if (ws.toLowerCase() === hintNorm)
939
- return sock;
1194
+ return [ws, sock];
940
1195
  }
1196
+ // An ancestor's daemon counts only at or below the worktree root the hint
1197
+ // sits in: both are prefixes of the hint, so "at or below" is "at least as
1198
+ // long".
1199
+ const worktree = linkedWorktreeRootOf(workspaceHint);
1200
+ const floor = worktree ? canonicalWorkspaceRoot(worktree).length : 0;
941
1201
  let bestWs = "";
942
- let bestSock = null;
1202
+ let best = null;
943
1203
  for (const [ws, sock] of entries) {
944
1204
  const wsNorm = ws.toLowerCase();
1205
+ if (wsNorm.length < floor)
1206
+ continue;
945
1207
  if (hintNorm.startsWith(wsNorm + path.sep) || hintNorm === wsNorm) {
946
1208
  if (wsNorm.length > bestWs.length) {
947
1209
  bestWs = wsNorm;
948
- bestSock = sock;
1210
+ best = [ws, sock];
949
1211
  }
950
1212
  }
951
1213
  }
952
- if (bestSock)
953
- return bestSock;
954
- return null;
1214
+ return best;
1215
+ }
1216
+ /** The workspace a live daemon registered for `socket`, or null. */
1217
+ function registeredWorkspaceOf(socket) {
1218
+ const hit = liveDaemonEntries().find(([, sock]) => sock === socket);
1219
+ return hit ? hit[0] : null;
955
1220
  }
956
1221
  /** All live `[workspace, socket]` entries in `~/.vexp/daemons.json`, dropping
957
1222
  * stale ones whose socket no longer exists (same liveness filter as
@@ -1003,7 +1268,8 @@ export function resolveTargeting() {
1003
1268
  const { root: workspaceRoot, source } = resolveWorkspaceWithSource();
1004
1269
  const explicit = process.env["VEXP_SOCKET"];
1005
1270
  if (explicit) {
1006
- return { socket: explicit, source, socketOrigin: "explicit", workspaceRoot };
1271
+ const daemonRoot = registeredWorkspaceOf(explicit) ?? undefined;
1272
+ return { socket: explicit, source, socketOrigin: "explicit", workspaceRoot, daemonRoot };
1007
1273
  }
1008
1274
  if (process.platform === "win32") {
1009
1275
  // Workspace-specific pipe name file written by the daemon
@@ -1011,27 +1277,79 @@ export function resolveTargeting() {
1011
1277
  try {
1012
1278
  const pipeName = fs.readFileSync(pipeFile, "utf-8").trim();
1013
1279
  if (pipeName)
1014
- return { socket: pipeName, source, socketOrigin: "workspace-local", workspaceRoot };
1280
+ return { socket: pipeName, source, socketOrigin: "workspace-local", workspaceRoot, daemonRoot: workspaceRoot };
1015
1281
  }
1016
1282
  catch { /* missing */ }
1017
1283
  // Registry
1018
- const fromRegistry = pickFromDaemonRegistry(workspaceRoot);
1019
- if (fromRegistry)
1020
- return { socket: fromRegistry, source, socketOrigin: "registry", workspaceRoot };
1284
+ const fromRegistry = pickRegistryEntry(workspaceRoot);
1285
+ if (fromRegistry) {
1286
+ return { socket: fromRegistry[1], source, socketOrigin: "registry", workspaceRoot, daemonRoot: fromRegistry[0] };
1287
+ }
1021
1288
  // Hash-based last-ditch (daemon should always register, so this is rare)
1022
1289
  const hash = fnvHash(canonicalWorkspaceRoot(workspaceRoot).toLowerCase());
1023
- return { socket: `\\\\.\\pipe\\vexp-${hash.slice(0, 8)}`, source, socketOrigin: "hash-fallback", workspaceRoot };
1290
+ return {
1291
+ socket: `\\\\.\\pipe\\vexp-${hash.slice(0, 8)}`,
1292
+ source,
1293
+ socketOrigin: "hash-fallback",
1294
+ workspaceRoot,
1295
+ daemonRoot: workspaceRoot,
1296
+ };
1024
1297
  }
1025
1298
  // Unix: prefer workspace-local if the socket file actually exists
1026
1299
  const cwdSocket = path.join(workspaceRoot, ".vexp", "daemon.sock");
1027
- if (fs.existsSync(cwdSocket))
1028
- return { socket: cwdSocket, source, socketOrigin: "workspace-local", workspaceRoot };
1300
+ if (fs.existsSync(cwdSocket)) {
1301
+ return { socket: cwdSocket, source, socketOrigin: "workspace-local", workspaceRoot, daemonRoot: workspaceRoot };
1302
+ }
1029
1303
  // Registry (Linux + macOS)
1030
- const fromRegistry = pickFromDaemonRegistry(workspaceRoot);
1031
- if (fromRegistry)
1032
- return { socket: fromRegistry, source, socketOrigin: "registry", workspaceRoot };
1304
+ const fromRegistry = pickRegistryEntry(workspaceRoot);
1305
+ if (fromRegistry) {
1306
+ return { socket: fromRegistry[1], source, socketOrigin: "registry", workspaceRoot, daemonRoot: fromRegistry[0] };
1307
+ }
1033
1308
  return { socket: null, source, socketOrigin: "none", workspaceRoot };
1034
1309
  }
1310
+ /**
1311
+ * The workspace whose index answers for `t` when that index cannot hold
1312
+ * the target's files, or null.
1313
+ *
1314
+ * It cannot when the daemon reached is another root's (an ancestor's,
1315
+ * through the registry, or the one VEXP_SOCKET names) and the target lies
1316
+ * outside that root or inside a nested checkout below it: the walk and the
1317
+ * watcher prune every folder below the root that holds a `.git` file or
1318
+ * folder (vexp-core is_nested_git_checkout), so a nested clone, a submodule
1319
+ * or a worktree is never in it. A folder inside the root with no checkout
1320
+ * between them is in its index (a session opened on a subfolder), and a
1321
+ * repository the served root's workspace.json connects, and any folder
1322
+ * inside it, is served by that daemon on purpose: null for both. run_pipeline's header says it, because
1323
+ * its answers otherwise read as the target's (field report, 2026-11).
1324
+ */
1325
+ export function foreignIndexRoot(t) {
1326
+ const served = t.daemonRoot;
1327
+ if (!served)
1328
+ return null;
1329
+ const norm = (p) => canonicalWorkspaceRoot(path.resolve(p)).replace(/[\\/]+$/, "").toLowerCase();
1330
+ const top = norm(served);
1331
+ const target = path.resolve(t.workspaceRoot);
1332
+ if (norm(target) === top)
1333
+ return null;
1334
+ // Walk from the target up to the checkout that holds it: the first folder
1335
+ // the served root's workspace connects (or whose backlink names it) is
1336
+ // served on purpose, whatever subfolder the session opened; the first
1337
+ // other folder with a .git is a checkout that index prunes; reaching the
1338
+ // served root means a plain subfolder of it. Deciding on the target alone
1339
+ // reported a subfolder of a connected repo (/work/repoA/sub) as foreign on
1340
+ // every call, though /work's daemon serves it (review, 2026-11-07).
1341
+ for (let current = target;; current = path.dirname(current)) {
1342
+ if (norm(current) === top)
1343
+ return null;
1344
+ const parent = parentWorkspaceOf(current);
1345
+ if (workspaceConnects(served, current) || (parent && norm(parent) === top))
1346
+ return null;
1347
+ if (fs.existsSync(path.join(current, ".git")))
1348
+ return served;
1349
+ if (path.dirname(current) === current)
1350
+ return served;
1351
+ }
1352
+ }
1035
1353
  /** Resolve the daemon socket path / named pipe (metadata discarded). */
1036
1354
  export function resolveDaemonSocket() {
1037
1355
  return resolveTargeting().socket;
@@ -1070,14 +1388,16 @@ export function targetingDiagnostic() {
1070
1388
  // daemon is down".
1071
1389
  const unresolved = t.source === "cwd-discovery" && !indexed;
1072
1390
  const live = liveDaemonEntries();
1391
+ // A value workspaceEnv set aside is shown as it came, and why it was not used.
1392
+ const shown = (raw, used) => !raw ? "(not set)" : used ? raw : `${raw} (not expanded by the editor: ignored)`;
1073
1393
  const lines = [
1074
1394
  "",
1075
1395
  "--- vexp targeting diagnostics ---",
1076
1396
  "The MCP server could not reach a vexp daemon for this session.",
1077
1397
  "",
1078
1398
  "Workspace resolution:",
1079
- ` VEXP_WORKSPACE ${vw || "(not set)"}`,
1080
- ` CLAUDE_PROJECT_DIR ${cpd || "(not set)"}`,
1399
+ ` VEXP_WORKSPACE ${shown(vw, workspaceEnv("VEXP_WORKSPACE"))}`,
1400
+ ` CLAUDE_PROJECT_DIR ${shown(cpd, workspaceEnv("CLAUDE_PROJECT_DIR"))}`,
1081
1401
  ` resolved workspace ${t.workspaceRoot} (via ${t.source}` +
1082
1402
  `${unresolved ? " — no indexed .vexp/ found walking up from cwd" : ""})`,
1083
1403
  ` socket tried ${sockTried}${sockExists ? "" : " (missing)"}`,
@@ -1202,11 +1522,121 @@ export function canonicalWorkspaceRoot(root) {
1202
1522
  }
1203
1523
  /** Deterministic socket/pipe path for a workspace root — mirrors the Rust
1204
1524
  * daemon's get_socket_path (vexp-core/src/utils.rs). */
1205
- function socketPathForWorkspace(ws) {
1525
+ /** The root of the multi-repo workspace `repoRoot` is a connected repo of, or
1526
+ * null: only while the parent config still exists and still lists it, so a
1527
+ * stale backlink never redirects. Lockstep with vexp-core main.rs
1528
+ * parent_workspace_redirect and the extension's resolveParentRedirect. */
1529
+ export function parentWorkspaceOf(repoRoot) {
1530
+ try {
1531
+ const backlink = JSON.parse(fs.readFileSync(path.join(repoRoot, ".vexp", "parent_workspace.json"), "utf-8"));
1532
+ if (typeof backlink?.workspace_config !== "string")
1533
+ return null;
1534
+ const configPath = backlink.workspace_config;
1535
+ const parentRoot = path.dirname(path.dirname(configPath));
1536
+ const self = path.resolve(repoRoot);
1537
+ if (path.resolve(parentRoot) === self)
1538
+ return null;
1539
+ return configListsRepo(configPath, parentRoot, self) ? parentRoot : null;
1540
+ }
1541
+ catch {
1542
+ return null;
1543
+ }
1544
+ }
1545
+ /** Whether the workspace.json at `configPath`, of the multi-repo workspace
1546
+ * at `parentRoot`, lists the repository at `self` (resolved). Throws when
1547
+ * the config cannot be read. */
1548
+ function configListsRepo(configPath, parentRoot, self) {
1549
+ const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
1550
+ if (!Array.isArray(config.repos))
1551
+ return false;
1552
+ return config.repos.some((r) => {
1553
+ if (typeof r?.path !== "string")
1554
+ return false;
1555
+ if (path.isAbsolute(r.path))
1556
+ return path.resolve(r.path) === self;
1557
+ return path.resolve(parentRoot, r.path) === self || path.resolve(parentRoot, ".vexp", r.path) === self;
1558
+ });
1559
+ }
1560
+ /** Whether the multi-repo workspace at `parentRoot` connects the repository
1561
+ * at `repoRoot` (its own .vexp/workspace.json lists it). */
1562
+ function workspaceConnects(parentRoot, repoRoot) {
1563
+ try {
1564
+ const self = path.resolve(repoRoot);
1565
+ if (path.resolve(parentRoot) === self)
1566
+ return false;
1567
+ return configListsRepo(path.join(parentRoot, ".vexp", "workspace.json"), parentRoot, self);
1568
+ }
1569
+ catch {
1570
+ return false;
1571
+ }
1572
+ }
1573
+ /** Whether the daemon behind an index_status reply serves `repoRoot`: it lists
1574
+ * it, or it has not reached the plan's repo cap (a daemon answers before it
1575
+ * has loaded the workspace's other repos). Lockstep with vexp-core main.rs
1576
+ * status_serves_repo. */
1577
+ export function statusServesRepo(status, repoRoot) {
1578
+ const st = (status ?? {});
1579
+ const real = (p) => {
1580
+ try {
1581
+ return fs.realpathSync(p);
1582
+ }
1583
+ catch {
1584
+ return path.resolve(p);
1585
+ }
1586
+ };
1587
+ const self = real(repoRoot);
1588
+ const listed = Array.isArray(st.repos) && st.repos.some((r) => typeof r?.path === "string" && r.path !== "" && real(r.path) === self);
1589
+ return listed || st.repos_limit_reached !== true;
1590
+ }
1591
+ export function socketPathForWorkspace(ws) {
1206
1592
  if (process.platform === "win32") {
1207
1593
  return `\\\\.\\pipe\\vexp-${fnvHash(canonicalWorkspaceRoot(ws).toLowerCase()).slice(0, 8)}`;
1208
1594
  }
1209
- return path.join(ws, ".vexp", "daemon.sock");
1595
+ const candidate = path.join(ws, ".vexp", "daemon.sock");
1596
+ // The socket address limit: the engine moves it to /tmp past 100 bytes
1597
+ // (vexp-core utils.rs get_socket_path).
1598
+ if (Buffer.byteLength(candidate) <= 100)
1599
+ return candidate;
1600
+ return `/tmp/vexp-${fnvHash(ws).slice(0, 12)}.sock`;
1601
+ }
1602
+ /** Whether `cwd` sits in a git repository of its own below `root`: a `.git`
1603
+ * directory, or the `.git` file of a linked worktree (a submodule's file
1604
+ * does not count). A worktree takes its main checkout's consent, not its
1605
+ * index, which prunes every nested checkout. Lockstep with vexp-core
1606
+ * utils.rs git_repo_below. */
1607
+ export function gitRepoBelow(root, cwd) {
1608
+ const real = (p) => {
1609
+ try {
1610
+ return fs.realpathSync(p);
1611
+ }
1612
+ catch {
1613
+ return path.resolve(p);
1614
+ }
1615
+ };
1616
+ const top = real(root);
1617
+ let current = real(cwd);
1618
+ while (current !== top && current.startsWith(top + path.sep)) {
1619
+ try {
1620
+ if (fs.statSync(path.join(current, ".git")).isDirectory())
1621
+ return true;
1622
+ }
1623
+ catch { /* none here */ }
1624
+ if (linkedWorktreeMain(current))
1625
+ return true;
1626
+ current = path.dirname(current);
1627
+ }
1628
+ return false;
1629
+ }
1630
+ /** Whether the daemon that last held this workspace's lock was started for an
1631
+ * agent's session (vexp-core index_lock.rs AGENT_DAEMON_ROLE). */
1632
+ export function startedForAgent(workspaceRoot) {
1633
+ try {
1634
+ const lock = JSON.parse(fs.readFileSync(path.join(workspaceRoot, ".vexp", "daemon.lock"), "utf-8"));
1635
+ return lock?.role === "agent daemon";
1636
+ }
1637
+ catch {
1638
+ return false;
1639
+ }
1210
1640
  }
1211
1641
  /** Human-friendly hint printed when a connection attempt fails — enumerates
1212
1642
  * what we tried to make the failure actionable instead of misleading. */
@@ -232,8 +232,13 @@ export function parseEngineVersion(stdout) {
232
232
  return last ? last : undefined;
233
233
  }
234
234
  /**
235
- * The folder `daemon-cmd` works on when run in `dir`: the nearest one with a
236
- * `.git` at or above it, else `dir` itself (find_repo_root in vexp-core).
235
+ * The folder `daemon-cmd` works on when run in `dir` (daemon_cmd_root in
236
+ * vexp-core): the nearest one with a `.git` at or above it, unless that one
237
+ * was never set up for vexp and a folder between it and `dir` was, which
238
+ * is then the nearest such folder; with no `.git` above, `dir` itself. Set
239
+ * up is the engine's is_workspace_marker: one of its consent files in the
240
+ * folder's .vexp/, and neither the home directory nor a filesystem root
241
+ * (forbidden_workspace_reason refuses both).
237
242
  */
238
243
  export function daemonCmdRoot(dir) {
239
244
  let start = path.resolve(dir);
@@ -243,10 +248,16 @@ export function daemonCmdRoot(dir) {
243
248
  catch {
244
249
  /* not there: the spelling given */
245
250
  }
251
+ const setUp = (d) => (process.env.VEXP_ALLOW_HOME_WORKSPACE === "1" ||
252
+ (upgradeAttemptKey(d) !== upgradeAttemptKey(vexpHome()) && path.dirname(d) !== d)) &&
253
+ ["manifest.json", "vexp.toml", "workspace.json", "index.db"].some((f) => fs.existsSync(path.join(d, ".vexp", f)));
254
+ const below = [];
246
255
  let current = start;
247
256
  for (;;) {
248
- if (fs.existsSync(path.join(current, ".git")))
249
- return current;
257
+ if (fs.existsSync(path.join(current, ".git"))) {
258
+ return setUp(current) ? current : (below.find(setUp) ?? current);
259
+ }
260
+ below.push(current);
250
261
  const parent = path.dirname(current);
251
262
  if (parent === current)
252
263
  return start;
@@ -260,8 +271,10 @@ export function daemonCmdRoot(dir) {
260
271
  *
261
272
  * - the stop half reads `<dir>/.vexp/daemon.pid`; with none there it stops
262
273
  * nothing, and the start half then races the daemon that is still up;
263
- * - `daemon-cmd` works on the git root at or above its cwd, so for a
264
- * workspace below one it would start a daemon on the folder above;
274
+ * - `daemon-cmd` works on the git root at or above its cwd unless a folder
275
+ * below an unset-up root was set up on its own (daemonCmdRoot), so for
276
+ * any other workspace below one it would start a daemon on the folder
277
+ * above;
265
278
  * - the engine refuses to start on the home directory, so a daemon an older
266
279
  * build left there would be stopped and not come back.
267
280
  */
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@ import { createServer } from "http";
7
7
  import { randomUUID } from "crypto";
8
8
  import fs from "fs";
9
9
  import path from "path";
10
- import { DaemonClient, resolveSocketByWorkspaceHash, resolveWorkspaceByHash } from "./daemon-client.js";
10
+ import { DaemonClient, resolveSocketByWorkspaceHash, resolveWorkspaceByHash, workspaceEnv } from "./daemon-client.js";
11
11
  import { GET_CONTEXT_CAPSULE_DEFINITION, handleGetContextCapsule, } from "./tools/get-context-capsule.js";
12
12
  import { GET_IMPACT_GRAPH_DEFINITION, handleGetImpactGraph, } from "./tools/get-impact-graph.js";
13
13
  import { SEARCH_LOGIC_FLOW_DEFINITION, handleSearchLogicFlow, } from "./tools/search-logic-flow.js";
@@ -34,44 +34,6 @@ const ALL_TOOL_DEFINITIONS = [
34
34
  EXPAND_VEXP_REF_DEFINITION,
35
35
  VERIFY_DONE_DEFINITION,
36
36
  ];
37
- /**
38
- * Minimal tool surface exposed to agents when VEXP_ALL_TOOLS is not set.
39
- *
40
- * Rationale: `run_pipeline` already subsumes capsule + impact + memory +
41
- * flow + save_observation + session_context internally. Exposing every
42
- * tool just bloats the agent's system prompt. With this set the agent sees
43
- * only the four irreducible capabilities:
44
- * 1. run_pipeline — primary context/impact/memory pipeline
45
- * 2. get_skeleton — file drill-down with detail levels
46
- * 3. index_status — daemon + repo health, discovery
47
- * 4. expand_vexp_ref — required to expand V-REF placeholders in v2
48
- *
49
- * Legacy tools remain registered in the dispatch switch so that any
50
- * existing caller that still sends them gets a normal response —
51
- * nothing is unregistered at the daemon level.
52
- */
53
- const ESSENTIAL_TOOL_DEFINITIONS = [
54
- RUN_PIPELINE_DEFINITION,
55
- GET_SKELETON_DEFINITION,
56
- INDEX_STATUS_DEFINITION,
57
- EXPAND_VEXP_REF_DEFINITION,
58
- VERIFY_DONE_DEFINITION,
59
- ];
60
- /**
61
- * Default surface (2.3.3): the two tools an agent needs up front. Every
62
- * schema in tools/list is resident in the agent's context on EVERY turn —
63
- * measured against true vanilla, the 4-tool surface plus mandate cost more
64
- * than run_pipeline ever saved on oriented tasks. So:
65
- * - `index_status` is diagnostics (vexp doctor / CLI territory) — hidden
66
- * by default, still dispatchable if called.
67
- * - `expand_vexp_ref` is only meaningful AFTER a response contains
68
- * [V-REF:...] placeholders — exposed dynamically at that moment via
69
- * notifications/tools/list_changed. Agents that don't refresh their
70
- * tool list fall back to the in-band alternative every V-REF response
71
- * already suggests ("or Read the file"), and direct calls to the tool
72
- * keep working whether or not it is listed.
73
- * VEXP_ALL_TOOLS=1 restores the full surface.
74
- */
75
37
  /**
76
38
  * Trim a definition down to what `tools/list` has to carry.
77
39
  *
@@ -95,6 +57,9 @@ const LISTING_OVERRIDES = {
95
57
  properties: {
96
58
  task: { type: "string", description: "The task, anchored on real identifiers or paths" },
97
59
  preset: { type: "string", enum: ["auto", "explore", "modify", "debug", "refactor"] },
60
+ // `eager` stays out of the listing, as in vexp-core's: the hint in
61
+ // every compact answer names it ("pass `eager: true` to inline
62
+ // bodies"), and the full schema and dispatch take it.
98
63
  },
99
64
  required: ["task"],
100
65
  },
@@ -119,11 +84,31 @@ const LISTING_OVERRIDES = {
119
84
  "the impacted tests. Run those tests. No parameters.",
120
85
  inputSchema: { type: "object", properties: {} },
121
86
  },
87
+ expand_vexp_ref: {
88
+ // Word for word vexp-core's slim_for_listing (mcp_stdio.rs).
89
+ description: "Fetch the code behind a [V-REF:xxxx] marker left in compressed context - or just Read the file.",
90
+ inputSchema: {
91
+ type: "object",
92
+ properties: { hash: { type: "string" } },
93
+ required: ["hash"],
94
+ },
95
+ },
122
96
  };
123
97
  export function slimForListing(def) {
124
98
  const o = LISTING_OVERRIDES[def.name];
125
99
  return o ? { ...def, description: o.description, inputSchema: o.inputSchema } : def;
126
100
  }
101
+ /**
102
+ * Default listed surface (VEXP_ALL_TOOLS unset): four tools, the ones the
103
+ * native vexp-core server lists (CORE_LISTED_TOOLS in mcp_stdio.rs). Every
104
+ * schema in tools/list is resident in the agent's context on EVERY turn, and
105
+ * measured against true vanilla (2.3.3) a larger surface plus mandate cost
106
+ * more than run_pipeline saved on oriented tasks; run_pipeline already
107
+ * subsumes capsule, impact, flow and memory. The listing is static (see the
108
+ * ListTools handler for why it never changes mid-session), and listing is
109
+ * not authorization: every tool in ALL_TOOL_DEFINITIONS stays dispatchable,
110
+ * index_status included. VEXP_ALL_TOOLS=1 lists the full surface.
111
+ */
127
112
  const MINIMAL_TOOL_DEFINITIONS = [
128
113
  RUN_PIPELINE_DEFINITION,
129
114
  GET_SKELETON_DEFINITION,
@@ -133,6 +118,12 @@ const MINIMAL_TOOL_DEFINITIONS = [
133
118
  // instruction. The Rust server has always listed it; this surface did not
134
119
  // even implement it, and a user found that out for us.
135
120
  VERIFY_DONE_DEFINITION,
121
+ // Listed because this server's answers carry [V-REF:...] markers: compact
122
+ // output (the default) leaves every pivot body behind one. Unlisted, the
123
+ // agents behind .vscode/mcp.json could only Read the whole file for each
124
+ // body (field report, 2026-11: "V-REF needs extra round trips"). Appended,
125
+ // not inserted, so the listing's prefix is what it was.
126
+ EXPAND_VEXP_REF_DEFINITION,
136
127
  ];
137
128
  function allToolsEnabled() {
138
129
  const v = process.env.VEXP_ALL_TOOLS;
@@ -212,8 +203,8 @@ export function createMcpServer(daemon) {
212
203
  // 1,200 tokens over a typical tail. Publishing the change is ~24x worse
213
204
  // than never hiding the tool.
214
205
  //
215
- // So the listing is now static, and the in-band fallback every V-REF
216
- // response already carries ("or Read the file") covers the rest.
206
+ // So the listing is static, and it carries expand_vexp_ref from the first
207
+ // tools/list, as vexp-core's does.
217
208
  server.setRequestHandler(ListToolsRequestSchema, () => ({
218
209
  tools: allToolsEnabled()
219
210
  ? ALL_TOOL_DEFINITIONS
@@ -467,7 +458,8 @@ async function startHttp(fallbackDaemon, port) {
467
458
  httpServer.removeListener("error", onError);
468
459
  console.error(`[vexp-mcp] HTTP server listening on 127.0.0.1:${actualPort}`);
469
460
  // Write actual port and token so the extension and agent configs can discover them
470
- const workspace = process.env.VEXP_WORKSPACE;
461
+ // Not an unexpanded `${workspaceFolder}`: it names no folder.
462
+ const workspace = workspaceEnv("VEXP_WORKSPACE");
471
463
  if (workspace) {
472
464
  try {
473
465
  fs.writeFileSync(`${workspace}/.vexp/mcp.port`, String(actualPort), "utf-8");
@@ -38,6 +38,55 @@ export function gateActivityLines(hook) {
38
38
  }
39
39
  return { lines, unoriented: unanchored + withheld };
40
40
  }
41
+ /** The reassurance every surface says word for word (vexp-core gate.rs DEVMIND_OPTIONAL). */
42
+ export const DEVMIND_OPTIONAL = "DevMind is optional: everything else in vexp works the same without it.";
43
+ /**
44
+ * What an agent is told when LLM compression is on in the config and the
45
+ * daemon runs the rule compressor. It was always "Restart the daemon or
46
+ * re-run `vexp setup-llm`", whatever the daemon's reason: on a machine where
47
+ * DevMind stays off by policy (no GPU it can use) an agent that relayed it
48
+ * repeated the hour of retries a user had just spent (field report,
49
+ * 2026-11-08), and a bare `vexp setup-llm` is a wizard an agent's shell
50
+ * cannot answer. Now: off by policy is said as such, with nothing to do; any
51
+ * other reason is given in place of the generic advice, which stays only
52
+ * for a daemon that gives none.
53
+ *
54
+ * Off by policy: `llm_off_cause` is a kind. A daemon from before that field
55
+ * (3.3.9, the field absent, not null) said "DevMind needs a GPU and none is
56
+ * usable on this machine" for every such cause, and only then. Lockstep
57
+ * with packages/vexp-cli/src/devmind.ts (devmindOff) and
58
+ * packages/vexp-vscode/src/ui/llm-advice.ts.
59
+ */
60
+ /** The agent's instruction for a cause nothing on this machine changes. */
61
+ export const DEVMIND_OFF_AGENT_NOTHING = "Results are complete with vexp's rule compressor; there is nothing to fix. Do not restart the daemon or re-run setup-llm.";
62
+ /**
63
+ * The agent's instruction for a cause the user can change (index_status
64
+ * `llm_off_fixable`, gate.rs kind_is_fixable). Lockstep with the doctors'
65
+ * "After the fix, restart the daemon." (vexp-cli devmind.ts, vexp-vscode
66
+ * doctor-lines.ts): the restart is the user's, after the user's fix.
67
+ */
68
+ export const DEVMIND_OFF_AGENT_FIXABLE = "Results are complete with vexp's rule compressor. The fix above is the user's to make; do not restart the daemon or re-run setup-llm yourself.";
69
+ export function llmInactiveNote(status) {
70
+ if (status.llm_configured_but_inactive !== true || status.compressor === "llm")
71
+ return undefined;
72
+ const reason = typeof status.llm_inactive_reason === "string" ? status.llm_inactive_reason.trim().replace(/\.+$/, "") : "";
73
+ const off = "llm_off_cause" in status
74
+ ? typeof status.llm_off_cause === "string" && status.llm_off_cause !== ""
75
+ : /needs a GPU/i.test(reason);
76
+ if (off) {
77
+ // A cause the user can change ends its reason with "..., then restart
78
+ // the daemon": "there is nothing to fix. Do not restart the daemon"
79
+ // after it gave an agent two opposite instructions (review,
80
+ // 2026-11-08). Either way the change is not the agent's to make.
81
+ return (`DevMind (optional local LLM) is off on this machine: ${reason || "DevMind needs a GPU"}. ${DEVMIND_OPTIONAL} ` +
82
+ (status.llm_off_fixable === true ? DEVMIND_OFF_AGENT_FIXABLE : DEVMIND_OFF_AGENT_NOTHING));
83
+ }
84
+ if (reason) {
85
+ return `**LLM compression is enabled in config, but this daemon is running the rule compressor, so results are not LLM-compressed.** Reason: ${reason}.`;
86
+ }
87
+ return ("⚠️ A local LLM model is installed and enabled in config, but this daemon is running the rule compressor. " +
88
+ "Restart the daemon (`vexp daemon-cmd restart`) or re-run `vexp setup-llm` — until then, results are NOT LLM-compressed.");
89
+ }
41
90
  export async function handleIndexStatus(params, daemon) {
42
91
  IndexStatusSchema.parse(params);
43
92
  // Client-side: how THIS MCP process resolved its target (before talking to any
@@ -132,9 +181,9 @@ function formatStatusAsText(status, targeting) {
132
181
  lines.push(`| Last query time | ${status.last_query_time_ms}ms |`);
133
182
  }
134
183
  lines.push("");
135
- if (status.llm_configured_but_inactive) {
136
- lines.push("⚠️ A local LLM model is installed and enabled in config, but this daemon is running the rule compressor. " +
137
- "Restart the daemon (`vexp daemon-cmd restart`) or re-run `vexp setup-llm` — until then, results are NOT LLM-compressed.");
184
+ const llmNote = llmInactiveNote(status);
185
+ if (llmNote) {
186
+ lines.push(llmNote);
138
187
  lines.push("");
139
188
  }
140
189
  // Coverage gaps (3.1). Files over max_file_size_kb were skipped with an
@@ -41,6 +41,14 @@ export const RunPipelineSchema = z.object({
41
41
  .boolean()
42
42
  .optional())
43
43
  .describe("Include full file content for pivot files (default: auto — read/debug inline bodies; modify/refactor return skeletons + V-REF)"),
44
+ // Declared here or it never reaches the daemon: z.object drops every key it
45
+ // does not declare, so `eager: true` sent through this server was removed
46
+ // before the call while the schema offered it and the answer's hint asked
47
+ // for it. No default, for the reason given above.
48
+ eager: z.preprocess(coerceBool, z
49
+ .boolean()
50
+ .optional())
51
+ .describe("Inline pivot bodies, covering tests and a raised budget in this one response"),
44
52
  repos: z.preprocess(coerceArray, z
45
53
  .array(z.string())
46
54
  .optional())
@@ -129,6 +137,15 @@ export async function handleRunPipeline(params, daemon) {
129
137
  const result = (await daemon.call("run_pipeline", validated));
130
138
  const scoped = validated.repos?.length ? `, repos: ${validated.repos.join(", ")}` : "";
131
139
  const banner = `> vexp target: ${targeting.workspaceRoot} (via ${targeting.source}${scoped})`;
140
+ // Another root's daemon answered for a target its index cannot hold (a
141
+ // nested checkout with no daemon of its own yet): the answer reads as the
142
+ // target's unless the header says otherwise. index_status says it too, but
143
+ // an agent asks run_pipeline. Read after the call: it names the daemon
144
+ // that answered.
145
+ const foreign = daemon.foreignIndex?.() ?? null;
146
+ const mismatch = foreign
147
+ ? `\n> MISMATCH: this answer comes from the index of ${foreign.served}, not ${foreign.target} - ${foreign.target} is not indexed yet`
148
+ : "";
132
149
  // Safety net for daemons whose output predates the in-band coverage header:
133
150
  // never let a degraded status reach the agent invisibly. Newer daemons embed
134
151
  // an INDEX DEGRADED/EMPTY marker in `output` themselves — don't duplicate it.
@@ -136,5 +153,5 @@ export async function handleRunPipeline(params, daemon) {
136
153
  ? "\n> vexp status: degraded — index coverage too small to answer reliably; use Grep/Glob/Read directly and run `vexp index`."
137
154
  : "";
138
155
  // The Rust engine already produces formatted text output; we only prepend the banner.
139
- return `${banner}${degradedNote}\n${result.output}`;
156
+ return `${banner}${mismatch}${degradedNote}\n${result.output}`;
140
157
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vexp-mcp",
3
- "version": "3.3.8",
3
+ "version": "3.4.0",
4
4
  "license": "UNLICENSED",
5
5
  "description": "vexp MCP server — AI context tools for coding agents",
6
6
  "type": "module",
@@ -8,7 +8,7 @@
8
8
  "scripts": {
9
9
  "build": "tsc",
10
10
  "dev": "tsx src/index.ts",
11
- "test": "node --import tsx --test test/*.test.ts",
11
+ "test": "node --import tsx --import ./test/_sandbox-home.mjs --test test/*.test.ts",
12
12
  "clean": "rm -rf dist",
13
13
  "clean:artifacts": "node -e \"const fs=require('fs'),p=require('path');function w(d){if(!fs.existsSync(d))return;for(const e of fs.readdirSync(d,{withFileTypes:true})){const f=p.join(d,e.name);if(e.isDirectory())w(f);else if(/\\.(map|d\\.ts|d\\.ts\\.map)$/.test(e.name))fs.unlinkSync(f);}}w('dist');\"",
14
14
  "prepublishOnly": "npm run build && npm run clean:artifacts"