layermap 0.1.55 → 0.1.57

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/dist/cli.mjs CHANGED
@@ -8,7 +8,7 @@ var __export = (target, all) => {
8
8
 
9
9
  // src/cli.ts
10
10
  import { realpath as realpath4 } from "node:fs/promises";
11
- import path20 from "node:path";
11
+ import path23 from "node:path";
12
12
  import { parseArgs } from "node:util";
13
13
 
14
14
  // src/agent/call-log.ts
@@ -34,18 +34,322 @@ function mapCallLog(cache) {
34
34
  };
35
35
  }
36
36
 
37
+ // src/agent/claude-hooks.ts
38
+ import { appendFile as appendFile2, mkdir as mkdir2, readdir, readFile as readFile2, rm, stat as stat3 } from "node:fs/promises";
39
+ import os2 from "node:os";
40
+ import path3 from "node:path";
41
+
42
+ // src/agent/notes.ts
43
+ var AGENT_MAP_NOTE = "The layermap MCP server is available here. When a task needs to know what calls a function, what a change could affect beyond the code you are editing, or where code is used, use its project_explore_map tool (direction INCOMING, depth up to 8) instead of grep, then confirm in source; a change confined to code you have read does not need it. When the edits are done, call its project_check_changes tool once before reporting the work done.";
44
+ var antigravityMapNote = (server) => `${AGENT_MAP_NOTE} In Antigravity, call its tools through call_mcp_tool with ServerName ${server}. The server does not start in the project, so give every call an absolute path, and give project_check_changes the project's root as its path.`;
45
+ var AGENT_STOP_CHECK = "Code changed in this session. Before finishing, call the LayerMap tool project_check_changes: it lists the routes, jobs and commands the changes reach and the existing tests related to them. Check the affected entry points in source, and run the related tests if the change needs verifying. If it lists EXISTING TESTS CHANGED or code SHARED BY several areas, decide which of them the request is about; for the others, restore their tests and narrow the change. If it lists NEW MODULE DEPENDENCIES, check that each runs the way the project's layers do. If you already checked these changes, say so briefly and finish.";
46
+ var AGENT_STOP_CHECK_REPOSITORIES = "The changes are in more than one repository, or not in the one the session started in: call project_check_changes once for each, with its path set to the repository: ";
47
+ var projectHeading = (project) => `Project ${project} (paths are relative to it)`;
48
+
49
+ // src/agent/session-changes.ts
50
+ import { execFile } from "node:child_process";
51
+ import { createHash } from "node:crypto";
52
+ import { readFile, stat as stat2 } from "node:fs/promises";
53
+ import os from "node:os";
54
+ import path2 from "node:path";
55
+ var CODE_EXTENSIONS = [
56
+ "ts",
57
+ "tsx",
58
+ "mts",
59
+ "cts",
60
+ "js",
61
+ "jsx",
62
+ "mjs",
63
+ "cjs",
64
+ "go",
65
+ "py",
66
+ "java",
67
+ "wxml"
68
+ ];
69
+ var CODE_FILE = new RegExp(`\\.(?:${CODE_EXTENSIONS.join("|")})$`, "u");
70
+ var CODE_GLOBS = CODE_EXTENSIONS.map((extension) => `*.${extension}`);
71
+ var git = (cwd, args) => new Promise(
72
+ (resolve) => execFile(
73
+ "git",
74
+ ["-C", cwd, ...args],
75
+ { maxBuffer: 64 * 1024 * 1024, windowsHide: true },
76
+ (error51, stdout) => resolve(error51 ? "" : stdout)
77
+ )
78
+ );
79
+ async function repositoryGit(repository, args) {
80
+ const drivers = new Set(
81
+ (await git(repository, ["config", "--name-only", "--get-regexp", "^filter\\."])).split("\n").flatMap((key) => /^filter\.(.+)\.[^.]+$/su.exec(key)?.[1] ?? [])
82
+ );
83
+ const blank = [...drivers].flatMap(
84
+ (driver) => ["clean=", "process=", "required=false"].flatMap((setting) => [
85
+ "-c",
86
+ `filter.${driver}.${setting}`
87
+ ])
88
+ );
89
+ return git(repository, [
90
+ "-c",
91
+ "core.fsmonitor=false",
92
+ "-c",
93
+ "core.quotePath=false",
94
+ ...blank,
95
+ ...args
96
+ ]);
97
+ }
98
+ var isDirectory = async (given) => Boolean((await stat2(given).catch(() => void 0))?.isDirectory());
99
+ async function existingDirectory(given) {
100
+ let directory = given;
101
+ while (!await isDirectory(directory)) {
102
+ if (path2.dirname(directory) === directory) return void 0;
103
+ directory = path2.dirname(directory);
104
+ }
105
+ return directory;
106
+ }
107
+ async function repositoryAt(given) {
108
+ const directory = await existingDirectory(given);
109
+ return directory ? (await git(directory, ["rev-parse", "--show-toplevel"])).trim() : "";
110
+ }
111
+ async function codeEdits(files) {
112
+ const located = /* @__PURE__ */ new Map();
113
+ const locate2 = async (directory) => {
114
+ const [repository, prefix = ""] = (await git(directory, ["rev-parse", "--show-toplevel", "--show-prefix"])).split("\n");
115
+ return repository ? { repository, prefix } : void 0;
116
+ };
117
+ const edits = [];
118
+ for (const file2 of new Set(files)) {
119
+ if (!CODE_FILE.test(file2)) continue;
120
+ const directory = await existingDirectory(path2.dirname(file2));
121
+ if (!directory) continue;
122
+ if (!located.has(directory)) located.set(directory, locate2(directory));
123
+ const where = await located.get(directory);
124
+ if (!where) continue;
125
+ const rest = path2.relative(directory, file2).split(path2.sep).join("/");
126
+ edits.push({ kind: "edit", repository: where.repository, file: `${where.prefix}${rest}` });
127
+ }
128
+ return edits;
129
+ }
130
+ async function commandFiles(cwd, command) {
131
+ const words = [
132
+ ...new Set(
133
+ command.split(/[^A-Za-z0-9._/\\~:@+,%-]+/u).map((word) => word.replace(/[,:]+$/u, "")).filter(Boolean)
134
+ )
135
+ ];
136
+ const resolve = (base, word) => word.startsWith("~/") ? path2.join(os.homedir(), word.slice(2)) : path2.resolve(base, word);
137
+ const bases = [cwd];
138
+ for (const word of words.filter((word2) => !CODE_FILE.test(word2)).slice(0, 300)) {
139
+ if (bases.length > 20) break;
140
+ const named = resolve(cwd, word);
141
+ if (!bases.includes(named) && await isDirectory(named)) bases.push(named);
142
+ }
143
+ const files = /* @__PURE__ */ new Set();
144
+ for (const word of words.filter((word2) => CODE_FILE.test(word2)))
145
+ for (const base of bases) {
146
+ const file2 = resolve(base, word);
147
+ if (files.size < 200 && await isDirectory(path2.dirname(file2))) files.add(file2);
148
+ }
149
+ return [...files];
150
+ }
151
+ var hash = (content) => createHash("sha256").update(content).digest("hex");
152
+ async function fileStates(files) {
153
+ const states = {};
154
+ for (const file2 of files) {
155
+ const content = await readFile(file2).catch(() => void 0);
156
+ states[file2] = content ? hash(content) : "";
157
+ }
158
+ return states;
159
+ }
160
+ var changedFiles = (before, after) => Object.keys(before).filter((file2) => before[file2] !== after[file2]);
161
+ async function changedCode(repository) {
162
+ if (!await git(repository, ["rev-parse", "--verify", "--quiet", "HEAD"])) return /* @__PURE__ */ new Set();
163
+ const listed = await Promise.all([
164
+ repositoryGit(repository, ["diff", "HEAD", "--name-only", "--no-renames", "--", ...CODE_GLOBS]),
165
+ repositoryGit(repository, ["ls-files", "--others", "--exclude-standard", "--", ...CODE_GLOBS])
166
+ ]);
167
+ return new Set(listed.join("\n").split("\n").filter(Boolean));
168
+ }
169
+ async function checkRequest(changes, start, asked) {
170
+ const pending = /* @__PURE__ */ new Map();
171
+ for (const change of changes) {
172
+ if (change.kind === "check") pending.delete(change.repository);
173
+ else
174
+ pending.set(
175
+ change.repository,
176
+ (pending.get(change.repository) ?? /* @__PURE__ */ new Set()).add(change.file)
177
+ );
178
+ }
179
+ const due = [];
180
+ for (const [repository, files] of [...pending].sort(([a], [b]) => a < b ? -1 : 1)) {
181
+ const changed = await changedCode(repository);
182
+ const still = [...files].filter((file2) => changed.has(file2)).sort();
183
+ if (still.length)
184
+ due.push({
185
+ repository,
186
+ states: await fileStates(still.map((file2) => path2.join(repository, file2)))
187
+ });
188
+ }
189
+ const fingerprint = due.length ? hash(JSON.stringify(due)) : "";
190
+ if (!fingerprint || fingerprint === asked) return void 0;
191
+ const elsewhere = due.some(({ repository }) => repository !== start);
192
+ return {
193
+ text: elsewhere ? `${AGENT_STOP_CHECK} ${AGENT_STOP_CHECK_REPOSITORIES}${due.map(({ repository }) => repository).join(", ")}.` : AGENT_STOP_CHECK,
194
+ fingerprint
195
+ };
196
+ }
197
+ var [HEADING_START, HEADING_END] = projectHeading("\0").split("\0");
198
+ function checkedRepository(result, depth = 0) {
199
+ if (typeof result === "string") {
200
+ const line = result.split("\n", 1)[0] ?? "";
201
+ return line.startsWith(HEADING_START) && line.endsWith(HEADING_END) ? line.slice(HEADING_START.length, line.length - HEADING_END.length) : void 0;
202
+ }
203
+ if (!result || typeof result !== "object" || depth > 3) return void 0;
204
+ for (const value of Object.values(result)) {
205
+ const repository = checkedRepository(value, depth + 1);
206
+ if (repository) return repository;
207
+ }
208
+ return void 0;
209
+ }
210
+
211
+ // src/agent/claude-hooks.ts
212
+ var LEDGERS = path3.join(os2.tmpdir(), "layermap-sessions");
213
+ var STALE_MS = 7 * 24 * 60 * 60 * 1e3;
214
+ var EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
215
+ var CHECK_TOOL = /(?:^|__)project_check_changes$/u;
216
+ var stdin = async () => {
217
+ let text = "";
218
+ for await (const chunk of process.stdin) text += chunk;
219
+ return text;
220
+ };
221
+ async function main(input) {
222
+ const event = input.hook_event_name;
223
+ const session = (input.session_id ?? "").replace(/[^A-Za-z0-9_-]/gu, "") || "unknown";
224
+ const ledger = path3.join(LEDGERS, `${session}.jsonl`);
225
+ const cwd = input.cwd || process.cwd();
226
+ const read = async () => (await readFile2(ledger, "utf8").catch(() => "")).split("\n").flatMap((line) => {
227
+ try {
228
+ return line ? [JSON.parse(line)] : [];
229
+ } catch {
230
+ return [];
231
+ }
232
+ });
233
+ const note = async (...entries) => {
234
+ if (!entries.length) return;
235
+ await mkdir2(LEDGERS, { recursive: true });
236
+ await appendFile2(ledger, entries.map((entry) => `${JSON.stringify(entry)}
237
+ `).join(""));
238
+ };
239
+ const checking = process.env.LAYERMAP_STOP_CHECK !== "0";
240
+ if (event === "SessionStart") {
241
+ if (checking) {
242
+ await sweep();
243
+ if (!(await read()).some((entry) => entry.kind === "start"))
244
+ await note({ kind: "start", directory: cwd });
245
+ }
246
+ process.stdout.write(
247
+ `${JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: AGENT_MAP_NOTE } })}
248
+ `
249
+ );
250
+ return;
251
+ }
252
+ if (event === "SessionEnd") return rm(ledger, { force: true });
253
+ if (!checking) return;
254
+ const tool = input.tool_name ?? "";
255
+ const call = input.tool_use_id ?? "";
256
+ if (event === "PreToolUse" && tool === "Bash" && call) {
257
+ const command = input.tool_input?.command;
258
+ const files = typeof command === "string" ? await commandFiles(cwd, command) : [];
259
+ if (files.length) await note({ kind: "before", call, states: await fileStates(files) });
260
+ return;
261
+ }
262
+ if (event === "PreToolUse" && CHECK_TOOL.test(tool)) return compareBackground(await read(), note);
263
+ if (event === "PostToolUse" || event === "PostToolUseFailure") {
264
+ if (tool === "Bash") {
265
+ const before = lastBefore(await read(), call);
266
+ if (!before) return;
267
+ const task = input.tool_response?.backgroundTaskId;
268
+ if (typeof task === "string") return note({ kind: "background", call, task });
269
+ const edits = await codeEdits(changedFiles(before, await fileStates(Object.keys(before))));
270
+ return note(...edits, { kind: "ended", call });
271
+ }
272
+ const response = input.tool_response;
273
+ if (event === "PostToolUseFailure" || response?.is_error || response?.isError) return;
274
+ if (EDIT_TOOLS.has(tool)) {
275
+ const file2 = input.tool_input?.file_path ?? input.tool_input?.notebook_path;
276
+ if (typeof file2 === "string") await note(...await codeEdits([path3.resolve(cwd, file2)]));
277
+ return;
278
+ }
279
+ const repository = CHECK_TOOL.test(tool) ? checkedRepository(response) : void 0;
280
+ if (repository) await note({ kind: "check", repository });
281
+ return;
282
+ }
283
+ if (event === "Stop" && !input.stop_hook_active) {
284
+ const running = new Set(
285
+ (input.background_tasks ?? []).flatMap(
286
+ (task) => task.status === "running" && task.id ? [task.id] : []
287
+ )
288
+ );
289
+ await compareBackground(await read(), note, running);
290
+ const entries = await read();
291
+ const start = entries.find((entry) => entry.kind === "start")?.directory ?? cwd;
292
+ const asked = entries.findLast((entry) => entry.kind === "asked")?.fingerprint ?? "";
293
+ const request = await checkRequest(
294
+ entries.filter(
295
+ (entry) => entry.kind === "edit" || entry.kind === "check"
296
+ ),
297
+ await repositoryAt(start),
298
+ asked
299
+ );
300
+ if (!request) return;
301
+ await note({ kind: "asked", fingerprint: request.fingerprint });
302
+ process.stdout.write(`${JSON.stringify({ decision: "block", reason: request.text })}
303
+ `);
304
+ }
305
+ }
306
+ var lastBefore = (entries, call) => entries.findLast(
307
+ (entry) => entry.kind === "before" && entry.call === call
308
+ )?.states;
309
+ async function compareBackground(entries, note, running) {
310
+ const ended = new Set(entries.flatMap((entry) => entry.kind === "ended" ? [entry.call] : []));
311
+ for (const entry of entries) {
312
+ if (entry.kind !== "background" || ended.has(entry.call)) continue;
313
+ ended.add(entry.call);
314
+ const before = lastBefore(entries, entry.call);
315
+ if (!before) continue;
316
+ const now = await fileStates(Object.keys(before));
317
+ const changed = changedFiles(before, now);
318
+ await note(
319
+ ...await codeEdits(changed),
320
+ ...changed.length ? [{ kind: "before", call: entry.call, states: now }] : [],
321
+ ...!running || running.has(entry.task) ? [] : [{ kind: "ended", call: entry.call }]
322
+ );
323
+ }
324
+ }
325
+ async function sweep() {
326
+ const now = Date.now();
327
+ for (const name of await readdir(LEDGERS).catch(() => [])) {
328
+ const file2 = path3.join(LEDGERS, name);
329
+ const modified = (await stat3(file2).catch(() => void 0))?.mtimeMs ?? now;
330
+ if (now - modified > STALE_MS) await rm(file2, { force: true });
331
+ }
332
+ await rm(path3.join(os2.tmpdir(), "layermap-claude"), { recursive: true, force: true });
333
+ }
334
+ async function claudeHook() {
335
+ try {
336
+ await main(JSON.parse(await stdin()));
337
+ } catch {
338
+ }
339
+ }
340
+
37
341
  // src/agent/command.ts
