layermap 0.1.24 → 0.1.25

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/README.md CHANGED
@@ -143,9 +143,9 @@ This adds LayerMap to every dsh profile. Each session maps the project dsh was s
143
143
 
144
144
  In every agent, start a new session in a Git repository and ask as usual. LayerMap tells the agent
145
145
  when the map helps. A session started in a folder holding several repositories, or one that moves
146
- to another repository, works too: each map tool call maps the repository its path names. On first
147
- launch, npx downloads the pinned `layermap` package from npm; later
148
- launches use the cached copy, even offline.
146
+ to another repository, works too: each map tool call maps the repository its path names. The first
147
+ time a session starts a version of LayerMap, npm installs that pinned `layermap` package into
148
+ LayerMap's cache; later sessions start it from there, even offline.
149
149
 
150
150
  Claude Code asks once before each map tool runs in a project. Choose "don't ask again", or run
151
151
  `npx layermap allow claude` to allow the plugin's read-only tools everywhere.
@@ -177,8 +177,9 @@ things:
177
177
  - lets its read-only tools run without a prompt;
178
178
  - adds one marked sentence to the agent's instructions file.
179
179
 
180
- Use `--scope project` to set it up for a whole team, and `npx layermap remove …` to undo it. For any
181
- other MCP client, run `npx -y layermap mcp` as a stdio server in the repository.
180
+ Setup is for one machine; for a whole team, have each member install the plugin. `npx layermap
181
+ remove …` undoes it. For any other MCP client, run `npx -y layermap mcp` as a stdio server in the
182
+ repository.
182
183
 
183
184
  **Requirements:**
184
185
 
package/dist/cli.mjs CHANGED
@@ -7,7 +7,6 @@ var __export = (target, all) => {
7
7
  };
8
8
 
9
9
  // src/cli.ts
10
- import { fileURLToPath as fileURLToPath3 } from "node:url";
11
10
  import { parseArgs } from "node:util";
12
11
 
13
12
  // src/agent/environment.ts
@@ -154,17 +153,55 @@ function gitEnvironment() {
154
153
  });
155
154
  }
156
155
  var defaultGit = () => process.platform === "win32" ? findExecutable("git") ?? "git.exe" : "/usr/bin/git";