38
- import { chmod, lstat as lstat5, mkdir as mkdir3, readFile as readFile6, rename as rename3, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
342
+ import { chmod, lstat as lstat5, mkdir as mkdir4, readFile as readFile9, rename as rename4, rm as rm3, writeFile as writeFile3 } from "node:fs/promises";
39
343
  import { homedir as homedir2 } from "node:os";
40
- import path17 from "node:path";
344
+ import path20 from "node:path";
41
345
 
42
346
  // src/agent/environment.ts
43
- import { createHash as createHash6 } from "node:crypto";
44
- import { existsSync as existsSync6, readFileSync as readFileSync3 } from "node:fs";
45
- import { mkdir as mkdir2, readdir, readFile as readFile5, rename as rename2, rm, stat as stat2, utimes, writeFile } from "node:fs/promises";
347
+ import { createHash as createHash7 } from "node:crypto";
348
+ import { existsSync as existsSync7, readFileSync as readFileSync3 } from "node:fs";
349
+ import { mkdir as mkdir3, readdir as readdir2, readFile as readFile8, rename as rename3, rm as rm2, stat as stat4, utimes, writeFile as writeFile2 } from "node:fs/promises";
46
350
  import { createRequire } from "node:module";
47
351
  import { homedir } from "node:os";
48
- import path16 from "node:path";
352
+ import path19 from "node:path";
49
353
  import { fileURLToPath } from "node:url";
50
354
 
51
355
  // src/git-runner.ts
@@ -54,11 +358,11 @@ import { spawn } from "node:child_process";
54
358
  // src/platform.ts
55
359
  import { spawnSync } from "node:child_process";
56
360
  import { existsSync } from "node:fs";
57
- import path2 from "node:path";
361
+ import path4 from "node:path";
58
362
  var executableName = (name, platform = process.platform) => platform === "win32" ? `${name}.exe` : name;
59
363
  var searchPath = (env) => env.PATH ?? Object.entries(env).find(([name]) => name.toUpperCase() === "PATH")?.[1] ?? "";
60
364
  function findOnPath(files, env, platform) {
61
- const join = platform === "win32" ? path2.win32.join : path2.posix.join;
365
+ const join = platform === "win32" ? path4.win32.join : path4.posix.join;
62
366
  for (const directory of searchPath(env).split(platform === "win32" ? ";" : ":"))
63
367
  for (const file2 of files)
64
368
  if (directory && existsSync(join(directory, file2))) return join(directory, file2);
@@ -101,7 +405,7 @@ function stopProcessTree(pid, signal, platform = process.platform) {
101
405
  process.kill(-pid, signal);
102
406
  return;
103
407
  }
104
- const taskkill = path2.win32.join(
408
+ const taskkill = path4.win32.join(
105
409
  process.env.SystemRoot ?? "C:\\Windows",
106
410
  "System32",
107
411
  "taskkill.exe"
@@ -319,10 +623,10 @@ var GitRunner = class {
319
623
  return (await this.run(args, options)).stdout.toString("utf8").trim();
320
624
  }
321
625
  };
322
- async function gitGrep(git2, search, options) {
626
+ async function gitGrep(git3, search, options) {
323
627
  let found;
324
628
  try {
325
- found = (await git2.run(
629
+ found = (await git3.run(
326
630
  [
327
631
  "grep",
328
632
  // NUL after the path and the line number: the path as it is, whatever it holds, and no
@@ -349,27 +653,27 @@ async function gitGrep(git2, search, options) {
349
653
  }
350
654
  const hits = [];
351
655
  for (const record2 of found.split("\n")) {
352
- const [path21, line, text, extra] = record2.split("\0");
353
- if (path21 && line && text !== void 0 && extra === void 0)
354
- hits.push({ path: path21, line: Number(line), text });
656
+ const [path24, line, text, extra] = record2.split("\0");
657
+ if (path24 && line && text !== void 0 && extra === void 0)
658
+ hits.push({ path: path24, line: Number(line), text });
355
659
  }
356
660
  return { hits };
357
661
  }
358
662
 
359
663
  // src/layermap.ts
360
- import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
664
+ import { createHash as createHash6, randomUUID as randomUUID2 } from "node:crypto";
361
665
  import { mkdirSync, statSync } from "node:fs";
362
666
  import { lstat as lstat4, realpath as realpath2 } from "node:fs/promises";
363
- import path15 from "node:path";
667
+ import path17 from "node:path";
364
668
  import { setTimeout as delay } from "node:timers/promises";
365
669
  import { DatabaseSync } from "@photostructure/sqlite";
366
670
 
367
671
  // src/capture-policy.ts
368
- import path4 from "node:path";
672
+ import path6 from "node:path";
369
673
 
370
674
  // src/file-universe.ts
371
675
  import { lstat } from "node:fs/promises";
372
- import path3 from "node:path";
676
+ import path5 from "node:path";
373
677
  var FILE_UNIVERSE_ARGS = Object.freeze([
374
678
  "ls-files",
375
679
  "-z",
@@ -398,8 +702,8 @@ var parseFileUniverse = (output) => {
398
702
  const records = output.toString("utf8").split("\0");
399
703
  for (const record2 of records) {
400
704
  if (record2.length === 0) continue;
401
- const normalized = path3.posix.normalize(record2);
402
- if (normalized !== record2 || normalized === "." || normalized === ".." || normalized.startsWith("../") || path3.posix.isAbsolute(normalized) || normalized.includes("\\")) {
705
+ const normalized = path5.posix.normalize(record2);
706
+ if (normalized !== record2 || normalized === "." || normalized === ".." || normalized.startsWith("../") || path5.posix.isAbsolute(normalized) || normalized.includes("\\")) {
403
707
  throw new ProjectEvidenceFileUniverseError("PROJECT_FILE_UNIVERSE_INVALID");
404
708
  }
405
709
  files.add(normalized);
@@ -409,8 +713,8 @@ var parseFileUniverse = (output) => {
409
713
  );
410
714
  };
411
715
  var ProjectEvidenceFileUniverse = class {
412
- constructor(git2 = new GitRunner()) {
413
- this.git = git2;
716
+ constructor(git3 = new GitRunner()) {
717
+ this.git = git3;
414
718
  }
415
719
  git;
416
720
  async capture(root, signal) {
@@ -444,7 +748,7 @@ var ProjectEvidenceFileUniverse = class {
444
748
  const candidates = parseFileUniverse(listed);
445
749
  const present = await Promise.all(
446
750
  candidates.map(
447
- (file2) => lstat(path3.join(root, ...file2.split("/"))).then(
751
+ (file2) => lstat(path5.join(root, ...file2.split("/"))).then(
448
752
  () => true,
449
753
  (error51) => {
450
754
  if (error51.code === "ENOENT" || error51.code === "ENOTDIR") return false;
@@ -584,7 +888,7 @@ var ProjectEvidencePolicyError = class extends Error {
584
888
  var assertProjectEvidencePathNotSensitive = (relativePath) => {
585
889
  const segments2 = relativePath.toLowerCase().split("/");
586
890
  const basename = segments2.at(-1) ?? "";
587
- const extension = path4.posix.extname(basename);
891
+ const extension = path6.posix.extname(basename);
588
892
  const containsSensitiveSequence = sensitiveSegmentSequences.some(
589
893
  (sequence) => segments2.length >= sequence.length && segments2.some(
590
894
  (_, start) => sequence.every((segment, offset) => segments2[start + offset] === segment)
@@ -597,17 +901,17 @@ var assertProjectEvidencePathNotSensitive = (relativePath) => {
597
901
  };
598
902
  var isProjectEvidenceTraversalExcluded = (relativePath) => relativePath.toLowerCase().split("/").some((segment) => traversalExcludedSegmentSet.has(segment));
599
903
  var isProjectEvidenceTextPath = (relativePath) => {
600
- const basename = path4.posix.basename(relativePath).toLowerCase();
601
- const extension = path4.posix.extname(basename);
904
+ const basename = path6.posix.basename(relativePath).toLowerCase();
905
+ const extension = path6.posix.extname(basename);
602
906
  if (allowedTextBasenameSet.has(basename)) return true;
603
907
  return extension ? allowedTextExtensionSet.has(extension) : allowedExtensionlessNameSet.has(basename);
604
908
  };
605
909
 
606
910
  // src/code-commit-reader.ts
607
- import { createHash as createHash2 } from "node:crypto";
911
+ import { createHash as createHash3 } from "node:crypto";
608
912
 
609
913
  // src/core.ts
610
- import path5 from "node:path";
914
+ import path7 from "node:path";
611
915
 
612
916
  // node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js
613
917
  var external_exports = {};
@@ -740,7 +1044,7 @@ __export(external_exports, {
740
1044
  gt: () => _gt,
741
1045
  gte: () => _gte,
742
1046
  guid: () => guid2,
743
- hash: () => hash,
1047
+ hash: () => hash2,
744
1048
  hex: () => hex2,
745
1049
  hostname: () => hostname2,
746
1050
  httpUrl: () => httpUrl,
@@ -1375,10 +1679,10 @@ function mergeDefs(...defs) {
1375
1679
  function cloneDef(schema) {
1376
1680
  return mergeDefs(schema._zod.def);
1377
1681
  }
1378
- function getElementAtPath(obj, path21) {
1379
- if (!path21)
1682
+ function getElementAtPath(obj, path24) {
1683
+ if (!path24)
1380
1684
  return obj;
1381
- return path21.reduce((acc, key) => acc?.[key], obj);
1685
+ return path24.reduce((acc, key) => acc?.[key], obj);
1382
1686
  }
1383
1687
  function promiseAllObject(promisesObj) {
1384
1688
  const keys = Object.keys(promisesObj);
@@ -1787,11 +2091,11 @@ function explicitlyAborted(x, startIndex = 0) {
1787
2091
  }
1788
2092
  return false;
1789
2093
  }
1790
- function prefixIssues(path21, issues) {
2094
+ function prefixIssues(path24, issues) {
1791
2095
  return issues.map((iss) => {
1792
2096
  var _a3;
1793
2097
  (_a3 = iss).path ?? (_a3.path = []);
1794
- iss.path.unshift(path21);
2098
+ iss.path.unshift(path24);
1795
2099
  return iss;
1796
2100
  });
1797
2101
  }
@@ -1938,16 +2242,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
1938
2242
  }
1939
2243
  function formatError(error51, mapper = (issue2) => issue2.message) {
1940
2244
  const fieldErrors = { _errors: [] };
1941
- const processError = (error52, path21 = []) => {
2245
+ const processError = (error52, path24 = []) => {
1942
2246
  for (const issue2 of error52.issues) {
1943
2247
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1944
- issue2.errors.map((issues) => processError({ issues }, [...path21, ...issue2.path]));
2248
+ issue2.errors.map((issues) => processError({ issues }, [...path24, ...issue2.path]));
1945
2249
  } else if (issue2.code === "invalid_key") {
1946
- processError({ issues: issue2.issues }, [...path21, ...issue2.path]);
2250
+ processError({ issues: issue2.issues }, [...path24, ...issue2.path]);
1947
2251
  } else if (issue2.code === "invalid_element") {
1948
- processError({ issues: issue2.issues }, [...path21, ...issue2.path]);
2252
+ processError({ issues: issue2.issues }, [...path24, ...issue2.path]);
1949
2253
  } else {
1950
- const fullpath = [...path21, ...issue2.path];
2254
+ const fullpath = [...path24, ...issue2.path];
1951
2255
  if (fullpath.length === 0) {
1952
2256
  fieldErrors._errors.push(mapper(issue2));
1953
2257
  } else {
@@ -1974,17 +2278,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
1974
2278
  }
1975
2279
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
1976
2280
  const result = { errors: [] };
1977
- const processError = (error52, path21 = []) => {
2281
+ const processError = (error52, path24 = []) => {
1978
2282
  var _a3, _b;
1979
2283
  for (const issue2 of error52.issues) {
1980
2284
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1981
- issue2.errors.map((issues) => processError({ issues }, [...path21, ...issue2.path]));
2285
+ issue2.errors.map((issues) => processError({ issues }, [...path24, ...issue2.path]));
1982
2286
  } else if (issue2.code === "invalid_key") {
1983
- processError({ issues: issue2.issues }, [...path21, ...issue2.path]);
2287
+ processError({ issues: issue2.issues }, [...path24, ...issue2.path]);
1984
2288
  } else if (issue2.code === "invalid_element") {
1985
- processError({ issues: issue2.issues }, [...path21, ...issue2.path]);
2289
+ processError({ issues: issue2.issues }, [...path24, ...issue2.path]);
1986
2290
  } else {
1987
- const fullpath = [...path21, ...issue2.path];
2291
+ const fullpath = [...path24, ...issue2.path];
1988
2292
  if (fullpath.length === 0) {
1989
2293
  result.errors.push(mapper(issue2));
1990
2294
  continue;
@@ -2016,8 +2320,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
2016
2320
  }
2017
2321
  function toDotPath(_path) {
2018
2322
  const segs = [];
2019
- const path21 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
2020
- for (const seg of path21) {
2323
+ const path24 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
2324
+ for (const seg of path24) {
2021
2325
  if (typeof seg === "number")
2022
2326
  segs.push(`[${seg}]`);
2023
2327
  else if (typeof seg === "symbol")
@@ -13101,7 +13405,7 @@ __export(schemas_exports2, {
13101
13405
  float64: () => float64,
13102
13406
  function: () => _function,
13103
13407
  guid: () => guid2,
13104
- hash: () => hash,
13408
+ hash: () => hash2,
13105
13409
  hex: () => hex2,
13106
13410
  hostname: () => hostname2,
13107
13411
  httpUrl: () => httpUrl,
@@ -13729,7 +14033,7 @@ function hostname2(_params) {
13729
14033
  function hex2(_params) {
13730
14034
  return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params);
13731
14035
  }
13732
- function hash(alg, params) {
14036
+ function hash2(alg, params) {
13733
14037
  const enc = params?.enc ?? "hex";
13734
14038
  const format = `${alg}_${enc}`;
13735
14039
  const regex = regexes_exports[format];
@@ -14709,13 +15013,13 @@ function resolveRef(ref, ctx) {
14709
15013
  if (!ref.startsWith("#")) {
14710
15014
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14711
15015
  }
14712
- const path21 = ref.slice(1).split("/").filter(Boolean);
14713
- if (path21.length === 0) {
15016
+ const path24 = ref.slice(1).split("/").filter(Boolean);
15017
+ if (path24.length === 0) {
14714
15018
  return ctx.rootSchema;
14715
15019
  }
14716
15020
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14717
- if (path21[0] === defsKey) {
14718
- const key = path21[1];
15021
+ if (path24[0] === defsKey) {
15022
+ const key = path24[1];
14719
15023
  if (!key || !ctx.defs[key]) {
14720
15024
  throw new Error(`Reference not found: ${ref}`);
14721
15025
  }
@@ -15143,14 +15447,14 @@ var ProjectEvidencePathError = class extends Error {
15143
15447
  code;
15144
15448
  };
15145
15449
  var normalizeProjectEvidencePath = (value, allowRoot = false) => {
15146
- if (value.includes("\0") || path5.isAbsolute(value) || value.includes("\\")) {
15450
+ if (value.includes("\0") || path7.isAbsolute(value) || value.includes("\\")) {
15147
15451
  throw new ProjectEvidencePathError("PROJECT_PATH_INVALID");
15148
15452
  }
15149
15453
  if (value === ".") {
15150
15454
  if (allowRoot) return "";
15151
15455
  throw new ProjectEvidencePathError("PROJECT_PATH_INVALID");
15152
15456
  }
15153
- const normalized = path5.posix.normalize(value);
15457
+ const normalized = path7.posix.normalize(value);
15154
15458
  if (normalized.length === 0 || normalized !== value || normalized === ".." || normalized.startsWith("../") || value.split("/").some((segment) => segment.length === 0 || segment === "." || segment === "..")) {
15155
15459
  throw new ProjectEvidencePathError("PROJECT_PATH_INVALID");
15156
15460
  }
@@ -15172,7 +15476,7 @@ var ProjectEvidenceGrantPathPrefixSchema = external_exports.string().min(1).refi
15172
15476
  });
15173
15477
 
15174
15478
  // src/digest.ts
15175
- import { createHash } from "node:crypto";
15479
+ import { createHash as createHash2 } from "node:crypto";
15176
15480
  var normalize = (value, seen) => {
15177
15481
  if (value === null || typeof value === "string" || typeof value === "boolean") return value;
15178
15482
  if (typeof value === "number") {
@@ -15208,16 +15512,16 @@ var normalize = (value, seen) => {
15208
15512
  throw new TypeError(`Canonical JSON values cannot contain ${typeof value}.`);
15209
15513
  };
15210
15514
  var canonicalJson = (value) => JSON.stringify(normalize(value, /* @__PURE__ */ new Set()));
15211
- var digestValue = (value) => createHash("sha256").update(canonicalJson(value)).digest("hex");
15515
+ var digestValue = (value) => createHash2("sha256").update(canonicalJson(value)).digest("hex");
15212
15516
 
15213
15517
  // src/code-commit-reader.ts
15214
15518
  var BATCH_BYTES = 16 * 1024 * 1024;
15215
15519
  var BATCH_BLOBS = 4096;
15216
15520
  var CodeCommitReader = class _CodeCommitReader {
15217
- constructor(root, entries, git2, signal) {
15521
+ constructor(root, entries, git3, signal) {
15218
15522
  this.root = root;
15219
15523
  this.entries = entries;
15220
- this.git = git2;
15524
+ this.git = git3;
15221
15525
  this.signal = signal;
15222
15526
  this.byPath = new Map(entries.map((entry) => [entry.path, entry]));
15223
15527
  }
@@ -15232,14 +15536,14 @@ var CodeCommitReader = class _CodeCommitReader {
15232
15536
  if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(commit)) {
15233
15537
  throw new ProjectEvidenceError("PROJECT_CODE_COMMIT_INVALID", false);
15234
15538
  }
15235
- const git2 = new GitRunner();
15539
+ const git3 = new GitRunner();
15236
15540
  const options = { cwd: root, signal, timeoutMs: null, maxOutputBytes: null };
15237
- const resolved = (await git2.run(
15541
+ const resolved = (await git3.run(
15238
15542
  ["--no-replace-objects", "rev-parse", "--verify", `${commit}^{commit}`],
15239
15543
  options
15240
15544
  )).stdout.toString("utf8").trim();
15241
15545
  if (resolved !== commit) throw new ProjectEvidenceError("PROJECT_CODE_COMMIT_INVALID", false);
15242
- const tree = (await git2.run(
15546
+ const tree = (await git3.run(
15243
15547
  [
15244
15548
  "--no-replace-objects",
15245
15549
  "--literal-pathspecs",
@@ -15270,7 +15574,7 @@ var CodeCommitReader = class _CodeCommitReader {
15270
15574
  }
15271
15575
  if (selectedPath !== void 0 && (entries.length !== 1 || entries[0]?.path !== selectedPath))
15272
15576
  throw new ProjectEvidenceError("PROJECT_MAP_SOURCE_CHANGED", true);
15273
- return new _CodeCommitReader(root, entries, git2, signal);
15577
+ return new _CodeCommitReader(root, entries, git3, signal);
15274
15578
  }
15275
15579
  /**
15276
15580
  * Reads the files at the given paths in their order, many blobs to a Git process: one process
@@ -15333,7 +15637,7 @@ var CodeCommitReader = class _CodeCommitReader {
15333
15637
  return contents;
15334
15638
  }
15335
15639
  blobRead(source, content) {
15336
- const objectHash = createHash2(source.object.length === 64 ? "sha256" : "sha1").update(`blob ${content.byteLength}\0`).update(content).digest("hex");
15640
+ const objectHash = createHash3(source.object.length === 64 ? "sha256" : "sha1").update(`blob ${content.byteLength}\0`).update(content).digest("hex");
15337
15641
  if (content.byteLength !== source.bytes || objectHash !== source.object)
15338
15642
  throw new ProjectEvidenceError("PROJECT_CODE_BLOB_INVALID", false);
15339
15643
  const contentDigest2 = digestValue({ bytesBase64: content.toString("base64") });
@@ -15358,14 +15662,14 @@ var CodeCommitReader = class _CodeCommitReader {
15358
15662
  // src/code-worktree-reader.ts
15359
15663
  import { constants as fsConstants } from "node:fs";
15360
15664
  import { lstat as lstat2, open, realpath } from "node:fs/promises";
15361
- import path6 from "node:path";
15665
+ import path8 from "node:path";
15362
15666
  var fileSystemErrorCode = (error51) => {
15363
15667
  if (typeof error51 !== "object" || error51 === null || !("code" in error51)) return void 0;
15364
15668
  return typeof error51.code === "string" ? error51.code : void 0;
15365
15669
  };
15366
15670
  var isInsideRoot = (root, candidate) => {
15367
- const relative = path6.relative(root, candidate);
15368
- return relative === "" || !relative.startsWith(`..${path6.sep}`) && relative !== "..";
15671
+ const relative = path8.relative(root, candidate);
15672
+ return relative === "" || !relative.startsWith(`..${path8.sep}`) && relative !== "..";
15369
15673
  };
15370
15674
  var stablePathFingerprint = (stats) => (stats.isDirectory() ? ["directory", stats.dev, stats.ino] : [
15371
15675
  stats.dev,
@@ -15408,7 +15712,7 @@ var StableProjectCaptureSession = class _StableProjectCaptureSession {
15408
15712
  }
15409
15713
  async captureFile(relativePath) {
15410
15714
  this.assertNotAborted();
15411
- const absolutePath = path6.join(this.root, ...relativePath.split("/"));
15715
+ const absolutePath = path8.join(this.root, ...relativePath.split("/"));
15412
15716
  const stats = await this.inspectPath(absolutePath, true);
15413
15717
  const fingerprint = stablePathFingerprint(stats);
15414
15718
  const byteLength = stats.isDirectory() ? 0 : Number(stats.size);
@@ -15530,11 +15834,11 @@ var StableProjectCaptureSession = class _StableProjectCaptureSession {
15530
15834
  if (!isInsideRoot(this.root, absolutePath)) {
15531
15835
  throw new ProjectEvidenceError("PROJECT_PATH_OUTSIDE_ROOT", false);
15532
15836
  }
15533
- const relative = path6.relative(this.root, absolutePath);
15534
- const components = relative === "" ? [] : relative.split(path6.sep);
15837
+ const relative = path8.relative(this.root, absolutePath);
15838
+ const components = relative === "" ? [] : relative.split(path8.sep);
15535
15839
  const paths = [
15536
15840
  this.root,
15537
- ...components.map((_, index) => path6.join(this.root, ...components.slice(0, index + 1)))
15841
+ ...components.map((_, index) => path8.join(this.root, ...components.slice(0, index + 1)))
15538
15842
  ];
15539
15843
  let finalStats;
15540
15844
  for (const [index, currentPath] of paths.entries()) {
@@ -15575,10 +15879,10 @@ var StableProjectCaptureSession = class _StableProjectCaptureSession {
15575
15879
  };
15576
15880
 
15577
15881
  // src/project-map-installed.ts
15578
- import { createHash as createHash3 } from "node:crypto";
15882
+ import { createHash as createHash4 } from "node:crypto";
15579
15883
  import { existsSync as existsSync2, readdirSync, readFileSync, realpathSync } from "node:fs";
15580
15884
  import { isBuiltin } from "node:module";
15581
- import path7 from "node:path";
15885
+ import path9 from "node:path";
15582
15886
  var INSTALL_RECORDS = [
15583
15887
  ".pnpm/lock.yaml",
15584
15888
  ".package-lock.json",
@@ -15600,13 +15904,13 @@ function mapPackageOf(specifier) {
15600
15904
  }
15601
15905
  function mapInstalledPath(realRoot, relative) {
15602
15906
  try {
15603
- const real = realpathSync.native(path7.join(realRoot, relative));
15604
- return real.startsWith(`${realRoot}${path7.sep}`) ? real : void 0;
15907
+ const real = realpathSync.native(path9.join(realRoot, relative));
15908
+ return real.startsWith(`${realRoot}${path9.sep}`) ? real : void 0;
15605
15909
  } catch {
15606
15910
  return void 0;
15607
15911
  }
15608
15912
  }
15609
- var contentDigest = (file2) => createHash3("sha256").update(readFileSync(file2)).digest("hex");
15913
+ var contentDigest = (file2) => createHash4("sha256").update(readFileSync(file2)).digest("hex");
15610
15914
  var versionOf = (realRoot, relative) => {
15611
15915
  const manifest = mapInstalledPath(realRoot, `${relative}/package.json`);
15612
15916
  if (!manifest) return "not in the project";
@@ -15618,21 +15922,21 @@ var versionOf = (realRoot, relative) => {
15618
15922
  };
15619
15923
  function installedAt(realRoot, directory, real) {
15620
15924
  const records = INSTALL_RECORDS.flatMap((name) => {
15621
- const file2 = mapInstalledPath(realRoot, path7.posix.join(directory, name));
15925
+ const file2 = mapInstalledPath(realRoot, path9.posix.join(directory, name));
15622
15926
  return file2 ? [[name, contentDigest(file2)]] : [];
15623
15927
  });
15624
15928
  if (records.length) return records;
15625
15929
  const packages = readdirSync(real).flatMap((name) => {
15626
15930
  if (name.startsWith(".")) return [];
15627
15931
  if (!name.startsWith("@")) return [name];
15628
- const scope = mapInstalledPath(realRoot, path7.posix.join(directory, name));
15932
+ const scope = mapInstalledPath(realRoot, path9.posix.join(directory, name));
15629
15933
  return scope ? readdirSync(scope).map((inner) => `${name}/${inner}`) : [];
15630
15934
  });
15631
- const beside = path7.join(realRoot, path7.posix.dirname(directory));
15935
+ const beside = path9.join(realRoot, path9.posix.dirname(directory));
15632
15936
  return {
15633
15937
  packages: packages.sort().map((name) => [name, versionOf(realRoot, `${directory}/${name}`)]),
15634
15938
  lockfiles: LOCKFILES.flatMap((name) => {
15635
- const file2 = path7.join(beside, name);
15939
+ const file2 = path9.join(beside, name);
15636
15940
  return existsSync2(file2) ? [[name, contentDigest(file2)]] : [];
15637
15941
  })
15638
15942
  };
@@ -15641,15 +15945,15 @@ function mapInstalledDigest(root, paths) {
15641
15945
  const realRoot = realpathSync.native(root);
15642
15946
  const directories = /* @__PURE__ */ new Set(["."]);
15643
15947
  for (const file2 of paths) {
15644
- let at = path7.posix.dirname(file2);
15948
+ let at = path9.posix.dirname(file2);
15645
15949
  while (at !== "." && !directories.has(at)) {
15646
15950
  directories.add(at);
15647
- at = path7.posix.dirname(at);
15951
+ at = path9.posix.dirname(at);
15648
15952
  }
15649
15953
  }
15650
15954
  const installed = [];
15651
15955
  for (const directory of [...directories].sort()) {
15652
- const modules = path7.posix.join(directory, "node_modules");
15956
+ const modules = path9.posix.join(directory, "node_modules");
15653
15957
  const real = mapInstalledPath(realRoot, modules);
15654
15958
  if (real) installed.push([modules, installedAt(realRoot, modules, real)]);
15655
15959
  }
@@ -15657,7 +15961,7 @@ function mapInstalledDigest(root, paths) {
15657
15961
  }
15658
15962
 
15659
15963
  // src/source-scope.ts
15660
- import path8 from "node:path";
15964
+ import path10 from "node:path";
15661
15965
  var InitialEvidenceScopeSchema = external_exports.object({
15662
15966
  pathPrefixes: external_exports.array(ProjectEvidenceGrantPathPrefixSchema).min(1).max(64)
15663
15967
  }).strict();
@@ -15745,7 +16049,7 @@ var includesInitialEvidencePath = (relativePath, scope) => {
15745
16049
  if (isProjectEvidenceTraversalExcluded(relativePath) || inExcludedDirectory(relativePath))
15746
16050
  return false;
15747
16051
  const basename = relativePath.toLowerCase().split("/").at(-1) ?? "";
15748
- return extensions.has(path8.posix.extname(basename)) || SOURCE_POLICY.documentationFiles.includes(basename) || SOURCE_POLICY.configurationFiles.includes(basename) || SOURCE_POLICY.workspaceFiles.includes(relativePath);
16052
+ return extensions.has(path10.posix.extname(basename)) || SOURCE_POLICY.documentationFiles.includes(basename) || SOURCE_POLICY.configurationFiles.includes(basename) || SOURCE_POLICY.workspaceFiles.includes(relativePath);
15749
16053
  };
15750
16054
 
15751
16055
  // src/code-index-capture.ts
@@ -16122,8 +16426,8 @@ var MapAnalysisSchema = external_exports.object({
16122
16426
  var mapPathAllowed = (relative, prefixes) => prefixes.some(
16123
16427
  (prefix) => prefix === "." || relative === prefix || relative.startsWith(`${prefix}/`)
16124
16428
  );
16125
- var mapTestPath = (path21) => /(?:^|\/)(?:__tests__|tests?|fixtures?|testFixtures|e2e|testdata)(?:\/|$)|\.(?:spec|test)\.|_test\.(?:go|py)$|(?:^|\/)(?:test_[^/]*\.py|conftest\.py)$/iu.test(
16126
- path21
16429
+ var mapTestPath = (path24) => /(?:^|\/)(?:__tests__|tests?|fixtures?|testFixtures|e2e|testdata)(?:\/|$)|\.(?:spec|test)\.|_test\.(?:go|py)$|(?:^|\/)(?:test_[^/]*\.py|conftest\.py)$/iu.test(
16430
+ path24
16127
16431
  );
16128
16432
  var mapRunnableTest = (file2) => /_test\.(?:go|py)$|(?:^|\/)test_[^/]*\.py$|(?:\.(?:test|spec)|\.e2e-spec|(?:^|\/)__tests__\/.*)\.[cm]?[jt]sx?$|(?:^|\/)(?:Test|IT)[A-Z]\w*\.(?:java|kt)$|(?:Test|Tests|TestCase|IT|ITCase)\.(?:java|kt)$/u.test(
16129
16433
  file2
@@ -16228,11 +16532,11 @@ var string4 = (value) => {
16228
16532
  var identity = (id2, reconstructed) => id2 === reconstructed ? [] : [JSON.stringify(id2)];
16229
16533
  function encodeMapText(graph) {
16230
16534
  const files = /* @__PURE__ */ new Map();
16231
- const file2 = (path21) => {
16232
- let ref = files.get(path21);
16535
+ const file2 = (path24) => {
16536
+ let ref = files.get(path24);
16233
16537
  if (!ref) {
16234
16538
  ref = `F${files.size + 1}`;
16235
- files.set(path21, ref);
16539
+ files.set(path24, ref);
16236
16540
  }
16237
16541
  return ref;
16238
16542
  };
@@ -16280,7 +16584,7 @@ function encodeMapText(graph) {
16280
16584
  rows2.push(`B ${node(frontier.entityRef)} ${frontier.direction}`);
16281
16585
  return [
16282
16586
  ...header,
16283
- ...[...files].map(([path21, ref]) => `${ref} ${JSON.stringify(path21)}`),
16587
+ ...[...files].map(([path24, ref]) => `${ref} ${JSON.stringify(path24)}`),
16284
16588
  ...rows2
16285
16589
  ].join("\n");
16286
16590
  }
@@ -16300,10 +16604,10 @@ function decodeMapText(text) {
16300
16604
  const at = (value) => {
16301
16605
  const match = /^(F[1-9]\d*):(\d+)-(\d+)@(\d+)-(\d+)$/u.exec(value ?? "");
16302
16606
  if (!match) return failed();
16303
- const path21 = files.get(match[1] ?? "");
16304
- if (path21 === void 0) return failed();
16607
+ const path24 = files.get(match[1] ?? "");
16608
+ if (path24 === void 0) return failed();
16305
16609
  return MapAnchorSchema.parse({
16306
- path: path21,
16610
+ path: path24,
16307
16611
  startLine: Number(match[2]),
16308
16612
  endLine: Number(match[3]),
16309
16613
  start: Number(match[4]),
@@ -16380,8 +16684,8 @@ function decodeMapText(text) {
16380
16684
  var locationSchema = MapAnchorSchema.describe(
16381
16685
  "Source location: start/end are zero-based UTF-16 offsets with an exclusive end; line numbers are one-based."
16382
16686
  );
16383
- var location = ({ path: path21, startLine, endLine, start, end }) => ({
16384
- path: path21,
16687
+ var location = ({ path: path24, startLine, endLine, start, end }) => ({
16688
+ path: path24,
16385
16689
  startLine,
16386
16690
  endLine,
16387
16691
  start,
@@ -16484,11 +16788,11 @@ var MapNavigationObjectsSchema = external_exports.union([
16484
16788
  ),
16485
16789
  external_exports.object({ files: external_exports.array(searchFileSchema) }).passthrough().refine((value) => !("format" in value), "Text navigation must decode through its format.").transform(
16486
16790
  (value) => value.files.flatMap(
16487
- ({ path: path21, symbols }) => symbols.map(({ id: id2, name, kind, startLine, endLine, start, end, execution }) => ({
16791
+ ({ path: path24, symbols }) => symbols.map(({ id: id2, name, kind, startLine, endLine, start, end, execution }) => ({
16488
16792
  id: id2,
16489
16793
  name,
16490
16794
  kind,
16491
- anchor: { path: path21, startLine, endLine, start, end },
16795
+ anchor: { path: path24, startLine, endLine, start, end },
16492
16796
  ...execution ? { execution } : {}
16493
16797
  }))
16494
16798
  )
@@ -16501,10 +16805,10 @@ var mapSearchNavigation = (result) => {
16501
16805
  for (const [index, object2] of found.entries()) {
16502
16806
  const ranking = rankings[index];
16503
16807
  if (!ranking) throw new Error("PROJECT_MAP_SEARCH_RANKING_MISSING");
16504
- const path21 = object2.anchor.path;
16808
+ const path24 = object2.anchor.path;
16505
16809
  let file2 = files.at(-1);
16506
- if (file2?.path !== path21) {
16507
- file2 = { path: path21, symbols: [] };
16810
+ if (file2?.path !== path24) {
16811
+ file2 = { path: path24, symbols: [] };
16508
16812
  files.push(file2);
16509
16813
  }
16510
16814
  file2.symbols.push({
@@ -16635,8 +16939,8 @@ var MapViewGraph = class {
16635
16939
  }
16636
16940
  return object2;
16637
16941
  }
16638
- objectsAt(path21) {
16639
- return this.statements.path.all(this.version, path21).map((row) => {
16942
+ objectsAt(path24) {
16943
+ return this.statements.path.all(this.version, path24).map((row) => {
16640
16944
  const object2 = MapObjectSchema.parse(JSON.parse(String(row.object_json)));
16641
16945
  this.objects.set(object2.id, object2);
16642
16946
  return object2;
@@ -16662,8 +16966,8 @@ var MapViewGraph = class {
16662
16966
  return this.statements.children.all(this.version, ref).map((row) => String(row.to_ref));
16663
16967
  }
16664
16968
  /** The declarations of a file other code can name, without the file itself. */
16665
- declarationsAt(path21) {
16666
- return this.objectsAt(path21).filter(
16969
+ declarationsAt(path24) {
16970
+ return this.objectsAt(path24).filter(
16667
16971
  (object2) => !mapIsModule(object2) && this.isAddressable(object2)
16668
16972
  );
16669
16973
  }
@@ -16771,8 +17075,8 @@ var MapViewGraph = class {
16771
17075
  );
16772
17076
  }
16773
17077
  };
16774
- function mapSelectDeclarations(graph, path21, name, line) {
16775
- const objects2 = graph.objectsAt(path21).filter((object2) => !mapIsModule(object2));
17078
+ function mapSelectDeclarations(graph, path24, name, line) {
17079
+ const objects2 = graph.objectsAt(path24).filter((object2) => !mapIsModule(object2));
16776
17080
  const matching = name === void 0 ? objects2 : objects2.filter(
16777
17081
  (object2) => object2.name === name || name.includes(".") && graph.qualifiedName(object2.id) === name
16778
17082
  );
@@ -16794,12 +17098,12 @@ function requireMapObject(store, version2, selector, prefixes) {
16794
17098
  if ([entityRef, locator, symbol2].filter((value) => value !== void 0).length !== 1 || entityRef !== void 0 && !entityRef.length)
16795
17099
  throw new ProjectEvidenceError("PROJECT_READ_INPUT_INVALID", false);
16796
17100
  if (symbol2) {
16797
- const path21 = normalizeProjectEvidencePath(symbol2.path);
16798
- if (!mapPathAllowed(path21, prefixes))
17101
+ const path24 = normalizeProjectEvidencePath(symbol2.path);
17102
+ if (!mapPathAllowed(path24, prefixes))
16799
17103
  throw new ProjectEvidenceError("PROJECT_MAP_OBJECT_NOT_FOUND", false);
16800
17104
  const selected = mapSelectDeclarations(
16801
17105
  new MapViewGraph(store, version2),
16802
- path21,
17106
+ path24,
16803
17107
  symbol2.name,
16804
17108
  symbol2.line
16805
17109
  );
@@ -16810,14 +17114,14 @@ function requireMapObject(store, version2, selector, prefixes) {
16810
17114
  }
16811
17115
  let rows2;
16812
17116
  if (locator) {
16813
- const path21 = normalizeProjectEvidencePath(locator.path);
17117
+ const path24 = normalizeProjectEvidencePath(locator.path);
16814
17118
  if (!Number.isSafeInteger(locator.start) || locator.start < 0 || locator.kind !== void 0 && !MapObjectKindSchema.safeParse(locator.kind).success)
16815
17119
  throw new ProjectEvidenceError("PROJECT_READ_INPUT_INVALID", false);
16816
- if (!mapPathAllowed(path21, prefixes))
17120
+ if (!mapPathAllowed(path24, prefixes))
16817
17121
  throw new ProjectEvidenceError("PROJECT_MAP_OBJECT_NOT_FOUND", false);
16818
17122
  rows2 = store.database.prepare(`SELECT object_json FROM project_map_objects
16819
17123
  WHERE version_ref = ? AND path = ? AND json_extract(object_json, '$.anchor.start') = ?
16820
- AND (? IS NULL OR kind = ?) LIMIT 2`).all(version2, path21, locator.start, locator.kind ?? null, locator.kind ?? null);
17124
+ AND (? IS NULL OR kind = ?) LIMIT 2`).all(version2, path24, locator.start, locator.kind ?? null, locator.kind ?? null);
16821
17125
  } else {
16822
17126
  rows2 = store.database.prepare(
16823
17127
  "SELECT object_json FROM project_map_objects WHERE version_ref = ? AND entity_ref = ?"
@@ -16858,13 +17162,13 @@ function mapQueryPage(count, materialize, navigation, budget) {
16858
17162
 
16859
17163
  // src/project-map-query-selection.ts
16860
17164
  var mapQuerySelection = (input, knownKinds) => {
16861
- const path21 = normalizeProjectEvidencePath(input.path ?? ".", true) || ".";
17165
+ const path24 = normalizeProjectEvidencePath(input.path ?? ".", true) || ".";
16862
17166
  const kinds = input.kinds ?? knownKinds;
16863
17167
  if (!Array.isArray(kinds) || !kinds.length || kinds.length > knownKinds.length || kinds.some((kind) => !knownKinds.includes(kind)))
16864
17168
  throw new ProjectEvidenceError("PROJECT_READ_INPUT_INVALID", false);
16865
- return { path: path21, kinds: [...new Set(kinds)].sort() };
17169
+ return { path: path24, kinds: [...new Set(kinds)].sort() };
16866
17170
  };
16867
- var mapQueryPathMatches = (path21, prefix) => prefix === "." || path21 === prefix || path21.startsWith(`${prefix}/`);
17171
+ var mapQueryPathMatches = (path24, prefix) => prefix === "." || path24 === prefix || path24.startsWith(`${prefix}/`);
16868
17172
  var MAP_RELATION_TARGET_JOIN = `LEFT JOIN project_map_unit_objects t ON t.entity_ref = r.to_ref
16869
17173
  AND EXISTS (SELECT 1 FROM project_map_version_units target
16870
17174
  WHERE target.version_ref = r.version_ref AND target.unit_ref = t.unit_ref AND target.path = t.path)`;
@@ -16966,7 +17270,7 @@ var declarationKinds = /* @__PURE__ */ new Set([
16966
17270
  "METHOD",
16967
17271
  "TYPE"
16968
17272
  ]);
16969
- var fileStem = (path21) => path21.slice(path21.lastIndexOf("/") + 1).replace(/\.(?:[cm]?[jt]sx?|vue|svelte|go|pyi?)$/iu, "");
17273
+ var fileStem = (path24) => path24.slice(path24.lastIndexOf("/") + 1).replace(/\.(?:[cm]?[jt]sx?|vue|svelte|go|pyi?)$/iu, "");
16970
17274
  var compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
16971
17275
  var compareRows = (left, right) => right.ranking.score - left.ranking.score || compareText(left.object.anchor.path, right.object.anchor.path) || compareText(left.object.id, right.object.id);
16972
17276
  function mapSearchQuery(input) {
@@ -16993,10 +17297,10 @@ function mapSearchQuery(input) {
16993
17297
  }
16994
17298
  function rank(object2, documentation, relationCount, query, focus) {
16995
17299
  const name = object2.name.toLowerCase();
16996
- const path21 = object2.anchor.path.toLowerCase();
17300
+ const path24 = object2.anchor.path.toLowerCase();
16997
17301
  const values = {
16998
17302
  NAME: [name],
16999
- PATH: [path21],
17303
+ PATH: [path24],
17000
17304
  DOCUMENTATION: documentation.map((text) => text.toLowerCase())
17001
17305
  };
17002
17306
  const matched = query.terms.map((term) => ({
@@ -17021,12 +17325,12 @@ function rank(object2, documentation, relationCount, query, focus) {
17021
17325
  score += 7e3;
17022
17326
  signals.push("SYMBOL_CONTAINS");
17023
17327
  } else if (matchedFields.includes("NAME")) signals.push("SYMBOL_CONTAINS");
17024
- if (object2.kind === "FILE" && fileStem(path21) === normalizedQuery) {
17328
+ if (object2.kind === "FILE" && fileStem(path24) === normalizedQuery) {
17025
17329
  score += 11e3;
17026
17330
  signals.push("EXACT_FILE_STEM");
17027
17331
  }
17028
17332
  if (matchedFields.includes("PATH")) {
17029
- score += path21.includes(normalizedQuery) ? 2500 : 0;
17333
+ score += path24.includes(normalizedQuery) ? 2500 : 0;
17030
17334
  signals.push("PATH_CONTAINS");
17031
17335
  }
17032
17336
  if (matchedFields.includes("DOCUMENTATION")) {
@@ -17041,8 +17345,8 @@ function rank(object2, documentation, relationCount, query, focus) {
17041
17345
  score += kindWeight[object2.kind] + Math.min(1200, relationCount * 20) + (focus?.score ?? 0);
17042
17346
  if (declarationKinds.has(object2.kind)) signals.push("DECLARATION");
17043
17347
  if (relationCount > 0) signals.push("GRAPH_CONNECTED");
17044
- const isTest = mapTestPath(path21);
17045
- const isGenerated = generatedPath.test(path21);
17348
+ const isTest = mapTestPath(path24);
17349
+ const isGenerated = generatedPath.test(path24);
17046
17350
  const hasTestIntent = query.terms.some((term) => testQuery.test(term));
17047
17351
  score += isTest ? hasTestIntent ? 1e3 : -5e3 : 300;
17048
17352
  score += isGenerated ? -3e3 : 300;
@@ -17554,13 +17858,13 @@ function utf16Offsets(text) {
17554
17858
  }
17555
17859
  function offsetConverter(files, offsets) {
17556
17860
  const converters = /* @__PURE__ */ new Map();
17557
- return (path21, offset) => {
17558
- let convert = converters.get(path21);
17861
+ return (path24, offset) => {
17862
+ let convert = converters.get(path24);
17559
17863
  if (!convert) {
17560
- const text = files[path21];
17864
+ const text = files[path24];
17561
17865
  if (text === void 0) return invalid();
17562
17866
  convert = offsets === "UTF16" ? (value) => value <= text.length ? value : invalid() : utf16Offsets(text);
17563
- converters.set(path21, convert);
17867
+ converters.set(path24, convert);
17564
17868
  }
17565
17869
  return convert(offset);
17566
17870
  };
@@ -17591,7 +17895,7 @@ function mapFactsAnalysis(facts, input, context) {
17591
17895
  const collect = new MapOutputCollector(output);
17592
17896
  const positions = new MapSourcePositions(input.files);
17593
17897
  const offset = offsetConverter(input.files, context.offsets);
17594
- const anchor = (path21, start, end) => positions.span(path21, offset(path21, start), offset(path21, end));
17898
+ const anchor = (path24, start, end) => positions.span(path24, offset(path24, start), offset(path24, end));
17595
17899
  const located = /* @__PURE__ */ new Map();
17596
17900
  const canonical = /* @__PURE__ */ new Map();
17597
17901
  const bySpan = /* @__PURE__ */ new Map();
@@ -17766,7 +18070,7 @@ function referencePage(found, positions, offset, reference) {
17766
18070
  // src/project-map-process.ts
17767
18071
  import { execFileSync, spawn as spawn2 } from "node:child_process";
17768
18072
  import { existsSync as existsSync3, readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
17769
- import path9 from "node:path";
18073
+ import path11 from "node:path";
17770
18074
 
17771
18075
  // src/project-map-failure.ts
17772
18076
  var PhaseSchema = external_exports.enum([
@@ -17893,24 +18197,24 @@ var ProjectMapStopUnconfirmedError = class extends ProjectEvidenceError {
17893
18197
  }
17894
18198
  };
17895
18199
  var installedMapParserResources = () => {
17896
- const directory = path9.dirname(path9.resolve(process.argv[1] ?? "."));
18200
+ const directory = path11.dirname(path11.resolve(process.argv[1] ?? "."));
17897
18201
  return {
17898
- workerPath: path9.join(directory, "project-map-worker.mjs"),
17899
- compilerPath: path9.join(directory, "project-map-native/tsc")
18202
+ workerPath: path11.join(directory, "project-map-worker.mjs"),
18203
+ compilerPath: path11.join(directory, "project-map-native/tsc")
17900
18204
  };
17901
18205
  };
17902
18206
  var installedPythonMapResources = () => {
17903
- const directory = path9.dirname(path9.resolve(process.argv[1] ?? "."));
18207
+ const directory = path11.dirname(path11.resolve(process.argv[1] ?? "."));
17904
18208
  return {
17905
- workerPath: path9.join(directory, "project-map-python-worker.mjs"),
17906
- compilerPath: path9.join(directory, "project-map-python/typeshed")
18209
+ workerPath: path11.join(directory, "project-map-python-worker.mjs"),
18210
+ compilerPath: path11.join(directory, "project-map-python/typeshed")
17907
18211
  };
17908
18212
  };
17909
18213
  function discoverJavaRuntime(env = process.env) {
17910
18214
  const homes = [env.LAYERMAP_JAVA_HOME, env.JAVA_HOME];
17911
- for (const directory of (env.PATH ?? env.Path ?? "").split(path9.delimiter)) {
17912
- const java = path9.join(directory, executableName("java"));
17913
- if (directory && existsSync3(java)) homes.push(path9.dirname(path9.dirname(realpathSync2(java))));
18215
+ for (const directory of (env.PATH ?? env.Path ?? "").split(path11.delimiter)) {
18216
+ const java = path11.join(directory, executableName("java"));
18217
+ if (directory && existsSync3(java)) homes.push(path11.dirname(path11.dirname(realpathSync2(java))));
17914
18218
  }
17915
18219
  homes.push(
17916
18220
  ...["/opt/homebrew/opt", "/usr/local/opt"].flatMap(
@@ -17918,7 +18222,7 @@ function discoverJavaRuntime(env = process.env) {
17918
18222
  (formula) => `${prefix}/${formula}/libexec/openjdk.jdk/Contents/Home`
17919
18223
  )
17920
18224
  ),
17921
- ...env.HOME ? [path9.join(env.HOME, ".sdkman/candidates/java/current")] : []
18225
+ ...env.HOME ? [path11.join(env.HOME, ".sdkman/candidates/java/current")] : []
17922
18226
  );
17923
18227
  if (process.platform === "darwin")
17924
18228
  try {
@@ -17933,12 +18237,12 @@ function discoverJavaRuntime(env = process.env) {
17933
18237
  }
17934
18238
  for (const home of homes) {
17935
18239
  if (!home) continue;
17936
- const runtimePath = path9.join(home, "bin", executableName("java"));
17937
- if (!existsSync3(runtimePath) || !existsSync3(path9.join(home, "bin", executableName("javac"))))
18240
+ const runtimePath = path11.join(home, "bin", executableName("java"));
18241
+ if (!existsSync3(runtimePath) || !existsSync3(path11.join(home, "bin", executableName("javac"))))
17938
18242
  continue;
17939
18243
  let release = "";
17940
18244
  try {
17941
- release = readFileSync2(path9.join(home, "release"), "utf8");
18245
+ release = readFileSync2(path11.join(home, "release"), "utf8");
17942
18246
  } catch {
17943
18247
  continue;
17944
18248
  }
@@ -17949,26 +18253,26 @@ function discoverJavaRuntime(env = process.env) {
17949
18253
  return void 0;
17950
18254
  }
17951
18255
  var installedJavaMapResources = () => {
17952
- const directory = path9.dirname(path9.resolve(process.argv[1] ?? "."));
17953
- const compilerPath = path9.join(directory, "project-map-java/java-map.jar");
18256
+ const directory = path11.dirname(path11.resolve(process.argv[1] ?? "."));
18257
+ const compilerPath = path11.join(directory, "project-map-java/java-map.jar");
17954
18258
  return {
17955
- workerPath: path9.join(directory, "project-map-java-worker.mjs"),
18259
+ workerPath: path11.join(directory, "project-map-java-worker.mjs"),
17956
18260
  compilerPath,
17957
18261
  // A build without a JDK leaves no analyzer to run, whatever runtime this machine has.
17958
18262
  ...existsSync3(compilerPath) ? discoverJavaRuntime() : {}
17959
18263
  };
17960
18264
  };
17961
18265
  var installedGoMapResources = () => {
17962
- const directory = path9.dirname(path9.resolve(process.argv[1] ?? "."));
18266
+ const directory = path11.dirname(path11.resolve(process.argv[1] ?? "."));
17963
18267
  return {
17964
- workerPath: path9.join(directory, "project-map-go-worker.mjs"),
17965
- compilerPath: path9.join(directory, "project-map-go/go-map")
18268
+ workerPath: path11.join(directory, "project-map-go-worker.mjs"),
18269
+ compilerPath: path11.join(directory, "project-map-go/go-map")
17966
18270
  };
17967
18271
  };
17968
18272
  function runMapOperation(resources, input, schema, signal, observeTiming) {
17969
18273
  if (signal.aborted)
17970
18274
  return Promise.reject(new ProjectEvidenceError("PROJECT_READ_CANCELLED", true));
17971
- if (!path9.isAbsolute(resources.workerPath) || !path9.isAbsolute(resources.compilerPath)) {
18275
+ if (!path11.isAbsolute(resources.workerPath) || !path11.isAbsolute(resources.compilerPath)) {
17972
18276
  return Promise.reject(
17973
18277
  new ProjectEvidenceError("PROJECT_MAP_PARSER_CONFIGURATION_INVALID", false)
17974
18278
  );
@@ -18171,8 +18475,8 @@ var goWork = /(?:^|\/)go\.work$/u;
18171
18475
  var codeHosts = /* @__PURE__ */ new Set(["github.com", "gitlab.com", "bitbucket.org"]);
18172
18476
  var GO_MAP_LANGUAGE = Object.freeze({
18173
18477
  id: "go-1.24-map-v11",
18174
- claims: (path21) => path21.endsWith(".go"),
18175
- reads: (path21) => goModule.test(path21) || goWork.test(path21),
18478
+ claims: (path24) => path24.endsWith(".go"),
18479
+ reads: (path24) => goModule.test(path24) || goWork.test(path24),
18176
18480
  // A module path, or the standard library, whose first path element has no dot.
18177
18481
  importName: (specifier) => {
18178
18482
  const parts = specifier.split("/");
@@ -18181,7 +18485,7 @@ var GO_MAP_LANGUAGE = Object.freeze({
18181
18485
  return parts.slice(0, size).join("/");
18182
18486
  },
18183
18487
  // Go imports a package: the directory of the file.
18184
- importTarget: (path21) => `${path21.slice(0, path21.lastIndexOf("/") + 1) || "./"}`,
18488
+ importTarget: (path24) => `${path24.slice(0, path24.lastIndexOf("/") + 1) || "./"}`,
18185
18489
  create: () => new GoMapAnalyzer()
18186
18490
  });
18187
18491
  var GO_GAPS = [
@@ -18206,8 +18510,8 @@ var goMapAnalysis = (facts, input, configurations) => mapFactsAnalysis(facts, in
18206
18510
  typeIssues: "GO_TYPE_CHECK_ISSUES",
18207
18511
  contract: "Declares a Go interface. This does not establish runtime enforcement or business authority."
18208
18512
  });
18209
- var goLocalModules = (path21, text) => {
18210
- const directive = goWork.test(path21) ? "use" : "replace";
18513
+ var goLocalModules = (path24, text) => {
18514
+ const directive = goWork.test(path24) ? "use" : "replace";
18211
18515
  const found = [];
18212
18516
  let block = false;
18213
18517
  for (const raw of text.split("\n")) {
@@ -18221,37 +18525,37 @@ var goLocalModules = (path21, text) => {
18221
18525
  const target = directive === "use" ? entry : entry?.split("=>")[1];
18222
18526
  const directory = target?.trim().split(/\s+/u)[0]?.replace(/^(["`])(.*)\1$/u, "$2");
18223
18527
  if (!directory || !/^\.\.?(?:\/|$)/u.test(directory)) continue;
18224
- const joined = posix.normalize(posix.join(posix.dirname(path21), directory)).replace(/\/$/u, "");
18528
+ const joined = posix.normalize(posix.join(posix.dirname(path24), directory)).replace(/\/$/u, "");
18225
18529
  if (joined !== ".." && !joined.startsWith("../")) found.push(joined);
18226
18530
  }
18227
18531
  return found;
18228
18532
  };
18229
18533
  var goModuleGroups = (files, text) => {
18230
- const modules = files.filter((path21) => goModule.test(path21)).sort();
18231
- const moduleAt = new Map(modules.map((path21) => [posix.dirname(path21), path21]));
18232
- const parent = new Map(modules.map((path21) => [path21, path21]));
18233
- const root = (path21) => {
18234
- const up = parent.get(path21) ?? path21;
18235
- return up === path21 ? path21 : root(up);
18534
+ const modules = files.filter((path24) => goModule.test(path24)).sort();
18535
+ const moduleAt = new Map(modules.map((path24) => [posix.dirname(path24), path24]));
18536
+ const parent = new Map(modules.map((path24) => [path24, path24]));
18537
+ const root = (path24) => {
18538
+ const up = parent.get(path24) ?? path24;
18539
+ return up === path24 ? path24 : root(up);
18236
18540
  };
18237
18541
  const works = [];
18238
- for (const path21 of [...files].filter((file2) => goModule.test(file2) || goWork.test(file2)).sort()) {
18239
- const linked = goLocalModules(path21, text(path21)).flatMap((dir) => moduleAt.get(dir) ?? []);
18240
- const first = goWork.test(path21) ? linked[0] : path21;
18542
+ for (const path24 of [...files].filter((file2) => goModule.test(file2) || goWork.test(file2)).sort()) {
18543
+ const linked = goLocalModules(path24, text(path24)).flatMap((dir) => moduleAt.get(dir) ?? []);
18544
+ const first = goWork.test(path24) ? linked[0] : path24;
18241
18545
  if (!first) continue;
18242
- if (goWork.test(path21)) works.push([path21, first]);
18546
+ if (goWork.test(path24)) works.push([path24, first]);
18243
18547
  for (const module of linked) {
18244
18548
  const [low = first, high = module] = [root(first), root(module)].sort();
18245
18549
  if (low !== high) parent.set(high, low);
18246
18550
  }
18247
18551
  }
18248
18552
  const members = /* @__PURE__ */ new Map();
18249
- for (const path21 of modules) members.set(root(path21), [...members.get(root(path21)) ?? [], path21]);
18553
+ for (const path24 of modules) members.set(root(path24), [...members.get(root(path24)) ?? [], path24]);
18250
18554
  const named = new Map(works.reverse().map(([work, module]) => [root(module), work]));
18251
18555
  return new Map(
18252
- modules.map((path21) => [
18253
- path21,
18254
- { configPath: named.get(root(path21)) ?? root(path21), modules: members.get(root(path21)) ?? [] }
18556
+ modules.map((path24) => [
18557
+ path24,
18558
+ { configPath: named.get(root(path24)) ?? root(path24), modules: members.get(root(path24)) ?? [] }
18255
18559
  ])
18256
18560
  );
18257
18561
  };
@@ -18281,28 +18585,28 @@ var GoMapAnalyzer = class {
18281
18585
  }
18282
18586
  async analyze(session, signal) {
18283
18587
  const paths = session.readable.map((entry) => entry.path);
18284
- const groupOf = goModuleGroups(paths, (path21) => session.texts[path21] ?? "");
18285
- const moduleOf = (path21) => {
18588
+ const groupOf = goModuleGroups(paths, (path24) => session.texts[path24] ?? "");
18589
+ const moduleOf = (path24) => {
18286
18590
  let best;
18287
18591
  for (const modFile of groupOf.keys()) {
18288
18592
  const directory = modFile.slice(0, modFile.lastIndexOf("/") + 1);
18289
- if (path21.startsWith(directory) && (!best || directory.length > best.lastIndexOf("/") + 1))
18593
+ if (path24.startsWith(directory) && (!best || directory.length > best.lastIndexOf("/") + 1))
18290
18594
  best = modFile;
18291
18595
  }
18292
18596
  return best;
18293
18597
  };
18294
18598
  const contexts = /* @__PURE__ */ new Map();
18295
- for (const path21 of paths) {
18296
- if (!this.claims(path21)) continue;
18297
- const module = moduleOf(path21);
18599
+ for (const path24 of paths) {
18600
+ if (!this.claims(path24)) continue;
18601
+ const module = moduleOf(path24);
18298
18602
  const group = module ? groupOf.get(module) : void 0;
18299
18603
  const configPath = group?.configPath ?? "";
18300
18604
  const into = contexts.get(configPath);
18301
- if (into) into.sources.push(path21);
18605
+ if (into) into.sources.push(path24);
18302
18606
  else
18303
18607
  contexts.set(configPath, {
18304
18608
  configurations: group ? [.../* @__PURE__ */ new Set([...group.modules, configPath])].sort() : [],
18305
- sources: [path21]
18609
+ sources: [path24]
18306
18610
  });
18307
18611
  }
18308
18612
  for (const [configPath, { configurations, sources }] of [...contexts].sort(
@@ -18310,11 +18614,11 @@ var GoMapAnalyzer = class {
18310
18614
  )) {
18311
18615
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
18312
18616
  const files = /* @__PURE__ */ Object.create(null);
18313
- for (const path21 of [...sources, ...configurations]) {
18314
- const text = session.texts[path21];
18617
+ for (const path24 of [...sources, ...configurations]) {
18618
+ const text = session.texts[path24];
18315
18619
  if (text === void 0)
18316
18620
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
18317
- files[path21] = text;
18621
+ files[path24] = text;
18318
18622
  }
18319
18623
  const input = {
18320
18624
  contextRef: digestValue({
@@ -18348,8 +18652,8 @@ var GoMapAnalyzer = class {
18348
18652
  if (!existsSync4(this.resources.compilerPath))
18349
18653
  return { pages: references.map(() => null), requiredFiles: [] };
18350
18654
  const files = /* @__PURE__ */ Object.create(null);
18351
- for (const [path21, value] of Object.entries(input.files))
18352
- if (this.claims(path21) || this.reads(path21)) files[path21] = value;
18655
+ for (const [path24, value] of Object.entries(input.files))
18656
+ if (this.claims(path24) || this.reads(path24)) files[path24] = value;
18353
18657
  const facts = await this.operation(
18354
18658
  {
18355
18659
  ...input,
@@ -18378,14 +18682,14 @@ var BUILD_FILES = [
18378
18682
  "pom.xml"
18379
18683
  ];
18380
18684
  var buildFile = /(?:^|\/)(?:pom\.xml|(?:build|settings)\.gradle(?:\.kts)?)$/u;
18381
- var directoryOf = (path21) => path21.slice(0, path21.lastIndexOf("/") + 1);
18382
- var nameOf = (path21) => path21.slice(path21.lastIndexOf("/") + 1);
18685
+ var directoryOf = (path24) => path24.slice(0, path24.lastIndexOf("/") + 1);
18686
+ var nameOf = (path24) => path24.slice(path24.lastIndexOf("/") + 1);
18383
18687
  var DEFAULT_RELEASE = 21;
18384
18688
  var platformPackage = /^(?:java|jdk|sun|com\.sun|javax\.(?:annotation\.processing|crypto|imageio|lang\.model|management|naming|net|print|script|security|sound|sql|swing|tools|transaction\.xa|xml))(?:\.|$)/u;
18385
18689
  var JAVA_MAP_LANGUAGE = Object.freeze({
18386
18690
  id: "javac-lombok-1.18.48-map-v10",
18387
- claims: (path21) => path21.endsWith(".java"),
18388
- reads: (path21) => buildFile.test(path21),
18691
+ claims: (path24) => path24.endsWith(".java"),
18692
+ reads: (path24) => buildFile.test(path24),
18389
18693
  // A package of the Java platform, or a library named by its first two package segments.
18390
18694
  importName: (specifier) => platformPackage.test(specifier) ? "Java standard library" : specifier.split(".").slice(0, 2).join("."),
18391
18695
  create: () => new JavaMapAnalyzer()
@@ -18475,8 +18779,8 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18475
18779
  // The worker's request for a context: the Java sources and the release.
18476
18780
  request(input, buildTexts) {
18477
18781
  const files = /* @__PURE__ */ Object.create(null);
18478
- for (const [path21, text] of Object.entries(input.files))
18479
- if (this.claims(path21)) files[path21] = text;
18782
+ for (const [path24, text] of Object.entries(input.files))
18783
+ if (this.claims(path24)) files[path24] = text;
18480
18784
  return {
18481
18785
  files,
18482
18786
  release: javaRelease(buildTexts, this.resources.runtimeVersion)
@@ -18491,35 +18795,35 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18491
18795
  }
18492
18796
  async analyze(session, signal) {
18493
18797
  this.refreshRuntime();
18494
- const builds = session.readable.map((entry) => entry.path).filter((path21) => buildFile.test(path21));
18495
- for (const path21 of builds) session.configuration(path21);
18496
- const rank2 = (path21) => BUILD_FILES.indexOf(nameOf(path21));
18798
+ const builds = session.readable.map((entry) => entry.path).filter((path24) => buildFile.test(path24));
18799
+ for (const path24 of builds) session.configuration(path24);
18800
+ const rank2 = (path24) => BUILD_FILES.indexOf(nameOf(path24));
18497
18801
  const roots = /* @__PURE__ */ new Map();
18498
18802
  const modules = /* @__PURE__ */ new Map();
18499
- for (const path21 of builds) {
18500
- const directory = directoryOf(path21);
18803
+ for (const path24 of builds) {
18804
+ const directory = directoryOf(path24);
18501
18805
  const current = modules.get(directory);
18502
- if (current === void 0 || rank2(path21) < rank2(current)) modules.set(directory, path21);
18503
- const text = session.texts[path21] ?? "";
18504
- if (/settings\.gradle(?:\.kts)?$/u.test(path21) || path21.endsWith("pom.xml") && /<modules>/u.test(text)) {
18806
+ if (current === void 0 || rank2(path24) < rank2(current)) modules.set(directory, path24);
18807
+ const text = session.texts[path24] ?? "";
18808
+ if (/settings\.gradle(?:\.kts)?$/u.test(path24) || path24.endsWith("pom.xml") && /<modules>/u.test(text)) {
18505
18809
  const root = roots.get(directory);
18506
- if (root === void 0 || rank2(path21) < rank2(root)) roots.set(directory, path21);
18810
+ if (root === void 0 || rank2(path24) < rank2(root)) roots.set(directory, path24);
18507
18811
  }
18508
18812
  }
18509
- const configOf = (path21) => {
18813
+ const configOf = (path24) => {
18510
18814
  let outer;
18511
18815
  for (const directory of roots.keys())
18512
- if (path21.startsWith(directory) && (outer === void 0 || directory.length < outer.length))
18816
+ if (path24.startsWith(directory) && (outer === void 0 || directory.length < outer.length))
18513
18817
  outer = directory;
18514
18818
  if (outer !== void 0) return roots.get(outer);
18515
18819
  let nearest;
18516
18820
  for (const directory of modules.keys())
18517
- if (path21.startsWith(directory) && (nearest === void 0 || directory.length > nearest.length))
18821
+ if (path24.startsWith(directory) && (nearest === void 0 || directory.length > nearest.length))
18518
18822
  nearest = directory;
18519
18823
  return nearest === void 0 ? "" : modules.get(nearest);
18520
18824
  };
18521
- const output = (path21) => [...modules.keys()].some(
18522
- (directory) => path21.startsWith(`${directory}build/`) || path21.startsWith(`${directory}target/`)
18825
+ const output = (path24) => [...modules.keys()].some(
18826
+ (directory) => path24.startsWith(`${directory}build/`) || path24.startsWith(`${directory}target/`)
18523
18827
  );
18524
18828
  const groups = /* @__PURE__ */ new Map();
18525
18829
  for (const entry of session.readable) {
@@ -18534,13 +18838,13 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18534
18838
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
18535
18839
  const files = /* @__PURE__ */ Object.create(null);
18536
18840
  const rootBuilds = configPath ? BUILD_FILES.map((name) => `${directoryOf(configPath)}${name}`).filter(
18537
- (path21) => builds.includes(path21)
18841
+ (path24) => builds.includes(path24)
18538
18842
  ) : [];
18539
- for (const path21 of [...groups.get(configPath) ?? [], ...rootBuilds]) {
18540
- const text = session.texts[path21];
18843
+ for (const path24 of [...groups.get(configPath) ?? [], ...rootBuilds]) {
18844
+ const text = session.texts[path24];
18541
18845
  if (text === void 0)
18542
18846
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
18543
- files[path21] = text;
18847
+ files[path24] = text;
18544
18848
  }
18545
18849
  const input = {
18546
18850
  contextRef: digestValue({
@@ -18582,7 +18886,7 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18582
18886
  const prior = JavaStateSchema.safeParse(previous?.state).data;
18583
18887
  const incremental = previous && prior?.basis === basis ? {
18584
18888
  changed: Object.keys(request.files).filter(
18585
- (path21) => digests.get(path21) !== previous.digests.get(path21)
18889
+ (path24) => digests.get(path24) !== previous.digests.get(path24)
18586
18890
  ),
18587
18891
  state: prior.java
18588
18892
  } : void 0;
@@ -18611,14 +18915,14 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18611
18915
  continue;
18612
18916
  }
18613
18917
  const focus = new Set(facts.focus);
18614
- if (!incremental || facts.focus.some((path21) => !Object.hasOwn(request.files, path21)) || incremental.changed.some((path21) => !focus.has(path21)))
18918
+ if (!incremental || facts.focus.some((path24) => !Object.hasOwn(request.files, path24)) || incremental.changed.some((path24) => !focus.has(path24)))
18615
18919
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
18616
18920
  analysis.objects = analysis.objects.filter((object2) => focus.has(object2.anchor.path));
18617
18921
  analysis.relations = analysis.relations.filter((relation) => focus.has(relation.anchor.path));
18618
18922
  analysis.notes = analysis.notes.filter((note) => focus.has(note.anchor.path));
18619
18923
  session.accept(analysis, {
18620
18924
  state: state2,
18621
- linked: analysis.parsedFiles.filter((path21) => !focus.has(path21))
18925
+ linked: analysis.parsedFiles.filter((path24) => !focus.has(path24))
18622
18926
  });
18623
18927
  }
18624
18928
  }
@@ -18933,12 +19237,12 @@ var PYTHON_STANDARD_LIBRARY = /* @__PURE__ */ new Set([
18933
19237
  // src/project-map-language-python.ts
18934
19238
  var CONFIGURATION = ["pyrightconfig.json", "pyproject.toml", "setup.cfg"];
18935
19239
  var pythonConfig = /(?:^|\/)(?:pyrightconfig\.json|pyproject\.toml|setup\.cfg)$/u;
18936
- var directoryOf2 = (path21) => path21.slice(0, path21.lastIndexOf("/") + 1);
19240
+ var directoryOf2 = (path24) => path24.slice(0, path24.lastIndexOf("/") + 1);
18937
19241
  var DEFAULT_PYTHON = { major: 3, minor: 13 };
18938
19242
  var PYTHON_MAP_LANGUAGE = Object.freeze({
18939
19243
  id: "pyright-1.1.414-map-v14",
18940
- claims: (path21) => /\.pyi?$/u.test(path21),
18941
- reads: (path21) => pythonConfig.test(path21),
19244
+ claims: (path24) => /\.pyi?$/u.test(path24),
19245
+ reads: (path24) => pythonConfig.test(path24),
18942
19246
  // An absolute import names the standard library or a distribution's top-level package.
18943
19247
  importName: (specifier) => {
18944
19248
  const top = specifier.split(".", 1)[0] ?? specifier;
@@ -18994,16 +19298,16 @@ var PythonMapAnalyzer = class {
18994
19298
  }
18995
19299
  async analyze(session, signal) {
18996
19300
  const roots = /* @__PURE__ */ new Map();
18997
- for (const path21 of session.readable.map((entry) => entry.path).filter((path22) => pythonConfig.test(path22))) {
18998
- const directory = directoryOf2(path21);
19301
+ for (const path24 of session.readable.map((entry) => entry.path).filter((path25) => pythonConfig.test(path25))) {
19302
+ const directory = directoryOf2(path24);
18999
19303
  const current = roots.get(directory);
19000
19304
  const rank2 = (file2) => CONFIGURATION.indexOf(file2.slice(directory.length));
19001
- if (current === void 0 || rank2(path21) < rank2(current)) roots.set(directory, path21);
19305
+ if (current === void 0 || rank2(path24) < rank2(current)) roots.set(directory, path24);
19002
19306
  }
19003
- const rootOf = (path21) => {
19307
+ const rootOf = (path24) => {
19004
19308
  let best;
19005
19309
  for (const directory of roots.keys())
19006
- if (path21.startsWith(directory) && (best === void 0 || directory.length > best.length))
19310
+ if (path24.startsWith(directory) && (best === void 0 || directory.length > best.length))
19007
19311
  best = directory;
19008
19312
  return best === void 0 ? "" : roots.get(best);
19009
19313
  };
@@ -19018,11 +19322,11 @@ var PythonMapAnalyzer = class {
19018
19322
  for (const configPath of [...groups.keys()].sort()) {
19019
19323
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
19020
19324
  const files = /* @__PURE__ */ Object.create(null);
19021
- for (const path21 of [...groups.get(configPath) ?? [], ...configPath ? [configPath] : []]) {
19022
- const text = session.texts[path21];
19325
+ for (const path24 of [...groups.get(configPath) ?? [], ...configPath ? [configPath] : []]) {
19326
+ const text = session.texts[path24];
19023
19327
  if (text === void 0)
19024
19328
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
19025
- files[path21] = text;
19329
+ files[path24] = text;
19026
19330
  }
19027
19331
  const input = {
19028
19332
  contextRef: digestValue({
@@ -19068,8 +19372,8 @@ var PythonMapAnalyzer = class {
19068
19372
  }
19069
19373
  async references(input, references, signal, observe) {
19070
19374
  const files = /* @__PURE__ */ Object.create(null);
19071
- for (const [path21, value] of Object.entries(input.files))
19072
- if (this.claims(path21) || pythonConfig.test(path21)) files[path21] = value;
19375
+ for (const [path24, value] of Object.entries(input.files))
19376
+ if (this.claims(path24) || pythonConfig.test(path24)) files[path24] = value;
19073
19377
  const facts = await this.operation(
19074
19378
  {
19075
19379
  ...input,
@@ -19093,7 +19397,7 @@ var PythonMapAnalyzer = class {
19093
19397
  import { availableParallelism } from "node:os";
19094
19398
 
19095
19399
  // src/project-map-miniprogram.ts
19096
- import path10 from "node:path";
19400
+ import path12 from "node:path";
19097
19401
  import {
19098
19402
  isCallExpression,
19099
19403
  isExpressionStatement,
@@ -19111,9 +19415,9 @@ var miniprogramTemplateOf = (script, inventory) => /\.[cm]?[jt]sx?$/u.test(scrip
19111
19415
  function miniprogramConfiguration(template, inventory) {
19112
19416
  const own = template.replace(/\.wxml$/u, ".json");
19113
19417
  const configuration = inventory.has(own) ? { own } : {};
19114
- for (let directory = path10.posix.dirname(template); ; directory = path10.posix.dirname(directory)) {
19418
+ for (let directory = path12.posix.dirname(template); ; directory = path12.posix.dirname(directory)) {
19115
19419
  const root = directory === "." ? "" : directory;
19116
- const app = path10.posix.join(root, "app.json");
19420
+ const app = path12.posix.join(root, "app.json");
19117
19421
  if (inventory.has(app)) return { ...configuration, app, root };
19118
19422
  if (!root) return configuration;
19119
19423
  }
@@ -19126,9 +19430,9 @@ var miniprogramEventOf = (target) => {
19126
19430
  // src/project-map-language-typescript.ts
19127
19431
  var TYPESCRIPT_MAP_LANGUAGE = Object.freeze({
19128
19432
  id: "typescript-7.0.2-map-v35",
19129
- claims: (path21) => /\.[cm]?[jt]sx?$/u.test(path21),
19433
+ claims: (path24) => /\.[cm]?[jt]sx?$/u.test(path24),
19130
19434
  readsRequests: true,
19131
- reads: (path21) => path21.endsWith(".json") || path21.endsWith(".wxml") || path21 === "pnpm-workspace.yaml",
19435
+ reads: (path24) => path24.endsWith(".json") || path24.endsWith(".wxml") || path24 === "pnpm-workspace.yaml",
19132
19436
  create: () => new TypeScriptMapAnalyzer()
19133
19437
  });
19134
19438
  var WORKERS_AT_ONCE = Math.min(4, availableParallelism());
@@ -19155,7 +19459,7 @@ var KeptDiscoverySchema = external_exports.object({
19155
19459
  installed: external_exports.string(),
19156
19460
  files: external_exports.array(external_exports.tuple([external_exports.string(), external_exports.string().nullable(), external_exports.string().nullable()]))
19157
19461
  }).strict();
19158
- var sameShape = (left, right) => left.installed === right.installed && left.files.size === right.files.size && [...left.files].every(([path21, { shape }]) => right.files.get(path21)?.shape === shape);
19462
+ var sameShape = (left, right) => left.installed === right.installed && left.files.size === right.files.size && [...left.files].every(([path24, { shape }]) => right.files.get(path24)?.shape === shape);
19159
19463
  var stopUnconfirmed = async (runs) => (await Promise.allSettled(runs)).flatMap((settled) => settled.status === "rejected" ? [settled.reason] : []).find((reason) => reason instanceof ProjectMapStopUnconfirmedError);
19160
19464
  async function inOrder(tasks, take, signal, sizes) {
19161
19465
  const stopping = new AbortController();
@@ -19319,9 +19623,9 @@ var TypeScriptMapAnalyzer = class {
19319
19623
  first = void 0;
19320
19624
  validateMapAnalysis(analysis, input);
19321
19625
  if (!analysis.requiredFiles.length) return analysis;
19322
- const required2 = analysis.requiredFiles.map((path21) => {
19323
- const entry = byPath.get(path21);
19324
- if (!entry || Object.hasOwn(texts, path21))
19626
+ const required2 = analysis.requiredFiles.map((path24) => {
19627
+ const entry = byPath.get(path24);
19628
+ if (!entry || Object.hasOwn(texts, path24))
19325
19629
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
19326
19630
  return entry;
19327
19631
  });
@@ -19341,7 +19645,7 @@ var TypeScriptMapAnalyzer = class {
19341
19645
  discovered: kept.discovered,
19342
19646
  shape: {
19343
19647
  installed: kept.installed,
19344
- files: new Map(kept.files.map(([path21, digest, shape2]) => [path21, { digest, shape: shape2 }]))
19648
+ files: new Map(kept.files.map(([path24, digest, shape2]) => [path24, { digest, shape: shape2 }]))
19345
19649
  }
19346
19650
  };
19347
19651
  const known = kept?.key === configurationKey ? kept.discovered : void 0;
@@ -19398,7 +19702,7 @@ var TypeScriptMapAnalyzer = class {
19398
19702
  key: configurationKey,
19399
19703
  discovered,
19400
19704
  installed: installed.digest,
19401
- files: [...shape.files].map(([path21, file2]) => [path21, file2.digest, file2.shape])
19705
+ files: [...shape.files].map(([path24, file2]) => [path24, file2.digest, file2.shape])
19402
19706
  });
19403
19707
  if (!admitted(discovered))
19404
19708
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
@@ -19450,17 +19754,17 @@ var MAP_LANGUAGES = Object.freeze([
19450
19754
  ]);
19451
19755
  var mapAnalyzerSuite = (languages) => languages.map((language) => language.id).sort().join("+");
19452
19756
  var PROJECT_MAP_ANALYZER = mapAnalyzerSuite(MAP_LANGUAGES);
19453
- var mapCodePath = (path21) => MAP_LANGUAGES.some((language) => language.claims(path21));
19454
- var languageOf = (path21) => MAP_LANGUAGES.find((language) => language.claims(path21));
19455
- var mapReadsRequests = (path21) => languageOf(path21)?.readsRequests === true;
19456
- var mapLanguageOf = (path21) => languageOf(path21)?.id;
19757
+ var mapCodePath = (path24) => MAP_LANGUAGES.some((language) => language.claims(path24));
19758
+ var languageOf = (path24) => MAP_LANGUAGES.find((language) => language.claims(path24));
19759
+ var mapReadsRequests = (path24) => languageOf(path24)?.readsRequests === true;
19760
+ var mapLanguageOf = (path24) => languageOf(path24)?.id;
19457
19761
  var npmPackage = (specifier) => {
19458
19762
  if (specifier.startsWith("node:")) return "node:*";
19459
19763
  const parts = specifier.split("/");
19460
19764
  return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0] ?? specifier;
19461
19765
  };
19462
19766
  var mapExternalImport = (sourcePath, specifier) => languageOf(sourcePath)?.importName?.(specifier) ?? npmPackage(specifier);
19463
- var mapImportTarget = (path21) => languageOf(path21)?.importTarget?.(path21) ?? path21;
19767
+ var mapImportTarget = (path24) => languageOf(path24)?.importTarget?.(path24) ?? path24;
19464
19768
 
19465
19769
  // src/project-map-view.ts
19466
19770
  var MAP_VIEW_FORMAT = "PROJECT_MAP_VIEW_V1";
@@ -19500,10 +19804,10 @@ var notFound = () => {
19500
19804
  };
19501
19805
  var MAP_KINDS_LEGEND = "kinds f function, c class, m method, p property, v variable, t type, i interface, e enum; numbers are 1-based source lines";
19502
19806
  var MAP_DECLARATION_LEGEND = `@n marks where a relationship occurs and +n counts further sites, which project_find_references lists; a quoted path after the sites is the route the call or value is registered under there: its HTTP methods when the registration names them, then its path joined with the prefixes of the routers it is registered on, as far as the same function or file sets them (a prefix added where a router is mounted or passed in is not included); route "\u2026" after a decorator is the full route the decorator maps, its class's path joined with its own. Static relationships are grouped by the declaration that owns them. Callers are direct calls, uses as a value (stored, passed, returned or selected, then usually invoked through that value) and calls through an interface, type or base member that a declaration implements (dispatched from); dispatches to lists the members that implement an interface, type or base member, which a call through it may reach; trace stops names calls whose target is a function value, a member without a mapped implementation or a computed key, which only source reading can follow; possible callers by name are calls elsewhere, in the same language, of a member with a method's name on a receiver of unknown type (an untyped value, or one an unloaded package produced); they may or may not reach that method.`;
19503
- var within = (path21, directory) => directory === "." || path21.startsWith(`${directory}/`);
19504
- var parentDirectory = (path21) => {
19505
- const slash = path21.lastIndexOf("/");
19506
- return slash < 0 ? "." : path21.slice(0, slash);
19807
+ var within = (path24, directory) => directory === "." || path24.startsWith(`${directory}/`);
19808
+ var parentDirectory = (path24) => {
19809
+ const slash = path24.lastIndexOf("/");
19810
+ return slash < 0 ? "." : path24.slice(0, slash);
19507
19811
  };
19508
19812
  var compareText2 = (left, right) => left < right ? -1 : left > right ? 1 : 0;
19509
19813
  var byCount = ([leftName, left], [rightName, right]) => right - left || compareText2(leftName, rightName);
@@ -19577,7 +19881,7 @@ function pageBlocks(view, head, whole, offset, budget) {
19577
19881
  if (offset === blocks.length) return materialize(0);
19578
19882
  return mapQueryPage(blocks.length - offset, materialize, (page) => page, budget);
19579
19883
  }
19580
- var inModule = (path21, module) => module.direct ? parentDirectory(path21) === module.directory : within(path21, module.directory);
19884
+ var inModule = (path24, module) => module.direct ? parentDirectory(path24) === module.directory : within(path24, module.directory);
19581
19885
  var moduleLabel = (module) => module.direct ? `${module.directory === "." ? "" : `${module.directory}/`}* (files directly here)` : `${module.directory}/`;
19582
19886
  function childModules(module, files) {
19583
19887
  if (module.direct) return [];
@@ -19632,9 +19936,9 @@ function mapProjectModules(entries) {
19632
19936
  (entry) => entry.state === "TEXT" && mapCodePath(entry.path) && !mapTestPath(entry.path)
19633
19937
  ).map((entry) => entry.path)
19634
19938
  );
19635
- return (path21) => {
19636
- if (mapTestPath(path21)) return void 0;
19637
- const module = modules.find((candidate) => inModule(path21, candidate));
19939
+ return (path24) => {
19940
+ if (mapTestPath(path24)) return void 0;
19941
+ const module = modules.find((candidate) => inModule(path24, candidate));
19638
19942
  return module && moduleLabel(module);
19639
19943
  };
19640
19944
  }
@@ -19732,12 +20036,12 @@ function loadMemberCalls(store, version2) {
19732
20036
  FROM project_map_relations
19733
20037
  WHERE version_ref = ? AND to_ref IS NULL AND json_extract(relation_json, '$.kind') = 'CALLS'
19734
20038
  AND json_extract(relation_json, '$.unresolvedReason') IN ('SYMBOL_NOT_RESOLVED', 'SYNTAX_ONLY')`).all(version2)) {
19735
- const path21 = String(row.path);
20039
+ const path24 = String(row.path);
19736
20040
  const target = String(row.target);
19737
20041
  const name = MEMBER_NAME.exec(target)?.[1];
19738
- const language = mapLanguageOf(path21);
20042
+ const language = mapLanguageOf(path24);
19739
20043
  if (!name || !language) continue;
19740
- const call = { from: String(row.from_ref), path: path21, line: Number(row.line), target };
20044
+ const call = { from: String(row.from_ref), path: path24, line: Number(row.line), target };
19741
20045
  const key = memberKey(language, name);
19742
20046
  const known = calls.get(key);
19743
20047
  if (known) known.push(call);
@@ -19798,10 +20102,10 @@ function loadCoverageNotes(store, version2) {
19798
20102
  if (!codes.includes(gap.code)) codes.push(gap.code);
19799
20103
  files.set(gap.path, codes);
19800
20104
  }
19801
- for (const [path21, codes] of files)
20105
+ for (const [path24, codes] of files)
19802
20106
  if (codes.length > 1 && codes.includes("NOT_IN_PARSED_CONTEXT"))
19803
20107
  files.set(
19804
- path21,
20108
+ path24,
19805
20109
  codes.filter((code) => code !== "NOT_IN_PARSED_CONTEXT")
19806
20110
  );
19807
20111
  const missing = [...notInstalled].sort();
@@ -19846,9 +20150,9 @@ function directoryView(facts, imports, coverage, entries, input, directory, pref
19846
20150
  const visiblePaths = new Set(visible.map((entry) => entry.path));
19847
20151
  const code = visible.filter((entry) => entry.state === "TEXT" && mapCodePath(entry.path)).map((entry) => entry.path);
19848
20152
  const modules = mapModules(directory, code);
19849
- const moduleOf = (path21) => modules.find((module) => inModule(path21, module));
19850
- const outside = (path21) => {
19851
- const parts = path21.split("/");
20153
+ const moduleOf = (path24) => modules.find((module) => inModule(path24, module));
20154
+ const outside = (path24) => {
20155
+ const parts = path24.split("/");
19852
20156
  return `${parts.slice(0, Math.min(2, parts.length - 1)).join("/") || "."}/ (outside)`;
19853
20157
  };
19854
20158
  const moduleImports = /* @__PURE__ */ new Map();
@@ -19872,8 +20176,8 @@ function directoryView(facts, imports, coverage, entries, input, directory, pref
19872
20176
  const blocks = [];
19873
20177
  if (modules.length > 1) {
19874
20178
  const sizes = /* @__PURE__ */ new Map();
19875
- for (const path21 of code) {
19876
- const module = moduleOf(path21);
20179
+ for (const path24 of code) {
20180
+ const module = moduleOf(path24);
19877
20181
  if (module) increment(sizes, moduleLabel(module));
19878
20182
  }
19879
20183
  blocks.push(
@@ -19902,18 +20206,18 @@ function directoryView(facts, imports, coverage, entries, input, directory, pref
19902
20206
  )}${packages.length > shown.length ? `, +${packages.length - shown.length} more` : ""}`
19903
20207
  );
19904
20208
  }
19905
- const lineCount = (path21) => {
19906
- const file2 = facts.files.get(path21);
19907
- const gaps = coverage.files.get(path21) ?? [];
20209
+ const lineCount = (path24) => {
20210
+ const file2 = facts.files.get(path24);
20211
+ const gaps = coverage.files.get(path24) ?? [];
19908
20212
  if (file2?.parsed === false) return `[not parsed${gaps.length ? `: ${gaps.join("; ")}` : ""}]`;
19909
20213
  return `${file2 ? `${file2.lines}L` : "?L"}${gaps.length ? ` [${gaps.join("; ")}]` : ""}`;
19910
20214
  };
19911
20215
  const codeDirectories = /* @__PURE__ */ new Set();
19912
- for (const path21 of code)
19913
- for (let parent = parentDirectory(path21); parent !== "." && !codeDirectories.has(parent); parent = parentDirectory(parent))
20216
+ for (const path24 of code)
20217
+ for (let parent = parentDirectory(path24); parent !== "." && !codeDirectories.has(parent); parent = parentDirectory(parent))
19914
20218
  codeDirectories.add(parent);
19915
- const groupOf = (path21) => {
19916
- let group = parentDirectory(path21);
20219
+ const groupOf = (path24) => {
20220
+ let group = parentDirectory(path24);
19917
20221
  for (let parent = group; parent !== "." && parent !== directory && !codeDirectories.has(parent); parent = parentDirectory(parent))
19918
20222
  group = parent;
19919
20223
  return group;
@@ -19945,11 +20249,11 @@ function directoryView(facts, imports, coverage, entries, input, directory, pref
19945
20249
  ]);
19946
20250
  }
19947
20251
  const detailed = [
19948
- ...code.map((path21) => {
19949
- const declarations2 = (facts.exported.get(path21) ?? []).map(({ text: text2 }) => text2);
20252
+ ...code.map((path24) => {
20253
+ const declarations2 = (facts.exported.get(path24) ?? []).map(({ text: text2 }) => text2);
19950
20254
  return [
19951
- path21,
19952
- `${path21} ${lineCount(path21)}${declarations2.length ? `: ${declarations2.join(", ")}` : ""}`
20255
+ path24,
20256
+ `${path24} ${lineCount(path24)}${declarations2.length ? `: ${declarations2.join(", ")}` : ""}`
19953
20257
  ];
19954
20258
  }),
19955
20259
  ...listedOther.map((entry) => [
@@ -19960,7 +20264,7 @@ function directoryView(facts, imports, coverage, entries, input, directory, pref
19960
20264
  ];
19961
20265
  const directories = /* @__PURE__ */ new Map();
19962
20266
  for (const entry of [
19963
- ...code.map((path21) => ({ path: path21, item: lineCount(path21) })),
20267
+ ...code.map((path24) => ({ path: path24, item: lineCount(path24) })),
19964
20268
  ...listedOther.map((entry2) => ({
19965
20269
  path: entry2.path,
19966
20270
  item: entry2.state === "TEXT" ? "" : `(${entry2.state})`
@@ -19988,10 +20292,10 @@ function directoryView(facts, imports, coverage, entries, input, directory, pref
19988
20292
  );
19989
20293
  const text = visible.filter((entry) => entry.state === "TEXT").length;
19990
20294
  const resolution = /* @__PURE__ */ new Map();
19991
- for (const path21 of code) {
19992
- const counts = facts.calls.get(path21);
20295
+ for (const path24 of code) {
20296
+ const counts = facts.calls.get(path24);
19993
20297
  if (!counts) continue;
19994
- const language = facts.files.get(path21)?.language ?? "unknown";
20298
+ const language = facts.files.get(path24)?.language ?? "unknown";
19995
20299
  const total = resolution.get(language) ?? { resolved: 0, unresolved: 0, external: 0 };
19996
20300
  total.resolved += counts.resolved;
19997
20301
  total.unresolved += counts.unresolved;
@@ -20048,8 +20352,8 @@ var DeclarationGroups = class {
20048
20352
  prefixes;
20049
20353
  showTests;
20050
20354
  memberCalls;
20051
- visible(path21) {
20052
- return mapPathAllowed(path21, this.prefixes) && (this.showTests || !mapTestPath(path21));
20355
+ visible(path24) {
20356
+ return mapPathAllowed(path24, this.prefixes) && (this.showTests || !mapTestPath(path24));
20053
20357
  }
20054
20358
  entry(object2, imported = false) {
20055
20359
  if (mapMiniprogramTemplate(object2.anchor.path)) return "(template)";
@@ -20094,11 +20398,11 @@ var DeclarationGroups = class {
20094
20398
  value.lines.push(line);
20095
20399
  aggregates.set(key, value);
20096
20400
  };
20097
- const dispatch = (arrow, label, ref2, path21, line) => {
20401
+ const dispatch = (arrow, label, ref2, path24, line) => {
20098
20402
  const other = graph.object(graph.owner(ref2));
20099
20403
  if (owned.has(other.id)) return;
20100
- if (!this.visible(path21)) {
20101
- if (mapPathAllowed(path21, this.prefixes)) omittedTests++;
20404
+ if (!this.visible(path24)) {
20405
+ if (mapPathAllowed(path24, this.prefixes)) omittedTests++;
20102
20406
  return;
20103
20407
  }
20104
20408
  add(arrow, label, other, line);
@@ -20255,7 +20559,7 @@ var DeclarationGroups = class {
20255
20559
  else files2.set(call.path, [item]);
20256
20560
  }
20257
20561
  lines.push(
20258
- ` \u2190 possible callers by name: ${[...files2].map(([path21, items]) => `${path21}: ${items.join(", ")}`).join("; ")}${inTests}`
20562
+ ` \u2190 possible callers by name: ${[...files2].map(([path24, items]) => `${path24}: ${items.join(", ")}`).join("; ")}${inTests}`
20259
20563
  );
20260
20564
  } else if (possibleInTests)
20261
20565
  lines.push(` \u2190 possible callers by name: ${possibleInTests} in test files (includeTests)`);
@@ -20291,14 +20595,14 @@ var DeclarationGroups = class {
20291
20595
  return { lines, neighbors: [...new Set(neighbors)] };
20292
20596
  }
20293
20597
  };
20294
- function fileView(store, coverage, graph, input, path21, prefixes) {
20295
- const entry = store.getEntry(input.version, path21);
20296
- if (!entry || !mapPathAllowed(path21, prefixes)) return notFound();
20297
- const showTests = input.includeTests === true || mapTestPath(path21);
20298
- const module = mapCodePath(path21) ? graph.objectsAt(path21).find((object2) => mapIsModule(object2)) : mapMiniprogramTemplate(path21) ? graph.objectsAt(path21).find((object2) => mapIsModule(object2) && object2.parsing === "PARSED") : void 0;
20299
- const gaps = coverage.files.get(path21) ?? [];
20598
+ function fileView(store, coverage, graph, input, path24, prefixes) {
20599
+ const entry = store.getEntry(input.version, path24);
20600
+ if (!entry || !mapPathAllowed(path24, prefixes)) return notFound();
20601
+ const showTests = input.includeTests === true || mapTestPath(path24);
20602
+ const module = mapCodePath(path24) ? graph.objectsAt(path24).find((object2) => mapIsModule(object2)) : mapMiniprogramTemplate(path24) ? graph.objectsAt(path24).find((object2) => mapIsModule(object2) && object2.parsing === "PARSED") : void 0;
20603
+ const gaps = coverage.files.get(path24) ?? [];
20300
20604
  const head = [
20301
- `PROJECT MAP \xB7 FILE ${path21} \xB7 ${entry.state !== "TEXT" ? entry.state : module ? module.parsing === "NOT_PARSED" ? `not parsed${gaps.length ? ` (${gaps.join("; ")})` : ""}; read it as text` : `${module.anchor.endLine} lines${gaps.length ? ` \xB7 ${gaps.join("; ")}` : ""}` : `${entry.byteLength} bytes, not analyzed; read it as text`}`
20605
+ `PROJECT MAP \xB7 FILE ${path24} \xB7 ${entry.state !== "TEXT" ? entry.state : module ? module.parsing === "NOT_PARSED" ? `not parsed${gaps.length ? ` (${gaps.join("; ")})` : ""}; read it as text` : `${module.anchor.endLine} lines${gaps.length ? ` \xB7 ${gaps.join("; ")}` : ""}` : `${entry.byteLength} bytes, not analyzed; read it as text`}`
20302
20606
  ];
20303
20607
  if (!module || entry.state !== "TEXT")
20304
20608
  return pageBlocks("FILE", head, [], input.offset ?? 0, input.outputBudget);
@@ -20318,7 +20622,7 @@ function fileView(store, coverage, graph, input, path21, prefixes) {
20318
20622
  tags.set(relation.from, list);
20319
20623
  }
20320
20624
  const describe3 = (object2) => [
20321
- `${object2.name} ${mapDeclarationLabel(object2)}${object2.anchor.path === path21 ? "" : ` (${object2.anchor.path})`}`,
20625
+ `${object2.name} ${mapDeclarationLabel(object2)}${object2.anchor.path === path24 ? "" : ` (${object2.anchor.path})`}`,
20322
20626
  ...tags.get(object2.id) ?? []
20323
20627
  ].join(" ");
20324
20628
  const declarations2 = [];
@@ -20333,11 +20637,11 @@ function fileView(store, coverage, graph, input, path21, prefixes) {
20333
20637
  );
20334
20638
  }
20335
20639
  const elsewhere = /* @__PURE__ */ new Map();
20336
- for (const object2 of graph.objectsAt(path21)) {
20640
+ for (const object2 of graph.objectsAt(path24)) {
20337
20641
  const parent = mapIsModule(object2) ? void 0 : graph.parent(object2.id);
20338
20642
  if (parent === void 0 || !graph.isAddressable(object2)) continue;
20339
20643
  const container = graph.object(parent);
20340
- if (mapIsModule(container) || container.anchor.path === path21) continue;
20644
+ if (mapIsModule(container) || container.anchor.path === path24) continue;
20341
20645
  const into = elsewhere.get(parent);
20342
20646
  if (into) into.push(object2);
20343
20647
  else elsewhere.set(parent, [object2]);
@@ -20351,7 +20655,7 @@ function fileView(store, coverage, graph, input, path21, prefixes) {
20351
20655
  if (declarations2.length) blocks.push(["DECLARATIONS (* exported)", ...declarations2].join("\n"));
20352
20656
  const imports = /* @__PURE__ */ new Set();
20353
20657
  const external = /* @__PURE__ */ new Set();
20354
- const fileObjects = graph.objectsAt(path21).map((object2) => object2.id);
20658
+ const fileObjects = graph.objectsAt(path24).map((object2) => object2.id);
20355
20659
  for (const relation of graph.relationsFrom(fileObjects)) {
20356
20660
  if (relation.kind !== "IMPORTS") continue;
20357
20661
  if (relation.to === void 0) external.add(relation.target);
@@ -20362,8 +20666,8 @@ function fileView(store, coverage, graph, input, path21, prefixes) {
20362
20666
  }
20363
20667
  const importers = /* @__PURE__ */ new Set();
20364
20668
  const testImporters = /* @__PURE__ */ new Set();
20365
- const imported = mapImportTarget(path21);
20366
- const packageModules = imported === path21 ? [module.id] : store.listEntries(input.version).filter((entry2) => mapImportTarget(entry2.path) === imported).flatMap((entry2) => graph.objectsAt(entry2.path).filter((object2) => mapIsModule(object2))).map((object2) => object2.id);
20669
+ const imported = mapImportTarget(path24);
20670
+ const packageModules = imported === path24 ? [module.id] : store.listEntries(input.version).filter((entry2) => mapImportTarget(entry2.path) === imported).flatMap((entry2) => graph.objectsAt(entry2.path).filter((object2) => mapIsModule(object2))).map((object2) => object2.id);
20367
20671
  for (const relation of graph.relationsTo(packageModules)) {
20368
20672
  if (relation.kind !== "IMPORTS") continue;
20369
20673
  const source = relation.anchor.path;
@@ -20391,16 +20695,16 @@ function fileView(store, coverage, graph, input, path21, prefixes) {
20391
20695
  if (scope.length) blocks.push(["MODULE SCOPE (top-level statements)", ...scope].join("\n"));
20392
20696
  return pageBlocks("FILE", head, blocks, input.offset ?? 0, input.outputBudget);
20393
20697
  }
20394
- function declarationView(graph, input, path21, prefixes, memberCalls) {
20698
+ function declarationView(graph, input, path24, prefixes, memberCalls) {
20395
20699
  const requested = input.depth ?? 1;
20396
20700
  if (!Number.isSafeInteger(requested) || requested < 1 || requested > MAP_VIEW_LIMITS.directedDepth)
20397
20701
  return invalid2();
20398
20702
  const both = (input.direction ?? "BOTH") === "BOTH";
20399
20703
  const depth = both ? Math.min(requested, MAP_VIEW_LIMITS.bothDepth) : requested;
20400
20704
  const { name, line } = input;
20401
- const selected = mapSelectDeclarations(graph, path21, name, line);
20705
+ const selected = mapSelectDeclarations(graph, path24, name, line);
20402
20706
  if (!selected.length) return notFound();
20403
- const showTests = input.includeTests === true || mapTestPath(path21);
20707
+ const showTests = input.includeTests === true || mapTestPath(path24);
20404
20708
  const groups = new DeclarationGroups(graph, input, prefixes, showTests, memberCalls);
20405
20709
  const blocks = [];
20406
20710
  const seen = /* @__PURE__ */ new Set();
@@ -20448,7 +20752,7 @@ function declarationView(graph, input, path21, prefixes, memberCalls) {
20448
20752
  );
20449
20753
  }
20450
20754
  const head = [
20451
- `PROJECT MAP \xB7 DECLARATION ${path21}${name === void 0 ? "" : ` ${name}`}${line === void 0 ? "" : ` line ${line}`} \xB7 direction ${input.direction ?? "BOTH"} \xB7 depth ${depth}${depth < requested ? ` (BOTH is limited to ${MAP_VIEW_LIMITS.bothDepth})` : ""}${prefixes.includes(".") ? "" : " \xB7 limited to authorized paths"}`,
20755
+ `PROJECT MAP \xB7 DECLARATION ${path24}${name === void 0 ? "" : ` ${name}`}${line === void 0 ? "" : ` line ${line}`} \xB7 direction ${input.direction ?? "BOTH"} \xB7 depth ${depth}${depth < requested ? ` (BOTH is limited to ${MAP_VIEW_LIMITS.bothDepth})` : ""}${prefixes.includes(".") ? "" : " \xB7 limited to authorized paths"}`,
20452
20756
  ...truncated ? [`Expansion stopped at ${MAP_VIEW_LIMITS.declarations} declarations.`] : [],
20453
20757
  ...(input.direction ?? "BOTH") === "OUTGOING" ? [] : [callerCoverage(input.textSearch ?? DEFAULT_TEXT_SEARCH)]
20454
20758
  ];
@@ -20576,10 +20880,10 @@ var ProjectMapQuery = class {
20576
20880
  view(input, signal) {
20577
20881
  this.requireReadableMap(input.version, signal);
20578
20882
  const { offset, prefixes } = admission(input);
20579
- const path21 = normalizeProjectEvidencePath(input.path, true) || ".";
20883
+ const path24 = normalizeProjectEvidencePath(input.path, true) || ".";
20580
20884
  const view = mapView(
20581
20885
  this.store,
20582
- { ...input, path: path21, offset, allowedPathPrefixes: prefixes },
20886
+ { ...input, path: path24, offset, allowedPathPrefixes: prefixes },
20583
20887
  this.views
20584
20888
  );
20585
20889
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
@@ -20780,13 +21084,13 @@ var ProjectMapSourceReader = class _ProjectMapSourceReader {
20780
21084
  */
20781
21085
  async readAll(expected) {
20782
21086
  if (this.signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
20783
- const paths = expected.map(({ path: path21 }) => {
20784
- assertProjectEvidencePathNotSensitive(path21);
20785
- if (isProjectEvidenceTraversalExcluded(path21))
21087
+ const paths = expected.map(({ path: path24 }) => {
21088
+ assertProjectEvidencePathNotSensitive(path24);
21089
+ if (isProjectEvidenceTraversalExcluded(path24))
20786
21090
  throw new ProjectEvidenceError("PROJECT_FILE_NOT_ALLOWED", false);
20787
- return path21;
21091
+ return path24;
20788
21092
  });
20789
- const results = this.commit ? await this.commit.readAll(paths) : await concurrently(paths, (path21) => this.session.captureFile(path21));
21093
+ const results = this.commit ? await this.commit.readAll(paths) : await concurrently(paths, (path24) => this.session.captureFile(path24));
20790
21094
  for (const [index, { entry }] of results.entries()) {
20791
21095
  const wanted = expected[index];
20792
21096
  if (entry.state !== wanted?.state || entry.contentDigest !== wanted.contentDigest || entry.byteLength !== wanted.byteLength)
@@ -20939,12 +21243,12 @@ var CodeIndexQuery = class {
20939
21243
  })
20940
21244
  });
20941
21245
  }
20942
- const isDirectory = normalizedPath.length === 0 || this.store.listEntries(input.version).some((candidate) => candidate.path.startsWith(`${normalizedPath}/`));
21246
+ const isDirectory2 = normalizedPath.length === 0 || this.store.listEntries(input.version).some((candidate) => candidate.path.startsWith(`${normalizedPath}/`));
20943
21247
  this.assertNotAborted(signal);
20944
21248
  return Object.freeze({
20945
21249
  pathStatus: Object.freeze({
20946
21250
  path: reportedPath,
20947
- status: isDirectory ? "DIRECTORY" : "NOT_INCLUDED_IN_REVISION"
21251
+ status: isDirectory2 ? "DIRECTORY" : "NOT_INCLUDED_IN_REVISION"
20948
21252
  })
20949
21253
  });
20950
21254
  }
@@ -21246,7 +21550,7 @@ ${scopeDigest}`;
21246
21550
  };
21247
21551
 
21248
21552
  // src/code-index-store.ts
21249
- import { createHash as createHash4, randomBytes, randomUUID } from "node:crypto";
21553
+ import { createHash as createHash5, randomBytes, randomUUID } from "node:crypto";
21250
21554
  var CODE_INDEX_SCHEMA = `
21251
21555
  CREATE TABLE project_code_meta (meta_key TEXT PRIMARY KEY, meta_value TEXT NOT NULL);
21252
21556
  CREATE TABLE project_code_versions (
@@ -21528,7 +21832,7 @@ var CodeIndexStore = class {
21528
21832
  const staged = this.stageUnits(buildRef, paths, linked);
21529
21833
  const reused = linked ? this.database.prepare(`SELECT path, unit_ref FROM project_map_version_units
21530
21834
  WHERE version_ref = ? AND path IN (SELECT value FROM json_each(?))`).all(linked.version, JSON.stringify([...linked.paths])).map((row) => ({ path: String(row.path), unit: String(row.unit_ref) })) : [];
21531
- if (reused.length !== (linked?.paths.size ?? 0) || reused.some(({ path: path21 }) => !paths.has(path21)) || staged.some(({ path: path21 }) => linked?.paths.has(path21)))
21835
+ if (reused.length !== (linked?.paths.size ?? 0) || reused.some(({ path: path24 }) => !paths.has(path24)) || staged.some(({ path: path24 }) => linked?.paths.has(path24)))
21532
21836
  throw new MapReplayConflict();
21533
21837
  const units = [...staged, ...reused].sort(
21534
21838
  (left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0
@@ -21582,7 +21886,7 @@ var CodeIndexStore = class {
21582
21886
  const member = this.database.prepare(
21583
21887
  "INSERT INTO project_map_version_units VALUES (?, ?, ?)"
21584
21888
  );
21585
- for (const { path: path21, unit } of reused) member.run(version2.version, path21, unit);
21889
+ for (const { path: path24, unit } of reused) member.run(version2.version, path24, unit);
21586
21890
  this.database.prepare("INSERT INTO project_map_coverage VALUES (?, ?)").run(version2.version, canonicalJson(coverage));
21587
21891
  }
21588
21892
  this.database.exec(`DELETE FROM project_map_publish_objects;
@@ -21637,7 +21941,7 @@ var CodeIndexStore = class {
21637
21941
  corrupt2();
21638
21942
  }
21639
21943
  if (linked) {
21640
- const unlinked = database.prepare("SELECT path FROM project_map_version_units WHERE version_ref = ?").all(linked.version).map((row) => String(row.path)).filter((path21) => !linked.paths.has(path21));
21944
+ const unlinked = database.prepare("SELECT path FROM project_map_version_units WHERE version_ref = ?").all(linked.version).map((row) => String(row.path)).filter((path24) => !linked.paths.has(path24));
21641
21945
  if (database.prepare(`SELECT 1 FROM project_map_objects gone
21642
21946
  WHERE gone.version_ref = ? AND gone.path IN (SELECT value FROM json_each(?))
21643
21947
  AND gone.entity_ref NOT IN (SELECT entity_ref FROM project_map_publish_objects)
@@ -21659,17 +21963,17 @@ var CodeIndexStore = class {
21659
21963
  const units = [];
21660
21964
  for (const row of database.prepare(`SELECT path FROM project_map_publish_objects
21661
21965
  UNION SELECT path FROM project_map_publish_relations ORDER BY path`).all()) {
21662
- const path21 = String(row.path);
21663
- const hash2 = createHash4("sha256").update(path21).update("\0");
21966
+ const path24 = String(row.path);
21967
+ const hash3 = createHash5("sha256").update(path24).update("\0");
21664
21968
  for (const [mark, statement] of [
21665
21969
  ["object", objects2],
21666
21970
  ["relation", relations],
21667
21971
  ["note", pathNotes]
21668
21972
  ])
21669
- for (const fact of statement.all(path21))
21973
+ for (const fact of statement.all(path24))
21670
21974
  for (const value of Object.values(fact))
21671
- hash2.update(mark).update("\0").update(String(value)).update("\0");
21672
- units.push({ path: path21, unit: hash2.digest("hex") });
21975
+ hash3.update(mark).update("\0").update(String(value)).update("\0");
21976
+ units.push({ path: path24, unit: hash3.digest("hex") });
21673
21977
  }
21674
21978
  return units;
21675
21979
  }
@@ -21687,13 +21991,13 @@ var CodeIndexStore = class {
21687
21991
  "INSERT INTO project_map_unit_notes SELECT ?, * FROM project_map_publish_notes WHERE path = ?"
21688
21992
  );
21689
21993
  const member = database.prepare("INSERT INTO project_map_version_units VALUES (?, ?, ?)");
21690
- for (const { path: path21, unit } of units) {
21691
- if (insertUnit.run(unit, path21).changes) {
21692
- unitObjects.run(unit, path21);
21693
- unitRelations.run(unit, path21);
21694
- unitNotes.run(unit, path21);
21994
+ for (const { path: path24, unit } of units) {
21995
+ if (insertUnit.run(unit, path24).changes) {
21996
+ unitObjects.run(unit, path24);
21997
+ unitRelations.run(unit, path24);
21998
+ unitNotes.run(unit, path24);
21695
21999
  }
21696
- member.run(version2, path21, unit);
22000
+ member.run(version2, path24, unit);
21697
22001
  }
21698
22002
  }
21699
22003
  /**
@@ -21991,19 +22295,19 @@ function replayableContexts(parent, digests, claims) {
21991
22295
  const { analysis, paths } = parent.shell(ref);
21992
22296
  const files = /* @__PURE__ */ new Set([...codeFiles(context, analysis.parsedFiles, claims), ...paths ?? []]);
21993
22297
  factFiles.set(ref, files);
21994
- for (const path21 of files) {
21995
- const refs = sharing.get(path21) ?? /* @__PURE__ */ new Set();
22298
+ for (const path24 of files) {
22299
+ const refs = sharing.get(path24) ?? /* @__PURE__ */ new Set();
21996
22300
  refs.add(ref);
21997
- sharing.set(path21, refs);
22301
+ sharing.set(path24, refs);
21998
22302
  }
21999
22303
  if (!paths || !contextFiles(context).every(
22000
- (path21) => digests.get(path21) !== void 0 && digests.get(path21) === parent.entries.get(path21)
22304
+ (path24) => digests.get(path24) !== void 0 && digests.get(path24) === parent.entries.get(path24)
22001
22305
  ))
22002
22306
  analyzed.add(ref);
22003
22307
  }
22004
22308
  for (const ref of analyzed)
22005
- for (const path21 of factFiles.get(ref) ?? [])
22006
- for (const other of sharing.get(path21) ?? []) analyzed.add(other);
22309
+ for (const path24 of factFiles.get(ref) ?? [])
22310
+ for (const other of sharing.get(path24) ?? []) analyzed.add(other);
22007
22311
  const replayable = new Set([...parent.contexts.keys()].filter((ref) => !analyzed.has(ref)));
22008
22312
  return { replayable, sharing, factFiles };
22009
22313
  }
@@ -22035,8 +22339,8 @@ var ProjectMapAnalyzer = class {
22035
22339
  languages;
22036
22340
  observe;
22037
22341
  id;
22038
- claims(path21) {
22039
- return this.languages.some((language) => language.claims(path21));
22342
+ claims(path24) {
22343
+ return this.languages.some((language) => language.claims(path24));
22040
22344
  }
22041
22345
  // A context holds one language's code, so its requests are that language's.
22042
22346
  async references(input, references, signal, until) {
@@ -22045,8 +22349,8 @@ var ProjectMapAnalyzer = class {
22045
22349
  return language?.references ? language.references(input, references, signal, this.observe, until) : { pages: references.map(() => null), requiredFiles: [] };
22046
22350
  }
22047
22351
  // A context's compiler diagnostics, undefined for a language without a compiler to ask.
22048
- diagnostics(input, path21, signal) {
22049
- return this.languages.find((language) => language.claims(path21))?.diagnostics?.(input, signal, this.observe);
22352
+ diagnostics(input, path24, signal) {
22353
+ return this.languages.find((language) => language.claims(path24))?.diagnostics?.(input, signal, this.observe);
22050
22354
  }
22051
22355
  async analyze(reader, entries, installed, signal, consume, keep, parent) {
22052
22356
  const result = {
@@ -22070,7 +22374,7 @@ var ProjectMapAnalyzer = class {
22070
22374
  const digests = /* @__PURE__ */ new Map();
22071
22375
  for (const entry of entries)
22072
22376
  if (entry.contentDigest) digests.set(entry.path, entry.contentDigest);
22073
- const claims = (path21) => this.claims(path21);
22377
+ const claims = (path24) => this.claims(path24);
22074
22378
  const { replayable, sharing, factFiles } = parent ? replayableContexts(parent, digests, claims) : {
22075
22379
  replayable: /* @__PURE__ */ new Set(),
22076
22380
  sharing: /* @__PURE__ */ new Map(),
@@ -22082,7 +22386,7 @@ var ProjectMapAnalyzer = class {
22082
22386
  const linked = /* @__PURE__ */ new Set();
22083
22387
  const analyzedFiles = /* @__PURE__ */ new Set();
22084
22388
  const stagedPaths = /* @__PURE__ */ new Set();
22085
- const requestDigest = (request, files2) => digestValue({ request, files: files2.map((path21) => [path21, digests.get(path21) ?? null]) });
22389
+ const requestDigest = (request, files2) => digestValue({ request, files: files2.map((path24) => [path24, digests.get(path24) ?? null]) });
22086
22390
  const replaysDigest = (contextRef2, digest) => parent !== void 0 && replayable.has(contextRef2) && parent.contexts.get(contextRef2)?.requestDigest === digest;
22087
22391
  const replays = (contextRef2, request, files2) => replaysDigest(contextRef2, requestDigest(request, files2));
22088
22392
  const reuse = (contextRef2, request, files2) => {
@@ -22123,7 +22427,7 @@ var ProjectMapAnalyzer = class {
22123
22427
  const ref = analysis.contexts[0]?.ref ?? "";
22124
22428
  if (options?.linked?.length) {
22125
22429
  if (!parent || analysis.contexts.length !== 1) return invalidParent();
22126
- for (const path21 of options.linked) linked.add(path21);
22430
+ for (const path24 of options.linked) linked.add(path24);
22127
22431
  this.observe?.({
22128
22432
  operation: "LINK",
22129
22433
  phase: "FINISHED",
@@ -22150,7 +22454,7 @@ var ProjectMapAnalyzer = class {
22150
22454
  });
22151
22455
  for (const file2 of analysis.parsedFiles) parsed.add(file2);
22152
22456
  const staged = factPaths(analysis);
22153
- for (const path21 of staged) stagedPaths.add(path21);
22457
+ for (const path24 of staged) stagedPaths.add(path24);
22154
22458
  for (const context of analysis.contexts) {
22155
22459
  for (const file2 of context.configurationFiles) configurationInputs.add(file2);
22156
22460
  if (!replayed.has(context.ref))
@@ -22181,7 +22485,7 @@ var ProjectMapAnalyzer = class {
22181
22485
  reuse,
22182
22486
  replays,
22183
22487
  previous,
22184
- configuration: (path21) => configurationInputs.add(path21),
22488
+ configuration: (path24) => configurationInputs.add(path24),
22185
22489
  kept: parent?.kept(language.id),
22186
22490
  keep: (state2) => keep(language.id, state2),
22187
22491
  observe: this.observe
@@ -22220,12 +22524,12 @@ var ProjectMapAnalyzer = class {
22220
22524
  if (files.objects.length) accept(files);
22221
22525
  if (parent && (replayed.size || linked.size)) {
22222
22526
  for (const ref of replayed.keys())
22223
- for (const path21 of factFiles.get(ref) ?? invalidParent())
22224
- if (analyzedFiles.has(path21) || [...sharing.get(path21) ?? []].some((other) => !replayed.has(other)))
22527
+ for (const path24 of factFiles.get(ref) ?? invalidParent())
22528
+ if (analyzedFiles.has(path24) || [...sharing.get(path24) ?? []].some((other) => !replayed.has(other)))
22225
22529
  throw new MapReplayConflict();
22226
- for (const paths of replayed.values()) for (const path21 of paths) linked.add(path21);
22227
- for (const path21 of linked)
22228
- if (analyzedFiles.has(path21) || stagedPaths.has(path21)) throw new MapReplayConflict();
22530
+ for (const paths of replayed.values()) for (const path24 of paths) linked.add(path24);
22531
+ for (const path24 of linked)
22532
+ if (analyzedFiles.has(path24) || stagedPaths.has(path24)) throw new MapReplayConflict();
22229
22533
  parent.link([...linked]);
22230
22534
  }
22231
22535
  result.parsedFiles = [...parsed].sort();
@@ -22262,12 +22566,12 @@ var ProjectMapReferenceQuery = class {
22262
22566
  return source;
22263
22567
  }
22264
22568
  // The compiler contexts a file is in.
22265
- contexts(version2, path21) {
22569
+ contexts(version2, path24) {
22266
22570
  return this.store.database.prepare(`SELECT DISTINCT c.context_ref, c.context_json
22267
22571
  FROM project_map_contexts c, json_each(c.context_json, '$.inputFiles') f
22268
22572
  WHERE c.version_ref = ? AND f.value = ?
22269
22573
  AND json_extract(c.context_json, '$.mode') != 'SYNTAX_ONLY'
22270
- ORDER BY c.context_ref`).all(version2, path21).map((value) => MapContextSchema.parse(JSON.parse(String(value.context_json))));
22574
+ ORDER BY c.context_ref`).all(version2, path24).map((value) => MapContextSchema.parse(JSON.parse(String(value.context_json))));
22271
22575
  }
22272
22576
  // A context's files as the version captured them.
22273
22577
  entries(version2, context) {
@@ -22302,7 +22606,7 @@ var ProjectMapReferenceQuery = class {
22302
22606
  * A context's compiler diagnostics: the stored result of a compile of the same inputs, or a
22303
22607
  * compile's, stored for the next. Undefined for a language without a compiler to ask.
22304
22608
  */
22305
- async compileDiagnostics(version2, source, context, path21, signal) {
22609
+ async compileDiagnostics(version2, source, context, path24, signal) {
22306
22610
  const key = digestValue({
22307
22611
  operation: "DIAGNOSTICS",
22308
22612
  inputs: this.compileInputs(version2, source, context)
@@ -22310,7 +22614,7 @@ var ProjectMapReferenceQuery = class {
22310
22614
  const stored = this.store.compileResults(version2, [key]);
22311
22615
  if (stored.has(key)) return MapDiagnosticsSchema.parse(stored.get(key));
22312
22616
  const { reader, request } = await this.open(version2, source, context, signal);
22313
- const result = await this.analyzer.diagnostics(request, path21, signal);
22617
+ const result = await this.analyzer.diagnostics(request, path24, signal);
22314
22618
  await reader.assertStable();
22315
22619
  if (!result) return void 0;
22316
22620
  if (result.requiredFiles.length)
@@ -22384,7 +22688,7 @@ var ProjectMapReferenceQuery = class {
22384
22688
  /** The configurations of the contexts a version's files are in. */
22385
22689
  contextConfigurations(version2, paths) {
22386
22690
  return paths.flatMap(
22387
- (path21) => this.contexts(version2, path21).flatMap((context) => context.configPath ?? [])
22691
+ (path24) => this.contexts(version2, path24).flatMap((context) => context.configPath ?? [])
22388
22692
  );
22389
22693
  }
22390
22694
  /**
@@ -22410,8 +22714,8 @@ var ProjectMapReferenceQuery = class {
22410
22714
  unchecked.push(configPath);
22411
22715
  continue;
22412
22716
  }
22413
- const [path21] = context.rootFiles ?? context.inputFiles;
22414
- const result = path21 === void 0 ? void 0 : await this.compileDiagnostics(input.version, source, context, path21, signal);
22717
+ const [path24] = context.rootFiles ?? context.inputFiles;
22718
+ const result = path24 === void 0 ? void 0 : await this.compileDiagnostics(input.version, source, context, path24, signal);
22415
22719
  if (!result) continue;
22416
22720
  const found = new Map(
22417
22721
  result.diagnostics.map((item) => [
@@ -22442,9 +22746,9 @@ var ProjectMapReferenceQuery = class {
22442
22746
  const compiles = /* @__PURE__ */ new Map();
22443
22747
  for (const ref of input.refs) {
22444
22748
  const object2 = requireMapObject(this.store, input.version, { entityRef: ref }, ["."]);
22445
- const path21 = object2.anchor.path;
22446
- const contexts = contextsOf.get(path21) ?? this.contexts(input.version, path21);
22447
- contextsOf.set(path21, contexts);
22749
+ const path24 = object2.anchor.path;
22750
+ const contexts = contextsOf.get(path24) ?? this.contexts(input.version, path24);
22751
+ contextsOf.set(path24, contexts);
22448
22752
  const readable = object2.symbolStart === void 0 ? [] : contexts;
22449
22753
  found.set(ref, {
22450
22754
  uses: [],
@@ -22504,8 +22808,8 @@ var ProjectMapReferenceQuery = class {
22504
22808
  );
22505
22809
  if (!prefixes.length || prefixes.length > 64)
22506
22810
  throw new ProjectEvidenceError("PROJECT_READ_INPUT_INVALID", false);
22507
- const { path: path21, name, line, entityRef, locator } = input;
22508
- if (path21 === void 0 !== (name === void 0) || line !== void 0 && name === void 0)
22811
+ const { path: path24, name, line, entityRef, locator } = input;
22812
+ if (path24 === void 0 !== (name === void 0) || line !== void 0 && name === void 0)
22509
22813
  throw new ProjectEvidenceError("PROJECT_READ_INPUT_INVALID", false);
22510
22814
  const selection = mapQuerySelection(
22511
22815
  { path: input.within, kinds: input.kinds },
@@ -22518,7 +22822,7 @@ var ProjectMapReferenceQuery = class {
22518
22822
  {
22519
22823
  entityRef,
22520
22824
  locator,
22521
- symbol: path21 !== void 0 && name !== void 0 ? { path: path21, name, ...line === void 0 ? {} : { line } } : void 0
22825
+ symbol: path24 !== void 0 && name !== void 0 ? { path: path24, name, ...line === void 0 ? {} : { line } } : void 0
22522
22826
  },
22523
22827
  prefixes
22524
22828
  );
@@ -22763,8 +23067,8 @@ var CodeIndex = class {
22763
23067
  for (const entry of this.store.listEntries(candidate))
22764
23068
  if (entry.contentDigest) entries2.set(entry.path, entry.contentDigest);
22765
23069
  let changed = 0;
22766
- for (const [path21, digest] of digests) if (entries2.get(path21) !== digest) changed++;
22767
- for (const path21 of entries2.keys()) if (!digests.has(path21)) changed++;
23070
+ for (const [path24, digest] of digests) if (entries2.get(path24) !== digest) changed++;
23071
+ for (const path24 of entries2.keys()) if (!digests.has(path24)) changed++;
22768
23072
  if (!best || changed < best.changed) best = { version: candidate, entries: entries2, changed };
22769
23073
  }
22770
23074
  if (!best) return void 0;
@@ -22923,8 +23227,8 @@ var CodeIndex = class {
22923
23227
  };
22924
23228
 
22925
23229
  // src/project-map-change-diff.ts
22926
- import { lstat as lstat3, open as open2, readFile as readFile2 } from "node:fs/promises";
22927
- import path12 from "node:path";
23230
+ import { lstat as lstat3, open as open2, readFile as readFile4 } from "node:fs/promises";
23231
+ import path14 from "node:path";
22928
23232
 
22929
23233
  // src/project-map-change-runtime.ts
22930
23234
  import { transformSync } from "esbuild";
@@ -22936,16 +23240,16 @@ var LOADERS = {
22936
23240
  };
22937
23241
  var DECORATED = /\b__decorat(?:orStart|eClass|eParam)\b/u;
22938
23242
  var PAIRS = 4e6;
22939
- var mapErasable = (path21) => !path21.endsWith(".d.ts") && LOADERS[path21.slice(path21.lastIndexOf("."))] !== void 0;
22940
- function erase(text, path21) {
22941
- const loader = LOADERS[path21.slice(path21.lastIndexOf("."))];
23243
+ var mapErasable = (path24) => !path24.endsWith(".d.ts") && LOADERS[path24.slice(path24.lastIndexOf("."))] !== void 0;
23244
+ function erase(text, path24) {
23245
+ const loader = LOADERS[path24.slice(path24.lastIndexOf("."))];
22942
23246
  if (!loader) return void 0;
22943
23247
  let code;
22944
23248
  let map2;
22945
23249
  try {
22946
23250
  ({ code, map: map2 } = transformSync(text, {
22947
23251
  loader,
22948
- sourcefile: path21,
23252
+ sourcefile: path24,
22949
23253
  target: "esnext",
22950
23254
  // Lowered, so a decorator shows in the helpers it needs.
22951
23255
  supported: { decorators: false },
@@ -23028,9 +23332,9 @@ function sourceLines(map2, count) {
23028
23332
  return from;
23029
23333
  }
23030
23334
  var touches = (region, [start, end]) => region.from <= region.to ? start <= region.to && region.from <= end : start <= region.to && end >= region.from;
23031
- function mapRuntimeLines(path21, baseText, text, hunks) {
23032
- const before = erase(baseText, path21);
23033
- const after = erase(text, path21);
23335
+ function mapRuntimeLines(path24, baseText, text, hunks) {
23336
+ const before = erase(baseText, path24);
23337
+ const after = erase(text, path24);
23034
23338
  if (!before || !after) return void 0;
23035
23339
  const regions = hunks.map((hunk) => ({
23036
23340
  base: hunk.baseCount ? { from: hunk.baseStart, to: hunk.baseStart + hunk.baseCount - 1 } : { from: hunk.baseStart + 1, to: hunk.baseStart },
@@ -23096,8 +23400,8 @@ function changedIn(base, working, region) {
23096
23400
  }
23097
23401
 
23098
23402
  // src/project-map-names.ts
23099
- import { readFile } from "node:fs/promises";
23100
- import path11 from "node:path";
23403
+ import { readFile as readFile3 } from "node:fs/promises";
23404
+ import path13 from "node:path";
23101
23405
  var CONFIG_KEY = /^\s*(?:export\s+|-\s+)?["']?([A-Za-z_][\w.-]*)["']?\s*(?:=|:(?:\s|$))/u;
23102
23406
  var CODE_READS = [
23103
23407
  // process.env.NAME, import.meta.env.NAME
@@ -23129,7 +23433,7 @@ function codeReads(line, file2) {
23129
23433
  for (const match of line.matchAll(pattern)) if (match[1]) names.add(match[1]);
23130
23434
  return names;
23131
23435
  }
23132
- async function strandedNames(project, files, configuration, git2, options) {
23436
+ async function strandedNames(project, files, configuration, git3, options) {
23133
23437
  const from = /* @__PURE__ */ new Map();
23134
23438
  for (const file2 of files) {
23135
23439
  const lines = file2.removed;
@@ -23143,7 +23447,7 @@ async function strandedNames(project, files, configuration, git2, options) {
23143
23447
  if (key) names2.add(key);
23144
23448
  for (const match of line.matchAll(PLACEHOLDER)) if (match[1]) names2.add(match[1]);
23145
23449
  } else for (const name of codeReads(line, file2.path)) names2.add(name);
23146
- const text = await readFile(path11.join(project, file2.path), "utf8").catch(() => void 0);
23450
+ const text = await readFile3(path13.join(project, file2.path), "utf8").catch(() => void 0);
23147
23451
  if (text === void 0) continue;
23148
23452
  for (const name of names2)
23149
23453
  if (NAME.test(name) && !PLATFORM.test(name) && !from.has(name) && !wholeName(name).test(text))
@@ -23155,7 +23459,7 @@ async function strandedNames(project, files, configuration, git2, options) {
23155
23459
  const patterns = new Map(
23156
23460
  names.map((name) => [name, { whole: wholeName(name), quoted: quotedName(name) }])
23157
23461
  );
23158
- const search = await gitGrep(git2, { strings: names, paths: ["."], words: true }, options);
23462
+ const search = await gitGrep(git3, { strings: names, paths: ["."], words: true }, options);
23159
23463
  if (search.failed) return { names: [], failed: search.failed, ...past };
23160
23464
  const changed = new Map(files.map((file2) => [file2.path, file2.lines]));
23161
23465
  const moved = /* @__PURE__ */ new Set();
@@ -23189,7 +23493,7 @@ async function strandedNames(project, files, configuration, git2, options) {
23189
23493
  var strandedNameLine = ({ name, from, mentions }) => `${name}, gone from ${from}: ${mentions.slice(0, LIMIT.mentions).join(", ")}${mentions.length > LIMIT.mentions ? `, +${mentions.length - LIMIT.mentions} more` : ""}`;
23190
23494
 
23191
23495
  // src/project-map-change-diff.ts
23192
- var git = new GitRunner();
23496
+ var git2 = new GitRunner();
23193
23497
  var gitOptions = (cwd, signal) => ({
23194
23498
  cwd,
23195
23499
  signal,
@@ -23202,7 +23506,7 @@ async function resolveMapBase(project, base, signal) {
23202
23506
  throw new ProjectEvidenceError("LAYERMAP_BASE_INVALID", false);
23203
23507
  let commit;
23204
23508
  try {
23205
- commit = (await git.run(
23509
+ commit = (await git2.run(
23206
23510
  ["rev-parse", "--verify", "--quiet", `${base}^{commit}`],
23207
23511
  gitOptions(project, signal)
23208
23512
  )).stdout.toString().trim();
@@ -23215,7 +23519,7 @@ async function resolveMapBase(project, base, signal) {
23215
23519
  }
23216
23520
  async function readMapChanges(project, base, signal, options = { names: true }) {
23217
23521
  const commit = await resolveMapBase(project, base, signal);
23218
- const diff = (await git.run(
23522
+ const diff = (await git2.run(
23219
23523
  [
23220
23524
  "-c",
23221
23525
  "core.quotePath=false",
@@ -23242,9 +23546,9 @@ async function readMapChanges(project, base, signal, options = { names: true })
23242
23546
  if (file2.basePath && file2.status !== "ADDED" && !file2.binary && mapTestPath(file2.basePath) && mapLanguageOf(file2.basePath))
23243
23547
  files[index] = {
23244
23548
  ...file2,
23245
- baseText: (await git.run(["show", `${commit}:${file2.basePath}`], gitOptions(project, signal))).stdout.toString("utf8")
23549
+ baseText: (await git2.run(["show", `${commit}:${file2.basePath}`], gitOptions(project, signal))).stdout.toString("utf8")
23246
23550
  };
23247
- const untracked = (await git.run(["ls-files", "--others", "--exclude-standard", "-z"], gitOptions(project, signal))).stdout.toString("utf8").split("\0").filter((path21) => path21 && !inExcludedDirectory(path21));
23551
+ const untracked = (await git2.run(["ls-files", "--others", "--exclude-standard", "-z"], gitOptions(project, signal))).stdout.toString("utf8").split("\0").filter((path24) => path24 && !inExcludedDirectory(path24));
23248
23552
  for (const file2 of untracked)
23249
23553
  files.push({
23250
23554
  path: file2,
@@ -23255,14 +23559,14 @@ async function readMapChanges(project, base, signal, options = { names: true })
23255
23559
  removed: [],
23256
23560
  // git diff says which tracked files are binary; an untracked one in a language the map does
23257
23561
  // not analyze is told the way git tells it, by a NUL in its first 8000 bytes.
23258
- binary: !mapLanguageOf(file2) && await startsBinary(path12.join(project, file2))
23562
+ binary: !mapLanguageOf(file2) && await startsBinary(path14.join(project, file2))
23259
23563
  });
23260
23564
  await eraseTypes(project, commit, files, signal);
23261
23565
  const stranded = options.names ? await strandedNames(
23262
23566
  project,
23263
23567
  files,
23264
23568
  (file2) => nonCodeKind(file2) === "configuration",
23265
- git,
23569
+ git2,
23266
23570
  gitOptions(project, signal)
23267
23571
  ) : { names: [] };
23268
23572
  return { base, commit, files, quoted: parsed.quoted, stranded };
@@ -23274,8 +23578,8 @@ async function eraseTypes(project, commit, files, signal) {
23274
23578
  for (let at = 0; at < erasable.length; at += 8)
23275
23579
  await Promise.all(
23276
23580
  erasable.slice(at, at + 8).map(async ([index, file2]) => {
23277
- const text = await readFile2(path12.join(project, file2.path), "utf8").catch(() => void 0);
23278
- const baseText = file2.status === "ADDED" || !file2.basePath ? "" : await git.run(["show", `${commit}:${file2.basePath}`], gitOptions(project, signal)).then((result) => result.stdout.toString("utf8")).catch(() => void 0);
23581
+ const text = await readFile4(path14.join(project, file2.path), "utf8").catch(() => void 0);
23582
+ const baseText = file2.status === "ADDED" || !file2.basePath ? "" : await git2.run(["show", `${commit}:${file2.basePath}`], gitOptions(project, signal)).then((result) => result.stdout.toString("utf8")).catch(() => void 0);
23279
23583
  if (text === void 0 || baseText === void 0) return;
23280
23584
  const hunks = file2.hunks.length ? file2.hunks : [{ baseStart: 0, baseCount: 0, start: 1, count: text.split("\n").length }];
23281
23585
  const runtime = mapRuntimeLines(file2.path, baseText, text, hunks);
@@ -23373,7 +23677,7 @@ function mapPathNow(files) {
23373
23677
  (file2) => file2.basePath !== void 0 && file2.status !== "DELETED" ? [[file2.basePath, file2.path]] : []
23374
23678
  )
23375
23679
  );
23376
- return (path21) => moved.get(path21) ?? path21;
23680
+ return (path24) => moved.get(path24) ?? path24;
23377
23681
  }
23378
23682
  var overlaps = (lines, start, end) => lines.some(([from, to]) => from <= end && start <= to);
23379
23683
  var workingLine = (file2, line) => {
@@ -23397,7 +23701,7 @@ var NON_CODE = [
23397
23701
  [/(?:^|\/)\.env[^/]*$|\.(?:ya?ml|toml|ini|properties|conf|cfg)$/iu, "configuration"],
23398
23702
  [/\.(?:html?|jinja2?|j2|hbs|ejs|tmpl|tpl|gohtml|vue|svelte|wxml)$/iu, "template"]
23399
23703
  ];
23400
- var nonCodeKind = (path21) => NON_CODE.find(([pattern]) => pattern.test(path21))?.[1];
23704
+ var nonCodeKind = (path24) => NON_CODE.find(([pattern]) => pattern.test(path24))?.[1];
23401
23705
  var UNANALYZED = [
23402
23706
  [/\.(?:sh|bash|zsh|fish|ps1|bat|cmd)$/iu, "shell script"],
23403
23707
  [/\.(?:css|scss|sass|less|styl|wxss|acss)$/iu, "style sheet"],
@@ -23405,11 +23709,11 @@ var UNANALYZED = [
23405
23709
  [/\/$/u, "nested repository"]
23406
23710
  ];
23407
23711
  var DOCUMENTATION = /\.(?:md|mdx|markdown|rst|adoc)$|(?:^|\/)(?:LICENSE|NOTICE)[^/]*$/iu;
23408
- var unmappedKind = (path21, binary) => nonCodeKind(path21) ?? (binary ? "binary file" : DOCUMENTATION.test(path21) ? void 0 : UNANALYZED.find(([pattern]) => pattern.test(path21))?.[1] ?? "unanalyzed file");
23712
+ var unmappedKind = (path24, binary) => nonCodeKind(path24) ?? (binary ? "binary file" : DOCUMENTATION.test(path24) ? void 0 : UNANALYZED.find(([pattern]) => pattern.test(path24))?.[1] ?? "unanalyzed file");
23409
23713
 
23410
23714
  // src/project-map-changes.ts
23411
- import { readFile as readFile4 } from "node:fs/promises";
23412
- import path14 from "node:path";
23715
+ import { readFile as readFile6 } from "node:fs/promises";
23716
+ import path16 from "node:path";
23413
23717
 
23414
23718
  // src/project-map-change-types.ts
23415
23719
  var LIMITS = Object.freeze({
@@ -23472,7 +23776,7 @@ var LITERAL = /(["'`])((?:\\.|(?!\1)[^\\])*)\1/gu;
23472
23776
  var MOUNTING = /(?:\b(?:prefix|root_path|base_path|basePath|baseURL|baseUrl)\s*[=:]|\b(?:Group|Route|Mount|mount|use|include_router|PathPrefix|StripPrefix)\s*\()\s*$/u;
23473
23777
  var LIMIT2 = Object.freeze({ routes: 40, clients: 5 });
23474
23778
  var ROUTE = /^(?:[A-Z]+(?:\|[A-Z]+)* +)?\/\S*$/u;
23475
- var segments = (path21) => path21.split("/").filter(Boolean).map((text) => ({ text, param: PARAM.test(text) || /[{}$<>%]/u.test(text) }));
23779
+ var segments = (path24) => path24.split("/").filter(Boolean).map((text) => ({ text, param: PARAM.test(text) || /[{}$<>%]/u.test(text) }));
23476
23780
  function mapRouteLabel(label) {
23477
23781
  const match = /^([A-Z]+(?:\|[A-Z]+)*) +(\S.*)$/u.exec(label);
23478
23782
  return match ? { methods: (match[1] ?? "").split("|"), path: match[2] ?? "" } : { path: label };
@@ -23505,10 +23809,10 @@ function requestedPath(literal3, joined) {
23505
23809
  const match = /^(?:https?:\/\/[^/\s]+|(?:\$\{[^}]*\})+|@\{|redirect:|forward:)?(\/[^\s?#()"'`,;|]*)/u.exec(
23506
23810
  literal3
23507
23811
  ) ?? void 0;
23508
- const path21 = match?.[1];
23509
- if (!path21 || path21.startsWith("//") || path21.length < 3) return void 0;
23510
- const parts = segments(path21);
23511
- if (joined && path21.endsWith("/")) parts.push({ text: "*", param: true });
23812
+ const path24 = match?.[1];
23813
+ if (!path24 || path24.startsWith("//") || path24.length < 3) return void 0;
23814
+ const parts = segments(path24);
23815
+ if (joined && path24.endsWith("/")) parts.push({ text: "*", param: true });
23512
23816
  return parts;
23513
23817
  }
23514
23818
  var same = (route, requested) => route.param || !requested.param && route.text === requested.text;
@@ -23563,7 +23867,7 @@ function routeRegistrations(store, version2) {
23563
23867
  }
23564
23868
  return { routes, sites: sites2 };
23565
23869
  }
23566
- async function routeClients(routes, registrations, git2, options) {
23870
+ async function routeClients(routes, registrations, git3, options) {
23567
23871
  const searchable = routes.map((entry) => ({ ...entry, segments: routeSegments(entry.route) })).filter(
23568
23872
  (entry) => entry.segments.some((segment) => !segment.param && segment.text.length >= 3)
23569
23873
  );
@@ -23576,7 +23880,7 @@ async function routeClients(routes, registrations, git2, options) {
23576
23880
  for (const entry of wanted)
23577
23881
  for (const segment of entry.segments) if (!segment.param) needles.add(`/${segment.text}`);
23578
23882
  if (!needles.size) return { routes: [] };
23579
- const search = await gitGrep(git2, { strings: [...needles], paths: CLIENT_FILES }, options);
23883
+ const search = await gitGrep(git3, { strings: [...needles], paths: CLIENT_FILES }, options);
23580
23884
  if (search.failed) return { routes: [], failed: search.failed, ...past };
23581
23885
  const clients = /* @__PURE__ */ new Map();
23582
23886
  for (const { path: file2, line, text } of search.hits) {
@@ -23670,11 +23974,11 @@ var USED_BY = {
23670
23974
  OVERRIDES: "overridden"
23671
23975
  };
23672
23976
  var runsTarget = (relation) => CALLER_KINDS.has(relation.kind) && !relation.event;
23673
- var changeUnits = (graph, path21) => mapMiniprogramTemplate(path21) ? graph.objectsAt(path21).filter((object2) => mapIsModule(object2) && object2.parsing === "PARSED") : graph.declarationsAt(path21);
23674
- function changedUnits(graph, path21, lines) {
23977
+ var changeUnits = (graph, path24) => mapMiniprogramTemplate(path24) ? graph.objectsAt(path24).filter((object2) => mapIsModule(object2) && object2.parsing === "PARSED") : graph.declarationsAt(path24);
23978
+ function changedUnits(graph, path24, lines) {
23675
23979
  const refs = /* @__PURE__ */ new Set();
23676
23980
  let topLevel = false;
23677
- const inFile = changeUnits(graph, path21);
23981
+ const inFile = changeUnits(graph, path24);
23678
23982
  for (const [from, to] of lines) {
23679
23983
  const containing = inFile.filter(
23680
23984
  (object2) => object2.anchor.startLine <= to && from <= object2.anchor.endLine
@@ -24197,12 +24501,12 @@ var Tracer = class {
24197
24501
  this.mentions.set(route, (this.mentions.get(route) ?? /* @__PURE__ */ new Set()).add(file2));
24198
24502
  }
24199
24503
  /** A related test file; the closest relation (lowest rank) explains it. */
24200
- test(path21, name, why, rank2) {
24201
- if (!mapRunnableTest(path21)) return;
24202
- const known = this.tests.get(path21) ?? { names: /* @__PURE__ */ new Set(), why, rank: rank2 };
24504
+ test(path24, name, why, rank2) {
24505
+ if (!mapRunnableTest(path24)) return;
24506
+ const known = this.tests.get(path24) ?? { names: /* @__PURE__ */ new Set(), why, rank: rank2 };
24203
24507
  if (rank2 < known.rank) Object.assign(known, { why, rank: rank2 });
24204
24508
  if (name && !name.startsWith("<")) known.names.add(name);
24205
- this.tests.set(path21, known);
24509
+ this.tests.set(path24, known);
24206
24510
  }
24207
24511
  };
24208
24512
  var entriesOf = /* @__PURE__ */ new WeakMap();
@@ -24251,19 +24555,19 @@ function findTestEntries(graph, ref) {
24251
24555
  }
24252
24556
 
24253
24557
  // src/project-map-change-edges.ts
24254
- var same2 = (path21) => path21;
24558
+ var same2 = (path24) => path24;
24255
24559
  var compare = (left, right) => left < right ? -1 : left > right ? 1 : 0;
24256
- function linksOf(side, path21) {
24560
+ function linksOf(side, path24) {
24257
24561
  const imports = /* @__PURE__ */ new Map();
24258
24562
  const calls = /* @__PURE__ */ new Map();
24259
- if (path21 === void 0) return { imports, calls };
24563
+ if (path24 === void 0) return { imports, calls };
24260
24564
  const { graph } = side;
24261
- for (const relation of graph.relationsFrom(graph.objectsAt(path21).map((object2) => object2.id))) {
24565
+ for (const relation of graph.relationsFrom(graph.objectsAt(path24).map((object2) => object2.id))) {
24262
24566
  const line = relation.anchor.startLine;
24263
- if (relation.to === void 0 || !side.counts(path21, line)) continue;
24567
+ if (relation.to === void 0 || !side.counts(path24, line)) continue;
24264
24568
  if (relation.kind === "IMPORTS") {
24265
24569
  const target = graph.object(relation.to).anchor.path;
24266
- if (target === path21) continue;
24570
+ if (target === path24) continue;
24267
24571
  const to = side.pathNow(target);
24268
24572
  const found = imports.get(to) ?? { to, lines: [] };
24269
24573
  found.lines.push(line);
@@ -24271,7 +24575,7 @@ function linksOf(side, path21) {
24271
24575
  } else if (CALLER_KINDS.has(relation.kind)) {
24272
24576
  const ref = graph.owner(relation.to);
24273
24577
  const owner = graph.object(ref);
24274
- if (owner.anchor.path === path21 || mapIsModule(owner)) continue;
24578
+ if (owner.anchor.path === path24 || mapIsModule(owner)) continue;
24275
24579
  const to = side.pathNow(owner.anchor.path);
24276
24580
  const key = `${to}\0${graph.declarationKey(owner)}`;
24277
24581
  const found = calls.get(key) ?? { to, lines: [], ref };
@@ -24302,17 +24606,17 @@ function mapChangeLinks(store, working, base, files) {
24302
24606
  counts: always,
24303
24607
  pathOf,
24304
24608
  declaration: (file2, ref) => {
24305
- const path21 = pathOf(file2);
24306
- if (path21 === void 0) return void 0;
24307
- let keys = declared.get(path21);
24609
+ const path24 = pathOf(file2);
24610
+ if (path24 === void 0) return void 0;
24611
+ let keys = declared.get(path24);
24308
24612
  if (!keys) {
24309
24613
  keys = new Map(
24310
- changeUnits(baseGraph, path21).map((object2) => [
24614
+ changeUnits(baseGraph, path24).map((object2) => [
24311
24615
  baseGraph.declarationKey(object2),
24312
24616
  object2.id
24313
24617
  ])
24314
24618
  );
24315
- declared.set(path21, keys);
24619
+ declared.set(path24, keys);
24316
24620
  }
24317
24621
  return keys.get(graph.declarationKey(graph.object(ref)));
24318
24622
  }
@@ -24322,8 +24626,8 @@ function mapChangeLinks(store, working, base, files) {
24322
24626
  before = {
24323
24627
  graph,
24324
24628
  pathNow: same2,
24325
- counts: (path21, line) => {
24326
- const file2 = changedAt.get(path21);
24629
+ counts: (path24, line) => {
24630
+ const file2 = changedAt.get(path24);
24327
24631
  return !file2 || !overlaps(file2.lines, line, line);
24328
24632
  },
24329
24633
  pathOf: (file2) => file2.status === "ADDED" ? void 0 : file2.path,
@@ -24357,9 +24661,9 @@ function callersOf(side, ref) {
24357
24661
  const home = side.graph.object(ref).anchor.path;
24358
24662
  const files = /* @__PURE__ */ new Set();
24359
24663
  for (const relation of side.graph.relationsTo([ref])) {
24360
- const path21 = relation.anchor.path;
24361
- if (!CALLER_KINDS.has(relation.kind) || path21 === home || mapTestPath(path21)) continue;
24362
- if (side.counts(path21, relation.anchor.startLine)) files.add(side.pathNow(path21));
24664
+ const path24 = relation.anchor.path;
24665
+ if (!CALLER_KINDS.has(relation.kind) || path24 === home || mapTestPath(path24)) continue;
24666
+ if (side.counts(path24, relation.anchor.startLine)) files.add(side.pathNow(path24));
24363
24667
  }
24364
24668
  return [...files].sort();
24365
24669
  }
@@ -24420,8 +24724,8 @@ function mapChangeEdges(links) {
24420
24724
  }
24421
24725
 
24422
24726
  // src/project-map-change-tests.ts
24423
- import { readFile as readFile3 } from "node:fs/promises";
24424
- import path13 from "node:path";
24727
+ import { readFile as readFile5 } from "node:fs/promises";
24728
+ import path15 from "node:path";
24425
24729
 
24426
24730
  // src/project-map-route-paths.ts
24427
24731
  import {
@@ -24548,7 +24852,7 @@ var MAP_PATH_PARAMETER = "{}";
24548
24852
  async function existingTestsChanged(before, after, file2, project) {
24549
24853
  if (!file2.basePath || file2.baseText === void 0) return [];
24550
24854
  const baseLines = file2.baseText.split("\n");
24551
- const workingLines = file2.status !== "DELETED" && project ? (await readFile3(path13.join(project, file2.path), "utf8").catch(() => void 0))?.split(
24855
+ const workingLines = file2.status !== "DELETED" && project ? (await readFile5(path15.join(project, file2.path), "utf8").catch(() => void 0))?.split(
24552
24856
  "\n"
24553
24857
  ) ?? [] : [];
24554
24858
  const body = (lines, object2) => lines.slice(object2.anchor.startLine - 1, object2.anchor.endLine).map((line) => line.trimEnd());
@@ -24585,10 +24889,10 @@ function importerTests(graph, objects2, tracer, importers) {
24585
24889
  }
24586
24890
  const next = [];
24587
24891
  for (const imported of modules)
24588
- for (const { path: path21, module } of importers.get(imported) ?? [])
24589
- if (mapTestPath(path21))
24892
+ for (const { path: path24, module } of importers.get(imported) ?? [])
24893
+ if (mapTestPath(path24))
24590
24894
  tracer.test(
24591
- path21,
24895
+ path24,
24592
24896
  void 0,
24593
24897
  hop ? "imports a changed file indirectly" : "imports a changed file",
24594
24898
  hop ? 4 : 2
@@ -24613,17 +24917,17 @@ function supportTests(store, version2, tracer) {
24613
24917
  function mapPathIndex(paths) {
24614
24918
  const testsIn = /* @__PURE__ */ new Map();
24615
24919
  const under = /* @__PURE__ */ new Map();
24616
- const add = (map2, key, path21) => {
24920
+ const add = (map2, key, path24) => {
24617
24921
  const found = map2.get(key);
24618
- if (found) found.push(path21);
24619
- else map2.set(key, [path21]);
24922
+ if (found) found.push(path24);
24923
+ else map2.set(key, [path24]);
24620
24924
  };
24621
- for (const path21 of paths) {
24622
- const slash = path21.lastIndexOf("/");
24623
- const directory = slash < 0 ? "" : path21.slice(0, slash + 1);
24624
- if (mapTestPath(path21)) add(testsIn, directory, path21);
24925
+ for (const path24 of paths) {
24926
+ const slash = path24.lastIndexOf("/");
24927
+ const directory = slash < 0 ? "" : path24.slice(0, slash + 1);
24928
+ if (mapTestPath(path24)) add(testsIn, directory, path24);
24625
24929
  const name = directory.slice(directory.lastIndexOf("/", directory.length - 2) + 1, -1);
24626
- if (name) add(under, name, path21);
24930
+ if (name) add(under, name, path24);
24627
24931
  }
24628
24932
  return { testsIn, under };
24629
24933
  }
@@ -24716,7 +25020,7 @@ var RouteRequests = class {
24716
25020
  }
24717
25021
  const batch = this.candidates.slice(at, at + READ_BATCH);
24718
25022
  const texts = await Promise.all(
24719
- batch.map((file2) => readFile3(path13.join(project, file2), "utf8").catch(() => void 0))
25023
+ batch.map((file2) => readFile5(path15.join(project, file2), "utf8").catch(() => void 0))
24720
25024
  );
24721
25025
  for (const [index, text] of texts.entries())
24722
25026
  if (text !== void 0) yield [batch[index], text];
@@ -24757,9 +25061,9 @@ async function routeTests(requests, entries, tracer) {
24757
25061
  }
24758
25062
  return requested;
24759
25063
  }
24760
- function wholePath(text, path21) {
24761
- for (let at = text.indexOf(path21); at >= 0; at = text.indexOf(path21, at + 1))
24762
- if (!/[\w./-]/u.test(text[at + path21.length] ?? "")) return true;
25064
+ function wholePath(text, path24) {
25065
+ for (let at = text.indexOf(path24); at >= 0; at = text.indexOf(path24, at + 1))
25066
+ if (!/[\w./-]/u.test(text[at + path24.length] ?? "")) return true;
24763
25067
  return false;
24764
25068
  }
24765
25069
  async function unworkedRequests(requests, tracer, reaching) {
@@ -24780,14 +25084,14 @@ async function unworkedRequests(requests, tracer, reaching) {
24780
25084
  }
24781
25085
  }
24782
25086
  }
24783
- function sameDirectoryTests(paths, path21, tracer) {
24784
- const slash = path21.lastIndexOf("/");
24785
- for (const candidate of paths.testsIn.get(slash < 0 ? "" : path21.slice(0, slash + 1)) ?? [])
25087
+ function sameDirectoryTests(paths, path24, tracer) {
25088
+ const slash = path24.lastIndexOf("/");
25089
+ for (const candidate of paths.testsIn.get(slash < 0 ? "" : path24.slice(0, slash + 1)) ?? [])
24786
25090
  tracer.test(candidate, void 0, "in the same directory", 3);
24787
25091
  }
24788
- function routesIn(graph, path21) {
25092
+ function routesIn(graph, path24) {
24789
25093
  const routes = /* @__PURE__ */ new Set();
24790
- for (const relation of graph.relationsFrom(graph.objectsAt(path21).map((object2) => object2.id))) {
25094
+ for (const relation of graph.relationsFrom(graph.objectsAt(path24).map((object2) => object2.id))) {
24791
25095
  const route = mapRegisteredRoute(relation);
24792
25096
  if (route) routes.add(route);
24793
25097
  }
@@ -24825,9 +25129,9 @@ async function mapRemovedImpact(input) {
24825
25129
  new MapShapeUses(before, input.shapes, input.until)
24826
25130
  );
24827
25131
  const changedIn2 = changedInBase(changes.files);
24828
- const pathNow = (path21) => {
24829
- const file2 = changedIn2.get(path21);
24830
- return file2?.status === "DELETED" ? void 0 : file2?.path ?? path21;
25132
+ const pathNow = (path24) => {
25133
+ const file2 = changedIn2.get(path24);
25134
+ return file2?.status === "DELETED" ? void 0 : file2?.path ?? path24;
24831
25135
  };
24832
25136
  const nowAt = (anchor) => {
24833
25137
  const file2 = changedIn2.get(anchor.path);
@@ -24842,11 +25146,11 @@ async function mapRemovedImpact(input) {
24842
25146
  const samePlace = (anchor, place) => anchor.path === place.path && anchor.startLine === place.startLine && anchor.endLine === place.endLine;
24843
25147
  const replaces = (now, removed2) => now.kind === removed2.kind && now.name === removed2.name;
24844
25148
  const relationsNow = /* @__PURE__ */ new Map();
24845
- const relationsIn = (path21) => {
24846
- let found = relationsNow.get(path21);
25149
+ const relationsIn = (path24) => {
25150
+ let found = relationsNow.get(path24);
24847
25151
  if (!found) {
24848
- found = graph.relationsFrom(graph.objectsAt(path21).map((object2) => object2.id));
24849
- relationsNow.set(path21, found);
25152
+ found = graph.relationsFrom(graph.objectsAt(path24).map((object2) => object2.id));
25153
+ relationsNow.set(path24, found);
24850
25154
  }
24851
25155
  return found;
24852
25156
  };
@@ -24955,13 +25259,13 @@ async function mapRemovedImpact(input) {
24955
25259
  });
24956
25260
  const lost = /* @__PURE__ */ new Map();
24957
25261
  const changedAt = changedInWorkingTree(changes.files);
24958
- for (const path21 of input.mappedPaths().filter(mapMiniprogramTemplate)) {
24959
- const template = graph.objectsAt(path21).find((object2) => mapIsModule(object2));
25262
+ for (const path24 of input.mappedPaths().filter(mapMiniprogramTemplate)) {
25263
+ const template = graph.objectsAt(path24).find((object2) => mapIsModule(object2));
24960
25264
  if (!template) continue;
24961
25265
  const broken = graph.relationsFrom(graph.scope(template.id).refs).filter((relation) => relation.to === void 0 && NAMING_KINDS.has(relation.kind));
24962
25266
  if (!broken.length) continue;
24963
- const file2 = changedAt.get(path21);
24964
- const basePath = file2 ? file2.basePath : path21;
25267
+ const file2 = changedAt.get(path24);
25268
+ const basePath = file2 ? file2.basePath : path24;
24965
25269
  const was = basePath === void 0 ? void 0 : before.objectsAt(basePath).find(mapIsModule);
24966
25270
  const links = was ? before.relationsFrom(before.scope(was.id).refs) : [];
24967
25271
  for (const relation of broken) {
@@ -24970,7 +25274,7 @@ async function mapRemovedImpact(input) {
24970
25274
  );
24971
25275
  if (earlier.some((link) => link.to === void 0)) continue;
24972
25276
  const event = miniprogramEventOf(relation.target);
24973
- const at = `${path21}:${relation.anchor.startLine}`;
25277
+ const at = `${path24}:${relation.anchor.startLine}`;
24974
25278
  if (file2 && overlaps(file2.lines, relation.anchor.startLine, relation.anchor.endLine)) {
24975
25279
  unclear.push({
24976
25280
  text: event ? `${at} binds the ${event.event} event of <${event.tag}>, which it does not emit` : relation.kind === "REFERENCES" ? `${at} puts <${relation.target}>, which its registration does not find` : `${at} binds ${relation.target}, which its page or component does not register`
@@ -24982,7 +25286,7 @@ async function mapRemovedImpact(input) {
24982
25286
  const object2 = before.object(reached);
24983
25287
  const name = mapIsModule(object2) ? `${object2.anchor.path} (template)${event ? `: ${event.event} event` : ""}` : `${object2.anchor.path}: ${before.qualifiedName(reached)} ${mapDeclarationLabel(object2)}`;
24984
25288
  const users = lost.get(name) ?? /* @__PURE__ */ new Set();
24985
- users.add(`${path21} (template)`);
25289
+ users.add(`${path24} (template)`);
24986
25290
  lost.set(name, users);
24987
25291
  }
24988
25292
  }
@@ -25025,15 +25329,15 @@ async function mapRemovedImpact(input) {
25025
25329
  ...removed2 ? { removed: true } : {}
25026
25330
  });
25027
25331
  }
25028
- for (const [path21, test] of beforeTracer.tests) {
25029
- const now = pathNow(path21);
25332
+ for (const [path24, test] of beforeTracer.tests) {
25333
+ const now = pathNow(path24);
25030
25334
  if (now === void 0) continue;
25031
25335
  tracer.test(now, void 0, test.why, test.rank);
25032
25336
  for (const name of test.names) tracer.test(now, name, test.why, test.rank);
25033
25337
  }
25034
25338
  for (const [area, known] of beforeTracer.areas)
25035
- for (const [path21, names] of known.tests) {
25036
- const now = pathNow(path21);
25339
+ for (const [path24, names] of known.tests) {
25340
+ const now = pathNow(path24);
25037
25341
  const place = pathNow(area);
25038
25342
  if (now !== void 0 && place !== void 0)
25039
25343
  tracer.shareArea(place, known.through, now, names);
@@ -25056,24 +25360,24 @@ async function mapRemovedImpact(input) {
25056
25360
  for (const ref of called) {
25057
25361
  const object2 = before.object(ref);
25058
25362
  if (mapIsModule(object2) || mapTestPath(object2.anchor.path) || gone2.has(ref)) continue;
25059
- const path21 = pathNow(object2.anchor.path);
25060
- if (path21 === void 0) continue;
25363
+ const path24 = pathNow(object2.anchor.path);
25364
+ if (path24 === void 0) continue;
25061
25365
  const key = before.declarationKey(object2);
25062
- const now = graph.declarationsAt(path21).find((candidate) => graph.declarationKey(candidate) === key);
25366
+ const now = graph.declarationsAt(path24).find((candidate) => graph.declarationKey(candidate) === key);
25063
25367
  if (!now) continue;
25064
25368
  const calls = tracer.callers(now.id).filter((caller) => !caller.uses);
25065
25369
  if (outsideTests(calls, graph).length || tracer.usesWithoutCalls(now.id).length) continue;
25066
25370
  if (!outsideTests(beforeTracer.callers(ref), before).length) continue;
25067
- candidates.push({ path: path21, name: before.qualifiedName(ref), now, tested: calls.length > 0 });
25371
+ candidates.push({ path: path24, name: before.qualifiedName(ref), now, tested: calls.length > 0 });
25068
25372
  }
25069
25373
  await tracer.shapes.read(candidates.map(({ now }) => now.id));
25070
25374
  const uncalled = [];
25071
25375
  const unknown2 = [];
25072
- for (const { path: path21, name, now, tested } of candidates) {
25376
+ for (const { path: path24, name, now, tested } of candidates) {
25073
25377
  if (tracer.shapes.unread.has(now.id)) unknown2.push(name);
25074
25378
  else if (!tracer.shapes.uses.get(now.id)?.some(({ owner, write }) => !write && !mapTestPath(graph.object(owner).anchor.path))) {
25075
25379
  uncalled.push(
25076
- `${path21}: ${name} ${mapDeclarationLabel(now)}${tested ? " (only tests call it now)" : ""}`
25380
+ `${path24}: ${name} ${mapDeclarationLabel(now)}${tested ? " (only tests call it now)" : ""}`
25077
25381
  );
25078
25382
  }
25079
25383
  }
@@ -25257,12 +25561,12 @@ Nothing changed against ${changes.base}.`;
25257
25561
  registrations.set(group.route, [...registrations.get(group.route) ?? [], group.subject]);
25258
25562
  const certain = impact.entries.filter((e) => e.certain).slice(0, LIST.entries);
25259
25563
  const possible = impact.entries.filter((e) => !e.certain).slice(0, LIST.entries);
25260
- const marked = new Set(
25564
+ const marked2 = new Set(
25261
25565
  [...certain, ...possible].filter((item) => item.route && !item.removed && registrations.has(item.label)).map((item) => item.label)
25262
25566
  );
25263
25567
  const label = (item) => item.route ? JSON.stringify(item.label) : item.label;
25264
25568
  const entry = (item) => {
25265
- const changedAt = marked.has(item.label) ? registrations.get(item.label) ?? [] : [];
25569
+ const changedAt = marked2.has(item.label) ? registrations.get(item.label) ?? [] : [];
25266
25570
  const registered = item.site ? `registered at ${item.site}${changedAt.includes(item.site) ? ", a line the diff changed" : ""}` : "";
25267
25571
  const elsewhere = changedAt.filter((site) => site !== item.site);
25268
25572
  const where = [
@@ -25282,7 +25586,7 @@ Nothing changed against ${changes.base}.`;
25282
25586
  LIST.entries
25283
25587
  );
25284
25588
  const listed = new Set([...certain, ...possible].map(entry));
25285
- if (marked.size)
25589
+ if (marked2.size)
25286
25590
  lines.push(
25287
25591
  "Where the diff changed a route's registration, check that the route still reaches the right handler."
25288
25592
  );
@@ -25371,7 +25675,7 @@ Nothing changed against ${changes.base}.`;
25371
25675
  ...incomplete,
25372
25676
  ...uncertainLines(
25373
25677
  impact.unclear.filter(
25374
- ({ group }) => group?.route === void 0 || !marked.has(group.route)
25678
+ ({ group }) => group?.route === void 0 || !marked2.has(group.route)
25375
25679
  )
25376
25680
  )
25377
25681
  ],
@@ -25440,9 +25744,9 @@ function pathBetween(edges, from, to) {
25440
25744
  if (via.has(target)) continue;
25441
25745
  via.set(target, module);
25442
25746
  if (target === to) {
25443
- const path21 = [to];
25444
- for (let step = module; step !== from; step = via.get(step) ?? from) path21.unshift(step);
25445
- return [from, ...path21];
25747
+ const path24 = [to];
25748
+ for (let step = module; step !== from; step = via.get(step) ?? from) path24.unshift(step);
25749
+ return [from, ...path24];
25446
25750
  }
25447
25751
  next.push(target);
25448
25752
  }
@@ -25495,11 +25799,11 @@ function newModuleDependencies(store, cache, working, files, links) {
25495
25799
  );
25496
25800
  }
25497
25801
  var MANIFEST = /(?:^|\/)(?:package\.json|go\.mod|pom\.xml|build\.gradle(?:\.kts)?|pyproject\.toml|setup\.py|setup\.cfg)$/u;
25498
- var directoryOf3 = (path21) => path21.slice(0, Math.max(path21.lastIndexOf("/"), 0));
25802
+ var directoryOf3 = (path24) => path24.slice(0, Math.max(path24.lastIndexOf("/"), 0));
25499
25803
  var directoryLabel = (directory) => directory ? `${directory}/` : "./";
25500
25804
  function mapReuseImports(store, cache, working) {
25501
25805
  const roots = store.listEntries(working).filter((entry) => MANIFEST.test(entry.path)).map((entry) => directoryOf3(entry.path)).sort((left, right) => right.length - left.length);
25502
- const packageOf = (path21) => roots.find((root) => !root || path21.startsWith(`${root}/`)) ?? "";
25806
+ const packageOf = (path24) => roots.find((root) => !root || path24.startsWith(`${root}/`)) ?? "";
25503
25807
  const directories = /* @__PURE__ */ new Map();
25504
25808
  const packages = /* @__PURE__ */ new Map();
25505
25809
  const files = /* @__PURE__ */ new Set();
@@ -25532,21 +25836,21 @@ function mapReuseImports(store, cache, working) {
25532
25836
  };
25533
25837
  const graph = new MapViewGraph(store, working);
25534
25838
  const usedFrom = /* @__PURE__ */ new Map();
25535
- const used = (path21) => {
25536
- let found = usedFrom.get(path21);
25839
+ const used = (path24) => {
25840
+ let found = usedFrom.get(path24);
25537
25841
  if (found === void 0) {
25538
- found = graph.relationsTo(graph.objectsAt(path21).map((object2) => object2.id)).some((relation) => graph.object(relation.from).anchor.path !== path21);
25539
- usedFrom.set(path21, found);
25842
+ found = graph.relationsTo(graph.objectsAt(path24).map((object2) => object2.id)).some((relation) => graph.object(relation.from).anchor.path !== path24);
25843
+ usedFrom.set(path24, found);
25540
25844
  }
25541
25845
  return found;
25542
25846
  };
25543
- return (path21, existing) => {
25544
- const added = [directoryOf3(path21), packageOf(path21)];
25847
+ return (path24, existing) => {
25848
+ const added = [directoryOf3(path24), packageOf(path24)];
25545
25849
  const old = [directoryOf3(existing), packageOf(existing)];
25546
25850
  const ahead = use("NEW", added, old);
25547
- if (files.has(`${path21}\0${existing}`)) return ahead;
25548
- if (files.has(`${existing}\0${path21}`))
25549
- return { ...use("EXISTING", old, added), from: existing, to: path21 };
25851
+ if (files.has(`${path24}\0${existing}`)) return ahead;
25852
+ if (files.has(`${existing}\0${path24}`))
25853
+ return { ...use("EXISTING", old, added), from: existing, to: path24 };
25550
25854
  const usable = used(existing);
25551
25855
  if (usable && ahead.imported) return ahead;
25552
25856
  if (directories.get(old[0])?.has(added[0])) return use("EXISTING", old, added);
@@ -25568,9 +25872,9 @@ var KEYWORDS = new Set(
25568
25872
  );
25569
25873
  var ROWS = `SELECT entity_ref AS id, path, name, kind, object_json AS object
25570
25874
  FROM project_map_objects WHERE version_ref = ? AND kind <> 'PROPERTY'`;
25571
- function rows(store, version2, path21) {
25572
- const statement = store.database.prepare(path21 === void 0 ? ROWS : `${ROWS} AND path = ?`);
25573
- return (path21 === void 0 ? statement.all(version2) : statement.all(version2, path21)).map((row) => {
25875
+ function rows(store, version2, path24) {
25876
+ const statement = store.database.prepare(path24 === void 0 ? ROWS : `${ROWS} AND path = ?`);
25877
+ return (path24 === void 0 ? statement.all(version2) : statement.all(version2, path24)).map((row) => {
25574
25878
  const { anchor } = JSON.parse(String(row.object));
25575
25879
  return {
25576
25880
  id: String(row.id),
@@ -25612,10 +25916,10 @@ function lineWords(line) {
25612
25916
  var within2 = (lines, declaration) => lines.some(([from, to]) => from <= declaration.startLine && declaration.endLine <= to);
25613
25917
  var copyText = (code) => code.replace(/^export\s+(?:default\s+)?/u, "").replace(/\s+/gu, " ").trim();
25614
25918
  async function similarCode(store, working, base, files, read) {
25615
- const code = (path21) => mapCodePath(path21) && !mapTestPath(path21) && !MAP_MIGRATION_PATH.test(path21);
25919
+ const code = (path24) => mapCodePath(path24) && !mapTestPath(path24) && !MAP_MIGRATION_PATH.test(path24);
25616
25920
  const changed = files.filter((file2) => file2.status !== "DELETED" && code(file2.path));
25617
25921
  if (!changed.length) return [];
25618
- const names = (version2, path21) => new Set(declarations(rows(store, version2, path21)).map((item) => item.qualifiedName));
25922
+ const names = (version2, path24) => new Set(declarations(rows(store, version2, path24)).map((item) => item.qualifiedName));
25619
25923
  const movedOut = /* @__PURE__ */ new Set();
25620
25924
  if (base !== void 0)
25621
25925
  for (const file2 of files) {
@@ -25647,11 +25951,11 @@ async function similarCode(store, working, base, files, read) {
25647
25951
  const all = [];
25648
25952
  const shortCopies = /* @__PURE__ */ new Map();
25649
25953
  const texts = await Promise.all(
25650
- [...byPath].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(async ([path21, inFile]) => {
25954
+ [...byPath].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(async ([path24, inFile]) => {
25651
25955
  const found2 = declarations(inFile).filter(
25652
25956
  (item) => KINDS2.has(item.kind) && (long(item) ? longAdded : shortNames.has(item.qualifiedName))
25653
25957
  );
25654
- return { found: found2, text: found2.length ? await read(path21) : void 0 };
25958
+ return { found: found2, text: found2.length ? await read(path24) : void 0 };
25655
25959
  })
25656
25960
  );
25657
25961
  for (const { found: found2, text } of texts) {
@@ -25786,10 +26090,10 @@ async function mapChangeImpact(store, views, working, base, changes, links, shap
25786
26090
  const mappedPaths = () => mapped ??= store.database.prepare("SELECT DISTINCT path FROM project_map_objects WHERE version_ref = ?").all(working).map((row) => String(row.path));
25787
26091
  let paths;
25788
26092
  const pathIndex = () => paths ??= mapPathIndex(mappedPaths());
25789
- const topLevelChanged = (path21) => {
25790
- const text = `top-level code of ${path21} changed (imports, constants or registrations)`;
26093
+ const topLevelChanged = (path24) => {
26094
+ const text = `top-level code of ${path24} changed (imports, constants or registrations)`;
25791
26095
  if (!unclear.some((note) => note.text === text))
25792
- unclear.push({ text, group: { kind: "TOP_LEVEL", subject: path21 } });
26096
+ unclear.push({ text, group: { kind: "TOP_LEVEL", subject: path24 } });
25793
26097
  };
25794
26098
  for (const file2 of changes.files) {
25795
26099
  const objects2 = file2.status === "DELETED" || file2.binary ? [] : graph.objectsAt(file2.path);
@@ -25919,15 +26223,15 @@ async function mapChangeImpact(store, views, working, base, changes, links, shap
25919
26223
  project,
25920
26224
  mappedPaths
25921
26225
  }) : void 0;
25922
- for (const path21 of taken?.topLevel ?? []) topLevelChanged(path21);
26226
+ for (const path24 of taken?.topLevel ?? []) topLevelChanged(path24);
25923
26227
  unclear.push(...taken?.unclear ?? []);
25924
26228
  return {
25925
26229
  changed,
25926
26230
  removed: taken?.removed ?? [],
25927
26231
  rewrittenTests: taken?.rewrittenTests ?? [],
25928
26232
  entries: [...tracer.entries.values()].sort(entryOrder),
25929
- tests: [...tracer.tests].map(([path21, test]) => ({
25930
- path: path21,
26233
+ tests: [...tracer.tests].map(([path24, test]) => ({
26234
+ path: path24,
25931
26235
  names: [...test.names].sort(),
25932
26236
  why: test.why,
25933
26237
  rank: test.rank
@@ -25937,7 +26241,7 @@ async function mapChangeImpact(store, views, working, base, changes, links, shap
25937
26241
  areas: [...tracer.areas].map(([area, known]) => ({
25938
26242
  area,
25939
26243
  through: [...known.through].sort(),
25940
- tests: [...known.tests].map(([path21, names]) => ({ path: path21, names: [...names].sort() })).sort((left, right) => right.names.length - left.names.length)
26244
+ tests: [...known.tests].map(([path24, names]) => ({ path: path24, names: [...names].sort() })).sort((left, right) => right.names.length - left.names.length)
25941
26245
  })).sort((left, right) => right.tests.length - left.tests.length),
25942
26246
  unclear: [
25943
26247
  ...new Map([...unclear, ...tracer.unclear].map((note) => [note.text, note])).values()
@@ -26026,9 +26330,9 @@ function mapChangesData(changes, impact, edges) {
26026
26330
  return {
26027
26331
  base: changes.base,
26028
26332
  commit: changes.commit,
26029
- files: changes.files.map(({ path: path21, basePath, status }) => ({
26030
- path: path21,
26031
- ...basePath !== void 0 && basePath !== path21 ? { basePath } : {},
26333
+ files: changes.files.map(({ path: path24, basePath, status }) => ({
26334
+ path: path24,
26335
+ ...basePath !== void 0 && basePath !== path24 ? { basePath } : {},
26032
26336
  status
26033
26337
  })),
26034
26338
  tests: impact.tests,
@@ -26112,7 +26416,7 @@ async function checkMapChanges(input, signal) {
26112
26416
  working,
26113
26417
  base,
26114
26418
  changes.files,
26115
- (file2) => readFile4(path14.join(project, file2), "utf8").catch(() => void 0)
26419
+ (file2) => readFile6(path16.join(project, file2), "utf8").catch(() => void 0)
26116
26420
  )
26117
26421
  ),
26118
26422
  changes.files.length ? await compileBreaks(input, views, changes, base, until, signal, phase, baseVersion) : void 0
@@ -26141,7 +26445,7 @@ async function mapRouteClients(project, store, working, impact, signal) {
26141
26445
  ...impact.removedRoutes.filter((route) => !served(route)).map((route) => ({ route, removed: true }))
26142
26446
  ];
26143
26447
  if (!routes.length) return { routes: [] };
26144
- return routeClients(routes, registrations, git, gitOptions(project, signal));
26448
+ return routeClients(routes, registrations, git2, gitOptions(project, signal));
26145
26449
  }
26146
26450
  async function compileBreaks(input, views, changes, base, until, signal, phase, baseVersion) {
26147
26451
  const { index, working } = input;
@@ -26189,7 +26493,7 @@ async function compileBreaks(input, views, changes, base, until, signal, phase,
26189
26493
  signal
26190
26494
  ) : { contexts: [], unchecked: [] };
26191
26495
  const inBase = changedInBase(changes.files);
26192
- const named = (path21, item) => `${path21}\0${item.code}\0${item.span}\0${item.text}`;
26496
+ const named = (path24, item) => `${path24}\0${item.code}\0${item.span}\0${item.text}`;
26193
26497
  const compiled = new Map(before.contexts.map((context) => [context.configPath, context.errors]));
26194
26498
  const unchecked = new Set(after.unchecked);
26195
26499
  const errors = /* @__PURE__ */ new Set();
@@ -26249,7 +26553,7 @@ CREATE INDEX layermap_commit_version ON layermap_commit_versions(version_ref);
26249
26553
  `;
26250
26554
  var schemaVersion = (database) => Number(database.prepare("PRAGMA user_version").get()?.user_version ?? 0);
26251
26555
  function openMapDatabase(file2) {
26252
- mkdirSync(path15.dirname(file2), { recursive: true, mode: 448 });
26556
+ mkdirSync(path17.dirname(file2), { recursive: true, mode: 448 });
26253
26557
  const database = new DatabaseSync(file2);
26254
26558
  try {
26255
26559
  database.exec(BUSY_TIMEOUT);
@@ -26308,10 +26612,10 @@ async function lockMapBuilds(file2, signal) {
26308
26612
  throw error51;
26309
26613
  }
26310
26614
  }
26311
- var mapDatabasePath = (cacheDirectory2, canonicalProject) => path15.join(
26615
+ var mapDatabasePath = (cacheDirectory2, canonicalProject) => path17.join(
26312
26616
  cacheDirectory2,
26313
26617
  "projects",
26314
- createHash5("sha256").update(canonicalProject).digest("hex").slice(0, 24),
26618
+ createHash6("sha256").update(canonicalProject).digest("hex").slice(0, 24),
26315
26619
  "map.sqlite"
26316
26620
  );
26317
26621
  var LayerMap = class _LayerMap {
@@ -26340,12 +26644,12 @@ var LayerMap = class _LayerMap {
26340
26644
  closed = false;
26341
26645
  static async open(options) {
26342
26646
  const project = await realpath2(options.project);
26343
- const stat4 = await lstat4(project, { bigint: true });
26344
- if (!stat4.isDirectory()) throw new ProjectEvidenceError("PROJECT_PATH_INVALID", false);
26647
+ const stat6 = await lstat4(project, { bigint: true });
26648
+ if (!stat6.isDirectory()) throw new ProjectEvidenceError("PROJECT_PATH_INVALID", false);
26345
26649
  const source = {
26346
26650
  kind: "WORKTREE",
26347
- projectRef: `layermap:${createHash5("sha256").update(project).digest("hex").slice(0, 24)}`,
26348
- directory: { canonicalPath: project, device: String(stat4.dev), inode: String(stat4.ino) }
26651
+ projectRef: `layermap:${createHash6("sha256").update(project).digest("hex").slice(0, 24)}`,
26652
+ directory: { canonicalPath: project, device: String(stat6.dev), inode: String(stat6.ino) }
26349
26653
  };
26350
26654
  const file2 = mapDatabasePath(options.cacheDirectory, project);
26351
26655
  const store = new CodeIndexStore(
@@ -26366,7 +26670,7 @@ var LayerMap = class _LayerMap {
26366
26670
  store,
26367
26671
  void 0,
26368
26672
  analyzer,
26369
- (signal) => lockMapBuilds(path15.join(path15.dirname(file2), "build.lock"), signal)
26673
+ (signal) => lockMapBuilds(path17.join(path17.dirname(file2), "build.lock"), signal)
26370
26674
  ),
26371
26675
  analyzer.id,
26372
26676
  { maxBytes: options.maxOutputBytes ?? 96 * 1024, envelopeBytes: 0 },
@@ -26623,29 +26927,56 @@ var LayerMap = class _LayerMap {
26623
26927
  }
26624
26928
  };
26625
26929
 
26930
+ // src/agent/launcher.ts
26931
+ import { existsSync as existsSync6 } from "node:fs";
26932
+ import { readFile as readFile7, rename as rename2, writeFile } from "node:fs/promises";
26933
+ import path18 from "node:path";
26934
+ var launcherScript = (template, args = '["mcp"]') => `// Generated from scripts/launcher.mjs.
26935
+ ${template.replace("__ARGUMENTS__", args)}`;
26936
+ var LAUNCHERS = {
26937
+ "server.mjs": '["mcp"]',
26938
+ "cli.mjs": "process.argv.slice(2)"
26939
+ };
26940
+ var launcherTemplate = (packageRoot2) => [
26941
+ path18.join(packageRoot2, "dist", "launcher.mjs"),
26942
+ path18.join(packageRoot2, "scripts", "launcher.mjs")
26943
+ ].find(existsSync6);
26944
+ async function writeLauncher(directory, name, template) {
26945
+ const file2 = path18.join(directory, name);
26946
+ const content = launcherScript(template, LAUNCHERS[name]);
26947
+ if (await readFile7(file2, "utf8").catch(() => void 0) === content) return;
26948
+ await writeFile(`${file2}.${process.pid}`, content);
26949
+ await rename2(`${file2}.${process.pid}`, file2);
26950
+ }
26951
+ async function refreshLaunchers(directory, template) {
26952
+ const text = await readFile7(template, "utf8");
26953
+ for (const name of Object.keys(LAUNCHERS))
26954
+ if (existsSync6(path18.join(directory, name))) await writeLauncher(directory, name, text);
26955
+ }
26956
+
26626
26957
  // src/agent/environment.ts
26627
26958
  var packageRoot = (() => {
26628
- for (let directory = path16.dirname(fileURLToPath(import.meta.url)); ; ) {
26629
- const manifest = path16.join(directory, "package.json");
26630
- if (existsSync6(manifest) && JSON.parse(readFileSync3(manifest, "utf8")).name === "layermap")
26959
+ for (let directory = path19.dirname(fileURLToPath(import.meta.url)); ; ) {
26960
+ const manifest = path19.join(directory, "package.json");
26961
+ if (existsSync7(manifest) && JSON.parse(readFileSync3(manifest, "utf8")).name === "layermap")
26631
26962
  return directory;
26632
- if (path16.dirname(directory) === directory) throw new Error("LayerMap cannot find its package.");
26633
- directory = path16.dirname(directory);
26963
+ if (path19.dirname(directory) === directory) throw new Error("LayerMap cannot find its package.");
26964
+ directory = path19.dirname(directory);
26634
26965
  }
26635
26966
  })();
26636
- var packageVersion = async () => JSON.parse(await readFile5(path16.join(packageRoot, "package.json"), "utf8")).version;
26967
+ var packageVersion = async () => JSON.parse(await readFile8(path19.join(packageRoot, "package.json"), "utf8")).version;
26637
26968
  var userCache = (env) => {
26638
- if (process.platform === "darwin") return path16.join(homedir(), "Library", "Caches", "layermap");
26969
+ if (process.platform === "darwin") return path19.join(homedir(), "Library", "Caches", "layermap");
26639
26970
  if (process.platform === "win32")
26640
- return path16.join(
26641
- env.LOCALAPPDATA || path16.join(homedir(), "AppData", "Local"),
26971
+ return path19.join(
26972
+ env.LOCALAPPDATA || path19.join(homedir(), "AppData", "Local"),
26642
26973
  "layermap",
26643
26974
  "Cache"
26644
26975
  );
26645
- return path16.join(env.XDG_CACHE_HOME || path16.join(homedir(), ".cache"), "layermap");
26976
+ return path19.join(env.XDG_CACHE_HOME || path19.join(homedir(), ".cache"), "layermap");
26646
26977
  };
26647
- var cacheDirectory = (env = process.env) => env.LAYERMAP_CACHE ? path16.resolve(env.LAYERMAP_CACHE) : userCache(env);
26648
- var installDirectory = (env = process.env) => env.LAYERMAP_HOME ? path16.resolve(env.LAYERMAP_HOME) : userCache(env);
26978
+ var cacheDirectory = (env = process.env) => env.LAYERMAP_CACHE ? path19.resolve(env.LAYERMAP_CACHE) : userCache(env);
26979
+ var installDirectory = (env = process.env) => env.LAYERMAP_HOME ? path19.resolve(env.LAYERMAP_HOME) : userCache(env);
26649
26980
  var projectDirectory = async (directory) => {
26650
26981
  try {
26651
26982
  const { stdout } = await new GitRunner().run(["rev-parse", "--show-toplevel"], {
@@ -26654,7 +26985,7 @@ var projectDirectory = async (directory) => {
26654
26985
  });
26655
26986
  return { directory: stdout.toString().trim(), git: true };
26656
26987
  } catch {
26657
- return { directory: path16.resolve(directory), git: false };
26988
+ return { directory: path19.resolve(directory), git: false };
26658
26989
  }
26659
26990
  };
26660
26991
  var relativeTo = (directory, value) => Object.fromEntries(
@@ -26663,7 +26994,7 @@ var relativeTo = (directory, value) => Object.fromEntries(
26663
26994
  Object.fromEntries(
26664
26995
  Object.entries(resources).map(([key, field]) => [
26665
26996
  key,
26666
- key.endsWith("Path") && typeof field === "string" && field.startsWith(directory) ? path16.relative(directory, field) : field
26997
+ key.endsWith("Path") && typeof field === "string" && field.startsWith(directory) ? path19.relative(directory, field) : field
26667
26998
  ])
26668
26999
  )
26669
27000
  ])
@@ -26674,7 +27005,7 @@ var resolvePlaceholder = (field) => {
26674
27005
  createRequire(import.meta.url).resolve("typescript/package.json")
26675
27006
  );
26676
27007
  const native = `@typescript/typescript-${process.platform}-${process.arch}/package.json`;
26677
- return path16.join(path16.dirname(compiler.resolve(native)), "lib", executableName("tsc"));
27008
+ return path19.join(path19.dirname(compiler.resolve(native)), "lib", executableName("tsc"));
26678
27009
  }
26679
27010
  const resolved = field.replaceAll("{platform}", process.platform).replaceAll("{arch}", process.arch);
26680
27011
  return field.includes("{platform}") ? executableName(resolved) : resolved;
@@ -26686,42 +27017,45 @@ var absoluteIn = (directory, value) => Object.fromEntries(
26686
27017
  Object.entries(resources).map(([key, field]) => {
26687
27018
  if (!key.endsWith("Path") || typeof field !== "string") return [key, field];
26688
27019
  const resolved = resolvePlaceholder(field);
26689
- return [key, path16.isAbsolute(resolved) ? resolved : path16.join(directory, resolved)];
27020
+ return [key, path19.isAbsolute(resolved) ? resolved : path19.join(directory, resolved)];
26690
27021
  })
26691
27022
  )
26692
27023
  ])
26693
27024
  );
26694
27025
  var readAnalyzers = async (directory) => {
26695
- const file2 = path16.join(directory, "analyzers.json");
26696
- if (!existsSync6(file2)) return void 0;
26697
- const analyzers = absoluteIn(directory, JSON.parse(await readFile5(file2, "utf8")));
27026
+ const file2 = path19.join(directory, "analyzers.json");
27027
+ if (!existsSync7(file2)) return void 0;
27028
+ const analyzers = absoluteIn(directory, JSON.parse(await readFile8(file2, "utf8")));
26698
27029
  return analyzers.java.runtimePath ? analyzers : { ...analyzers, java: { ...analyzers.java, ...discoverJavaRuntime() } };
26699
27030
  };
26700
27031
  var sourceDigest = async () => {
26701
- const hash2 = createHash6("sha256").update(await readFile5(path16.join(packageRoot, "package.json")));
27032
+ const hash3 = createHash7("sha256").update(await readFile8(path19.join(packageRoot, "package.json")));
26702
27033
  for (const part of ["src", "go-map", "java-map", "scripts"]) {
26703
- const directory = path16.join(packageRoot, part);
26704
- if (!existsSync6(directory)) continue;
26705
- for (const entry of (await readdir(directory, { recursive: true })).sort()) {
26706
- const file2 = path16.join(directory, entry);
26707
- const info = await stat2(file2);
26708
- if (info.isFile()) hash2.update(`${part}/${entry}\0${info.size}\0${info.mtimeMs}\0`);
27034
+ const directory = path19.join(packageRoot, part);
27035
+ if (!existsSync7(directory)) continue;
27036
+ for (const entry of (await readdir2(directory, { recursive: true })).sort()) {
27037
+ const file2 = path19.join(directory, entry);
27038
+ const info = await stat4(file2);
27039
+ if (info.isFile()) hash3.update(`${part}/${entry}\0${info.size}\0${info.mtimeMs}\0`);
26709
27040
  }
26710
27041
  }
26711
- return hash2.digest("hex").slice(0, 16);
27042
+ return hash3.digest("hex").slice(0, 16);
26712
27043
  };
26713
27044
  async function resolveAnalyzers(cache, log2, env = process.env) {
26714
- for (const directory2 of [env.LAYERMAP_ANALYZERS, path16.join(packageRoot, "analyzers")]) {
26715
- const analyzers = directory2 && await readAnalyzers(path16.resolve(directory2));
27045
+ for (const directory2 of [env.LAYERMAP_ANALYZERS, path19.join(packageRoot, "analyzers")]) {
27046
+ const analyzers = directory2 && await readAnalyzers(path19.resolve(directory2));
26716
27047
  if (analyzers) return analyzers;
26717
27048
  }
26718
- const directory = path16.join(cache, "analyzers", await sourceDigest());
27049
+ const directory = path19.join(cache, "analyzers", await sourceDigest());
26719
27050
  const built = await readAnalyzers(directory);
26720
- if (built) return built;
27051
+ if (built) {
27052
+ await markInUse(directory);
27053
+ return built;
27054
+ }
26721
27055
  log2("Building the language analyzers (once per LayerMap version)...");
26722
27056
  const staging = `${directory}.${process.pid}`;
26723
- await rm(staging, { recursive: true, force: true });
26724
- await mkdir2(staging, { recursive: true, mode: 448 });
27057
+ await rm2(staging, { recursive: true, force: true });
27058
+ await mkdir3(staging, { recursive: true, mode: 448 });
26725
27059
  const builder = new URL("../../scripts/build.mjs", import.meta.url).href;
26726
27060
  const { buildProjectMapParser } = await import(builder);
26727
27061
  const parser = await buildProjectMapParser(staging);
@@ -26731,83 +27065,108 @@ async function resolveAnalyzers(cache, log2, env = process.env) {
26731
27065
  python: parser.pythonResources,
26732
27066
  java: parser.javaResources
26733
27067
  });
26734
- await writeFile(path16.join(staging, "analyzers.json"), `${JSON.stringify(stored, null, 2)}
27068
+ await writeFile2(path19.join(staging, "analyzers.json"), `${JSON.stringify(stored, null, 2)}
26735
27069
  `);
26736
- await rename2(staging, directory).catch(() => rm(staging, { recursive: true, force: true }));
27070
+ await rename3(staging, directory).catch(() => rm2(staging, { recursive: true, force: true }));
27071
+ await markInUse(directory);
26737
27072
  return await readAnalyzers(directory);
26738
27073
  }
26739
27074
  var DAY = 24 * 60 * 60 * 1e3;
27075
+ var MARK_EVERY_MS = 10 * 60 * 1e3;
27076
+ var marked = /* @__PURE__ */ new Set();
27077
+ var touch = async (file2, now = Date.now()) => {
27078
+ await writeFile2(file2, "");
27079
+ await utimes(file2, now / 1e3, now / 1e3);
27080
+ };
27081
+ async function markInUse(build) {
27082
+ const file2 = path19.join(build, "last-used");
27083
+ await touch(file2);
27084
+ if (marked.has(build)) return;
27085
+ marked.add(build);
27086
+ setInterval(() => void touch(file2).catch(() => void 0), MARK_EVERY_MS).unref();
27087
+ }
27088
+ var lastUsed = async (directory) => {
27089
+ const marker = path19.join(directory, "last-used");
27090
+ return (await stat4(existsSync7(marker) ? marker : directory).catch(() => void 0))?.mtimeMs;
27091
+ };
26740
27092
  async function pruneCache(cache, project, now = Date.now(), installed = packageRoot, env = process.env) {
26741
- const used = path16.join(path16.dirname(mapDatabasePath(cache, project)), "last-used");
26742
- await mkdir2(path16.dirname(used), { recursive: true, mode: 448 });
26743
- await writeFile(used, project);
27093
+ const used = path19.join(path19.dirname(mapDatabasePath(cache, project)), "last-used");
27094
+ await mkdir3(path19.dirname(used), { recursive: true, mode: 448 });
27095
+ await writeFile2(used, project);
26744
27096
  await utimes(used, now / 1e3, now / 1e3);
26745
- const projects = path16.join(cache, "projects");
26746
- for (const name of await readdir(projects).catch(() => [])) {
26747
- const directory = path16.join(projects, name);
26748
- const marker = path16.join(directory, "last-used");
26749
- const last = (await stat2(existsSync6(marker) ? marker : directory).catch(() => void 0))?.mtimeMs;
26750
- const owner = await readFile5(marker, "utf8").catch(() => "");
27097
+ const projects = path19.join(cache, "projects");
27098
+ for (const name of await readdir2(projects).catch(() => [])) {
27099
+ const directory = path19.join(projects, name);
27100
+ const last = await lastUsed(directory);
27101
+ const owner = await readFile8(path19.join(directory, "last-used"), "utf8").catch(() => "");
26751
27102
  if (last !== void 0 && now - last > 30 * DAY || owner !== "" && await gone(owner))
26752
- await rm(directory, { recursive: true, force: true });
26753
- }
26754
- const builds = path16.join(cache, "analyzers");
26755
- const current = await sourceDigest();
26756
- for (const name of await readdir(builds).catch(() => [])) {
26757
- if (name === current) continue;
26758
- const built = (await stat2(path16.join(builds, name)).catch(() => void 0))?.mtimeMs;
26759
- if (built !== void 0 && now - built > (name.includes(".") ? DAY / 24 : DAY))
26760
- await rm(path16.join(builds, name), { recursive: true, force: true });
26761
- }
26762
- const own = path16.dirname(path16.dirname(installed));
26763
- const versions = path16.join(installDirectory(env), "versions");
26764
- const launched = path16.dirname(own) === versions;
26765
- if (launched) await pruneVersions(versions, own, now);
26766
- const npx = launched ? path16.join(
26767
- env.npm_config_cache || (process.platform === "win32" ? path16.join(env.LOCALAPPDATA || path16.join(homedir(), "AppData", "Local"), "npm-cache") : path16.join(homedir(), ".npm")),
27103
+ await rm2(directory, { recursive: true, force: true });
27104
+ }
27105
+ if (!env.LAYERMAP_ANALYZERS && !existsSync7(path19.join(packageRoot, "analyzers"))) {
27106
+ const builds = path19.join(cache, "analyzers");
27107
+ const current = await sourceDigest();
27108
+ for (const name of await readdir2(builds).catch(() => [])) {
27109
+ if (name === current) continue;
27110
+ const last = await lastUsed(path19.join(builds, name));
27111
+ if (last !== void 0 && now - last > (name.includes(".") ? DAY / 24 : DAY))
27112
+ await rm2(path19.join(builds, name), { recursive: true, force: true });
27113
+ }
27114
+ }
27115
+ const own = path19.dirname(path19.dirname(installed));
27116
+ const versions = path19.join(installDirectory(env), "versions");
27117
+ const launched = path19.dirname(own) === versions;
27118
+ if (launched) await pruneVersions(versions, installed, now);
27119
+ const npx = launched ? path19.join(
27120
+ env.npm_config_cache || (process.platform === "win32" ? path19.join(env.LOCALAPPDATA || path19.join(homedir(), "AppData", "Local"), "npm-cache") : path19.join(homedir(), ".npm")),
26768
27121
  "_npx"
26769
- ) : path16.dirname(own);
26770
- if (path16.basename(path16.dirname(installed)) === "node_modules" && path16.basename(npx) === "_npx")
27122
+ ) : path19.dirname(own);
27123
+ if (path19.basename(path19.dirname(installed)) === "node_modules" && path19.basename(npx) === "_npx")
26771
27124
  await pruneNpxInstalls(npx, installed, now);
26772
27125
  }
26773
- var gone = (directory) => stat2(directory).then(
27126
+ var gone = (directory) => stat4(directory).then(
26774
27127
  () => false,
26775
27128
  (error51) => error51.code === "ENOENT"
26776
27129
  );
26777
- async function pruneVersions(versions, own, now) {
26778
- const used = path16.join(own, "last-used");
26779
- await writeFile(used, "");
26780
- await utimes(used, now / 1e3, now / 1e3);
26781
- for (const name of await readdir(versions).catch(() => [])) {
26782
- const directory = path16.join(versions, name);
26783
- const marker = path16.join(directory, "last-used");
26784
- const last = (await stat2(existsSync6(marker) ? marker : directory).catch(() => void 0))?.mtimeMs;
26785
- if (last !== void 0 && now - last > (name.startsWith(".") ? DAY / 24 : 7 * DAY))
26786
- await rm(directory, { recursive: true, force: true });
27130
+ async function pruneVersions(versions, installed, now) {
27131
+ const own = path19.dirname(path19.dirname(installed));
27132
+ await touch(path19.join(own, "last-used"), now);
27133
+ const current = (await readFile8(path19.join(versions, "current"), "utf8").catch(() => "")).trim();
27134
+ if (!current) return;
27135
+ if (path19.basename(own) === current) {
27136
+ const template = launcherTemplate(installed);
27137
+ if (template) await refreshLaunchers(path19.dirname(versions), template);
27138
+ }
27139
+ for (const name of await readdir2(versions).catch(() => [])) {
27140
+ const installing = name.startsWith(".");
27141
+ if (name === current || !installing && !/^\d+\.\d+\.\d+$/u.test(name)) continue;
27142
+ const directory = path19.join(versions, name);
27143
+ const last = await lastUsed(directory);
27144
+ if (last !== void 0 && now - last > (installing ? DAY / 24 : 7 * DAY))
27145
+ await rm2(directory, { recursive: true, force: true });
26787
27146
  }
26788
27147
  }
26789
27148
  async function pruneNpxInstalls(npx, installed, now) {
26790
- const own = path16.dirname(path16.dirname(installed));
26791
- const manifest = async (file2) => JSON.parse(await readFile5(file2, "utf8").catch(() => "{}"));
27149
+ const own = path19.dirname(path19.dirname(installed));
27150
+ const manifest = async (file2) => JSON.parse(await readFile8(file2, "utf8").catch(() => "{}"));
26792
27151
  const parts = (version2) => version2?.split(".").map(Number) ?? [];
26793
- const current = parts((await manifest(path16.join(installed, "package.json"))).version);
27152
+ const current = parts((await manifest(path19.join(installed, "package.json"))).version);
26794
27153
  const older = (version2) => {
26795
27154
  for (let index = 0; index < 3; index++)
26796
27155
  if (version2[index] !== current[index]) return (version2[index] ?? 0) < (current[index] ?? 0);
26797
27156
  return false;
26798
27157
  };
26799
- for (const name of await readdir(npx).catch(() => [])) {
26800
- const directory = path16.join(npx, name);
27158
+ for (const name of await readdir2(npx).catch(() => [])) {
27159
+ const directory = path19.join(npx, name);
26801
27160
  if (directory === own) continue;
26802
- const requested = (await manifest(path16.join(directory, "package.json"))).dependencies ?? {};
27161
+ const requested = (await manifest(path19.join(directory, "package.json"))).dependencies ?? {};
26803
27162
  if (Object.keys(requested).join() !== "layermap") continue;
26804
27163
  const version2 = parts(
26805
- (await manifest(path16.join(directory, "node_modules", "layermap", "package.json"))).version
27164
+ (await manifest(path19.join(directory, "node_modules", "layermap", "package.json"))).version
26806
27165
  );
26807
27166
  if (version2.length !== 3 || version2.some(Number.isNaN) || !older(version2)) continue;
26808
- const at = (await stat2(directory).catch(() => void 0))?.mtimeMs;
27167
+ const at = (await stat4(directory).catch(() => void 0))?.mtimeMs;
26809
27168
  if (at !== void 0 && now - at > 7 * DAY)
26810
- await rm(directory, { recursive: true, force: true });
27169
+ await rm2(directory, { recursive: true, force: true });
26811
27170
  }
26812
27171
  }
26813
27172
 
@@ -26815,48 +27174,27 @@ async function pruneNpxInstalls(npx, installed, now) {
26815
27174
  var MARK = "// LayerMap's command, written by `layermap setup command`.";
26816
27175
  var commandScript = (directory) => `#!/usr/bin/env node
26817
27176
  ${MARK}
26818
- // It runs the newest LayerMap version installed in the directory below, where each agent's LayerMap
26819
- // plugin installs the version it starts. \`layermap remove command\` deletes this file.
27177
+ // It runs LayerMap's launcher in the directory below, which runs the LayerMap version each agent's
27178
+ // LayerMap plugin runs. \`layermap remove command\` deletes this file.
26820
27179
  if (typeof process.getBuiltinModule !== "function") {
26821
27180
  process.stderr.write("layermap: LayerMap needs Node.js 22.22 or later; this is " + process.version + "\\n");
26822
27181
  process.exit(1);
26823
27182
  }
26824
- const fs = process.getBuiltinModule("node:fs");
26825
27183
  const path = process.getBuiltinModule("node:path");
26826
27184
  const { pathToFileURL } = process.getBuiltinModule("node:url");
26827
- const versions = path.join(${JSON.stringify(directory)}, "versions");
26828
- const installed = (version) => path.join(versions, version, "node_modules", "layermap");
26829
- // A version being installed is a directory named .<version>-\u2026, and has no manifest in place yet.
26830
- const numbers = (version) => version.split(".").map(Number);
26831
- const newest = (fs.existsSync(versions) ? fs.readdirSync(versions) : [])
26832
- .filter((name) => /^\\d+\\.\\d+\\.\\d+$/.test(name) && fs.existsSync(path.join(installed(name), "package.json")))
26833
- .sort((a, b) => {
26834
- const [left, right] = [numbers(a), numbers(b)];
26835
- return left[0] - right[0] || left[1] - right[1] || left[2] - right[2];
26836
- })
26837
- .at(-1);
26838
- if (!newest) {
26839
- process.stderr.write(
26840
- "layermap: no LayerMap version is installed in " + versions + ". Start a session of an agent that has the LayerMap plugin, which installs its version there, then run this again.\\n",
26841
- );
26842
- process.exit(1);
26843
- }
26844
- const entry = path.join(
26845
- installed(newest),
26846
- JSON.parse(fs.readFileSync(path.join(installed(newest), "package.json"), "utf8")).bin.layermap,
26847
- );
26848
- process.argv = [process.argv[0], entry, ...process.argv.slice(2)];
26849
- import(pathToFileURL(entry).href).catch((error) => {
26850
- process.stderr.write("layermap: could not start LayerMap " + newest + ": " + (error?.message ?? error) + "\\n");
27185
+ const directory = ${JSON.stringify(directory)};
27186
+ process.env.LAYERMAP_HOME = directory;
27187
+ import(pathToFileURL(path.join(directory, "cli.mjs")).href).catch((error) => {
27188
+ process.stderr.write("layermap: could not start LayerMap: " + (error?.message ?? error) + "\\n");
26851
27189
  process.exit(1);
26852
27190
  });
26853
27191
  `;
26854
- var commandFile = (env = process.env) => path17.join(env.HOME || homedir2(), ".local", "bin", "layermap");
27192
+ var commandFile = (env = process.env) => path20.join(env.HOME || homedir2(), ".local", "bin", "layermap");
26855
27193
  async function state(file2) {
26856
27194
  const found = await lstat5(file2).catch(() => void 0);
26857
27195
  if (!found) return "absent";
26858
27196
  if (!found.isFile()) return "other";
26859
- return (await readFile6(file2, "utf8")).includes(MARK) ? "own" : "other";
27197
+ return (await readFile9(file2, "utf8")).includes(MARK) ? "own" : "other";
26860
27198
  }
26861
27199
  var unsupported = (log2) => {
26862
27200
  log2(
@@ -26875,23 +27213,30 @@ async function setupCommand(options) {
26875
27213
  );
26876
27214
  return false;
26877
27215
  }
27216
+ const directory = installDirectory(env);
27217
+ log2(`write LayerMap's launcher to ${path20.join(directory, "cli.mjs")}`);
26878
27218
  log2(`write LayerMap's command to ${file2}`);
26879
27219
  if (options.dryRun) return true;
26880
- await mkdir3(path17.dirname(file2), { recursive: true });
26881
- await writeFile2(`${file2}.${process.pid}`, commandScript(installDirectory(env)));
27220
+ const template = launcherTemplate(packageRoot);
27221
+ if (!template) throw new Error(`${packageRoot} has no launcher`);
27222
+ await mkdir4(directory, { recursive: true, mode: 448 });
27223
+ await writeLauncher(directory, "cli.mjs", await readFile9(template, "utf8"));
27224
+ await mkdir4(path20.dirname(file2), { recursive: true });
27225
+ await writeFile3(`${file2}.${process.pid}`, commandScript(directory));
26882
27226
  await chmod(`${file2}.${process.pid}`, 493);
26883
- await rename3(`${file2}.${process.pid}`, file2);
26884
- if (!(env.PATH ?? "").split(path17.delimiter).includes(path17.dirname(file2)))
26885
- log2(`${path17.dirname(file2)} is not on this shell's PATH: add it for the command to be found.`);
27227
+ await rename4(`${file2}.${process.pid}`, file2);
27228
+ if (!(env.PATH ?? "").split(path20.delimiter).includes(path20.dirname(file2)))
27229
+ log2(`${path20.dirname(file2)} is not on this shell's PATH: add it for the command to be found.`);
26886
27230
  log2(
26887
- `Done. \`layermap\` runs the newest LayerMap version installed in ${path17.join(installDirectory(env), "versions")}, where each agent's LayerMap plugin installs the version it starts.`
27231
+ `Done. \`layermap\` runs the LayerMap version each agent's LayerMap plugin runs, installed in ${path20.join(directory, "versions")}.`
26888
27232
  );
26889
27233
  return true;
26890
27234
  }
26891
27235
  async function removeCommand(options) {
26892
27236
  const { log: log2 } = options;
26893
27237
  if (process.platform === "win32") return unsupported(log2);
26894
- const file2 = commandFile(options.env ?? process.env);
27238
+ const env = options.env ?? process.env;
27239
+ const file2 = commandFile(env);
26895
27240
  const found = await state(file2);
26896
27241
  if (found === "other") {
26897
27242
  log2(`${file2} is not LayerMap's command: left as it is.`);
@@ -26903,7 +27248,8 @@ async function removeCommand(options) {
26903
27248
  }
26904
27249
  log2(`remove LayerMap's command from ${file2}`);
26905
27250
  if (options.dryRun) return true;
26906
- await rm2(file2);
27251
+ await rm3(file2);
27252
+ await rm3(path20.join(installDirectory(env), "cli.mjs"), { force: true });
26907
27253
  log2("Removed.");
26908
27254
  return true;
26909
27255
  }
@@ -26935,7 +27281,7 @@ var MAP_TOOL_NAMES = Object.freeze({
26935
27281
  references: "project_find_references",
26936
27282
  check: "project_check_changes"
26937
27283
  });
26938
- var mapDirectoryPath = (path21) => path21.length > 1 && path21.endsWith("/") && !path21.endsWith("//") ? path21.slice(0, -1) : path21;
27284
+ var mapDirectoryPath = (path24) => path24.length > 1 && path24.endsWith("/") && !path24.endsWith("//") ? path24.slice(0, -1) : path24;
26939
27285
  var ProjectMapSearchInputSchema = external_exports.object({
26940
27286
  path: external_exports.string().default("."),
26941
27287
  query: external_exports.string().min(1).max(256),
@@ -27000,37 +27346,33 @@ var mapToolDescriptions = (host) => {
27000
27346
  });
27001
27347
  };
27002
27348
 
27003
- // src/agent/notes.ts
27004
- var AGENT_MAP_NOTE = "The layermap MCP server is available here. When a task needs to know what calls a function, what a change could affect beyond the code you are editing, or where code is used, use its project_explore_map tool (direction INCOMING, depth up to 8) instead of grep, then confirm in source; a change confined to code you have read does not need it. When the edits are done, call its project_check_changes tool once before reporting the work done.";
27005
- var projectHeading = (project) => `Project ${project} (paths are relative to it)`;
27006
-
27007
27349
  // src/agent/projects.ts
27008
- import { existsSync as existsSync7 } from "node:fs";
27009
- import { readdir as readdir2, realpath as realpath3, stat as stat3 } from "node:fs/promises";
27010
- import path18 from "node:path";
27350
+ import { existsSync as existsSync8 } from "node:fs";
27351
+ import { readdir as readdir3, realpath as realpath3, stat as stat5 } from "node:fs/promises";
27352
+ import path21 from "node:path";
27011
27353
  var escapes = (relative) => {
27012
- const normal = path18.normalize(relative);
27013
- return normal === ".." || normal.startsWith(`..${path18.sep}`);
27354
+ const normal = path21.normalize(relative);
27355
+ return normal === ".." || normal.startsWith(`..${path21.sep}`);
27014
27356
  };
27015
27357
  async function locate(start, given) {
27016
- if (start.git && !path18.isAbsolute(given) && !escapes(given))
27358
+ if (start.git && !path21.isAbsolute(given) && !escapes(given))
27017
27359
  return { project: start.directory, path: given };
27018
- const absolute = path18.resolve(start.directory, given);
27360
+ const absolute = path21.resolve(start.directory, given);
27019
27361
  let directory = absolute;
27020
- while (!(await stat3(directory).catch(() => void 0))?.isDirectory()) {
27021
- if (path18.dirname(directory) === directory) return void 0;
27022
- directory = path18.dirname(directory);
27023
- }
27024
- const real = path18.join(await realpath3(directory), path18.relative(directory, absolute));
27025
- const { directory: project, git: git2 } = await projectDirectory(directory);
27026
- if (!git2) return void 0;
27027
- const relative = path18.relative(project, real);
27362
+ while (!(await stat5(directory).catch(() => void 0))?.isDirectory()) {
27363
+ if (path21.dirname(directory) === directory) return void 0;
27364
+ directory = path21.dirname(directory);
27365
+ }
27366
+ const real = path21.join(await realpath3(directory), path21.relative(directory, absolute));
27367
+ const { directory: project, git: git3 } = await projectDirectory(directory);
27368
+ if (!git3) return void 0;
27369
+ const relative = path21.relative(project, real);
27028
27370
  if (escapes(relative)) return void 0;
27029
- return { project, path: relative ? relative.split(path18.sep).join("/") : "." };
27371
+ return { project, path: relative ? relative.split(path21.sep).join("/") : "." };
27030
27372
  }
27031
27373
  async function repositoriesIn(directory) {
27032
- const entries = await readdir2(directory, { withFileTypes: true }).catch(() => []);
27033
- return entries.filter((entry) => entry.isDirectory() && existsSync7(path18.join(directory, entry.name, ".git"))).map((entry) => `${entry.name}/`).sort();
27374
+ const entries = await readdir3(directory, { withFileTypes: true }).catch(() => []);
27375
+ return entries.filter((entry) => entry.isDirectory() && existsSync8(path21.join(directory, entry.name, ".git"))).map((entry) => `${entry.name}/`).sort();
27034
27376
  }
27035
27377
  async function routeMapCall(start, { name, args }) {
27036
27378
  const references = name === MAP_TOOL_NAMES.references;
@@ -27041,7 +27383,7 @@ async function routeMapCall(start, { name, args }) {
27041
27383
  if (!located) {
27042
27384
  const repositories = start.git ? [] : await repositoriesIn(start.directory);
27043
27385
  const such = repositories.length ? `, such as ${repositories.join(", ")}` : "";
27044
- return named === "." ? `LAYERMAP_NOT_A_GIT_REPOSITORY: This session started in ${start.directory}, which is not in a Git repository. Name a file or directory in one, relative to that folder or absolute${such}.` : `LAYERMAP_NOT_A_GIT_REPOSITORY: ${path18.resolve(start.directory, named)} is not in a Git repository; LayerMap maps Git repositories${start.git ? "" : `. Name a file or directory in one, relative to ${start.directory} or absolute${such}`}.`;
27386
+ return named === "." ? `LAYERMAP_NOT_A_GIT_REPOSITORY: This session started in ${start.directory}, which is not in a Git repository. Name a file or directory in one, relative to that folder or absolute${such}.` : `LAYERMAP_NOT_A_GIT_REPOSITORY: ${path21.resolve(start.directory, named)} is not in a Git repository; LayerMap maps Git repositories${start.git ? "" : `. Name a file or directory in one, relative to ${start.directory} or absolute${such}`}.`;
27045
27387
  }
27046
27388
  if (!references) {
27047
27389
  const routed2 = value === void 0 ? args : { ...args, path: located.path };
@@ -27113,7 +27455,8 @@ var HINTS = {
27113
27455
  LAYERMAP_BASE_NOT_FOUND: "No such commit, branch or tag. Leave base out to compare with HEAD, or name an existing one such as main.",
27114
27456
  LAYERMAP_BASE_INVALID: "base names a commit, branch or tag, such as HEAD or main.",
27115
27457
  LAYERMAP_DIFF_TOO_LARGE: "The diff against base is too large for one check. Compare with a closer base, or check the change in parts.",
27116
- LAYERMAP_NOT_A_GIT_REPOSITORY: "LayerMap maps Git repositories. Run it in one, or name one with --project."
27458
+ LAYERMAP_NOT_A_GIT_REPOSITORY: "LayerMap maps Git repositories. Run it in one, or name one with --project.",
27459
+ LAYERMAP_DATABASE_NEWER: "A newer LayerMap version has updated this map, which this one cannot read. Call again: a server LayerMap's launcher started, as its plugins and setup do, moves to the machine's version before its next call; one started otherwise has to be restarted at that version."
27117
27460
  };
27118
27461
  var describeMapError = (error51) => error51 instanceof ProjectEvidenceError ? `${error51.code}${HINTS[error51.code] ? `: ${HINTS[error51.code]}` : ""}` : void 0;
27119
27462
  var EXAMPLES = {
@@ -27182,6 +27525,7 @@ var AGENT_MAP_INSTRUCTIONS = `Use the LayerMap tools instead of grep whenever a
27182
27525
 
27183
27526
  // src/agent/mcp.ts
27184
27527
  var ROOTS_WAIT_MS = 5e3;
27528
+ var RETIRE = "notifications/layermap/retire";
27185
27529
  var PROGRESS_EVERY_MS = 15e3;
27186
27530
  var PHASE_TEXT = {
27187
27531
  WAIT: "Waiting for the first build of the project's map",
@@ -27200,6 +27544,12 @@ function serveMcp(options) {
27200
27544
  const send = (message) => output.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}
27201
27545
  `);
27202
27546
  const calls = /* @__PURE__ */ new Map();
27547
+ let retiring = false;
27548
+ let end = () => {
27549
+ };
27550
+ const settle = () => {
27551
+ if (retiring && !calls.size) end();
27552
+ };
27203
27553
  const maps = /* @__PURE__ */ new Map();
27204
27554
  const session = new AbortController();
27205
27555
  let start = options.start;
@@ -27343,6 +27693,7 @@ ${text}` : text
27343
27693
  clearInterval(beat);
27344
27694
  if (!answered) finish("", false, true);
27345
27695
  calls.delete(id2);
27696
+ settle();
27346
27697
  }
27347
27698
  };
27348
27699
  const handle = (message) => {
@@ -27359,6 +27710,10 @@ ${text}` : text
27359
27710
  if (method === "notifications/roots/list_changed" && listsRoots) void readRoots();
27360
27711
  if (method === "notifications/cancelled")
27361
27712
  calls.get(params.requestId)?.abort();
27713
+ if (method === RETIRE) {
27714
+ retiring = true;
27715
+ settle();
27716
+ }
27362
27717
  return;
27363
27718
  }
27364
27719
  switch (method) {
@@ -27402,7 +27757,12 @@ ${text}` : text
27402
27757
  }
27403
27758
  };
27404
27759
  return new Promise((resolve) => {
27405
- const lines = createInterface({ input: options.input ?? process.stdin, crlfDelay: Infinity });
27760
+ const input = options.input ?? process.stdin;
27761
+ const lines = createInterface({ input, crlfDelay: Infinity });
27762
+ end = () => {
27763
+ lines.close();
27764
+ input.destroy?.();
27765
+ };
27406
27766
  lines.on("line", (line) => {
27407
27767
  if (!line.trim()) return;
27408
27768
  let message;
@@ -27429,23 +27789,24 @@ ${text}` : text
27429
27789
  }
27430
27790
 
27431
27791
  // src/agent/setup.ts
27432
- import { execFile } from "node:child_process";
27433
- import { existsSync as existsSync8 } from "node:fs";
27434
- import { mkdir as mkdir4, readFile as readFile7, rename as rename4, rm as rm3, writeFile as writeFile3 } from "node:fs/promises";
27792
+ import { execFile as execFile2 } from "node:child_process";
27793
+ import { existsSync as existsSync9 } from "node:fs";
27794
+ import { mkdir as mkdir5, readFile as readFile10, rm as rm4, writeFile as writeFile4 } from "node:fs/promises";
27435
27795
  import { homedir as homedir3 } from "node:os";
27436
- import path19 from "node:path";
27796
+ import path22 from "node:path";
27797
+ var SETUP_AGENTS = ["claude", "codex", "dsh", "antigravity"];
27798
+ var REPOSITORY = "https://github.com/coffeecoproject/layermap";
27799
+ var PLUGIN_DESCRIPTION = "A layered map of your codebase for coding agents: what calls a function, what a change affects up to the HTTP routes, handlers and jobs, and what each module contains, for TypeScript, JavaScript, Go, Python and Java. Built and kept locally; read-only.";
27437
27800
  var SERVER = "layermap";
27438
27801
  var SETUP_RULE = `mcp__${SERVER}`;
27439
27802
  var PLUGIN_RULE = `mcp__plugin_${SERVER}_${SERVER}`;
27440
27803
  var BEGIN = "<!-- layermap:begin -->";
27441
27804
  var END = "<!-- layermap:end -->";
27442
- var launcherScript = (template, version2, args = '["mcp"]') => `// Generated from scripts/launcher.mjs.
27443
- ${template.replace("__VERSION__", JSON.stringify(version2)).replace("__ARGUMENTS__", args)}`;
27444
- var PUBLISHED_LAUNCHER = path19.join(packageRoot, "dist", "launcher.mjs");
27445
- var launcherFile = (env = process.env) => path19.join(installDirectory(env), "server.mjs");
27446
- var mcpLaunchCommand = (env = process.env, published = existsSync8(PUBLISHED_LAUNCHER)) => {
27805
+ var PUBLISHED_LAUNCHER = path22.join(packageRoot, "dist", "launcher.mjs");
27806
+ var launcherFile = (env = process.env) => path22.join(installDirectory(env), "server.mjs");
27807
+ var mcpLaunchCommand = (env = process.env, published = existsSync9(PUBLISHED_LAUNCHER)) => {
27447
27808
  if (published) return ["node", launcherFile(env)];
27448
- const script = path19.resolve(process.argv[1] ?? "");
27809
+ const script = path22.resolve(process.argv[1] ?? "");
27449
27810
  const execArgv = [];
27450
27811
  for (let index = 0; index < process.execArgv.length; index++) {
27451
27812
  const argument = process.execArgv[index];
@@ -27459,7 +27820,7 @@ var mcpLaunchCommand = (env = process.env, published = existsSync8(PUBLISHED_LAU
27459
27820
  };
27460
27821
  var run = (command, args, env) => new Promise((resolve) => {
27461
27822
  const invocation = commandInvocation(command, args, env);
27462
- execFile(
27823
+ execFile2(
27463
27824
  invocation.file,
27464
27825
  invocation.args,
27465
27826
  {
@@ -27472,7 +27833,7 @@ var run = (command, args, env) => new Promise((resolve) => {
27472
27833
  );
27473
27834
  });
27474
27835
  async function allowInClaudeSettings(file2, rule = SETUP_RULE) {
27475
- const settings = existsSync8(file2) ? JSON.parse(await readFile7(file2, "utf8")) : {};
27836
+ const settings = existsSync9(file2) ? JSON.parse(await readFile10(file2, "utf8")) : {};
27476
27837
  if (typeof settings !== "object" || settings === null || Array.isArray(settings))
27477
27838
  throw new Error(`${file2} is not a settings object.`);
27478
27839
  settings.permissions ??= {};
@@ -27481,14 +27842,14 @@ async function allowInClaudeSettings(file2, rule = SETUP_RULE) {
27481
27842
  throw new Error(`${file2} has permissions.allow that is not a list.`);
27482
27843
  if (settings.permissions.allow.includes(rule)) return false;
27483
27844
  settings.permissions.allow.push(rule);
27484
- await mkdir4(path19.dirname(file2), { recursive: true });
27485
- await writeFile3(file2, `${JSON.stringify(settings, null, 2)}
27845
+ await mkdir5(path22.dirname(file2), { recursive: true });
27846
+ await writeFile4(file2, `${JSON.stringify(settings, null, 2)}
27486
27847
  `);
27487
27848
  return true;
27488
27849
  }
27489
27850
  var CODEX_TOOL_TIMEOUT_SEC = 300;
27490
27851
  async function configureCodexServer(file2) {
27491
- const lines = (await readFile7(file2, "utf8")).split("\n");
27852
+ const lines = (await readFile10(file2, "utf8")).split("\n");
27492
27853
  const header2 = lines.findIndex((line) => line.trim() === `[mcp_servers.${SERVER}]`);
27493
27854
  if (header2 < 0) throw new Error(`${file2} has no [mcp_servers.${SERVER}] table.`);
27494
27855
  let end = header2 + 1;
@@ -27504,52 +27865,52 @@ async function configureCodexServer(file2) {
27504
27865
  const added = Object.entries(wanted).filter(([key]) => !present.has(key)).map(([key, value]) => `${key} = ${value}`);
27505
27866
  if (!added.length) return false;
27506
27867
  lines.splice(header2 + 1, 0, ...added);
27507
- await writeFile3(file2, lines.join("\n"));
27868
+ await writeFile4(file2, lines.join("\n"));
27508
27869
  return true;
27509
27870
  }
27510
27871
  async function writeInstructionNote(file2, note = AGENT_MAP_NOTE) {
27511
27872
  const block = `${BEGIN}
27512
27873
  ${note}
27513
27874
  ${END}`;
27514
- const text = existsSync8(file2) ? await readFile7(file2, "utf8") : "";
27875
+ const text = existsSync9(file2) ? await readFile10(file2, "utf8") : "";
27515
27876
  const start = text.indexOf(BEGIN);
27516
27877
  const end = text.indexOf(END);
27517
27878
  const next = start >= 0 && end > start ? `${text.slice(0, start)}${block}${text.slice(end + END.length)}` : `${text}${text && !text.endsWith("\n") ? "\n" : ""}${text ? "\n" : ""}${block}
27518
27879
  `;
27519
27880
  if (next === text) return;
27520
- await mkdir4(path19.dirname(file2), { recursive: true });
27521
- await writeFile3(file2, next);
27881
+ await mkdir5(path22.dirname(file2), { recursive: true });
27882
+ await writeFile4(file2, next);
27522
27883
  }
27523
27884
  async function removeInstructionNote(file2) {
27524
- if (!existsSync8(file2)) return;
27525
- const text = await readFile7(file2, "utf8");
27885
+ if (!existsSync9(file2)) return;
27886
+ const text = await readFile10(file2, "utf8");
27526
27887
  const start = text.indexOf(BEGIN);
27527
27888
  const end = text.indexOf(END);
27528
27889
  if (start < 0 || end < start) return;
27529
27890
  const before = text.slice(0, start).replace(/\n\n$/u, "\n");
27530
27891
  const rest = `${before}${text.slice(end + END.length).replace(/^\n/u, "")}`;
27531
- if (!rest.trim()) await rm3(file2);
27532
- else await writeFile3(file2, rest);
27892
+ if (!rest.trim()) await rm4(file2);
27893
+ else await writeFile4(file2, rest);
27533
27894
  }
27534
27895
  async function disallowInClaudeSettings(file2) {
27535
- if (!existsSync8(file2)) return;
27536
- const settings = JSON.parse(await readFile7(file2, "utf8"));
27896
+ if (!existsSync9(file2)) return;
27897
+ const settings = JSON.parse(await readFile10(file2, "utf8"));
27537
27898
  const allow = settings?.permissions?.allow;
27538
27899
  const ours = (rule) => rule === SETUP_RULE || rule === PLUGIN_RULE;
27539
27900
  if (!Array.isArray(allow) || !allow.some(ours)) return;
27540
27901
  settings.permissions.allow = allow.filter((rule) => !ours(rule));
27541
27902
  if (!settings.permissions.allow.length) delete settings.permissions.allow;
27542
27903
  if (!Object.keys(settings.permissions).length) delete settings.permissions;
27543
- await writeFile3(file2, `${JSON.stringify(settings, null, 2)}
27904
+ await writeFile4(file2, `${JSON.stringify(settings, null, 2)}
27544
27905
  `);
27545
27906
  }
27546
27907
  var YAML_BEGIN = "# layermap:begin";
27547
27908
  var YAML_END = "# layermap:end";
27548
- var nodeDirectory = (env = process.env) => (env.PATH ?? "").split(path19.delimiter).find((directory) => path19.isAbsolute(directory) && existsSync8(path19.join(directory, "node"))) ?? path19.dirname(process.execPath);
27909
+ var nodeDirectory = (env = process.env) => (env.PATH ?? "").split(path22.delimiter).find((directory) => path22.isAbsolute(directory) && existsSync9(path22.join(directory, "node"))) ?? path22.dirname(process.execPath);
27549
27910
  var dshPatchBlock = (command, env) => {
27550
27911
  const node = nodeDirectory(env);
27551
- const [program = "", ...args] = command[0] === "node" ? [path19.join(node, "node"), ...command.slice(1)] : command;
27552
- const searchPath2 = `${JSON.stringify(`${node}${path19.delimiter}`)} + process.env.PATH`;
27912
+ const [program = "", ...args] = command[0] === "node" ? [path22.join(node, "node"), ...command.slice(1)] : command;
27913
+ const searchPath2 = `${JSON.stringify(`${node}${path22.delimiter}`)} + process.env.PATH`;
27553
27914
  return [
27554
27915
  `${YAML_BEGIN} (written by \`layermap setup dsh\`; \`layermap remove dsh\` deletes it)`,
27555
27916
  "- insert:",
@@ -27568,7 +27929,7 @@ var dshPatchBlock = (command, env) => {
27568
27929
  ].join("\n");
27569
27930
  };
27570
27931
  async function writeDshPatch(file2, block) {
27571
- const text = existsSync8(file2) ? await readFile7(file2, "utf8") : "";
27932
+ const text = existsSync9(file2) ? await readFile10(file2, "utf8") : "";
27572
27933
  const start = text.indexOf(YAML_BEGIN);
27573
27934
  const end = text.indexOf(YAML_END);
27574
27935
  let next;
@@ -27584,49 +27945,75 @@ async function writeDshPatch(file2, block) {
27584
27945
  `;
27585
27946
  }
27586
27947
  if (next === text) return;
27587
- await mkdir4(path19.dirname(file2), { recursive: true });
27588
- await writeFile3(file2, next);
27948
+ await mkdir5(path22.dirname(file2), { recursive: true });
27949
+ await writeFile4(file2, next);
27589
27950
  }
27590
27951
  async function removeDshPatch(file2) {
27591
- if (!existsSync8(file2)) return;
27592
- const text = await readFile7(file2, "utf8");
27952
+ if (!existsSync9(file2)) return;
27953
+ const text = await readFile10(file2, "utf8");
27593
27954
  const start = text.indexOf(YAML_BEGIN);
27594
27955
  const end = text.indexOf(YAML_END);
27595
27956
  if (start < 0 || end < start) return;
27596
27957
  const rest = `${text.slice(0, start)}${text.slice(end + YAML_END.length).replace(/^\n/u, "")}`;
27597
- if (!rest.trim()) return rm3(file2);
27958
+ if (!rest.trim()) return rm4(file2);
27598
27959
  const content = rest.split("\n").some((line) => line.trim() && !line.trim().startsWith("#"));
27599
- await writeFile3(file2, content ? rest : `${rest}${rest.endsWith("\n") ? "" : "\n"}[]
27960
+ await writeFile4(file2, content ? rest : `${rest}${rest.endsWith("\n") ? "" : "\n"}[]
27600
27961
  `);
27601
27962
  }
27963
+ var antigravityPlugin = (env = process.env) => path22.join(env.HOME || homedir3(), ".gemini", "config", "plugins", SERVER);
27964
+ var antigravityPluginFiles = (command, version2, note = true) => {
27965
+ const [program = "", ...args] = command;
27966
+ const json2 = (value) => `${JSON.stringify(value, null, 2)}
27967
+ `;
27968
+ return {
27969
+ "plugin.json": json2({
27970
+ name: SERVER,
27971
+ displayName: "LayerMap",
27972
+ version: version2,
27973
+ description: PLUGIN_DESCRIPTION,
27974
+ homepage: REPOSITORY,
27975
+ repository: REPOSITORY
27976
+ }),
27977
+ "mcp_config.json": json2({ mcpServers: { [SERVER]: { command: program, args } } }),
27978
+ ...note ? { [path22.join("rules", "AGENTS.md")]: `${antigravityMapNote(`${SERVER}_${SERVER}`)}
27979
+ ` } : {}
27980
+ };
27981
+ };
27602
27982
  var agentFiles = (options) => {
27603
27983
  const env = options.env ?? process.env;
27984
+ if (options.agent === "antigravity") {
27985
+ const plugin = antigravityPlugin(env);
27986
+ return {
27987
+ settings: path22.join(plugin, "mcp_config.json"),
27988
+ instructions: path22.join(plugin, "rules", "AGENTS.md")
27989
+ };
27990
+ }
27604
27991
  if (options.agent === "dsh") {
27605
- const home = env.DSH_HOME || path19.join(homedir3(), ".dsh");
27992
+ const home = env.DSH_HOME || path22.join(homedir3(), ".dsh");
27606
27993
  return {
27607
- settings: path19.join(home, "cordis.patch.yml"),
27608
- instructions: path19.join(home, "AGENTS.md")
27994
+ settings: path22.join(home, "cordis.patch.yml"),
27995
+ instructions: path22.join(home, "AGENTS.md")
27609
27996
  };
27610
27997
  }
27611
27998
  if (options.agent === "codex") {
27612
- const home = env.CODEX_HOME ?? path19.join(homedir3(), ".codex");
27613
- return { settings: path19.join(home, "config.toml"), instructions: path19.join(home, "AGENTS.md") };
27999
+ const home = env.CODEX_HOME ?? path22.join(homedir3(), ".codex");
28000
+ return { settings: path22.join(home, "config.toml"), instructions: path22.join(home, "AGENTS.md") };
27614
28001
  }
27615
28002
  if (options.scope === "user") {
27616
- const home = env.CLAUDE_CONFIG_DIR ?? path19.join(homedir3(), ".claude");
28003
+ const home = env.CLAUDE_CONFIG_DIR ?? path22.join(homedir3(), ".claude");
27617
28004
  return {
27618
- settings: path19.join(home, "settings.json"),
27619
- instructions: path19.join(home, "CLAUDE.md")
28005
+ settings: path22.join(home, "settings.json"),
28006
+ instructions: path22.join(home, "CLAUDE.md")
27620
28007
  };
27621
28008
  }
27622
28009
  const local = options.scope === "local";
27623
28010
  return {
27624
- settings: path19.join(
28011
+ settings: path22.join(
27625
28012
  options.project,
27626
28013
  ".claude",
27627
28014
  local ? "settings.local.json" : "settings.json"
27628
28015
  ),
27629
- instructions: path19.join(options.project, local ? "CLAUDE.local.md" : "CLAUDE.md")
28016
+ instructions: path22.join(options.project, local ? "CLAUDE.local.md" : "CLAUDE.md")
27630
28017
  };
27631
28018
  };
27632
28019
  async function setupAgent(options) {
@@ -27638,22 +28025,40 @@ async function setupAgent(options) {
27638
28025
  );
27639
28026
  return false;
27640
28027
  }
27641
- const published = existsSync8(PUBLISHED_LAUNCHER);
28028
+ const published = existsSync9(PUBLISHED_LAUNCHER);
27642
28029
  const command = mcpLaunchCommand(env, published);
27643
28030
  const quoted = command.map((part) => /^[\w./:@=-]+$/u.test(part) ? part : JSON.stringify(part));
27644
28031
  const { settings, instructions } = agentFiles(options);
27645
28032
  const note = options.instructions !== false;
27646
- const writeLauncher = async () => {
28033
+ const placeLauncher = async () => {
27647
28034
  if (!published) return;
27648
- const file2 = launcherFile(env);
27649
- await mkdir4(path19.dirname(file2), { recursive: true, mode: 448 });
27650
- await writeFile3(
27651
- `${file2}.${process.pid}`,
27652
- launcherScript(await readFile7(PUBLISHED_LAUNCHER, "utf8"), options.version)
27653
- );
27654
- await rename4(`${file2}.${process.pid}`, file2);
28035
+ const directory = installDirectory(env);
28036
+ await mkdir5(directory, { recursive: true, mode: 448 });
28037
+ await writeLauncher(directory, "server.mjs", await readFile10(PUBLISHED_LAUNCHER, "utf8"));
27655
28038
  };
27656
- if (published) log2(`write the launcher of LayerMap ${options.version} to ${launcherFile(env)}`);
28039
+ if (published) log2(`write LayerMap's launcher to ${launcherFile(env)}`);
28040
+ if (options.agent === "antigravity") {
28041
+ if (options.scope !== "user") {
28042
+ log2("Antigravity loads LayerMap's plugin in every project; --scope does not apply.");
28043
+ return false;
28044
+ }
28045
+ const plugin = antigravityPlugin(env);
28046
+ log2(`write LayerMap's plugin for Antigravity to ${plugin}`);
28047
+ if (note) log2(`with a rule naming the map tools, ${instructions}`);
28048
+ if (options.dryRun) return true;
28049
+ await placeLauncher();
28050
+ await rm4(plugin, { recursive: true, force: true });
28051
+ for (const [name, content] of Object.entries(
28052
+ antigravityPluginFiles(command, options.version, note)
28053
+ )) {
28054
+ await mkdir5(path22.dirname(path22.join(plugin, name)), { recursive: true });
28055
+ await writeFile4(path22.join(plugin, name), content);
28056
+ }
28057
+ log2(
28058
+ `Done. Start a new Antigravity conversation; its map tools come from the ${SERVER}_${SERVER} server, and Antigravity asks before each one's first use.`
28059
+ );
28060
+ return true;
28061
+ }
27657
28062
  if (options.agent === "dsh") {
27658
28063
  if (options.scope !== "user") {
27659
28064
  log2("DeepSeek Harness is set up for all its profiles at once; --scope does not apply.");
@@ -27662,7 +28067,7 @@ async function setupAgent(options) {
27662
28067
  log2(`add the ${SERVER} MCP server to ${settings}`);
27663
28068
  if (note) log2(`add a note naming the map tools to ${instructions}`);
27664
28069
  if (options.dryRun) return true;
27665
- await writeLauncher();
28070
+ await placeLauncher();
27666
28071
  await writeDshPatch(settings, dshPatchBlock(command, env));
27667
28072
  if (note) await writeInstructionNote(instructions);
27668
28073
  log2(
@@ -27682,7 +28087,7 @@ async function setupAgent(options) {
27682
28087
  }
27683
28088
  if (note) log2(`add a note naming the map tools to ${instructions}`);
27684
28089
  if (options.dryRun) return true;
27685
- await writeLauncher();
28090
+ await placeLauncher();
27686
28091
  const agentCommand = options.agent;
27687
28092
  const scope = options.agent === "claude" ? ["--scope", options.scope] : [];
27688
28093
  await run(agentCommand, ["mcp", "remove", SERVER, ...scope], env);
@@ -27704,7 +28109,11 @@ async function setupAgent(options) {
27704
28109
  async function allowAgent(options) {
27705
28110
  if (options.agent !== "claude") {
27706
28111
  options.log(
27707
- options.agent === "codex" ? "The Codex plugin already runs LayerMap's read-only tools without a prompt." : "DeepSeek Harness runs MCP tools without a prompt."
28112
+ {
28113
+ codex: "The Codex plugin already runs LayerMap's read-only tools without a prompt.",
28114
+ dsh: "DeepSeek Harness runs MCP tools without a prompt.",
28115
+ antigravity: "Antigravity asks before each map tool's first use; choose to always allow it there."
28116
+ }[options.agent]
27708
28117
  );
27709
28118
  return true;
27710
28119
  }
@@ -27718,6 +28127,14 @@ async function allowAgent(options) {
27718
28127
  async function removeAgent(options) {
27719
28128
  const env = options.env ?? process.env;
27720
28129
  const { settings, instructions } = agentFiles(options);
28130
+ if (options.agent === "antigravity") {
28131
+ const plugin = antigravityPlugin(env);
28132
+ options.log(`remove LayerMap's plugin for Antigravity, ${plugin}`);
28133
+ if (options.dryRun) return true;
28134
+ await rm4(plugin, { recursive: true, force: true });
28135
+ options.log("Removed.");
28136
+ return true;
28137
+ }
27721
28138
  if (options.agent === "dsh") {
27722
28139
  options.log(
27723
28140
  `remove the ${SERVER} MCP server from ${settings} and its note from ${instructions}`
@@ -27743,15 +28160,16 @@ async function removeAgent(options) {
27743
28160
  var USAGE = `LayerMap \u2014 a layered map of a codebase for coding agents.
27744
28161
 
27745
28162
  Usage:
27746
- layermap setup claude|codex|dsh [--scope user|local] [--no-instructions] [--dry-run]
28163
+ layermap setup ${SETUP_AGENTS.join("|")} [--scope user|local] [--no-instructions] [--dry-run]
27747
28164
  layermap allow claude [--scope user|project|local] [--dry-run]
27748
28165
  let the plugin's read-only tools run without a prompt
27749
- layermap remove claude|codex|dsh [--scope user|project|local] [--dry-run]
28166
+ layermap remove ${SETUP_AGENTS.join("|")} [--scope user|project|local] [--dry-run]
27750
28167
  layermap setup command [--dry-run] put a layermap command in ~/.local/bin, for shells with no
27751
28168
  plugin's on their PATH (Codex's commands, a terminal): it
27752
- runs the newest version the agents' plugins have installed
28169
+ runs the version the plugins run
27753
28170
  layermap remove command [--dry-run]
27754
28171
  layermap mcp [--project DIR] serve the map tools over MCP (stdio)
28172
+ layermap hook claude run the Claude Code plugin's hook for the event on stdin
27755
28173
  layermap index [--project DIR] build or update the map now
27756
28174
  layermap explore [PATH] [--name NAME] [--line N] [--direction INCOMING|OUTGOING|BOTH]
27757
28175
  [--depth N] [--tests] [--unresolved] [--offset N]
@@ -27774,10 +28192,10 @@ var log = (line) => process.stderr.write(`${line}
27774
28192
  async function checkedTests(project, tests) {
27775
28193
  const here = await realpath4(process.cwd());
27776
28194
  return tests.map((test) => {
27777
- const relative = path20.relative(project, path20.resolve(here, test));
27778
- if (!relative || relative === ".." || relative.startsWith(`..${path20.sep}`) || path20.isAbsolute(relative))
28195
+ const relative = path23.relative(project, path23.resolve(here, test));
28196
+ if (!relative || relative === ".." || relative.startsWith(`..${path23.sep}`) || path23.isAbsolute(relative))
27779
28197
  throw new Error(`${test} is not in ${project}.`);
27780
- return relative.split(path20.sep).join("/");
28198
+ return relative.split(path23.sep).join("/");
27781
28199
  });
27782
28200
  }
27783
28201
  var usage = (code) => {
@@ -27785,7 +28203,7 @@ var usage = (code) => {
27785
28203
  `);
27786
28204
  return code;
27787
28205
  };
27788
- async function main(argv) {
28206
+ async function main2(argv) {
27789
28207
  const { values, positionals } = parseArgs({
27790
28208
  args: argv,
27791
28209
  allowPositionals: true,
@@ -27820,8 +28238,13 @@ async function main(argv) {
27820
28238
  return 0;
27821
28239
  }
27822
28240
  if (values.help || !command) return usage(command ? 0 : 1);
28241
+ if (command === "hook") {
28242
+ if (rest[0] !== "claude" || rest.length !== 1) return usage(1);
28243
+ await claudeHook();
28244
+ return 0;
28245
+ }
27823
28246
  if (values.json && command !== "check" && command !== "imports") return usage(1);
27824
- const { directory: project, git: git2 } = await projectDirectory(values.project ?? process.cwd());
28247
+ const { directory: project, git: git3 } = await projectDirectory(values.project ?? process.cwd());
27825
28248
  const cache = cacheDirectory();
27826
28249
  const open3 = async (directory) => {
27827
28250
  const map3 = await LayerMap.open({
@@ -27841,7 +28264,7 @@ async function main(argv) {
27841
28264
  dryRun: values["dry-run"],
27842
28265
  log
27843
28266
  }) ? 0 : 1;
27844
- if (agent !== "claude" && agent !== "codex" && agent !== "dsh") return usage(1);
28267
+ if (!SETUP_AGENTS.includes(agent)) return usage(1);
27845
28268
  if (!["user", "project", "local"].includes(values.scope)) return usage(1);
27846
28269
  const done = await { setup: setupAgent, allow: allowAgent, remove: removeAgent }[command]({
27847
28270
  agent,
@@ -27857,7 +28280,7 @@ async function main(argv) {
27857
28280
  if (command === "mcp") {
27858
28281
  await serveMcp({
27859
28282
  version: version2,
27860
- start: { directory: project, git: git2 },
28283
+ start: { directory: project, git: git3 },
27861
28284
  open: open3,
27862
28285
  log,
27863
28286
  record: mapCallLog(cache)
@@ -27865,7 +28288,7 @@ async function main(argv) {
27865
28288
  return 0;
27866
28289
  }
27867
28290
  const number4 = (value) => value === void 0 ? void 0 : Number(value);
27868
- if (!git2) throw new ProjectEvidenceError("LAYERMAP_NOT_A_GIT_REPOSITORY", false);
28291
+ if (!git3) throw new ProjectEvidenceError("LAYERMAP_NOT_A_GIT_REPOSITORY", false);
27869
28292
  const map2 = await open3(project);
27870
28293
  const signal = new AbortController().signal;
27871
28294
  try {
@@ -27964,7 +28387,7 @@ async function main(argv) {
27964
28387
  await map2.close();
27965
28388
  }
27966
28389
  }
27967
- process.exitCode = await main(process.argv.slice(2)).catch((error51) => {
28390
+ process.exitCode = await main2(process.argv.slice(2)).catch((error51) => {
27968
28391
  log(
27969
28392
  `layermap: ${describeMapError(error51) ?? (error51 instanceof Error ? error51.message : String(error51))}`
27970
28393
  );