156
+ var FILTERING = /* @__PURE__ */ new Set(["diff", "status", "hash-object", "add", "stash", "update-index"]);
157
+ var subcommand = (args) => {
158
+ for (let index = 0; index < args.length; index++) {
159
+ if (args[index] === "-c" || args[index] === "-C") index++;
160
+ else if (!args[index]?.startsWith("-")) return args[index];
161
+ }
162
+ return void 0;
163
+ };
157
164
  var GitRunner = class {
158
165
  constructor(executable = defaultGit()) {
159
166
  this.executable = executable;
160
167
  }
161
168
  executable;
162
- run(args, options) {
163
- if (options.signal?.aborted) {
164
- return Promise.reject(new GitCommandError("Git command aborted."));
165
- }
169
+ async run(args, options) {
170
+ if (options.signal?.aborted) throw new GitCommandError("Git command aborted.");
166
171
  const readOnly = options.readOnly !== false;
167
- const finalArgs = readOnly ? ["--no-optional-locks", ...CONSTRAINED_CONFIG, ...args] : [...CONSTRAINED_CONFIG, ...args];
172
+ const config2 = [
173
+ ...CONSTRAINED_CONFIG,
174
+ ...FILTERING.has(subcommand(args) ?? "") ? await this.blankedFilters(options) : []
175
+ ];
176
+ return this.spawn(
177
+ readOnly ? ["--no-optional-locks", ...config2, ...args] : [...config2, ...args],
178
+ options
179
+ );
180
+ }
181
+ // Every filter driver the repository's config names, left with no program to run. Git reads its
182
+ // config without running anything; it lists none with status 1.
183
+ async blankedFilters(options) {
184
+ let listed;
185
+ try {
186
+ listed = (await this.spawn(
187
+ [...CONSTRAINED_CONFIG, "config", "--name-only", "--get-regexp", "^filter\\."],
188
+ { ...options, input: void 0 }
189
+ )).stdout.toString("utf8");
190
+ } catch (error51) {
191
+ if (error51 instanceof GitCommandError && error51.exitCode === 1) return [];
192
+ throw error51;
193
+ }
194
+ const drivers = new Set(
195
+ listed.split("\n").flatMap((key) => /^filter\.(.+)\.[^.]+$/su.exec(key)?.[1] ?? [])
196
+ );
197
+ return [...drivers].flatMap(
198
+ (driver) => ["clean=", "process=", "required=false"].flatMap((setting) => [
199
+ "-c",
200
+ `filter.${driver}.${setting}`
201
+ ])
202
+ );
203
+ }
204
+ spawn(finalArgs, options) {
168
205
  const timeoutMs = options.timeoutMs === void 0 ? 5e3 : options.timeoutMs;
169
206
  const maxOutputBytes = options.maxOutputBytes === void 0 ? 2 * 1024 * 1024 : options.maxOutputBytes;
170
207
  return new Promise((resolve, reject) => {
@@ -22675,6 +22712,11 @@ var NON_CODE = [
22675
22712
  var nonCodeKind = (path14) => NON_CODE.find(([pattern]) => pattern.test(path14))?.[1];
22676
22713
  var LIMITS = Object.freeze({ depth: 8, declarations: 800, changed: 200, chain: 3, byName: 40 });
22677
22714
  var CALLER_KINDS = /* @__PURE__ */ new Set(["CALLS", "REFERENCES"]);
22715
+ var USED_BY = {
22716
+ EXTENDS: "extended",
22717
+ IMPLEMENTS: "implemented",
22718
+ OVERRIDES: "overridden"
22719
+ };
22678
22720
  var IMPORT_KINDS3 = /* @__PURE__ */ new Set(["IMPORTS", "TEST_IMPORTS"]);
22679
22721
  var ROUTE2 = /^(?:[A-Z]+(?:\|[A-Z]+)* +)?\/\S*$/u;
22680
22722
  var areaOf = (file2) => /\.(?:go|java|kt)$/u.test(file2) ? file2.slice(0, file2.lastIndexOf("/") + 1) || "./" : file2;
@@ -22771,13 +22813,38 @@ var Tracer = class {
22771
22813
  if (this.callerCount.get(reached.ref) !== 0) continue;
22772
22814
  const object2 = this.graph.object(reached.ref);
22773
22815
  if (testCode(object2.anchor.path) || this.routes.has(reached.ref)) continue;
22774
- if (reached.depth === 0)
22816
+ if (reached.depth === 0) {
22817
+ const uses = this.usesWithoutCalls(reached.ref);
22775
22818
  this.unclear.push(
22776
- `${this.where(reached.ref)} has no callers in the map: it may be wired by a framework, called dynamically, or unused`
22819
+ uses.length ? `${this.where(reached.ref)} has no callers in the map, and is used without a call: ${uses.join("; ")}` : `${this.where(reached.ref)} has no callers in the map: it may be wired by a framework, called dynamically, or unused`
22777
22820
  );
22778
- else this.entry(this.where(reached.ref), false, reached, void 0, reached.certain, true);
22821
+ } else this.entry(this.where(reached.ref), false, reached, void 0, reached.certain, true);
22779
22822
  }
22780
22823
  }
22824
+ /**
22825
+ * The uses outside tests the map sees of a declaration besides calls: a class others extend or
22826
+ * implement, a member that overrides another or that others override, and a decorator that may
22827
+ * wire it to be run (a route, a task, a registry). A decorator of the language's own library
22828
+ * (dataclass, staticmethod) only shapes the declaration. Reading a value is a reference, so a
22829
+ * caller; writing one is not a use, as a value nothing reads is unused.
22830
+ */
22831
+ usesWithoutCalls(ref) {
22832
+ const uses = [];
22833
+ for (const relation of this.graph.relationsTo([ref])) {
22834
+ const verb = USED_BY[relation.kind];
22835
+ const owner = this.graph.owner(relation.from);
22836
+ if (verb && owner !== ref && !testCode(this.graph.object(owner).anchor.path))
22837
+ uses.push(`${verb} by ${this.where(owner)}`);
22838
+ }
22839
+ for (const relation of this.graph.relationsFrom([ref]))
22840
+ if (relation.kind === "OVERRIDES")
22841
+ uses.push(
22842
+ `overrides ${relation.to === void 0 ? relation.target : this.where(this.graph.owner(relation.to))}`
22843
+ );
22844
+ else if (relation.kind === "DECORATED_BY" && relation.unresolvedReason !== "COMPILER_LIBRARY")
22845
+ uses.push(`decorated by ${relation.target}`);
22846
+ return [...new Set(uses)];
22847
+ }
22781
22848
  callers(ref) {
22782
22849
  const callers = [];
22783
22850
  for (const relation of this.graph.relationsTo([ref]))
@@ -23028,7 +23095,8 @@ function mapChangeImpact(store, working, base, changes, project) {
23028
23095
  const now = declarations2(graph, path14).find(
23029
23096
  (candidate) => candidate.kind === object2.kind && graph.qualifiedName(candidate.id) === name
23030
23097
  );
23031
- if (!now || outsideTests(tracer.callers(now.id), graph).length) continue;
23098
+ if (!now || outsideTests(tracer.callers(now.id), graph).length || tracer.usesWithoutCalls(now.id).length)
23099
+ continue;
23032
23100
  if (!outsideTests(beforeTracer.callers(ref), before).length) continue;
23033
23101
  const tested = tracer.callers(now.id).length > 0;
23034
23102
  uncalled.push(
@@ -23283,7 +23351,7 @@ Nothing changed against ${changes.base}.`;
23283
23351
  LIST.changed
23284
23352
  );
23285
23353
  list(
23286
- "LEFT WITHOUT CALLERS (the diff removed or changed their last callers; nothing outside tests calls them now)",
23354
+ "LEFT WITHOUT CALLERS (the diff removed or changed their last callers; nothing outside tests calls or otherwise uses them now)",
23287
23355
  impact.uncalled,
23288
23356
  LIST.changed
23289
23357
  );
@@ -23750,7 +23818,7 @@ async function resolveAnalyzers(cache, log2, env = process.env) {
23750
23818
  return await readAnalyzers(directory);
23751
23819
  }
23752
23820
  var DAY = 24 * 60 * 60 * 1e3;
23753
- async function pruneCache(cache, project, now = Date.now(), installed = packageRoot) {
23821
+ async function pruneCache(cache, project, now = Date.now(), installed = packageRoot, env = process.env) {
23754
23822
  const used = path11.join(path11.dirname(mapDatabasePath(cache, project)), "last-used");
23755
23823
  await mkdir(path11.dirname(used), { recursive: true, mode: 448 });
23756
23824
  await writeFile(used, "");
@@ -23771,13 +23839,31 @@ async function pruneCache(cache, project, now = Date.now(), installed = packageR
23771
23839
  if (built !== void 0 && now - built > (name.includes(".") ? DAY / 24 : DAY))
23772
23840
  await rm(path11.join(builds, name), { recursive: true, force: true });
23773
23841
  }
23774
- await pruneNpxInstalls(installed, now);
23842
+ const own = path11.dirname(path11.dirname(installed));
23843
+ const versions = path11.join(cache, "versions");
23844
+ const launched = path11.dirname(own) === versions;
23845
+ if (launched) await pruneVersions(versions, own, now);
23846
+ const npx = launched ? path11.join(
23847
+ env.npm_config_cache || (process.platform === "win32" ? path11.join(env.LOCALAPPDATA || path11.join(homedir(), "AppData", "Local"), "npm-cache") : path11.join(homedir(), ".npm")),
23848
+ "_npx"
23849
+ ) : path11.dirname(own);
23850
+ if (path11.basename(path11.dirname(installed)) === "node_modules" && path11.basename(npx) === "_npx")
23851
+ await pruneNpxInstalls(npx, installed, now);
23852
+ }
23853
+ async function pruneVersions(versions, own, now) {
23854
+ const used = path11.join(own, "last-used");
23855
+ await writeFile(used, "");
23856
+ await utimes(used, now / 1e3, now / 1e3);
23857
+ for (const name of await readdir(versions).catch(() => [])) {
23858
+ const directory = path11.join(versions, name);
23859
+ const marker = path11.join(directory, "last-used");
23860
+ const last = (await stat(existsSync5(marker) ? marker : directory).catch(() => void 0))?.mtimeMs;
23861
+ if (last !== void 0 && now - last > (name.startsWith(".") ? DAY / 24 : 7 * DAY))
23862
+ await rm(directory, { recursive: true, force: true });
23863
+ }
23775
23864
  }
23776
- async function pruneNpxInstalls(installed, now) {
23865
+ async function pruneNpxInstalls(npx, installed, now) {
23777
23866
  const own = path11.dirname(path11.dirname(installed));
23778
- const npx = path11.dirname(own);
23779
- if (path11.basename(path11.dirname(installed)) !== "node_modules" || path11.basename(npx) !== "_npx")
23780
- return;
23781
23867
  const manifest = async (file2) => JSON.parse(await readFile2(file2, "utf8").catch(() => "{}"));
23782
23868
  const parts = (version2) => version2?.split(".").map(Number) ?? [];
23783
23869
  const current = parts((await manifest(path11.join(installed, "package.json"))).version);
@@ -23890,7 +23976,7 @@ var mapToolDescriptions = (host) => {
23890
23976
  return Object.freeze({
23891
23977
  search: `${lead("search")}Find declarations and files whose names, paths or source documentation match query terms. ANY (default) matches any term, ALL requires every term, LITERAL matches the exact text. Results are ranked by relevance and grouped by file with the declaration name, kind, 1-based line range and matched fields (${MAP_KINDS_LEGEND}). Zoom into a result with project_explore_map({path,name}) or ${host.readResult}. This is not a full-text search and does not prove absence; ${host.textSearch}. Continue with offset and unchanged conditions.`,
23892
23978
  explore: `${lead("explore")}Read the static project map, zooming from the whole project to one declaration. path "." or a directory lists modules, module imports, external packages and its files: with exported declarations when the listing is small, as file names and line counts by directory when larger, and as modules only when very large. Start here to see what exists before searching or reading. A file path lists its declarations and members, imports, importers and top-level statements. A file path with name (or Container.member), optionally narrowed by its start line, or with a line alone, shows that declaration's calls, callers (including uses as a value), writes, heritage, decorators and members, aggregated per related declaration with @line sites; closures and locals are folded into their named container. depth also expands the related declarations hop by hop: up to 8 in one direction, which traces callers up to entry points (INCOMING) or callees down (OUTGOING), and up to 3 for BOTH. To find what a change affects, select the declaration with direction INCOMING and a depth up to 8, continue from any NOT EXPANDED declarations the view names, then confirm the entry points in source. Test files and standard-library call targets are hidden and counted by default; includeTests and includeUnresolved show them. Views use ${MAP_KINDS_LEGEND}. In a declaration view, ${MAP_DECLARATION_LEGEND} ${host.readSource} The map is static: trace stops, possible callers by name, framework wiring and unresolved targets need source reading, and a missing relationship does not prove absence. When a page reports more entries, continue with offset and otherwise unchanged arguments.`,
23893
- check: `${lead("check")}Compares the working tree with a commit (HEAD by default, so uncommitted and untracked changes), finds the declarations the diff changed, removed or renamed, and follows their callers up to 8 levels. It reports, conclusion first: AFFECTED ENTRY POINTS reached through resolved calls, each route with its HTTP methods and full path and the chain to the change; POSSIBLY AFFECTED ones reached only through a call on an interface or base member; REQUESTED BY, the code and templates outside the tests that request the path of a route whose handler the change reaches or a route it removed, found by text; EXISTING TESTS CHANGED, the tests that existed before the diff and whose code it changed or removed; SHARED BY, when tests reach the changed code through more than one area (package or module), so a change meant for one feature may change others; NAMES STILL USED ELSEWHERE, environment variables and configuration keys the diff removed from a file that other files still read or set, found by text; NEW MODULE DEPENDENCIES, imports between the modules of the project overview that the base did not have, and those that make two modules depend on each other, for you to judge against the project's layers; EXISTING CODE LIKE THE NEW CODE, declarations the diff adds whose code reads almost the same as code the project already has; LEFT WITHOUT CALLERS, declarations whose last callers outside the tests the diff removed or changed; CHECK BY HAND for what a static map cannot follow (changed configuration, templates, migrations or dependency files, changed route registrations, declarations with no callers, calls by name on receivers of unknown type); and RELATED TESTS, the existing test files that call the changed code, import a changed file or sit beside it. It does not run or write tests: run the related ones if the change needs verifying; a failing or rewritten test of a feature the request is not about means the change leaked, so restore the test and narrow the change; a new dependency that runs against the layers or closes a cycle means moving what both modules need down rather than importing upward; new code like existing code means using the existing code, or removing the old if the new replaces it; code left without callers means deleting it, with the tests that only test it, when the change replaced it; call it once when the edits are done; and confirm the entry points in source, since an empty list does not prove a change safe.`,
23979
+ check: `${lead("check")}Compares the working tree with a commit (HEAD by default, so uncommitted and untracked changes), finds the declarations the diff changed, removed or renamed, and follows their callers up to 8 levels. It reports, conclusion first: AFFECTED ENTRY POINTS reached through resolved calls, each route with its HTTP methods and full path and the chain to the change; POSSIBLY AFFECTED ones reached only through a call on an interface or base member; REQUESTED BY, the code and templates outside the tests that request the path of a route whose handler the change reaches or a route it removed, found by text; EXISTING TESTS CHANGED, the tests that existed before the diff and whose code it changed or removed; SHARED BY, when tests reach the changed code through more than one area (package or module), so a change meant for one feature may change others; NAMES STILL USED ELSEWHERE, environment variables and configuration keys the diff removed from a file that other files still read or set, found by text; NEW MODULE DEPENDENCIES, imports between the modules of the project overview that the base did not have, and those that make two modules depend on each other, for you to judge against the project's layers; EXISTING CODE LIKE THE NEW CODE, declarations the diff adds whose code reads almost the same as code the project already has; LEFT WITHOUT CALLERS, declarations whose last callers outside the tests the diff removed or changed, and that nothing extends, implements, overrides or wires with a decorator; CHECK BY HAND for what a static map cannot follow (changed configuration, templates, migrations or dependency files, changed route registrations, declarations with no callers, calls by name on receivers of unknown type); and RELATED TESTS, the existing test files that call the changed code, import a changed file or sit beside it. It does not run or write tests: run the related ones if the change needs verifying; a failing or rewritten test of a feature the request is not about means the change leaked, so restore the test and narrow the change; a new dependency that runs against the layers or closes a cycle means moving what both modules need down rather than importing upward; new code like existing code means using the existing code, or removing the old if the new replaces it; code left without callers means deleting it, with the tests that only test it, when the change replaced it; call it once when the edits are done; and confirm the entry points in source, since an empty list does not prove a change safe.`,
23894
23980
  references: `${lead("references")}Compute usages of a mapped declaration from current source, including aliases, re-exports and non-call references. Select it with symbol {path,name,line?} as printed by project_explore_map or project_search_map (line is its start line when names repeat), or with an entityRef or locator {path,start,kind}. Broader and more expensive than the cached callers in project_explore_map; file or unsupported declarations may lack a reference target. path and kinds filter usage locations before paging. ${host.grantRules}objects contains compact declarations; targetRef and reference ownerRef identify them. ${host.readReference} A file that several compiler contexts read (such as packages of one workspace) lists its references once per context, each with that context's configPath. Continue with nextCursor and unchanged conditions, including after an empty partial page. Filtered exhaustion and missing results do not prove absence.`
23895
23981
  });
23896
23982
  };
@@ -24229,7 +24315,7 @@ ${text}` : text
24229
24315
  // src/agent/setup.ts
24230
24316
  import { execFile as execFile2 } from "node:child_process";
24231
24317
  import { existsSync as existsSync7 } from "node:fs";
24232
- import { mkdir as mkdir2, readFile as readFile3, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
24318
+ import { mkdir as mkdir2, readFile as readFile3, rename as rename2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
24233
24319
  import { homedir as homedir2 } from "node:os";
24234
24320
  import path13 from "node:path";
24235
24321
  var SERVER = "layermap";
@@ -24237,16 +24323,13 @@ var SETUP_RULE = `mcp__${SERVER}`;
24237
24323
  var PLUGIN_RULE = `mcp__plugin_${SERVER}_${SERVER}`;
24238
24324
  var BEGIN = "<!-- layermap:begin -->";
24239
24325
  var END = "<!-- layermap:end -->";
24240
- var npxServerArgs = (version2) => [
24241
- "--prefer-offline",
24242
- "-y",
24243
- `layermap@${version2}`,
24244
- "mcp"
24245
- ];
24246
- var mcpLaunchCommand = (version2, platform = process.platform) => {
24326
+ var launcherScript = (template, version2) => `// Generated from scripts/launcher.mjs.
24327
+ ${template.replace("__VERSION__", JSON.stringify(version2))}`;
24328
+ var PUBLISHED_LAUNCHER = path13.join(packageRoot, "dist", "launcher.mjs");
24329
+ var launcherFile = (env = process.env) => path13.join(cacheDirectory(env), "server.mjs");
24330
+ var mcpLaunchCommand = (env = process.env, published = existsSync7(PUBLISHED_LAUNCHER)) => {
24331
+ if (published) return ["node", launcherFile(env)];
24247
24332
  const script = path13.resolve(process.argv[1] ?? "");
24248
- if (script.includes(`${path13.sep}_npx${path13.sep}`))
24249
- return [...platform === "win32" ? ["cmd", "/c"] : [], "npx", ...npxServerArgs(version2)];
24250
24333
  const execArgv = [];
24251
24334
  for (let index = 0; index < process.execArgv.length; index++) {
24252
24335
  const argument = process.execArgv[index];
@@ -24295,6 +24378,7 @@ async function configureCodexServer(file2) {
24295
24378
  while (end < lines.length && !lines[end]?.trim().startsWith("[")) end++;
24296
24379
  const wanted = {
24297
24380
  default_tools_approval_mode: '"approve"',
24381
+ startup_timeout_sec: "120",
24298
24382
  tool_timeout_sec: "120"
24299
24383
  };
24300
24384
  const present = new Set(
@@ -24344,13 +24428,10 @@ async function disallowInClaudeSettings(file2) {
24344
24428
  }
24345
24429
  var YAML_BEGIN = "# layermap:begin";
24346
24430
  var YAML_END = "# layermap:end";
24347
- var nodeDirectory = (env = process.env) => (env.PATH ?? "").split(path13.delimiter).find(
24348
- (directory) => path13.isAbsolute(directory) && existsSync7(path13.join(directory, "node")) && existsSync7(path13.join(directory, "npx"))
24349
- ) ?? path13.dirname(process.execPath);
24431
+ var nodeDirectory = (env = process.env) => (env.PATH ?? "").split(path13.delimiter).find((directory) => path13.isAbsolute(directory) && existsSync7(path13.join(directory, "node"))) ?? path13.dirname(process.execPath);
24350
24432
  var dshPatchBlock = (command, env) => {
24351
24433
  const node = nodeDirectory(env);
24352
- const npx = path13.join(node, "npx");
24353
- const [program = "", ...args] = command[0] === "npx" && existsSync7(npx) ? [npx, ...command.slice(1)] : command;
24434
+ const [program = "", ...args] = command[0] === "node" ? [path13.join(node, "node"), ...command.slice(1)] : command;
24354
24435
  const searchPath2 = `${JSON.stringify(`${node}${path13.delimiter}`)} + process.env.PATH`;
24355
24436
  return [
24356
24437
  `${YAML_BEGIN} (written by \`layermap setup dsh\`; \`layermap remove dsh\` deletes it)`,
@@ -24434,10 +24515,28 @@ var agentFiles = (options) => {
24434
24515
  async function setupAgent(options) {
24435
24516
  const env = options.env ?? process.env;
24436
24517
  const { log: log2 } = options;
24437
- const command = mcpLaunchCommand(options.version);
24518
+ if (options.scope === "project") {
24519
+ log2(
24520
+ "Setup registers this machine's launcher, so it does not write a project's shared settings. Have each machine run setup (--scope user or local), or install the plugin; `layermap remove claude --scope project` still removes an earlier project setup."
24521
+ );
24522
+ return false;
24523
+ }
24524
+ const published = existsSync7(PUBLISHED_LAUNCHER);
24525
+ const command = mcpLaunchCommand(env, published);
24438
24526
  const quoted = command.map((part) => /^[\w./:@=-]+$/u.test(part) ? part : JSON.stringify(part));
24439
24527
  const { settings, instructions } = agentFiles(options);
24440
24528
  const note = options.instructions !== false;
24529
+ const writeLauncher = async () => {
24530
+ if (!published) return;
24531
+ const file2 = launcherFile(env);
24532
+ await mkdir2(path13.dirname(file2), { recursive: true, mode: 448 });
24533
+ await writeFile2(
24534
+ `${file2}.${process.pid}`,
24535
+ launcherScript(await readFile3(PUBLISHED_LAUNCHER, "utf8"), options.version)
24536
+ );
24537
+ await rename2(`${file2}.${process.pid}`, file2);
24538
+ };
24539
+ if (published) log2(`write the launcher of LayerMap ${options.version} to ${launcherFile(env)}`);
24441
24540
  if (options.agent === "dsh") {
24442
24541
  if (options.scope !== "user") {
24443
24542
  log2("DeepSeek Harness is set up for all its profiles at once; --scope does not apply.");
@@ -24446,6 +24545,7 @@ async function setupAgent(options) {
24446
24545
  log2(`add the ${SERVER} MCP server to ${settings}`);
24447
24546
  if (note) log2(`add a note naming the map tools to ${instructions}`);
24448
24547
  if (options.dryRun) return true;
24548
+ await writeLauncher();
24449
24549
  await writeDshPatch(settings, dshPatchBlock(command, env));
24450
24550
  if (note) await writeInstructionNote(instructions);
24451
24551
  log2(
@@ -24459,10 +24559,13 @@ async function setupAgent(options) {
24459
24559
  log2(`allow ${SETUP_RULE} in ${settings}`);
24460
24560
  } else {
24461
24561
  log2(`codex mcp add ${SERVER} -- ${quoted.join(" ")}`);
24462
- log2(`set default_tools_approval_mode = "approve" and tool_timeout_sec = 120 in ${settings}`);
24562
+ log2(
24563
+ `set default_tools_approval_mode = "approve", startup_timeout_sec = 120 and tool_timeout_sec = 120 in ${settings}`
24564
+ );
24463
24565
  }
24464
24566
  if (note) log2(`add a note naming the map tools to ${instructions}`);
24465
24567
  if (options.dryRun) return true;
24568
+ await writeLauncher();
24466
24569
  const agentCommand = options.agent;
24467
24570
  const scope = options.agent === "claude" ? ["--scope", options.scope] : [];
24468
24571
  await run(agentCommand, ["mcp", "remove", SERVER, ...scope], env);
@@ -24523,7 +24626,7 @@ async function removeAgent(options) {
24523
24626
  var USAGE = `LayerMap \u2014 a layered map of a codebase for coding agents.
24524
24627
 
24525
24628
  Usage:
24526
- layermap setup claude|codex|dsh [--scope user|project|local] [--no-instructions] [--dry-run]
24629
+ layermap setup claude|codex|dsh [--scope user|local] [--no-instructions] [--dry-run]
24527
24630
  layermap allow claude [--scope user|project|local] [--dry-run]
24528
24631
  let the plugin's read-only tools run without a prompt
24529
24632
  layermap remove claude|codex|dsh [--scope user|project|local] [--dry-run]
@@ -24574,11 +24677,6 @@ async function main(argv) {
24574
24677
  const version2 = await packageVersion();
24575
24678
  if (values.version) {
24576
24679
  process.stdout.write(`${version2}
24577
- `);
24578
- return 0;
24579
- }
24580
- if (command === "entry") {
24581
- process.stdout.write(`${fileURLToPath3(import.meta.url)}
24582
24680
  `);
24583
24681
  return 0;
24584
24682
  }
@@ -0,0 +1,105 @@
1
+ // Starts one LayerMap version's MCP server in this process. The version is installed once into
2
+ // LayerMap's cache, from where every later start runs without npm or a network. The agent starts
3
+ // this in the project, which stays the working directory the server maps; npm runs in the cache,
4
+ // so the project's own npm settings and packages play no part in what gets installed.
5
+ import { spawn } from "node:child_process";
6
+ import {
7
+ existsSync,
8
+ mkdirSync,
9
+ mkdtempSync,
10
+ readFileSync,
11
+ renameSync,
12
+ rmSync,
13
+ writeFileSync,
14
+ } from "node:fs";
15
+ import { homedir } from "node:os";
16
+ import path from "node:path";
17
+ import { pathToFileURL } from "node:url";
18
+
19
+ const VERSION = __VERSION__;
20
+
21
+ // The same directory as cacheDirectory in src/agent/environment.ts.
22
+ const env = process.env;
23
+ const cache = env.LAYERMAP_CACHE
24
+ ? path.resolve(env.LAYERMAP_CACHE)
25
+ : process.platform === "darwin"
26
+ ? path.join(homedir(), "Library", "Caches", "layermap")
27
+ : process.platform === "win32"
28
+ ? path.join(env.LOCALAPPDATA || path.join(homedir(), "AppData", "Local"), "layermap", "Cache")
29
+ : path.join(env.XDG_CACHE_HOME || path.join(homedir(), ".cache"), "layermap");
30
+ const versions = path.join(cache, "versions");
31
+ const home = path.join(versions, VERSION);
32
+ const installed = path.join(home, "node_modules", "layermap");
33
+ const manifest = path.join(installed, "package.json");
34
+
35
+ // The npm of the Node running this, else the one on PATH.
36
+ const npm = () => {
37
+ const directory = path.dirname(process.execPath);
38
+ for (const cli of [
39
+ path.join(directory, "node_modules", "npm", "bin", "npm-cli.js"),
40
+ path.join(directory, "..", "lib", "node_modules", "npm", "bin", "npm-cli.js"),
41
+ ])
42
+ if (existsSync(cli)) return [process.execPath, [cli]];
43
+ if (process.platform === "win32") throw new Error(`no npm beside ${process.execPath}`);
44
+ return ["npm", []];
45
+ };
46
+
47
+ // npm installs into a directory of its own, renamed into place once complete, so no server starts
48
+ // from half an install, and two starting at once both end up with the one that was renamed first.
49
+ // --prefer-online has npm ask the registry for the versions it has, which a cached list may lack.
50
+ async function install() {
51
+ mkdirSync(versions, { recursive: true, mode: 0o700 });
52
+ const staging = mkdtempSync(path.join(versions, `.${VERSION}-`));
53
+ process.stderr.write(`layermap: installing layermap@${VERSION} with npm\n`);
54
+ const [command, prefix] = npm();
55
+ const args = [
56
+ ...prefix,
57
+ "install",
58
+ `layermap@${VERSION}`,
59
+ "--prefix",
60
+ staging,
61
+ "--prefer-online",
62
+ "--omit=dev",
63
+ "--no-audit",
64
+ "--no-fund",
65
+ "--no-update-notifier",
66
+ "--loglevel=error",
67
+ ];
68
+ await new Promise((resolve, reject) => {
69
+ const child = spawn(command, args, {
70
+ cwd: staging,
71
+ stdio: ["ignore", "pipe", "pipe"],
72
+ windowsHide: true,
73
+ });
74
+ let output = "";
75
+ child.stdout.on("data", (data) => (output += data));
76
+ child.stderr.on("data", (data) => (output += data));
77
+ child.on("error", reject);
78
+ child.on("close", (code) =>
79
+ code === 0 ? resolve() : reject(new Error(`npm exited with ${code}\n${output.trim()}`)),
80
+ );
81
+ }).catch((error) => {
82
+ rmSync(staging, { recursive: true, force: true });
83
+ throw error;
84
+ });
85
+ try {
86
+ renameSync(staging, home);
87
+ } catch (error) {
88
+ rmSync(staging, { recursive: true, force: true });
89
+ if (!existsSync(manifest)) throw error;
90
+ }
91
+ }
92
+
93
+ try {
94
+ if (!existsSync(manifest)) await install();
95
+ // LayerMap removes a version from its cache once nothing has started it for a week.
96
+ writeFileSync(path.join(home, "last-used"), "");
97
+ const entry = path.join(installed, JSON.parse(readFileSync(manifest, "utf8")).bin.layermap);
98
+ process.argv = [process.argv[0], entry, "mcp"];
99
+ await import(pathToFileURL(entry).href);
100
+ } catch (error) {
101
+ process.stderr.write(
102
+ `layermap: could not start LayerMap ${VERSION}: ${error?.message ?? error}\n`,
103
+ );
104
+ process.exit(1);
105
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "layermap",
3
- "version": "0.1.24",
3
+ "version": "0.1.25",
4
4
  "mcpName": "io.github.coffeecoproject/layermap",
5
5
  "description": "A layered map of a codebase for coding agents: directories, modules and call chains across TypeScript, JavaScript, Go, Python and Java.",
6
6
  "license": "Apache-2.0",
package/pi/layermap.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  // LayerMap for Pi. scripts/plugins.ts fills in the notes and writes plugins/pi/layermap.mjs, which
3
3
  // the npm package ships as its Pi extension (`pi install npm:layermap`).
4
4
  //
5
- // The map runs in LayerMap's own MCP server, started with node in the session's directory; its
5
+ // The map runs in LayerMap's own MCP server, started with Pi's Node in the session's directory; its
6
6
  // tools become Pi tools of the same names. Like the Claude Code plugin's stop hook, the extension
7
7
  // asks the agent once, before it settles, to check what its code edits affect.
8
8
  import { execFile, spawn } from "node:child_process";
@@ -36,7 +36,7 @@ class MapServer {
36
36
  constructor(cwd) {
37
37
  this.pending = new Map();
38
38
  this.next = 1;
39
- this.child = spawn("node", [CLI, "mcp"], {
39
+ this.child = spawn(process.execPath, [CLI, "mcp"], {
40
40
  cwd,
41
41
  stdio: ["pipe", "pipe", "ignore"],
42
42
  windowsHide: true,
@@ -108,6 +108,30 @@ const git = (cwd, args) =>
108
108
  ),
109
109
  );
110
110
 
111
+ // Git in a repository with no program its own config names: no fsmonitor, and no filter its
112
+ // attributes would put a changed file's content through.
113
+ async function repositoryGit(repository, args) {
114
+ const drivers = new Set(
115
+ (await git(repository, ["config", "--name-only", "--get-regexp", "^filter\\."]))
116
+ .split("\n")
117
+ .flatMap((key) => /^filter\.(.+)\.[^.]+$/su.exec(key)?.[1] ?? []),
118
+ );
119
+ const blank = [...drivers].flatMap((driver) =>
120
+ ["clean=", "process=", "required=false"].flatMap((setting) => [
121
+ "-c",
122
+ `filter.${driver}.${setting}`,
123
+ ]),
124
+ );
125
+ return git(repository, [
126
+ "-c",
127
+ "core.fsmonitor=false",
128
+ "-c",
129
+ "core.quotePath=false",
130
+ ...blank,
131
+ ...args,
132
+ ]);
133
+ }
134
+
111
135
  // The Git repository around a path, or the nearest directory of it that exists; empty outside one.
112
136
  async function repositoryAt(given) {
113
137
  let directory = given;
@@ -141,25 +165,8 @@ async function changedCode(repository) {
141
165
  const changed = new Map();
142
166
  if (!(await git(repository, ["rev-parse", "--verify", "--quiet", "HEAD"]))) return changed;
143
167
  const listed = await Promise.all([
144
- git(repository, [
145
- "-c",
146
- "core.quotePath=false",
147
- "diff",
148
- "HEAD",
149
- "--name-only",
150
- "--no-renames",
151
- "--",
152
- ...CODE_GLOBS,
153
- ]),
154
- git(repository, [
155
- "-c",
156
- "core.quotePath=false",
157
- "ls-files",
158
- "--others",
159
- "--exclude-standard",
160
- "--",
161
- ...CODE_GLOBS,
162
- ]),
168
+ repositoryGit(repository, ["diff", "HEAD", "--name-only", "--no-renames", "--", ...CODE_GLOBS]),
169
+ repositoryGit(repository, ["ls-files", "--others", "--exclude-standard", "--", ...CODE_GLOBS]),
163
170
  ]);
164
171
  const files = [...new Set(listed.join("\n").split("\n").filter(Boolean))].sort();
165
172
  for (const file of files) {
@@ -228,7 +235,7 @@ export default function layermap(pi) {
228
235
  if (server && !server.dead) return server;
229
236
  starting ??= (async () => {
230
237
  const next = new MapServer(cwd);
231
- const tools = await next.start("0.1.24");
238
+ const tools = await next.start("0.1.25");
232
239
  for (const tool of tools) {
233
240
  if (registered.has(tool.name)) continue;
234
241
  registered.add(tool.name);