layermap 0.1.47 → 0.1.49

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,16 +8,39 @@ var __export = (target, all) => {
8
8
 
9
9
  // src/cli.ts
10
10
  import { realpath as realpath4 } from "node:fs/promises";
11
- import path18 from "node:path";
11
+ import path19 from "node:path";
12
12
  import { parseArgs } from "node:util";
13
13
 
14
+ // src/agent/call-log.ts
15
+ import { appendFile, mkdir, rename, stat } from "node:fs/promises";
16
+ import path from "node:path";
17
+ var LIMIT_BYTES = 2 * 1024 * 1024;
18
+ function mapCallLog(cache) {
19
+ const directory = path.join(cache, "logs");
20
+ const file2 = path.join(directory, "calls.jsonl");
21
+ let queue = Promise.resolve();
22
+ return (record2) => {
23
+ queue = queue.then(async () => {
24
+ await mkdir(directory, { recursive: true, mode: 448 });
25
+ if (((await stat(file2).catch(() => void 0))?.size ?? 0) > LIMIT_BYTES)
26
+ await rename(file2, path.join(directory, "calls.1.jsonl"));
27
+ await appendFile(file2, `${JSON.stringify({ ...record2, pid: process.pid })}
28
+ `, {
29
+ mode: 384
30
+ });
31
+ }).catch(() => {
32
+ });
33
+ return queue;
34
+ };
35
+ }
36
+
14
37
  // src/agent/environment.ts
15
38
  import { createHash as createHash6 } from "node:crypto";
16
39
  import { existsSync as existsSync6, readFileSync as readFileSync3 } from "node:fs";
17
- import { mkdir, readdir, readFile as readFile4, rename, rm, stat, utimes, writeFile } from "node:fs/promises";
40
+ import { mkdir as mkdir2, readdir, readFile as readFile4, rename as rename2, rm, stat as stat2, utimes, writeFile } from "node:fs/promises";
18
41
  import { createRequire } from "node:module";
19
42
  import { homedir } from "node:os";
20
- import path15 from "node:path";
43
+ import path16 from "node:path";
21
44
  import { fileURLToPath } from "node:url";
22
45
 
23
46
  // src/git-runner.ts
@@ -26,11 +49,11 @@ import { spawn } from "node:child_process";
26
49
  // src/platform.ts
27
50
  import { spawnSync } from "node:child_process";
28
51
  import { existsSync } from "node:fs";
29
- import path from "node:path";
52
+ import path2 from "node:path";
30
53
  var executableName = (name, platform = process.platform) => platform === "win32" ? `${name}.exe` : name;
31
54
  var searchPath = (env) => env.PATH ?? Object.entries(env).find(([name]) => name.toUpperCase() === "PATH")?.[1] ?? "";
32
55
  function findOnPath(files, env, platform) {
33
- const join = platform === "win32" ? path.win32.join : path.posix.join;
56
+ const join = platform === "win32" ? path2.win32.join : path2.posix.join;
34
57
  for (const directory of searchPath(env).split(platform === "win32" ? ";" : ":"))
35
58
  for (const file2 of files)
36
59
  if (directory && existsSync(join(directory, file2))) return join(directory, file2);
@@ -73,7 +96,7 @@ function stopProcessTree(pid, signal, platform = process.platform) {
73
96
  process.kill(-pid, signal);
74
97
  return;
75
98
  }
76
- const taskkill = path.win32.join(
99
+ const taskkill = path2.win32.join(
77
100
  process.env.SystemRoot ?? "C:\\Windows",
78
101
  "System32",
79
102
  "taskkill.exe"
@@ -321,9 +344,9 @@ async function gitGrep(git2, search, options) {
321
344
  }
322
345
  const hits = [];
323
346
  for (const record2 of found.split("\n")) {
324
- const [path19, line, text, extra] = record2.split("\0");
325
- if (path19 && line && text !== void 0 && extra === void 0)
326
- hits.push({ path: path19, line: Number(line), text });
347
+ const [path20, line, text, extra] = record2.split("\0");
348
+ if (path20 && line && text !== void 0 && extra === void 0)
349
+ hits.push({ path: path20, line: Number(line), text });
327
350
  }
328
351
  return { hits };
329
352
  }
@@ -331,17 +354,17 @@ async function gitGrep(git2, search, options) {
331
354
  // src/layermap.ts
332
355
  import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
333
356
  import { mkdirSync, statSync } from "node:fs";
334
- import { lstat as lstat3, realpath as realpath2 } from "node:fs/promises";
335
- import path14 from "node:path";
357
+ import { lstat as lstat4, realpath as realpath2 } from "node:fs/promises";
358
+ import path15 from "node:path";
336
359
  import { setTimeout as delay } from "node:timers/promises";
337
360
  import { DatabaseSync } from "@photostructure/sqlite";
338
361
 
339
362
  // src/capture-policy.ts
340
- import path3 from "node:path";
363
+ import path4 from "node:path";
341
364
 
342
365
  // src/file-universe.ts
343
366
  import { lstat } from "node:fs/promises";
344
- import path2 from "node:path";
367
+ import path3 from "node:path";
345
368
  var FILE_UNIVERSE_ARGS = Object.freeze([
346
369
  "ls-files",
347
370
  "-z",
@@ -370,8 +393,8 @@ var parseFileUniverse = (output) => {
370
393
  const records = output.toString("utf8").split("\0");
371
394
  for (const record2 of records) {
372
395
  if (record2.length === 0) continue;
373
- const normalized = path2.posix.normalize(record2);
374
- if (normalized !== record2 || normalized === "." || normalized === ".." || normalized.startsWith("../") || path2.posix.isAbsolute(normalized) || normalized.includes("\\")) {
396
+ const normalized = path3.posix.normalize(record2);
397
+ if (normalized !== record2 || normalized === "." || normalized === ".." || normalized.startsWith("../") || path3.posix.isAbsolute(normalized) || normalized.includes("\\")) {
375
398
  throw new ProjectEvidenceFileUniverseError("PROJECT_FILE_UNIVERSE_INVALID");
376
399
  }
377
400
  files.add(normalized);
@@ -416,7 +439,7 @@ var ProjectEvidenceFileUniverse = class {
416
439
  const candidates = parseFileUniverse(listed);
417
440
  const present = await Promise.all(
418
441
  candidates.map(
419
- (file2) => lstat(path2.join(root, ...file2.split("/"))).then(
442
+ (file2) => lstat(path3.join(root, ...file2.split("/"))).then(
420
443
  () => true,
421
444
  (error51) => {
422
445
  if (error51.code === "ENOENT" || error51.code === "ENOTDIR") return false;
@@ -556,7 +579,7 @@ var ProjectEvidencePolicyError = class extends Error {
556
579
  var assertProjectEvidencePathNotSensitive = (relativePath) => {
557
580
  const segments2 = relativePath.toLowerCase().split("/");
558
581
  const basename = segments2.at(-1) ?? "";
559
- const extension = path3.posix.extname(basename);
582
+ const extension = path4.posix.extname(basename);
560
583
  const containsSensitiveSequence = sensitiveSegmentSequences.some(
561
584
  (sequence) => segments2.length >= sequence.length && segments2.some(
562
585
  (_, start) => sequence.every((segment, offset) => segments2[start + offset] === segment)
@@ -569,8 +592,8 @@ var assertProjectEvidencePathNotSensitive = (relativePath) => {
569
592
  };
570
593
  var isProjectEvidenceTraversalExcluded = (relativePath) => relativePath.toLowerCase().split("/").some((segment) => traversalExcludedSegmentSet.has(segment));
571
594
  var isProjectEvidenceTextPath = (relativePath) => {
572
- const basename = path3.posix.basename(relativePath).toLowerCase();
573
- const extension = path3.posix.extname(basename);
595
+ const basename = path4.posix.basename(relativePath).toLowerCase();
596
+ const extension = path4.posix.extname(basename);
574
597
  if (allowedTextBasenameSet.has(basename)) return true;
575
598
  return extension ? allowedTextExtensionSet.has(extension) : allowedExtensionlessNameSet.has(basename);
576
599
  };
@@ -579,7 +602,7 @@ var isProjectEvidenceTextPath = (relativePath) => {
579
602
  import { createHash as createHash2 } from "node:crypto";
580
603
 
581
604
  // src/core.ts
582
- import path4 from "node:path";
605
+ import path5 from "node:path";
583
606
 
584
607
  // node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js
585
608
  var external_exports = {};
@@ -1347,10 +1370,10 @@ function mergeDefs(...defs) {
1347
1370
  function cloneDef(schema) {
1348
1371
  return mergeDefs(schema._zod.def);
1349
1372
  }
1350
- function getElementAtPath(obj, path19) {
1351
- if (!path19)
1373
+ function getElementAtPath(obj, path20) {
1374
+ if (!path20)
1352
1375
  return obj;
1353
- return path19.reduce((acc, key) => acc?.[key], obj);
1376
+ return path20.reduce((acc, key) => acc?.[key], obj);
1354
1377
  }
1355
1378
  function promiseAllObject(promisesObj) {
1356
1379
  const keys = Object.keys(promisesObj);
@@ -1759,11 +1782,11 @@ function explicitlyAborted(x, startIndex = 0) {
1759
1782
  }
1760
1783
  return false;
1761
1784
  }
1762
- function prefixIssues(path19, issues) {
1785
+ function prefixIssues(path20, issues) {
1763
1786
  return issues.map((iss) => {
1764
1787
  var _a3;
1765
1788
  (_a3 = iss).path ?? (_a3.path = []);
1766
- iss.path.unshift(path19);
1789
+ iss.path.unshift(path20);
1767
1790
  return iss;
1768
1791
  });
1769
1792
  }
@@ -1910,16 +1933,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
1910
1933
  }
1911
1934
  function formatError(error51, mapper = (issue2) => issue2.message) {
1912
1935
  const fieldErrors = { _errors: [] };
1913
- const processError = (error52, path19 = []) => {
1936
+ const processError = (error52, path20 = []) => {
1914
1937
  for (const issue2 of error52.issues) {
1915
1938
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1916
- issue2.errors.map((issues) => processError({ issues }, [...path19, ...issue2.path]));
1939
+ issue2.errors.map((issues) => processError({ issues }, [...path20, ...issue2.path]));
1917
1940
  } else if (issue2.code === "invalid_key") {
1918
- processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1941
+ processError({ issues: issue2.issues }, [...path20, ...issue2.path]);
1919
1942
  } else if (issue2.code === "invalid_element") {
1920
- processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1943
+ processError({ issues: issue2.issues }, [...path20, ...issue2.path]);
1921
1944
  } else {
1922
- const fullpath = [...path19, ...issue2.path];
1945
+ const fullpath = [...path20, ...issue2.path];
1923
1946
  if (fullpath.length === 0) {
1924
1947
  fieldErrors._errors.push(mapper(issue2));
1925
1948
  } else {
@@ -1946,17 +1969,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
1946
1969
  }
1947
1970
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
1948
1971
  const result = { errors: [] };
1949
- const processError = (error52, path19 = []) => {
1972
+ const processError = (error52, path20 = []) => {
1950
1973
  var _a3, _b;
1951
1974
  for (const issue2 of error52.issues) {
1952
1975
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1953
- issue2.errors.map((issues) => processError({ issues }, [...path19, ...issue2.path]));
1976
+ issue2.errors.map((issues) => processError({ issues }, [...path20, ...issue2.path]));
1954
1977
  } else if (issue2.code === "invalid_key") {
1955
- processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1978
+ processError({ issues: issue2.issues }, [...path20, ...issue2.path]);
1956
1979
  } else if (issue2.code === "invalid_element") {
1957
- processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1980
+ processError({ issues: issue2.issues }, [...path20, ...issue2.path]);
1958
1981
  } else {
1959
- const fullpath = [...path19, ...issue2.path];
1982
+ const fullpath = [...path20, ...issue2.path];
1960
1983
  if (fullpath.length === 0) {
1961
1984
  result.errors.push(mapper(issue2));
1962
1985
  continue;
@@ -1988,8 +2011,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
1988
2011
  }
1989
2012
  function toDotPath(_path) {
1990
2013
  const segs = [];
1991
- const path19 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1992
- for (const seg of path19) {
2014
+ const path20 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
2015
+ for (const seg of path20) {
1993
2016
  if (typeof seg === "number")
1994
2017
  segs.push(`[${seg}]`);
1995
2018
  else if (typeof seg === "symbol")
@@ -14681,13 +14704,13 @@ function resolveRef(ref, ctx) {
14681
14704
  if (!ref.startsWith("#")) {
14682
14705
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14683
14706
  }
14684
- const path19 = ref.slice(1).split("/").filter(Boolean);
14685
- if (path19.length === 0) {
14707
+ const path20 = ref.slice(1).split("/").filter(Boolean);
14708
+ if (path20.length === 0) {
14686
14709
  return ctx.rootSchema;
14687
14710
  }
14688
14711
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14689
- if (path19[0] === defsKey) {
14690
- const key = path19[1];
14712
+ if (path20[0] === defsKey) {
14713
+ const key = path20[1];
14691
14714
  if (!key || !ctx.defs[key]) {
14692
14715
  throw new Error(`Reference not found: ${ref}`);
14693
14716
  }
@@ -15115,14 +15138,14 @@ var ProjectEvidencePathError = class extends Error {
15115
15138
  code;
15116
15139
  };
15117
15140
  var normalizeProjectEvidencePath = (value, allowRoot = false) => {
15118
- if (value.includes("\0") || path4.isAbsolute(value) || value.includes("\\")) {
15141
+ if (value.includes("\0") || path5.isAbsolute(value) || value.includes("\\")) {
15119
15142
  throw new ProjectEvidencePathError("PROJECT_PATH_INVALID");
15120
15143
  }
15121
15144
  if (value === ".") {
15122
15145
  if (allowRoot) return "";
15123
15146
  throw new ProjectEvidencePathError("PROJECT_PATH_INVALID");
15124
15147
  }
15125
- const normalized = path4.posix.normalize(value);
15148
+ const normalized = path5.posix.normalize(value);
15126
15149
  if (normalized.length === 0 || normalized !== value || normalized === ".." || normalized.startsWith("../") || value.split("/").some((segment) => segment.length === 0 || segment === "." || segment === "..")) {
15127
15150
  throw new ProjectEvidencePathError("PROJECT_PATH_INVALID");
15128
15151
  }
@@ -15330,14 +15353,14 @@ var CodeCommitReader = class _CodeCommitReader {
15330
15353
  // src/code-worktree-reader.ts
15331
15354
  import { constants as fsConstants } from "node:fs";
15332
15355
  import { lstat as lstat2, open, realpath } from "node:fs/promises";
15333
- import path5 from "node:path";
15356
+ import path6 from "node:path";
15334
15357
  var fileSystemErrorCode = (error51) => {
15335
15358
  if (typeof error51 !== "object" || error51 === null || !("code" in error51)) return void 0;
15336
15359
  return typeof error51.code === "string" ? error51.code : void 0;
15337
15360
  };
15338
15361
  var isInsideRoot = (root, candidate) => {
15339
- const relative = path5.relative(root, candidate);
15340
- return relative === "" || !relative.startsWith(`..${path5.sep}`) && relative !== "..";
15362
+ const relative = path6.relative(root, candidate);
15363
+ return relative === "" || !relative.startsWith(`..${path6.sep}`) && relative !== "..";
15341
15364
  };
15342
15365
  var stablePathFingerprint = (stats) => (stats.isDirectory() ? ["directory", stats.dev, stats.ino] : [
15343
15366
  stats.dev,
@@ -15380,7 +15403,7 @@ var StableProjectCaptureSession = class _StableProjectCaptureSession {
15380
15403
  }
15381
15404
  async captureFile(relativePath) {
15382
15405
  this.assertNotAborted();
15383
- const absolutePath = path5.join(this.root, ...relativePath.split("/"));
15406
+ const absolutePath = path6.join(this.root, ...relativePath.split("/"));
15384
15407
  const stats = await this.inspectPath(absolutePath, true);
15385
15408
  const fingerprint = stablePathFingerprint(stats);
15386
15409
  const byteLength = stats.isDirectory() ? 0 : Number(stats.size);
@@ -15502,11 +15525,11 @@ var StableProjectCaptureSession = class _StableProjectCaptureSession {
15502
15525
  if (!isInsideRoot(this.root, absolutePath)) {
15503
15526
  throw new ProjectEvidenceError("PROJECT_PATH_OUTSIDE_ROOT", false);
15504
15527
  }
15505
- const relative = path5.relative(this.root, absolutePath);
15506
- const components = relative === "" ? [] : relative.split(path5.sep);
15528
+ const relative = path6.relative(this.root, absolutePath);
15529
+ const components = relative === "" ? [] : relative.split(path6.sep);
15507
15530
  const paths = [
15508
15531
  this.root,
15509
- ...components.map((_, index) => path5.join(this.root, ...components.slice(0, index + 1)))
15532
+ ...components.map((_, index) => path6.join(this.root, ...components.slice(0, index + 1)))
15510
15533
  ];
15511
15534
  let finalStats;
15512
15535
  for (const [index, currentPath] of paths.entries()) {
@@ -15550,7 +15573,7 @@ var StableProjectCaptureSession = class _StableProjectCaptureSession {
15550
15573
  import { createHash as createHash3 } from "node:crypto";
15551
15574
  import { existsSync as existsSync2, readdirSync, readFileSync, realpathSync } from "node:fs";
15552
15575
  import { isBuiltin } from "node:module";
15553
- import path6 from "node:path";
15576
+ import path7 from "node:path";
15554
15577
  var INSTALL_RECORDS = [
15555
15578
  ".pnpm/lock.yaml",
15556
15579
  ".package-lock.json",
@@ -15572,8 +15595,8 @@ function mapPackageOf(specifier) {
15572
15595
  }
15573
15596
  function mapInstalledPath(realRoot, relative) {
15574
15597
  try {
15575
- const real = realpathSync.native(path6.join(realRoot, relative));
15576
- return real.startsWith(`${realRoot}${path6.sep}`) ? real : void 0;
15598
+ const real = realpathSync.native(path7.join(realRoot, relative));
15599
+ return real.startsWith(`${realRoot}${path7.sep}`) ? real : void 0;
15577
15600
  } catch {
15578
15601
  return void 0;
15579
15602
  }
@@ -15590,21 +15613,21 @@ var versionOf = (realRoot, relative) => {
15590
15613
  };
15591
15614
  function installedAt(realRoot, directory, real) {
15592
15615
  const records = INSTALL_RECORDS.flatMap((name) => {
15593
- const file2 = mapInstalledPath(realRoot, path6.posix.join(directory, name));
15616
+ const file2 = mapInstalledPath(realRoot, path7.posix.join(directory, name));
15594
15617
  return file2 ? [[name, contentDigest(file2)]] : [];
15595
15618
  });
15596
15619
  if (records.length) return records;
15597
15620
  const packages = readdirSync(real).flatMap((name) => {
15598
15621
  if (name.startsWith(".")) return [];
15599
15622
  if (!name.startsWith("@")) return [name];
15600
- const scope = mapInstalledPath(realRoot, path6.posix.join(directory, name));
15623
+ const scope = mapInstalledPath(realRoot, path7.posix.join(directory, name));
15601
15624
  return scope ? readdirSync(scope).map((inner) => `${name}/${inner}`) : [];
15602
15625
  });
15603
- const beside = path6.join(realRoot, path6.posix.dirname(directory));
15626
+ const beside = path7.join(realRoot, path7.posix.dirname(directory));
15604
15627
  return {
15605
15628
  packages: packages.sort().map((name) => [name, versionOf(realRoot, `${directory}/${name}`)]),
15606
15629
  lockfiles: LOCKFILES.flatMap((name) => {
15607
- const file2 = path6.join(beside, name);
15630
+ const file2 = path7.join(beside, name);
15608
15631
  return existsSync2(file2) ? [[name, contentDigest(file2)]] : [];
15609
15632
  })
15610
15633
  };
@@ -15613,15 +15636,15 @@ function mapInstalledDigest(root, paths) {
15613
15636
  const realRoot = realpathSync.native(root);
15614
15637
  const directories = /* @__PURE__ */ new Set(["."]);
15615
15638
  for (const file2 of paths) {
15616
- let at = path6.posix.dirname(file2);
15639
+ let at = path7.posix.dirname(file2);
15617
15640
  while (at !== "." && !directories.has(at)) {
15618
15641
  directories.add(at);
15619
- at = path6.posix.dirname(at);
15642
+ at = path7.posix.dirname(at);
15620
15643
  }
15621
15644
  }
15622
15645
  const installed = [];
15623
15646
  for (const directory of [...directories].sort()) {
15624
- const modules = path6.posix.join(directory, "node_modules");
15647
+ const modules = path7.posix.join(directory, "node_modules");
15625
15648
  const real = mapInstalledPath(realRoot, modules);
15626
15649
  if (real) installed.push([modules, installedAt(realRoot, modules, real)]);
15627
15650
  }
@@ -15629,7 +15652,7 @@ function mapInstalledDigest(root, paths) {
15629
15652
  }
15630
15653
 
15631
15654
  // src/source-scope.ts
15632
- import path7 from "node:path";
15655
+ import path8 from "node:path";
15633
15656
  var InitialEvidenceScopeSchema = external_exports.object({
15634
15657
  pathPrefixes: external_exports.array(ProjectEvidenceGrantPathPrefixSchema).min(1).max(64)
15635
15658
  }).strict();
@@ -15717,7 +15740,7 @@ var includesInitialEvidencePath = (relativePath, scope) => {
15717
15740
  if (isProjectEvidenceTraversalExcluded(relativePath) || inExcludedDirectory(relativePath))
15718
15741
  return false;
15719
15742
  const basename = relativePath.toLowerCase().split("/").at(-1) ?? "";
15720
- return extensions.has(path7.posix.extname(basename)) || SOURCE_POLICY.documentationFiles.includes(basename) || SOURCE_POLICY.configurationFiles.includes(basename) || SOURCE_POLICY.workspaceFiles.includes(relativePath);
15743
+ return extensions.has(path8.posix.extname(basename)) || SOURCE_POLICY.documentationFiles.includes(basename) || SOURCE_POLICY.configurationFiles.includes(basename) || SOURCE_POLICY.workspaceFiles.includes(relativePath);
15721
15744
  };
15722
15745
 
15723
15746
  // src/code-index-capture.ts
@@ -15955,8 +15978,7 @@ var MapRelationKindSchema = external_exports.enum([
15955
15978
  "IMPLEMENTS",
15956
15979
  // A member that implements or overrides the target member, so calls to it may dispatch here.
15957
15980
  "OVERRIDES",
15958
- "DECORATED_BY",
15959
- "TEST_IMPORTS"
15981
+ "DECORATED_BY"
15960
15982
  ]);
15961
15983
  var MapObjectLocatorSchema = external_exports.object({
15962
15984
  path: external_exports.string().min(1),
@@ -16018,7 +16040,6 @@ var MAP_RELATION_PRIORITY = Object.freeze({
16018
16040
  CALLS: 0,
16019
16041
  WRITES: 0,
16020
16042
  IMPORTS: 0,
16021
- TEST_IMPORTS: 0,
16022
16043
  EXTENDS: 0,
16023
16044
  IMPLEMENTS: 0,
16024
16045
  OVERRIDES: 0,
@@ -16096,8 +16117,8 @@ var MapAnalysisSchema = external_exports.object({
16096
16117
  var mapPathAllowed = (relative, prefixes) => prefixes.some(
16097
16118
  (prefix) => prefix === "." || relative === prefix || relative.startsWith(`${prefix}/`)
16098
16119
  );
16099
- var mapTestPath = (path19) => /(?:^|\/)(?:__tests__|tests?|fixtures?|testFixtures|e2e|testdata)(?:\/|$)|\.(?:spec|test)\.|_test\.(?:go|py)$|(?:^|\/)(?:test_[^/]*\.py|conftest\.py)$/iu.test(
16100
- path19
16120
+ var mapTestPath = (path20) => /(?:^|\/)(?:__tests__|tests?|fixtures?|testFixtures|e2e|testdata)(?:\/|$)|\.(?:spec|test)\.|_test\.(?:go|py)$|(?:^|\/)(?:test_[^/]*\.py|conftest\.py)$/iu.test(
16121
+ path20
16101
16122
  );
16102
16123
  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(
16103
16124
  file2
@@ -16146,7 +16167,7 @@ var MapReferenceResultSchema = external_exports.object({
16146
16167
  authority: external_exports.literal("CODE_FACTS_AND_SOURCE_DECLARATIONS_NOT_BUSINESS_AUTHORITY"),
16147
16168
  testing: external_exports.literal("TEST_ASSOCIATION_IS_NOT_BEHAVIOR_VERIFICATION"),
16148
16169
  object: MapObjectSchema,
16149
- query: external_exports.object({ path: external_exports.string(), kinds: external_exports.array(MapReferenceKindSchema) }).strict(),
16170
+ query: external_exports.object({ within: external_exports.string(), kinds: external_exports.array(MapReferenceKindSchema) }).strict(),
16150
16171
  references: external_exports.array(
16151
16172
  MapReferenceSchema.extend({
16152
16173
  contextRef: external_exports.string(),
@@ -16202,11 +16223,11 @@ var string4 = (value) => {
16202
16223
  var identity = (id2, reconstructed) => id2 === reconstructed ? [] : [JSON.stringify(id2)];
16203
16224
  function encodeMapText(graph) {
16204
16225
  const files = /* @__PURE__ */ new Map();
16205
- const file2 = (path19) => {
16206
- let ref = files.get(path19);
16226
+ const file2 = (path20) => {
16227
+ let ref = files.get(path20);
16207
16228
  if (!ref) {
16208
16229
  ref = `F${files.size + 1}`;
16209
- files.set(path19, ref);
16230
+ files.set(path20, ref);
16210
16231
  }
16211
16232
  return ref;
16212
16233
  };
@@ -16254,7 +16275,7 @@ function encodeMapText(graph) {
16254
16275
  rows2.push(`B ${node(frontier.entityRef)} ${frontier.direction}`);
16255
16276
  return [
16256
16277
  ...header,
16257
- ...[...files].map(([path19, ref]) => `${ref} ${JSON.stringify(path19)}`),
16278
+ ...[...files].map(([path20, ref]) => `${ref} ${JSON.stringify(path20)}`),
16258
16279
  ...rows2
16259
16280
  ].join("\n");
16260
16281
  }
@@ -16274,10 +16295,10 @@ function decodeMapText(text) {
16274
16295
  const at = (value) => {
16275
16296
  const match = /^(F[1-9]\d*):(\d+)-(\d+)@(\d+)-(\d+)$/u.exec(value ?? "");
16276
16297
  if (!match) return failed();
16277
- const path19 = files.get(match[1] ?? "");
16278
- if (path19 === void 0) return failed();
16298
+ const path20 = files.get(match[1] ?? "");
16299
+ if (path20 === void 0) return failed();
16279
16300
  return MapAnchorSchema.parse({
16280
- path: path19,
16301
+ path: path20,
16281
16302
  startLine: Number(match[2]),
16282
16303
  endLine: Number(match[3]),
16283
16304
  start: Number(match[4]),
@@ -16354,8 +16375,8 @@ function decodeMapText(text) {
16354
16375
  var locationSchema = MapAnchorSchema.describe(
16355
16376
  "Source location: start/end are zero-based UTF-16 offsets with an exclusive end; line numbers are one-based."
16356
16377
  );
16357
- var location = ({ path: path19, startLine, endLine, start, end }) => ({
16358
- path: path19,
16378
+ var location = ({ path: path20, startLine, endLine, start, end }) => ({
16379
+ path: path20,
16359
16380
  startLine,
16360
16381
  endLine,
16361
16382
  start,
@@ -16458,11 +16479,11 @@ var MapNavigationObjectsSchema = external_exports.union([
16458
16479
  ),
16459
16480
  external_exports.object({ files: external_exports.array(searchFileSchema) }).passthrough().refine((value) => !("format" in value), "Text navigation must decode through its format.").transform(
16460
16481
  (value) => value.files.flatMap(
16461
- ({ path: path19, symbols }) => symbols.map(({ id: id2, name, kind, startLine, endLine, start, end, execution }) => ({
16482
+ ({ path: path20, symbols }) => symbols.map(({ id: id2, name, kind, startLine, endLine, start, end, execution }) => ({
16462
16483
  id: id2,
16463
16484
  name,
16464
16485
  kind,
16465
- anchor: { path: path19, startLine, endLine, start, end },
16486
+ anchor: { path: path20, startLine, endLine, start, end },
16466
16487
  ...execution ? { execution } : {}
16467
16488
  }))
16468
16489
  )
@@ -16475,10 +16496,10 @@ var mapSearchNavigation = (result) => {
16475
16496
  for (const [index, object2] of found.entries()) {
16476
16497
  const ranking = rankings[index];
16477
16498
  if (!ranking) throw new Error("PROJECT_MAP_SEARCH_RANKING_MISSING");
16478
- const path19 = object2.anchor.path;
16499
+ const path20 = object2.anchor.path;
16479
16500
  let file2 = files.at(-1);
16480
- if (file2?.path !== path19) {
16481
- file2 = { path: path19, symbols: [] };
16501
+ if (file2?.path !== path20) {
16502
+ file2 = { path: path20, symbols: [] };
16482
16503
  files.push(file2);
16483
16504
  }
16484
16505
  file2.symbols.push({
@@ -16609,8 +16630,8 @@ var MapViewGraph = class {
16609
16630
  }
16610
16631
  return object2;
16611
16632
  }
16612
- objectsAt(path19) {
16613
- return this.statements.path.all(this.version, path19).map((row) => {
16633
+ objectsAt(path20) {
16634
+ return this.statements.path.all(this.version, path20).map((row) => {
16614
16635
  const object2 = MapObjectSchema.parse(JSON.parse(String(row.object_json)));
16615
16636
  this.objects.set(object2.id, object2);
16616
16637
  return object2;
@@ -16636,8 +16657,8 @@ var MapViewGraph = class {
16636
16657
  return this.statements.children.all(this.version, ref).map((row) => String(row.to_ref));
16637
16658
  }
16638
16659
  /** The declarations of a file other code can name, without the file itself. */
16639
- declarationsAt(path19) {
16640
- return this.objectsAt(path19).filter(
16660
+ declarationsAt(path20) {
16661
+ return this.objectsAt(path20).filter(
16641
16662
  (object2) => !mapIsModule(object2) && this.isAddressable(object2)
16642
16663
  );
16643
16664
  }
@@ -16745,8 +16766,8 @@ var MapViewGraph = class {
16745
16766
  );
16746
16767
  }
16747
16768
  };
16748
- function mapSelectDeclarations(graph, path19, name, line) {
16749
- const objects2 = graph.objectsAt(path19).filter((object2) => !mapIsModule(object2));
16769
+ function mapSelectDeclarations(graph, path20, name, line) {
16770
+ const objects2 = graph.objectsAt(path20).filter((object2) => !mapIsModule(object2));
16750
16771
  const matching = name === void 0 ? objects2 : objects2.filter(
16751
16772
  (object2) => object2.name === name || name.includes(".") && graph.qualifiedName(object2.id) === name
16752
16773
  );
@@ -16768,12 +16789,12 @@ function requireMapObject(store, version2, selector, prefixes) {
16768
16789
  if ([entityRef, locator, symbol2].filter((value) => value !== void 0).length !== 1 || entityRef !== void 0 && !entityRef.length)
16769
16790
  throw new ProjectEvidenceError("PROJECT_READ_INPUT_INVALID", false);
16770
16791
  if (symbol2) {
16771
- const path19 = normalizeProjectEvidencePath(symbol2.path);
16772
- if (!mapPathAllowed(path19, prefixes))
16792
+ const path20 = normalizeProjectEvidencePath(symbol2.path);
16793
+ if (!mapPathAllowed(path20, prefixes))
16773
16794
  throw new ProjectEvidenceError("PROJECT_MAP_OBJECT_NOT_FOUND", false);
16774
16795
  const selected = mapSelectDeclarations(
16775
16796
  new MapViewGraph(store, version2),
16776
- path19,
16797
+ path20,
16777
16798
  symbol2.name,
16778
16799
  symbol2.line
16779
16800
  );
@@ -16784,14 +16805,14 @@ function requireMapObject(store, version2, selector, prefixes) {
16784
16805
  }
16785
16806
  let rows2;
16786
16807
  if (locator) {
16787
- const path19 = normalizeProjectEvidencePath(locator.path);
16808
+ const path20 = normalizeProjectEvidencePath(locator.path);
16788
16809
  if (!Number.isSafeInteger(locator.start) || locator.start < 0 || locator.kind !== void 0 && !MapObjectKindSchema.safeParse(locator.kind).success)
16789
16810
  throw new ProjectEvidenceError("PROJECT_READ_INPUT_INVALID", false);
16790
- if (!mapPathAllowed(path19, prefixes))
16811
+ if (!mapPathAllowed(path20, prefixes))
16791
16812
  throw new ProjectEvidenceError("PROJECT_MAP_OBJECT_NOT_FOUND", false);
16792
16813
  rows2 = store.database.prepare(`SELECT object_json FROM project_map_objects
16793
16814
  WHERE version_ref = ? AND path = ? AND json_extract(object_json, '$.anchor.start') = ?
16794
- AND (? IS NULL OR kind = ?) LIMIT 2`).all(version2, path19, locator.start, locator.kind ?? null, locator.kind ?? null);
16815
+ AND (? IS NULL OR kind = ?) LIMIT 2`).all(version2, path20, locator.start, locator.kind ?? null, locator.kind ?? null);
16795
16816
  } else {
16796
16817
  rows2 = store.database.prepare(
16797
16818
  "SELECT object_json FROM project_map_objects WHERE version_ref = ? AND entity_ref = ?"
@@ -16832,13 +16853,13 @@ function mapQueryPage(count, materialize, navigation, budget) {
16832
16853
 
16833
16854
  // src/project-map-query-selection.ts
16834
16855
  var mapQuerySelection = (input, knownKinds) => {
16835
- const path19 = normalizeProjectEvidencePath(input.path ?? ".", true) || ".";
16856
+ const path20 = normalizeProjectEvidencePath(input.path ?? ".", true) || ".";
16836
16857
  const kinds = input.kinds ?? knownKinds;
16837
16858
  if (!Array.isArray(kinds) || !kinds.length || kinds.length > knownKinds.length || kinds.some((kind) => !knownKinds.includes(kind)))
16838
16859
  throw new ProjectEvidenceError("PROJECT_READ_INPUT_INVALID", false);
16839
- return { path: path19, kinds: [...new Set(kinds)].sort() };
16860
+ return { path: path20, kinds: [...new Set(kinds)].sort() };
16840
16861
  };
16841
- var mapQueryPathMatches = (path19, prefix) => prefix === "." || path19 === prefix || path19.startsWith(`${prefix}/`);
16862
+ var mapQueryPathMatches = (path20, prefix) => prefix === "." || path20 === prefix || path20.startsWith(`${prefix}/`);
16842
16863
  var MAP_RELATION_TARGET_JOIN = `LEFT JOIN project_map_unit_objects t ON t.entity_ref = r.to_ref
16843
16864
  AND EXISTS (SELECT 1 FROM project_map_version_units target
16844
16865
  WHERE target.version_ref = r.version_ref AND target.unit_ref = t.unit_ref AND target.path = t.path)`;
@@ -16855,7 +16876,6 @@ var relationWeight = {
16855
16876
  WRITES: 1200,
16856
16877
  READS: 900,
16857
16878
  IMPORTS: 800,
16858
- TEST_IMPORTS: 700,
16859
16879
  EXTENDS: 900,
16860
16880
  IMPLEMENTS: 900,
16861
16881
  OVERRIDES: 900,
@@ -16863,6 +16883,7 @@ var relationWeight = {
16863
16883
  REFERENCES: 500,
16864
16884
  CONTAINS: 250
16865
16885
  };
16886
+ var TEST_IMPORT_WEIGHT = 700;
16866
16887
  function mapSearchFocus(store, version2, refs, scope, signal) {
16867
16888
  const found = /* @__PURE__ */ new Map();
16868
16889
  if (!refs.length) return found;
@@ -16873,7 +16894,7 @@ function mapSearchFocus(store, version2, refs, scope, signal) {
16873
16894
  throw new ProjectEvidenceError("PROJECT_MAP_OBJECT_NOT_FOUND", false);
16874
16895
  for (const ref of refs) found.set(ref, { distance: 0, score: 1800 });
16875
16896
  let frontier = new Set(refs);
16876
- const edges = store.database.prepare(`SELECT r.from_ref, r.to_ref,
16897
+ const edges = store.database.prepare(`SELECT r.from_ref, r.to_ref, r.path,
16877
16898
  json_extract(r.relation_json, '$.kind') AS kind
16878
16899
  FROM project_map_relations r
16879
16900
  JOIN project_map_objects f ON f.version_ref = r.version_ref AND f.entity_ref = r.from_ref
@@ -16893,7 +16914,8 @@ function mapSearchFocus(store, version2, refs, scope, signal) {
16893
16914
  assertMapSearchActive(signal);
16894
16915
  const from = String(row.from_ref);
16895
16916
  const to = String(row.to_ref);
16896
- const weight = relationWeight[String(row.kind)];
16917
+ const kind = String(row.kind);
16918
+ const weight = kind === "IMPORTS" && mapTestPath(String(row.path)) ? TEST_IMPORT_WEIGHT : relationWeight[kind];
16897
16919
  if (weight === void 0)
16898
16920
  throw new ProjectEvidenceError("PROJECT_EVIDENCE_STORE_CORRUPT", false);
16899
16921
  for (const [parent, neighbor] of [
@@ -16939,7 +16961,7 @@ var declarationKinds = /* @__PURE__ */ new Set([
16939
16961
  "METHOD",
16940
16962
  "TYPE"
16941
16963
  ]);
16942
- var fileStem = (path19) => path19.slice(path19.lastIndexOf("/") + 1).replace(/\.(?:[cm]?[jt]sx?|vue|svelte|go|pyi?)$/iu, "");
16964
+ var fileStem = (path20) => path20.slice(path20.lastIndexOf("/") + 1).replace(/\.(?:[cm]?[jt]sx?|vue|svelte|go|pyi?)$/iu, "");
16943
16965
  var compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
16944
16966
  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);
16945
16967
  function mapSearchQuery(input) {
@@ -16966,10 +16988,10 @@ function mapSearchQuery(input) {
16966
16988
  }
16967
16989
  function rank(object2, documentation, relationCount, query, focus) {
16968
16990
  const name = object2.name.toLowerCase();
16969
- const path19 = object2.anchor.path.toLowerCase();
16991
+ const path20 = object2.anchor.path.toLowerCase();
16970
16992
  const values = {
16971
16993
  NAME: [name],
16972
- PATH: [path19],
16994
+ PATH: [path20],
16973
16995
  DOCUMENTATION: documentation.map((text) => text.toLowerCase())
16974
16996
  };
16975
16997
  const matched = query.terms.map((term) => ({
@@ -16994,12 +17016,12 @@ function rank(object2, documentation, relationCount, query, focus) {
16994
17016
  score += 7e3;
16995
17017
  signals.push("SYMBOL_CONTAINS");
16996
17018
  } else if (matchedFields.includes("NAME")) signals.push("SYMBOL_CONTAINS");
16997
- if (object2.kind === "FILE" && fileStem(path19) === normalizedQuery) {
17019
+ if (object2.kind === "FILE" && fileStem(path20) === normalizedQuery) {
16998
17020
  score += 11e3;
16999
17021
  signals.push("EXACT_FILE_STEM");
17000
17022
  }
17001
17023
  if (matchedFields.includes("PATH")) {
17002
- score += path19.includes(normalizedQuery) ? 2500 : 0;
17024
+ score += path20.includes(normalizedQuery) ? 2500 : 0;
17003
17025
  signals.push("PATH_CONTAINS");
17004
17026
  }
17005
17027
  if (matchedFields.includes("DOCUMENTATION")) {
@@ -17014,8 +17036,8 @@ function rank(object2, documentation, relationCount, query, focus) {
17014
17036
  score += kindWeight[object2.kind] + Math.min(1200, relationCount * 20) + (focus?.score ?? 0);
17015
17037
  if (declarationKinds.has(object2.kind)) signals.push("DECLARATION");
17016
17038
  if (relationCount > 0) signals.push("GRAPH_CONNECTED");
17017
- const isTest = mapTestPath(path19);
17018
- const isGenerated = generatedPath.test(path19);
17039
+ const isTest = mapTestPath(path20);
17040
+ const isGenerated = generatedPath.test(path20);
17019
17041
  const hasTestIntent = query.terms.some((term) => testQuery.test(term));
17020
17042
  score += isTest ? hasTestIntent ? 1e3 : -5e3 : 300;
17021
17043
  score += isGenerated ? -3e3 : 300;
@@ -17306,6 +17328,36 @@ function mapPageFrontier(frontier, rows2) {
17306
17328
  return frontier.filter(({ entityRef }) => visible.has(entityRef)).map((node) => ({ ...node }));
17307
17329
  }
17308
17330
 
17331
+ // src/project-map-imports.ts
17332
+ function loadMapImports(store, version2) {
17333
+ return store.database.prepare(`SELECT DISTINCT r.path AS source, t.path AS target,
17334
+ json_extract(r.relation_json, '$.anchor.startLine') AS line,
17335
+ json_extract(r.relation_json, '$.target') AS specifier,
17336
+ json_extract(r.relation_json, '$.unresolvedReason') AS reason
17337
+ FROM project_map_relations r NOT INDEXED
17338
+ ${MAP_RELATION_TARGET_JOIN}
17339
+ WHERE r.version_ref = ? AND json_extract(r.relation_json, '$.kind') = 'IMPORTS'
17340
+ ORDER BY source, line, target, specifier`).all(version2).map((row) => {
17341
+ const site = {
17342
+ source: String(row.source),
17343
+ line: Number(row.line),
17344
+ specifier: String(row.specifier)
17345
+ };
17346
+ return row.target === null ? { ...site, target: null, reason: String(row.reason) } : { ...site, target: String(row.target) };
17347
+ });
17348
+ }
17349
+ function mapProjectImports(rows2) {
17350
+ const imports = [];
17351
+ const unresolved = [];
17352
+ for (const row of rows2) {
17353
+ if (mapTestPath(row.source)) continue;
17354
+ const { source: from, line, specifier } = row;
17355
+ if (row.target === null) unresolved.push({ from, line, specifier, reason: row.reason });
17356
+ else if (row.target !== from) imports.push({ from, line, to: row.target, specifier });
17357
+ }
17358
+ return { imports, unresolved };
17359
+ }
17360
+
17309
17361
  // src/project-map-language-go.ts
17310
17362
  import { existsSync as existsSync4 } from "node:fs";
17311
17363
  import { posix } from "node:path";
@@ -17497,13 +17549,13 @@ function utf16Offsets(text) {
17497
17549
  }
17498
17550
  function offsetConverter(files, offsets) {
17499
17551
  const converters = /* @__PURE__ */ new Map();
17500
- return (path19, offset) => {
17501
- let convert = converters.get(path19);
17552
+ return (path20, offset) => {
17553
+ let convert = converters.get(path20);
17502
17554
  if (!convert) {
17503
- const text = files[path19];
17555
+ const text = files[path20];
17504
17556
  if (text === void 0) return invalid();
17505
17557
  convert = offsets === "UTF16" ? (value) => value <= text.length ? value : invalid() : utf16Offsets(text);
17506
- converters.set(path19, convert);
17558
+ converters.set(path20, convert);
17507
17559
  }
17508
17560
  return convert(offset);
17509
17561
  };
@@ -17534,7 +17586,7 @@ function mapFactsAnalysis(facts, input, context) {
17534
17586
  const collect = new MapOutputCollector(output);
17535
17587
  const positions = new MapSourcePositions(input.files);
17536
17588
  const offset = offsetConverter(input.files, context.offsets);
17537
- const anchor = (path19, start, end) => positions.span(path19, offset(path19, start), offset(path19, end));
17589
+ const anchor = (path20, start, end) => positions.span(path20, offset(path20, start), offset(path20, end));
17538
17590
  const located = /* @__PURE__ */ new Map();
17539
17591
  const canonical = /* @__PURE__ */ new Map();
17540
17592
  const bySpan = /* @__PURE__ */ new Map();
@@ -17709,7 +17761,7 @@ function referencePage(found, positions, offset, reference) {
17709
17761
  // src/project-map-process.ts
17710
17762
  import { execFileSync, spawn as spawn2 } from "node:child_process";
17711
17763
  import { existsSync as existsSync3, readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
17712
- import path8 from "node:path";
17764
+ import path9 from "node:path";
17713
17765
 
17714
17766
  // src/project-map-failure.ts
17715
17767
  var PhaseSchema = external_exports.enum([
@@ -17836,24 +17888,24 @@ var ProjectMapStopUnconfirmedError = class extends ProjectEvidenceError {
17836
17888
  }
17837
17889
  };
17838
17890
  var installedMapParserResources = () => {
17839
- const directory = path8.dirname(path8.resolve(process.argv[1] ?? "."));
17891
+ const directory = path9.dirname(path9.resolve(process.argv[1] ?? "."));
17840
17892
  return {
17841
- workerPath: path8.join(directory, "project-map-worker.mjs"),
17842
- compilerPath: path8.join(directory, "project-map-native/tsc")
17893
+ workerPath: path9.join(directory, "project-map-worker.mjs"),
17894
+ compilerPath: path9.join(directory, "project-map-native/tsc")
17843
17895
  };
17844
17896
  };
17845
17897
  var installedPythonMapResources = () => {
17846
- const directory = path8.dirname(path8.resolve(process.argv[1] ?? "."));
17898
+ const directory = path9.dirname(path9.resolve(process.argv[1] ?? "."));
17847
17899
  return {
17848
- workerPath: path8.join(directory, "project-map-python-worker.mjs"),
17849
- compilerPath: path8.join(directory, "project-map-python/typeshed")
17900
+ workerPath: path9.join(directory, "project-map-python-worker.mjs"),
17901
+ compilerPath: path9.join(directory, "project-map-python/typeshed")
17850
17902
  };
17851
17903
  };
17852
17904
  function discoverJavaRuntime(env = process.env) {
17853
17905
  const homes = [env.LAYERMAP_JAVA_HOME, env.JAVA_HOME];
17854
- for (const directory of (env.PATH ?? env.Path ?? "").split(path8.delimiter)) {
17855
- const java = path8.join(directory, executableName("java"));
17856
- if (directory && existsSync3(java)) homes.push(path8.dirname(path8.dirname(realpathSync2(java))));
17906
+ for (const directory of (env.PATH ?? env.Path ?? "").split(path9.delimiter)) {
17907
+ const java = path9.join(directory, executableName("java"));
17908
+ if (directory && existsSync3(java)) homes.push(path9.dirname(path9.dirname(realpathSync2(java))));
17857
17909
  }
17858
17910
  homes.push(
17859
17911
  ...["/opt/homebrew/opt", "/usr/local/opt"].flatMap(
@@ -17861,7 +17913,7 @@ function discoverJavaRuntime(env = process.env) {
17861
17913
  (formula) => `${prefix}/${formula}/libexec/openjdk.jdk/Contents/Home`
17862
17914
  )
17863
17915
  ),
17864
- ...env.HOME ? [path8.join(env.HOME, ".sdkman/candidates/java/current")] : []
17916
+ ...env.HOME ? [path9.join(env.HOME, ".sdkman/candidates/java/current")] : []
17865
17917
  );
17866
17918
  if (process.platform === "darwin")
17867
17919
  try {
@@ -17876,12 +17928,12 @@ function discoverJavaRuntime(env = process.env) {
17876
17928
  }
17877
17929
  for (const home of homes) {
17878
17930
  if (!home) continue;
17879
- const runtimePath = path8.join(home, "bin", executableName("java"));
17880
- if (!existsSync3(runtimePath) || !existsSync3(path8.join(home, "bin", executableName("javac"))))
17931
+ const runtimePath = path9.join(home, "bin", executableName("java"));
17932
+ if (!existsSync3(runtimePath) || !existsSync3(path9.join(home, "bin", executableName("javac"))))
17881
17933
  continue;
17882
17934
  let release = "";
17883
17935
  try {
17884
- release = readFileSync2(path8.join(home, "release"), "utf8");
17936
+ release = readFileSync2(path9.join(home, "release"), "utf8");
17885
17937
  } catch {
17886
17938
  continue;
17887
17939
  }
@@ -17892,26 +17944,26 @@ function discoverJavaRuntime(env = process.env) {
17892
17944
  return void 0;
17893
17945
  }
17894
17946
  var installedJavaMapResources = () => {
17895
- const directory = path8.dirname(path8.resolve(process.argv[1] ?? "."));
17896
- const compilerPath = path8.join(directory, "project-map-java/java-map.jar");
17947
+ const directory = path9.dirname(path9.resolve(process.argv[1] ?? "."));
17948
+ const compilerPath = path9.join(directory, "project-map-java/java-map.jar");
17897
17949
  return {
17898
- workerPath: path8.join(directory, "project-map-java-worker.mjs"),
17950
+ workerPath: path9.join(directory, "project-map-java-worker.mjs"),
17899
17951
  compilerPath,
17900
17952
  // A build without a JDK leaves no analyzer to run, whatever runtime this machine has.
17901
17953
  ...existsSync3(compilerPath) ? discoverJavaRuntime() : {}
17902
17954
  };
17903
17955
  };
17904
17956
  var installedGoMapResources = () => {
17905
- const directory = path8.dirname(path8.resolve(process.argv[1] ?? "."));
17957
+ const directory = path9.dirname(path9.resolve(process.argv[1] ?? "."));
17906
17958
  return {
17907
- workerPath: path8.join(directory, "project-map-go-worker.mjs"),
17908
- compilerPath: path8.join(directory, "project-map-go/go-map")
17959
+ workerPath: path9.join(directory, "project-map-go-worker.mjs"),
17960
+ compilerPath: path9.join(directory, "project-map-go/go-map")
17909
17961
  };
17910
17962
  };
17911
17963
  function runMapOperation(resources, input, schema, signal, observeTiming) {
17912
17964
  if (signal.aborted)
17913
17965
  return Promise.reject(new ProjectEvidenceError("PROJECT_READ_CANCELLED", true));
17914
- if (!path8.isAbsolute(resources.workerPath) || !path8.isAbsolute(resources.compilerPath)) {
17966
+ if (!path9.isAbsolute(resources.workerPath) || !path9.isAbsolute(resources.compilerPath)) {
17915
17967
  return Promise.reject(
17916
17968
  new ProjectEvidenceError("PROJECT_MAP_PARSER_CONFIGURATION_INVALID", false)
17917
17969
  );
@@ -18113,9 +18165,9 @@ var goModule = /(?:^|\/)go\.mod$/u;
18113
18165
  var goWork = /(?:^|\/)go\.work$/u;
18114
18166
  var codeHosts = /* @__PURE__ */ new Set(["github.com", "gitlab.com", "bitbucket.org"]);
18115
18167
  var GO_MAP_LANGUAGE = Object.freeze({
18116
- id: "go-1.24-map-v10",
18117
- claims: (path19) => path19.endsWith(".go"),
18118
- reads: (path19) => goModule.test(path19) || goWork.test(path19),
18168
+ id: "go-1.24-map-v11",
18169
+ claims: (path20) => path20.endsWith(".go"),
18170
+ reads: (path20) => goModule.test(path20) || goWork.test(path20),
18119
18171
  // A module path, or the standard library, whose first path element has no dot.
18120
18172
  importName: (specifier) => {
18121
18173
  const parts = specifier.split("/");
@@ -18124,7 +18176,7 @@ var GO_MAP_LANGUAGE = Object.freeze({
18124
18176
  return parts.slice(0, size).join("/");
18125
18177
  },
18126
18178
  // Go imports a package: the directory of the file.
18127
- importTarget: (path19) => `${path19.slice(0, path19.lastIndexOf("/") + 1) || "./"}`,
18179
+ importTarget: (path20) => `${path20.slice(0, path20.lastIndexOf("/") + 1) || "./"}`,
18128
18180
  create: () => new GoMapAnalyzer()
18129
18181
  });
18130
18182
  var GO_GAPS = [
@@ -18149,8 +18201,8 @@ var goMapAnalysis = (facts, input, configurations) => mapFactsAnalysis(facts, in
18149
18201
  typeIssues: "GO_TYPE_CHECK_ISSUES",
18150
18202
  contract: "Declares a Go interface. This does not establish runtime enforcement or business authority."
18151
18203
  });
18152
- var goLocalModules = (path19, text) => {
18153
- const directive = goWork.test(path19) ? "use" : "replace";
18204
+ var goLocalModules = (path20, text) => {
18205
+ const directive = goWork.test(path20) ? "use" : "replace";
18154
18206
  const found = [];
18155
18207
  let block = false;
18156
18208
  for (const raw of text.split("\n")) {
@@ -18164,37 +18216,37 @@ var goLocalModules = (path19, text) => {
18164
18216
  const target = directive === "use" ? entry : entry?.split("=>")[1];
18165
18217
  const directory = target?.trim().split(/\s+/u)[0]?.replace(/^(["`])(.*)\1$/u, "$2");
18166
18218
  if (!directory || !/^\.\.?(?:\/|$)/u.test(directory)) continue;
18167
- const joined = posix.normalize(posix.join(posix.dirname(path19), directory)).replace(/\/$/u, "");
18219
+ const joined = posix.normalize(posix.join(posix.dirname(path20), directory)).replace(/\/$/u, "");
18168
18220
  if (joined !== ".." && !joined.startsWith("../")) found.push(joined);
18169
18221
  }
18170
18222
  return found;
18171
18223
  };
18172
18224
  var goModuleGroups = (files, text) => {
18173
- const modules = files.filter((path19) => goModule.test(path19)).sort();
18174
- const moduleAt = new Map(modules.map((path19) => [posix.dirname(path19), path19]));
18175
- const parent = new Map(modules.map((path19) => [path19, path19]));
18176
- const root = (path19) => {
18177
- const up = parent.get(path19) ?? path19;
18178
- return up === path19 ? path19 : root(up);
18225
+ const modules = files.filter((path20) => goModule.test(path20)).sort();
18226
+ const moduleAt = new Map(modules.map((path20) => [posix.dirname(path20), path20]));
18227
+ const parent = new Map(modules.map((path20) => [path20, path20]));
18228
+ const root = (path20) => {
18229
+ const up = parent.get(path20) ?? path20;
18230
+ return up === path20 ? path20 : root(up);
18179
18231
  };
18180
18232
  const works = [];
18181
- for (const path19 of [...files].filter((file2) => goModule.test(file2) || goWork.test(file2)).sort()) {
18182
- const linked = goLocalModules(path19, text(path19)).flatMap((dir) => moduleAt.get(dir) ?? []);
18183
- const first = goWork.test(path19) ? linked[0] : path19;
18233
+ for (const path20 of [...files].filter((file2) => goModule.test(file2) || goWork.test(file2)).sort()) {
18234
+ const linked = goLocalModules(path20, text(path20)).flatMap((dir) => moduleAt.get(dir) ?? []);
18235
+ const first = goWork.test(path20) ? linked[0] : path20;
18184
18236
  if (!first) continue;
18185
- if (goWork.test(path19)) works.push([path19, first]);
18237
+ if (goWork.test(path20)) works.push([path20, first]);
18186
18238
  for (const module of linked) {
18187
18239
  const [low = first, high = module] = [root(first), root(module)].sort();
18188
18240
  if (low !== high) parent.set(high, low);
18189
18241
  }
18190
18242
  }
18191
18243
  const members = /* @__PURE__ */ new Map();
18192
- for (const path19 of modules) members.set(root(path19), [...members.get(root(path19)) ?? [], path19]);
18244
+ for (const path20 of modules) members.set(root(path20), [...members.get(root(path20)) ?? [], path20]);
18193
18245
  const named = new Map(works.reverse().map(([work, module]) => [root(module), work]));
18194
18246
  return new Map(
18195
- modules.map((path19) => [
18196
- path19,
18197
- { configPath: named.get(root(path19)) ?? root(path19), modules: members.get(root(path19)) ?? [] }
18247
+ modules.map((path20) => [
18248
+ path20,
18249
+ { configPath: named.get(root(path20)) ?? root(path20), modules: members.get(root(path20)) ?? [] }
18198
18250
  ])
18199
18251
  );
18200
18252
  };
@@ -18224,28 +18276,28 @@ var GoMapAnalyzer = class {
18224
18276
  }
18225
18277
  async analyze(session, signal) {
18226
18278
  const paths = session.readable.map((entry) => entry.path);
18227
- const groupOf = goModuleGroups(paths, (path19) => session.texts[path19] ?? "");
18228
- const moduleOf = (path19) => {
18279
+ const groupOf = goModuleGroups(paths, (path20) => session.texts[path20] ?? "");
18280
+ const moduleOf = (path20) => {
18229
18281
  let best;
18230
18282
  for (const modFile of groupOf.keys()) {
18231
18283
  const directory = modFile.slice(0, modFile.lastIndexOf("/") + 1);
18232
- if (path19.startsWith(directory) && (!best || directory.length > best.lastIndexOf("/") + 1))
18284
+ if (path20.startsWith(directory) && (!best || directory.length > best.lastIndexOf("/") + 1))
18233
18285
  best = modFile;
18234
18286
  }
18235
18287
  return best;
18236
18288
  };
18237
18289
  const contexts = /* @__PURE__ */ new Map();
18238
- for (const path19 of paths) {
18239
- if (!this.claims(path19)) continue;
18240
- const module = moduleOf(path19);
18290
+ for (const path20 of paths) {
18291
+ if (!this.claims(path20)) continue;
18292
+ const module = moduleOf(path20);
18241
18293
  const group = module ? groupOf.get(module) : void 0;
18242
18294
  const configPath = group?.configPath ?? "";
18243
18295
  const into = contexts.get(configPath);
18244
- if (into) into.sources.push(path19);
18296
+ if (into) into.sources.push(path20);
18245
18297
  else
18246
18298
  contexts.set(configPath, {
18247
18299
  configurations: group ? [.../* @__PURE__ */ new Set([...group.modules, configPath])].sort() : [],
18248
- sources: [path19]
18300
+ sources: [path20]
18249
18301
  });
18250
18302
  }
18251
18303
  for (const [configPath, { configurations, sources }] of [...contexts].sort(
@@ -18253,11 +18305,11 @@ var GoMapAnalyzer = class {
18253
18305
  )) {
18254
18306
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
18255
18307
  const files = /* @__PURE__ */ Object.create(null);
18256
- for (const path19 of [...sources, ...configurations]) {
18257
- const text = session.texts[path19];
18308
+ for (const path20 of [...sources, ...configurations]) {
18309
+ const text = session.texts[path20];
18258
18310
  if (text === void 0)
18259
18311
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
18260
- files[path19] = text;
18312
+ files[path20] = text;
18261
18313
  }
18262
18314
  const input = {
18263
18315
  contextRef: digestValue({
@@ -18291,8 +18343,8 @@ var GoMapAnalyzer = class {
18291
18343
  if (!existsSync4(this.resources.compilerPath))
18292
18344
  return { pages: references.map(() => null), requiredFiles: [] };
18293
18345
  const files = /* @__PURE__ */ Object.create(null);
18294
- for (const [path19, value] of Object.entries(input.files))
18295
- if (this.claims(path19) || this.reads(path19)) files[path19] = value;
18346
+ for (const [path20, value] of Object.entries(input.files))
18347
+ if (this.claims(path20) || this.reads(path20)) files[path20] = value;
18296
18348
  const facts = await this.operation(
18297
18349
  {
18298
18350
  ...input,
@@ -18321,14 +18373,14 @@ var BUILD_FILES = [
18321
18373
  "pom.xml"
18322
18374
  ];
18323
18375
  var buildFile = /(?:^|\/)(?:pom\.xml|(?:build|settings)\.gradle(?:\.kts)?)$/u;
18324
- var directoryOf = (path19) => path19.slice(0, path19.lastIndexOf("/") + 1);
18325
- var nameOf = (path19) => path19.slice(path19.lastIndexOf("/") + 1);
18376
+ var directoryOf = (path20) => path20.slice(0, path20.lastIndexOf("/") + 1);
18377
+ var nameOf = (path20) => path20.slice(path20.lastIndexOf("/") + 1);
18326
18378
  var DEFAULT_RELEASE = 21;
18327
18379
  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;
18328
18380
  var JAVA_MAP_LANGUAGE = Object.freeze({
18329
- id: "javac-lombok-1.18.48-map-v9",
18330
- claims: (path19) => path19.endsWith(".java"),
18331
- reads: (path19) => buildFile.test(path19),
18381
+ id: "javac-lombok-1.18.48-map-v10",
18382
+ claims: (path20) => path20.endsWith(".java"),
18383
+ reads: (path20) => buildFile.test(path20),
18332
18384
  // A package of the Java platform, or a library named by its first two package segments.
18333
18385
  importName: (specifier) => platformPackage.test(specifier) ? "Java standard library" : specifier.split(".").slice(0, 2).join("."),
18334
18386
  create: () => new JavaMapAnalyzer()
@@ -18415,15 +18467,14 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18415
18467
  observe?.({ ...event, phase: "FINISHED", elapsedMs: performance.now() - start });
18416
18468
  }
18417
18469
  }
18418
- // The worker's request for a context: the Java sources, the release and which are tests.
18470
+ // The worker's request for a context: the Java sources and the release.
18419
18471
  request(input, buildTexts) {
18420
18472
  const files = /* @__PURE__ */ Object.create(null);
18421
- for (const [path19, text] of Object.entries(input.files))
18422
- if (this.claims(path19)) files[path19] = text;
18473
+ for (const [path20, text] of Object.entries(input.files))
18474
+ if (this.claims(path20)) files[path20] = text;
18423
18475
  return {
18424
18476
  files,
18425
- release: javaRelease(buildTexts, this.resources.runtimeVersion),
18426
- tests: Object.keys(files).filter((path19) => mapTestPath(path19))
18477
+ release: javaRelease(buildTexts, this.resources.runtimeVersion)
18427
18478
  };
18428
18479
  }
18429
18480
  // The build files of a context's root directory, which declare its Java version.
@@ -18435,35 +18486,35 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18435
18486
  }
18436
18487
  async analyze(session, signal) {
18437
18488
  this.refreshRuntime();
18438
- const builds = session.readable.map((entry) => entry.path).filter((path19) => buildFile.test(path19));
18439
- for (const path19 of builds) session.configuration(path19);
18440
- const rank2 = (path19) => BUILD_FILES.indexOf(nameOf(path19));
18489
+ const builds = session.readable.map((entry) => entry.path).filter((path20) => buildFile.test(path20));
18490
+ for (const path20 of builds) session.configuration(path20);
18491
+ const rank2 = (path20) => BUILD_FILES.indexOf(nameOf(path20));
18441
18492
  const roots = /* @__PURE__ */ new Map();
18442
18493
  const modules = /* @__PURE__ */ new Map();
18443
- for (const path19 of builds) {
18444
- const directory = directoryOf(path19);
18494
+ for (const path20 of builds) {
18495
+ const directory = directoryOf(path20);
18445
18496
  const current = modules.get(directory);
18446
- if (current === void 0 || rank2(path19) < rank2(current)) modules.set(directory, path19);
18447
- const text = session.texts[path19] ?? "";
18448
- if (/settings\.gradle(?:\.kts)?$/u.test(path19) || path19.endsWith("pom.xml") && /<modules>/u.test(text)) {
18497
+ if (current === void 0 || rank2(path20) < rank2(current)) modules.set(directory, path20);
18498
+ const text = session.texts[path20] ?? "";
18499
+ if (/settings\.gradle(?:\.kts)?$/u.test(path20) || path20.endsWith("pom.xml") && /<modules>/u.test(text)) {
18449
18500
  const root = roots.get(directory);
18450
- if (root === void 0 || rank2(path19) < rank2(root)) roots.set(directory, path19);
18501
+ if (root === void 0 || rank2(path20) < rank2(root)) roots.set(directory, path20);
18451
18502
  }
18452
18503
  }
18453
- const configOf = (path19) => {
18504
+ const configOf = (path20) => {
18454
18505
  let outer;
18455
18506
  for (const directory of roots.keys())
18456
- if (path19.startsWith(directory) && (outer === void 0 || directory.length < outer.length))
18507
+ if (path20.startsWith(directory) && (outer === void 0 || directory.length < outer.length))
18457
18508
  outer = directory;
18458
18509
  if (outer !== void 0) return roots.get(outer);
18459
18510
  let nearest;
18460
18511
  for (const directory of modules.keys())
18461
- if (path19.startsWith(directory) && (nearest === void 0 || directory.length > nearest.length))
18512
+ if (path20.startsWith(directory) && (nearest === void 0 || directory.length > nearest.length))
18462
18513
  nearest = directory;
18463
18514
  return nearest === void 0 ? "" : modules.get(nearest);
18464
18515
  };
18465
- const output = (path19) => [...modules.keys()].some(
18466
- (directory) => path19.startsWith(`${directory}build/`) || path19.startsWith(`${directory}target/`)
18516
+ const output = (path20) => [...modules.keys()].some(
18517
+ (directory) => path20.startsWith(`${directory}build/`) || path20.startsWith(`${directory}target/`)
18467
18518
  );
18468
18519
  const groups = /* @__PURE__ */ new Map();
18469
18520
  for (const entry of session.readable) {
@@ -18478,13 +18529,13 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18478
18529
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
18479
18530
  const files = /* @__PURE__ */ Object.create(null);
18480
18531
  const rootBuilds = configPath ? BUILD_FILES.map((name) => `${directoryOf(configPath)}${name}`).filter(
18481
- (path19) => builds.includes(path19)
18532
+ (path20) => builds.includes(path20)
18482
18533
  ) : [];
18483
- for (const path19 of [...groups.get(configPath) ?? [], ...rootBuilds]) {
18484
- const text = session.texts[path19];
18534
+ for (const path20 of [...groups.get(configPath) ?? [], ...rootBuilds]) {
18535
+ const text = session.texts[path20];
18485
18536
  if (text === void 0)
18486
18537
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
18487
- files[path19] = text;
18538
+ files[path20] = text;
18488
18539
  }
18489
18540
  const input = {
18490
18541
  contextRef: digestValue({
@@ -18507,7 +18558,6 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18507
18558
  {
18508
18559
  configPath: configPath || null,
18509
18560
  release: request.release,
18510
- tests: request.tests,
18511
18561
  runtime,
18512
18562
  built: existsSync5(this.resources.compilerPath),
18513
18563
  lombokConfig
@@ -18527,7 +18577,7 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18527
18577
  const prior = JavaStateSchema.safeParse(previous?.state).data;
18528
18578
  const incremental = previous && prior?.basis === basis ? {
18529
18579
  changed: Object.keys(request.files).filter(
18530
- (path19) => digests.get(path19) !== previous.digests.get(path19)
18580
+ (path20) => digests.get(path20) !== previous.digests.get(path20)
18531
18581
  ),
18532
18582
  state: prior.java
18533
18583
  } : void 0;
@@ -18556,14 +18606,14 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18556
18606
  continue;
18557
18607
  }
18558
18608
  const focus = new Set(facts.focus);
18559
- if (!incremental || facts.focus.some((path19) => !Object.hasOwn(request.files, path19)) || incremental.changed.some((path19) => !focus.has(path19)))
18609
+ if (!incremental || facts.focus.some((path20) => !Object.hasOwn(request.files, path20)) || incremental.changed.some((path20) => !focus.has(path20)))
18560
18610
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
18561
18611
  analysis.objects = analysis.objects.filter((object2) => focus.has(object2.anchor.path));
18562
18612
  analysis.relations = analysis.relations.filter((relation) => focus.has(relation.anchor.path));
18563
18613
  analysis.notes = analysis.notes.filter((note) => focus.has(note.anchor.path));
18564
18614
  session.accept(analysis, {
18565
18615
  state,
18566
- linked: analysis.parsedFiles.filter((path19) => !focus.has(path19))
18616
+ linked: analysis.parsedFiles.filter((path20) => !focus.has(path20))
18567
18617
  });
18568
18618
  }
18569
18619
  }
@@ -18878,12 +18928,12 @@ var PYTHON_STANDARD_LIBRARY = /* @__PURE__ */ new Set([
18878
18928
  // src/project-map-language-python.ts
18879
18929
  var CONFIGURATION = ["pyrightconfig.json", "pyproject.toml", "setup.cfg"];
18880
18930
  var pythonConfig = /(?:^|\/)(?:pyrightconfig\.json|pyproject\.toml|setup\.cfg)$/u;
18881
- var directoryOf2 = (path19) => path19.slice(0, path19.lastIndexOf("/") + 1);
18931
+ var directoryOf2 = (path20) => path20.slice(0, path20.lastIndexOf("/") + 1);
18882
18932
  var DEFAULT_PYTHON = { major: 3, minor: 13 };
18883
18933
  var PYTHON_MAP_LANGUAGE = Object.freeze({
18884
- id: "pyright-1.1.414-map-v13",
18885
- claims: (path19) => /\.pyi?$/u.test(path19),
18886
- reads: (path19) => pythonConfig.test(path19),
18934
+ id: "pyright-1.1.414-map-v14",
18935
+ claims: (path20) => /\.pyi?$/u.test(path20),
18936
+ reads: (path20) => pythonConfig.test(path20),
18887
18937
  // An absolute import names the standard library or a distribution's top-level package.
18888
18938
  importName: (specifier) => {
18889
18939
  const top = specifier.split(".", 1)[0] ?? specifier;
@@ -18934,22 +18984,21 @@ var PythonMapAnalyzer = class {
18934
18984
  request(input) {
18935
18985
  return {
18936
18986
  root: input.configPath ? directoryOf2(input.configPath).replace(/\/$/u, "") : "",
18937
- pythonVersion: pythonVersion(input.files, input.configPath),
18938
- tests: Object.keys(input.files).filter((path19) => this.claims(path19) && mapTestPath(path19))
18987
+ pythonVersion: pythonVersion(input.files, input.configPath)
18939
18988
  };
18940
18989
  }
18941
18990
  async analyze(session, signal) {
18942
18991
  const roots = /* @__PURE__ */ new Map();
18943
- for (const path19 of session.readable.map((entry) => entry.path).filter((path20) => pythonConfig.test(path20))) {
18944
- const directory = directoryOf2(path19);
18992
+ for (const path20 of session.readable.map((entry) => entry.path).filter((path21) => pythonConfig.test(path21))) {
18993
+ const directory = directoryOf2(path20);
18945
18994
  const current = roots.get(directory);
18946
18995
  const rank2 = (file2) => CONFIGURATION.indexOf(file2.slice(directory.length));
18947
- if (current === void 0 || rank2(path19) < rank2(current)) roots.set(directory, path19);
18996
+ if (current === void 0 || rank2(path20) < rank2(current)) roots.set(directory, path20);
18948
18997
  }
18949
- const rootOf = (path19) => {
18998
+ const rootOf = (path20) => {
18950
18999
  let best;
18951
19000
  for (const directory of roots.keys())
18952
- if (path19.startsWith(directory) && (best === void 0 || directory.length > best.length))
19001
+ if (path20.startsWith(directory) && (best === void 0 || directory.length > best.length))
18953
19002
  best = directory;
18954
19003
  return best === void 0 ? "" : roots.get(best);
18955
19004
  };
@@ -18964,11 +19013,11 @@ var PythonMapAnalyzer = class {
18964
19013
  for (const configPath of [...groups.keys()].sort()) {
18965
19014
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
18966
19015
  const files = /* @__PURE__ */ Object.create(null);
18967
- for (const path19 of [...groups.get(configPath) ?? [], ...configPath ? [configPath] : []]) {
18968
- const text = session.texts[path19];
19016
+ for (const path20 of [...groups.get(configPath) ?? [], ...configPath ? [configPath] : []]) {
19017
+ const text = session.texts[path20];
18969
19018
  if (text === void 0)
18970
19019
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
18971
- files[path19] = text;
19020
+ files[path20] = text;
18972
19021
  }
18973
19022
  const input = {
18974
19023
  contextRef: digestValue({
@@ -19014,8 +19063,8 @@ var PythonMapAnalyzer = class {
19014
19063
  }
19015
19064
  async references(input, references, signal, observe) {
19016
19065
  const files = /* @__PURE__ */ Object.create(null);
19017
- for (const [path19, value] of Object.entries(input.files))
19018
- if (this.claims(path19) || pythonConfig.test(path19)) files[path19] = value;
19066
+ for (const [path20, value] of Object.entries(input.files))
19067
+ if (this.claims(path20) || pythonConfig.test(path20)) files[path20] = value;
19019
19068
  const facts = await this.operation(
19020
19069
  {
19021
19070
  ...input,
@@ -19039,7 +19088,7 @@ var PythonMapAnalyzer = class {
19039
19088
  import { availableParallelism } from "node:os";
19040
19089
 
19041
19090
  // src/project-map-miniprogram.ts
19042
- import path9 from "node:path";
19091
+ import path10 from "node:path";
19043
19092
  import {
19044
19093
  isCallExpression,
19045
19094
  isExpressionStatement,
@@ -19057,9 +19106,9 @@ var miniprogramTemplateOf = (script, inventory) => /\.[cm]?[jt]sx?$/u.test(scrip
19057
19106
  function miniprogramConfiguration(template, inventory) {
19058
19107
  const own = template.replace(/\.wxml$/u, ".json");
19059
19108
  const configuration = inventory.has(own) ? { own } : {};
19060
- for (let directory = path9.posix.dirname(template); ; directory = path9.posix.dirname(directory)) {
19109
+ for (let directory = path10.posix.dirname(template); ; directory = path10.posix.dirname(directory)) {
19061
19110
  const root = directory === "." ? "" : directory;
19062
- const app = path9.posix.join(root, "app.json");
19111
+ const app = path10.posix.join(root, "app.json");
19063
19112
  if (inventory.has(app)) return { ...configuration, app, root };
19064
19113
  if (!root) return configuration;
19065
19114
  }
@@ -19071,10 +19120,10 @@ var miniprogramEventOf = (target) => {
19071
19120
 
19072
19121
  // src/project-map-language-typescript.ts
19073
19122
  var TYPESCRIPT_MAP_LANGUAGE = Object.freeze({
19074
- id: "typescript-7.0.2-map-v33",
19075
- claims: (path19) => /\.[cm]?[jt]sx?$/u.test(path19),
19123
+ id: "typescript-7.0.2-map-v34",
19124
+ claims: (path20) => /\.[cm]?[jt]sx?$/u.test(path20),
19076
19125
  readsRequests: true,
19077
- reads: (path19) => path19.endsWith(".json") || path19.endsWith(".wxml") || path19 === "pnpm-workspace.yaml",
19126
+ reads: (path20) => path20.endsWith(".json") || path20.endsWith(".wxml") || path20 === "pnpm-workspace.yaml",
19078
19127
  create: () => new TypeScriptMapAnalyzer()
19079
19128
  });
19080
19129
  var CONFIGURATIONS_KEPT = 4;
@@ -19096,7 +19145,7 @@ function limit(atOnce) {
19096
19145
  }
19097
19146
  var MODULE_NAMES = /\b(?:from|import|require)\s*\(?\s*(["'`])([^"'`\n]+)\1|\/\/\/\s*<reference\s+(?:path|types|lib)\s*=\s*(["'])([^"'\n]+)\3/gu;
19098
19147
  var moduleNames = (text) => digestValue([...text.matchAll(MODULE_NAMES)].map((match) => match[2] ?? match[4] ?? ""));
19099
- var sameShape = (left, right) => left.installed === right.installed && left.files.size === right.files.size && [...left.files].every(([path19, { shape }]) => right.files.get(path19)?.shape === shape);
19148
+ var sameShape = (left, right) => left.installed === right.installed && left.files.size === right.files.size && [...left.files].every(([path20, { shape }]) => right.files.get(path20)?.shape === shape);
19100
19149
  var stopUnconfirmed = async (runs) => (await Promise.allSettled(runs)).flatMap((settled) => settled.status === "rejected" ? [settled.reason] : []).find((reason) => reason instanceof ProjectMapStopUnconfirmedError);
19101
19150
  async function inOrder(tasks, take, signal, sizes) {
19102
19151
  const stopping = new AbortController();
@@ -19265,9 +19314,9 @@ var TypeScriptMapAnalyzer = class {
19265
19314
  first = void 0;
19266
19315
  validateMapAnalysis(analysis, input);
19267
19316
  if (!analysis.requiredFiles.length) return analysis;
19268
- const required2 = analysis.requiredFiles.map((path19) => {
19269
- const entry = byPath.get(path19);
19270
- if (!entry || Object.hasOwn(texts, path19))
19317
+ const required2 = analysis.requiredFiles.map((path20) => {
19318
+ const entry = byPath.get(path20);
19319
+ if (!entry || Object.hasOwn(texts, path20))
19271
19320
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
19272
19321
  return entry;
19273
19322
  });
@@ -19387,17 +19436,17 @@ var MAP_LANGUAGES = Object.freeze([
19387
19436
  ]);
19388
19437
  var mapAnalyzerSuite = (languages) => languages.map((language) => language.id).sort().join("+");
19389
19438
  var PROJECT_MAP_ANALYZER = mapAnalyzerSuite(MAP_LANGUAGES);
19390
- var mapCodePath = (path19) => MAP_LANGUAGES.some((language) => language.claims(path19));
19391
- var languageOf = (path19) => MAP_LANGUAGES.find((language) => language.claims(path19));
19392
- var mapReadsRequests = (path19) => languageOf(path19)?.readsRequests === true;
19393
- var mapLanguageOf = (path19) => languageOf(path19)?.id;
19439
+ var mapCodePath = (path20) => MAP_LANGUAGES.some((language) => language.claims(path20));
19440
+ var languageOf = (path20) => MAP_LANGUAGES.find((language) => language.claims(path20));
19441
+ var mapReadsRequests = (path20) => languageOf(path20)?.readsRequests === true;
19442
+ var mapLanguageOf = (path20) => languageOf(path20)?.id;
19394
19443
  var npmPackage = (specifier) => {
19395
19444
  if (specifier.startsWith("node:")) return "node:*";
19396
19445
  const parts = specifier.split("/");
19397
19446
  return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0] ?? specifier;
19398
19447
  };
19399
19448
  var mapExternalImport = (sourcePath, specifier) => languageOf(sourcePath)?.importName?.(specifier) ?? npmPackage(specifier);
19400
- var mapImportTarget = (path19) => languageOf(path19)?.importTarget?.(path19) ?? path19;
19449
+ var mapImportTarget = (path20) => languageOf(path20)?.importTarget?.(path20) ?? path20;
19401
19450
 
19402
19451
  // src/project-map-view.ts
19403
19452
  var MAP_VIEW_FORMAT = "PROJECT_MAP_VIEW_V1";
@@ -19437,10 +19486,10 @@ var notFound = () => {
19437
19486
  };
19438
19487
  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";
19439
19488
  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.`;
19440
- var within = (path19, directory) => directory === "." || path19.startsWith(`${directory}/`);
19441
- var parentDirectory = (path19) => {
19442
- const slash = path19.lastIndexOf("/");
19443
- return slash < 0 ? "." : path19.slice(0, slash);
19489
+ var within = (path20, directory) => directory === "." || path20.startsWith(`${directory}/`);
19490
+ var parentDirectory = (path20) => {
19491
+ const slash = path20.lastIndexOf("/");
19492
+ return slash < 0 ? "." : path20.slice(0, slash);
19444
19493
  };
19445
19494
  var compareText2 = (left, right) => left < right ? -1 : left > right ? 1 : 0;
19446
19495
  var byCount = ([leftName, left], [rightName, right]) => right - left || compareText2(leftName, rightName);
@@ -19514,7 +19563,7 @@ function pageBlocks(view, head, whole, offset, budget) {
19514
19563
  if (offset === blocks.length) return materialize(0);
19515
19564
  return mapQueryPage(blocks.length - offset, materialize, (page) => page, budget);
19516
19565
  }
19517
- var inModule = (path19, module) => module.direct ? parentDirectory(path19) === module.directory : within(path19, module.directory);
19566
+ var inModule = (path20, module) => module.direct ? parentDirectory(path20) === module.directory : within(path20, module.directory);
19518
19567
  var moduleLabel = (module) => module.direct ? `${module.directory === "." ? "" : `${module.directory}/`}* (files directly here)` : `${module.directory}/`;
19519
19568
  function childModules(module, files) {
19520
19569
  if (module.direct) return [];
@@ -19569,25 +19618,12 @@ function mapProjectModules(entries) {
19569
19618
  (entry) => entry.state === "TEXT" && mapCodePath(entry.path) && !mapTestPath(entry.path)
19570
19619
  ).map((entry) => entry.path)
19571
19620
  );
19572
- return (path19) => {
19573
- if (mapTestPath(path19)) return void 0;
19574
- const module = modules.find((candidate) => inModule(path19, candidate));
19621
+ return (path20) => {
19622
+ if (mapTestPath(path20)) return void 0;
19623
+ const module = modules.find((candidate) => inModule(path20, candidate));
19575
19624
  return module && moduleLabel(module);
19576
19625
  };
19577
19626
  }
19578
- function loadImports(store, version2) {
19579
- return store.database.prepare(`SELECT r.path AS source, t.path AS target,
19580
- json_extract(r.relation_json, '$.target') AS specifier, count(*) AS count
19581
- FROM project_map_relations r NOT INDEXED
19582
- ${MAP_RELATION_TARGET_JOIN}
19583
- WHERE r.version_ref = ? AND json_extract(r.relation_json, '$.kind') IN ('IMPORTS', 'TEST_IMPORTS')
19584
- GROUP BY source, target, specifier`).all(version2).map((row) => ({
19585
- source: String(row.source),
19586
- target: row.target === null ? null : String(row.target),
19587
- specifier: String(row.specifier),
19588
- count: Number(row.count)
19589
- }));
19590
- }
19591
19627
  function loadDirectoryFacts(store, version2) {
19592
19628
  const files = /* @__PURE__ */ new Map();
19593
19629
  const declarations2 = [];
@@ -19656,7 +19692,6 @@ function loadDirectoryFacts(store, version2) {
19656
19692
  ]);
19657
19693
  }
19658
19694
  for (const list of exported.values()) list.sort((left, right) => left.start - right.start);
19659
- const imports = loadImports(store, version2);
19660
19695
  const calls = /* @__PURE__ */ new Map();
19661
19696
  for (const row of store.database.prepare(`SELECT path, count(*) AS total, sum(to_ref IS NOT NULL) AS resolved,
19662
19697
  sum(to_ref IS NULL AND json_extract(relation_json, '$.unresolvedReason')
@@ -19672,7 +19707,7 @@ function loadDirectoryFacts(store, version2) {
19672
19707
  unresolved: Number(row.total) - resolved - external
19673
19708
  });
19674
19709
  }
19675
- return { files, calls, exported, imports };
19710
+ return { files, calls, exported };
19676
19711
  }
19677
19712
  var MEMBER_NAME = /\.([A-Za-z_$][\w$]*)$/u;
19678
19713
  var memberKey = (language, name) => `${language}\0${name}`;
@@ -19683,12 +19718,12 @@ function loadMemberCalls(store, version2) {
19683
19718
  FROM project_map_relations
19684
19719
  WHERE version_ref = ? AND to_ref IS NULL AND json_extract(relation_json, '$.kind') = 'CALLS'
19685
19720
  AND json_extract(relation_json, '$.unresolvedReason') IN ('SYMBOL_NOT_RESOLVED', 'SYNTAX_ONLY')`).all(version2)) {
19686
- const path19 = String(row.path);
19721
+ const path20 = String(row.path);
19687
19722
  const target = String(row.target);
19688
19723
  const name = MEMBER_NAME.exec(target)?.[1];
19689
- const language = mapLanguageOf(path19);
19724
+ const language = mapLanguageOf(path20);
19690
19725
  if (!name || !language) continue;
19691
- const call = { from: String(row.from_ref), path: path19, line: Number(row.line), target };
19726
+ const call = { from: String(row.from_ref), path: path20, line: Number(row.line), target };
19692
19727
  const key = memberKey(language, name);
19693
19728
  const known = calls.get(key);
19694
19729
  if (known) known.push(call);
@@ -19749,10 +19784,10 @@ function loadCoverageNotes(store, version2) {
19749
19784
  if (!codes.includes(gap.code)) codes.push(gap.code);
19750
19785
  files.set(gap.path, codes);
19751
19786
  }
19752
- for (const [path19, codes] of files)
19787
+ for (const [path20, codes] of files)
19753
19788
  if (codes.length > 1 && codes.includes("NOT_IN_PARSED_CONTEXT"))
19754
19789
  files.set(
19755
- path19,
19790
+ path20,
19756
19791
  codes.filter((code) => code !== "NOT_IN_PARSED_CONTEXT")
19757
19792
  );
19758
19793
  const missing = [...notInstalled].sort();
@@ -19764,7 +19799,7 @@ function loadCoverageNotes(store, version2) {
19764
19799
  }
19765
19800
  var MapViewCache = class {
19766
19801
  facts = new VersionCache(loadDirectoryFacts);
19767
- importRows = new VersionCache(loadImports);
19802
+ importRows = new VersionCache(loadMapImports);
19768
19803
  calls = new VersionCache(loadMemberCalls);
19769
19804
  coverage = new VersionCache(loadCoverageNotes);
19770
19805
  directoryFacts(store, version2) {
@@ -19786,7 +19821,7 @@ var MapViewCache = class {
19786
19821
  this.coverage.clear();
19787
19822
  }
19788
19823
  };
19789
- function directoryView(facts, coverage, entries, input, directory, prefixes) {
19824
+ function directoryView(facts, imports, coverage, entries, input, directory, prefixes) {
19790
19825
  const showTests = input.includeTests === true || mapTestPath(`${directory}/`);
19791
19826
  const inScope = entries.filter(
19792
19827
  (entry) => within(entry.path, directory) && mapPathAllowed(entry.path, prefixes)
@@ -19797,35 +19832,34 @@ function directoryView(facts, coverage, entries, input, directory, prefixes) {
19797
19832
  const visiblePaths = new Set(visible.map((entry) => entry.path));
19798
19833
  const code = visible.filter((entry) => entry.state === "TEXT" && mapCodePath(entry.path)).map((entry) => entry.path);
19799
19834
  const modules = mapModules(directory, code);
19800
- const moduleOf = (path19) => modules.find((module) => inModule(path19, module));
19801
- const outside = (path19) => {
19802
- const parts = path19.split("/");
19835
+ const moduleOf = (path20) => modules.find((module) => inModule(path20, module));
19836
+ const outside = (path20) => {
19837
+ const parts = path20.split("/");
19803
19838
  return `${parts.slice(0, Math.min(2, parts.length - 1)).join("/") || "."}/ (outside)`;
19804
19839
  };
19805
19840
  const moduleImports = /* @__PURE__ */ new Map();
19806
19841
  const external = /* @__PURE__ */ new Map();
19807
19842
  let unresolvedLocal = 0;
19808
- for (const row of facts.imports) {
19809
- const { source, target, specifier, count } = row;
19843
+ for (const { source, target, specifier } of imports) {
19810
19844
  const from = visiblePaths.has(source) ? moduleOf(source) : void 0;
19811
19845
  if (!from) continue;
19812
19846
  if (target === null) {
19813
- if (specifier.startsWith(".") || specifier.startsWith("/")) unresolvedLocal += count;
19814
- else increment(external, mapExternalImport(source, specifier), count);
19847
+ if (specifier.startsWith(".") || specifier.startsWith("/")) unresolvedLocal++;
19848
+ else increment(external, mapExternalImport(source, specifier));
19815
19849
  continue;
19816
19850
  }
19817
19851
  if (!mapPathAllowed(target, prefixes) || !showTests && mapTestPath(target)) continue;
19818
19852
  const to = within(target, directory) ? moduleOf(target) : void 0;
19819
19853
  if (to === from) continue;
19820
19854
  const edges = moduleImports.get(moduleLabel(from)) ?? /* @__PURE__ */ new Map();
19821
- increment(edges, to ? moduleLabel(to) : outside(target), count);
19855
+ increment(edges, to ? moduleLabel(to) : outside(target));
19822
19856
  moduleImports.set(moduleLabel(from), edges);
19823
19857
  }
19824
19858
  const blocks = [];
19825
19859
  if (modules.length > 1) {
19826
19860
  const sizes = /* @__PURE__ */ new Map();
19827
- for (const path19 of code) {
19828
- const module = moduleOf(path19);
19861
+ for (const path20 of code) {
19862
+ const module = moduleOf(path20);
19829
19863
  if (module) increment(sizes, moduleLabel(module));
19830
19864
  }
19831
19865
  blocks.push(
@@ -19854,18 +19888,18 @@ function directoryView(facts, coverage, entries, input, directory, prefixes) {
19854
19888
  )}${packages.length > shown.length ? `, +${packages.length - shown.length} more` : ""}`
19855
19889
  );
19856
19890
  }
19857
- const lineCount = (path19) => {
19858
- const file2 = facts.files.get(path19);
19859
- const gaps = coverage.files.get(path19) ?? [];
19891
+ const lineCount = (path20) => {
19892
+ const file2 = facts.files.get(path20);
19893
+ const gaps = coverage.files.get(path20) ?? [];
19860
19894
  if (file2?.parsed === false) return `[not parsed${gaps.length ? `: ${gaps.join("; ")}` : ""}]`;
19861
19895
  return `${file2 ? `${file2.lines}L` : "?L"}${gaps.length ? ` [${gaps.join("; ")}]` : ""}`;
19862
19896
  };
19863
19897
  const codeDirectories = /* @__PURE__ */ new Set();
19864
- for (const path19 of code)
19865
- for (let parent = parentDirectory(path19); parent !== "." && !codeDirectories.has(parent); parent = parentDirectory(parent))
19898
+ for (const path20 of code)
19899
+ for (let parent = parentDirectory(path20); parent !== "." && !codeDirectories.has(parent); parent = parentDirectory(parent))
19866
19900
  codeDirectories.add(parent);
19867
- const groupOf = (path19) => {
19868
- let group = parentDirectory(path19);
19901
+ const groupOf = (path20) => {
19902
+ let group = parentDirectory(path20);
19869
19903
  for (let parent = group; parent !== "." && parent !== directory && !codeDirectories.has(parent); parent = parentDirectory(parent))
19870
19904
  group = parent;
19871
19905
  return group;
@@ -19897,11 +19931,11 @@ function directoryView(facts, coverage, entries, input, directory, prefixes) {
19897
19931
  ]);
19898
19932
  }
19899
19933
  const detailed = [
19900
- ...code.map((path19) => {
19901
- const declarations2 = (facts.exported.get(path19) ?? []).map(({ text: text2 }) => text2);
19934
+ ...code.map((path20) => {
19935
+ const declarations2 = (facts.exported.get(path20) ?? []).map(({ text: text2 }) => text2);
19902
19936
  return [
19903
- path19,
19904
- `${path19} ${lineCount(path19)}${declarations2.length ? `: ${declarations2.join(", ")}` : ""}`
19937
+ path20,
19938
+ `${path20} ${lineCount(path20)}${declarations2.length ? `: ${declarations2.join(", ")}` : ""}`
19905
19939
  ];
19906
19940
  }),
19907
19941
  ...listedOther.map((entry) => [
@@ -19912,7 +19946,7 @@ function directoryView(facts, coverage, entries, input, directory, prefixes) {
19912
19946
  ];
19913
19947
  const directories = /* @__PURE__ */ new Map();
19914
19948
  for (const entry of [
19915
- ...code.map((path19) => ({ path: path19, item: lineCount(path19) })),
19949
+ ...code.map((path20) => ({ path: path20, item: lineCount(path20) })),
19916
19950
  ...listedOther.map((entry2) => ({
19917
19951
  path: entry2.path,
19918
19952
  item: entry2.state === "TEXT" ? "" : `(${entry2.state})`
@@ -19940,10 +19974,10 @@ function directoryView(facts, coverage, entries, input, directory, prefixes) {
19940
19974
  );
19941
19975
  const text = visible.filter((entry) => entry.state === "TEXT").length;
19942
19976
  const resolution = /* @__PURE__ */ new Map();
19943
- for (const path19 of code) {
19944
- const counts = facts.calls.get(path19);
19977
+ for (const path20 of code) {
19978
+ const counts = facts.calls.get(path20);
19945
19979
  if (!counts) continue;
19946
- const language = facts.files.get(path19)?.language ?? "unknown";
19980
+ const language = facts.files.get(path20)?.language ?? "unknown";
19947
19981
  const total = resolution.get(language) ?? { resolved: 0, unresolved: 0, external: 0 };
19948
19982
  total.resolved += counts.resolved;
19949
19983
  total.unresolved += counts.unresolved;
@@ -19974,8 +20008,7 @@ var OUTGOING = {
19974
20008
  CALLS: "calls",
19975
20009
  REFERENCES: "uses as value",
19976
20010
  WRITES: "writes",
19977
- IMPORTS: "imports",
19978
- TEST_IMPORTS: "test imports"
20011
+ IMPORTS: "imports"
19979
20012
  };
19980
20013
  var INCOMING = {
19981
20014
  CALLS: "called by",
@@ -19985,7 +20018,6 @@ var INCOMING = {
19985
20018
  IMPLEMENTS: "implemented by",
19986
20019
  DECORATED_BY: "decorates"
19987
20020
  };
19988
- var IMPORT_KINDS = /* @__PURE__ */ new Set(["IMPORTS", "TEST_IMPORTS"]);
19989
20021
  var shows = (relation) => relation.kind === "REFERENCES" && mapMiniprogramTemplate(relation.anchor.path);
19990
20022
  var callerCoverage = (textSearch) => `Calls through dependency injection, framework routing, reflection or computed names are not mapped, so a complete view is not a complete caller list; confirm impact with project_find_references or ${textSearch}.`;
19991
20023
  var SPECIAL_METHOD = /^__\w+__$/u;
@@ -20002,8 +20034,8 @@ var DeclarationGroups = class {
20002
20034
  prefixes;
20003
20035
  showTests;
20004
20036
  memberCalls;
20005
- visible(path19) {
20006
- return mapPathAllowed(path19, this.prefixes) && (this.showTests || !mapTestPath(path19));
20037
+ visible(path20) {
20038
+ return mapPathAllowed(path20, this.prefixes) && (this.showTests || !mapTestPath(path20));
20007
20039
  }
20008
20040
  entry(object2, imported = false) {
20009
20041
  if (mapMiniprogramTemplate(object2.anchor.path)) return "(template)";
@@ -20048,11 +20080,11 @@ var DeclarationGroups = class {
20048
20080
  value.lines.push(line);
20049
20081
  aggregates.set(key, value);
20050
20082
  };
20051
- const dispatch = (arrow, label, ref2, path19, line) => {
20083
+ const dispatch = (arrow, label, ref2, path20, line) => {
20052
20084
  const other = graph.object(graph.owner(ref2));
20053
20085
  if (owned.has(other.id)) return;
20054
- if (!this.visible(path19)) {
20055
- if (mapPathAllowed(path19, this.prefixes)) omittedTests++;
20086
+ if (!this.visible(path20)) {
20087
+ if (mapPathAllowed(path20, this.prefixes)) omittedTests++;
20056
20088
  return;
20057
20089
  }
20058
20090
  add(arrow, label, other, line);
@@ -20086,7 +20118,7 @@ var DeclarationGroups = class {
20086
20118
  stops.set(key, value);
20087
20119
  if (relation.to === void 0) continue;
20088
20120
  }
20089
- if (IMPORT_KINDS.has(relation.kind) && mapIsModule(graph.object(relation.from))) continue;
20121
+ if (relation.kind === "IMPORTS" && mapIsModule(graph.object(relation.from))) continue;
20090
20122
  if (relation.to === void 0) {
20091
20123
  if (relation.kind === "DECORATED_BY")
20092
20124
  tags.push(decoratorTag(relation.target, relation.argument, relation.route));
@@ -20116,7 +20148,7 @@ var DeclarationGroups = class {
20116
20148
  else
20117
20149
  add(
20118
20150
  "\u2192",
20119
- relation.event ? `calls via ${relation.event} event` : shows(relation) ? "shows" : OUTGOING[relation.kind] ?? relation.kind.toLowerCase(),
20151
+ relation.event ? `calls via ${relation.event} event` : shows(relation) ? "shows" : relation.kind === "IMPORTS" && mapTestPath(relation.anchor.path) ? "test imports" : OUTGOING[relation.kind] ?? relation.kind.toLowerCase(),
20120
20152
  other,
20121
20153
  relation.anchor.startLine,
20122
20154
  relation.argument
@@ -20134,7 +20166,7 @@ var DeclarationGroups = class {
20134
20166
  );
20135
20167
  continue;
20136
20168
  }
20137
- if (!incoming || relation.kind === "CONTAINS" || IMPORT_KINDS.has(relation.kind)) continue;
20169
+ if (!incoming || relation.kind === "CONTAINS" || relation.kind === "IMPORTS") continue;
20138
20170
  const other = graph.object(graph.owner(relation.from));
20139
20171
  if (owned.has(other.id)) continue;
20140
20172
  if (!this.visible(relation.anchor.path)) {
@@ -20209,7 +20241,7 @@ var DeclarationGroups = class {
20209
20241
  else files2.set(call.path, [item]);
20210
20242
  }
20211
20243
  lines.push(
20212
- ` \u2190 possible callers by name: ${[...files2].map(([path19, items]) => `${path19}: ${items.join(", ")}`).join("; ")}${inTests}`
20244
+ ` \u2190 possible callers by name: ${[...files2].map(([path20, items]) => `${path20}: ${items.join(", ")}`).join("; ")}${inTests}`
20213
20245
  );
20214
20246
  } else if (possibleInTests)
20215
20247
  lines.push(` \u2190 possible callers by name: ${possibleInTests} in test files (includeTests)`);
@@ -20245,14 +20277,14 @@ var DeclarationGroups = class {
20245
20277
  return { lines, neighbors: [...new Set(neighbors)] };
20246
20278
  }
20247
20279
  };
20248
- function fileView(store, coverage, graph, input, path19, prefixes) {
20249
- const entry = store.getEntry(input.version, path19);
20250
- if (!entry || !mapPathAllowed(path19, prefixes)) return notFound();
20251
- const showTests = input.includeTests === true || mapTestPath(path19);
20252
- const module = mapCodePath(path19) ? graph.objectsAt(path19).find((object2) => mapIsModule(object2)) : mapMiniprogramTemplate(path19) ? graph.objectsAt(path19).find((object2) => mapIsModule(object2) && object2.parsing === "PARSED") : void 0;
20253
- const gaps = coverage.files.get(path19) ?? [];
20280
+ function fileView(store, coverage, graph, input, path20, prefixes) {
20281
+ const entry = store.getEntry(input.version, path20);
20282
+ if (!entry || !mapPathAllowed(path20, prefixes)) return notFound();
20283
+ const showTests = input.includeTests === true || mapTestPath(path20);
20284
+ const module = mapCodePath(path20) ? graph.objectsAt(path20).find((object2) => mapIsModule(object2)) : mapMiniprogramTemplate(path20) ? graph.objectsAt(path20).find((object2) => mapIsModule(object2) && object2.parsing === "PARSED") : void 0;
20285
+ const gaps = coverage.files.get(path20) ?? [];
20254
20286
  const head = [
20255
- `PROJECT MAP \xB7 FILE ${path19} \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`}`
20287
+ `PROJECT MAP \xB7 FILE ${path20} \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`}`
20256
20288
  ];
20257
20289
  if (!module || entry.state !== "TEXT")
20258
20290
  return pageBlocks("FILE", head, [], input.offset ?? 0, input.outputBudget);
@@ -20272,7 +20304,7 @@ function fileView(store, coverage, graph, input, path19, prefixes) {
20272
20304
  tags.set(relation.from, list);
20273
20305
  }
20274
20306
  const describe3 = (object2) => [
20275
- `${object2.name} ${mapDeclarationLabel(object2)}${object2.anchor.path === path19 ? "" : ` (${object2.anchor.path})`}`,
20307
+ `${object2.name} ${mapDeclarationLabel(object2)}${object2.anchor.path === path20 ? "" : ` (${object2.anchor.path})`}`,
20276
20308
  ...tags.get(object2.id) ?? []
20277
20309
  ].join(" ");
20278
20310
  const declarations2 = [];
@@ -20287,11 +20319,11 @@ function fileView(store, coverage, graph, input, path19, prefixes) {
20287
20319
  );
20288
20320
  }
20289
20321
  const elsewhere = /* @__PURE__ */ new Map();
20290
- for (const object2 of graph.objectsAt(path19)) {
20322
+ for (const object2 of graph.objectsAt(path20)) {
20291
20323
  const parent = mapIsModule(object2) ? void 0 : graph.parent(object2.id);
20292
20324
  if (parent === void 0 || !graph.isAddressable(object2)) continue;
20293
20325
  const container = graph.object(parent);
20294
- if (mapIsModule(container) || container.anchor.path === path19) continue;
20326
+ if (mapIsModule(container) || container.anchor.path === path20) continue;
20295
20327
  const into = elsewhere.get(parent);
20296
20328
  if (into) into.push(object2);
20297
20329
  else elsewhere.set(parent, [object2]);
@@ -20305,9 +20337,9 @@ function fileView(store, coverage, graph, input, path19, prefixes) {
20305
20337
  if (declarations2.length) blocks.push(["DECLARATIONS (* exported)", ...declarations2].join("\n"));
20306
20338
  const imports = /* @__PURE__ */ new Set();
20307
20339
  const external = /* @__PURE__ */ new Set();
20308
- const fileObjects = graph.objectsAt(path19).map((object2) => object2.id);
20340
+ const fileObjects = graph.objectsAt(path20).map((object2) => object2.id);
20309
20341
  for (const relation of graph.relationsFrom(fileObjects)) {
20310
- if (!IMPORT_KINDS.has(relation.kind)) continue;
20342
+ if (relation.kind !== "IMPORTS") continue;
20311
20343
  if (relation.to === void 0) external.add(relation.target);
20312
20344
  else {
20313
20345
  const target = graph.object(relation.to).anchor.path;
@@ -20316,10 +20348,10 @@ function fileView(store, coverage, graph, input, path19, prefixes) {
20316
20348
  }
20317
20349
  const importers = /* @__PURE__ */ new Set();
20318
20350
  const testImporters = /* @__PURE__ */ new Set();
20319
- const imported = mapImportTarget(path19);
20320
- const packageModules = imported === path19 ? [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);
20351
+ const imported = mapImportTarget(path20);
20352
+ const packageModules = imported === path20 ? [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);
20321
20353
  for (const relation of graph.relationsTo(packageModules)) {
20322
- if (!IMPORT_KINDS.has(relation.kind)) continue;
20354
+ if (relation.kind !== "IMPORTS") continue;
20323
20355
  const source = relation.anchor.path;
20324
20356
  if (!mapPathAllowed(source, prefixes)) continue;
20325
20357
  (!showTests && mapTestPath(source) ? testImporters : importers).add(source);
@@ -20345,16 +20377,16 @@ function fileView(store, coverage, graph, input, path19, prefixes) {
20345
20377
  if (scope.length) blocks.push(["MODULE SCOPE (top-level statements)", ...scope].join("\n"));
20346
20378
  return pageBlocks("FILE", head, blocks, input.offset ?? 0, input.outputBudget);
20347
20379
  }
20348
- function declarationView(graph, input, path19, prefixes, memberCalls) {
20380
+ function declarationView(graph, input, path20, prefixes, memberCalls) {
20349
20381
  const requested = input.depth ?? 1;
20350
20382
  if (!Number.isSafeInteger(requested) || requested < 1 || requested > MAP_VIEW_LIMITS.directedDepth)
20351
20383
  return invalid2();
20352
20384
  const both = (input.direction ?? "BOTH") === "BOTH";
20353
20385
  const depth = both ? Math.min(requested, MAP_VIEW_LIMITS.bothDepth) : requested;
20354
20386
  const { name, line } = input;
20355
- const selected = mapSelectDeclarations(graph, path19, name, line);
20387
+ const selected = mapSelectDeclarations(graph, path20, name, line);
20356
20388
  if (!selected.length) return notFound();
20357
- const showTests = input.includeTests === true || mapTestPath(path19);
20389
+ const showTests = input.includeTests === true || mapTestPath(path20);
20358
20390
  const groups = new DeclarationGroups(graph, input, prefixes, showTests, memberCalls);
20359
20391
  const blocks = [];
20360
20392
  const seen = /* @__PURE__ */ new Set();
@@ -20402,7 +20434,7 @@ function declarationView(graph, input, path19, prefixes, memberCalls) {
20402
20434
  );
20403
20435
  }
20404
20436
  const head = [
20405
- `PROJECT MAP \xB7 DECLARATION ${path19}${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"}`,
20437
+ `PROJECT MAP \xB7 DECLARATION ${path20}${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"}`,
20406
20438
  ...truncated ? [`Expansion stopped at ${MAP_VIEW_LIMITS.declarations} declarations.`] : [],
20407
20439
  ...(input.direction ?? "BOTH") === "OUTGOING" ? [] : [callerCoverage(input.textSearch ?? DEFAULT_TEXT_SEARCH)]
20408
20440
  ];
@@ -20425,6 +20457,7 @@ function mapView(store, input, cache = new MapViewCache()) {
20425
20457
  const coverage = cache.coverageNotes(store, input.version);
20426
20458
  return entry ? fileView(store, coverage, graph, input, input.path, prefixes) : directoryView(
20427
20459
  cache.directoryFacts(store, input.version),
20460
+ cache.imports(store, input.version),
20428
20461
  coverage,
20429
20462
  store.listEntries(input.version),
20430
20463
  input,
@@ -20529,10 +20562,10 @@ var ProjectMapQuery = class {
20529
20562
  view(input, signal) {
20530
20563
  this.requireReadableMap(input.version, signal);
20531
20564
  const { offset, prefixes } = admission(input);
20532
- const path19 = normalizeProjectEvidencePath(input.path, true) || ".";
20565
+ const path20 = normalizeProjectEvidencePath(input.path, true) || ".";
20533
20566
  const view = mapView(
20534
20567
  this.store,
20535
- { ...input, path: path19, offset, allowedPathPrefixes: prefixes },
20568
+ { ...input, path: path20, offset, allowedPathPrefixes: prefixes },
20536
20569
  this.views
20537
20570
  );
20538
20571
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
@@ -20733,13 +20766,13 @@ var ProjectMapSourceReader = class _ProjectMapSourceReader {
20733
20766
  */
20734
20767
  async readAll(expected) {
20735
20768
  if (this.signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
20736
- const paths = expected.map(({ path: path19 }) => {
20737
- assertProjectEvidencePathNotSensitive(path19);
20738
- if (isProjectEvidenceTraversalExcluded(path19))
20769
+ const paths = expected.map(({ path: path20 }) => {
20770
+ assertProjectEvidencePathNotSensitive(path20);
20771
+ if (isProjectEvidenceTraversalExcluded(path20))
20739
20772
  throw new ProjectEvidenceError("PROJECT_FILE_NOT_ALLOWED", false);
20740
- return path19;
20773
+ return path20;
20741
20774
  });
20742
- const results = this.commit ? await this.commit.readAll(paths) : await concurrently(paths, (path19) => this.session.captureFile(path19));
20775
+ const results = this.commit ? await this.commit.readAll(paths) : await concurrently(paths, (path20) => this.session.captureFile(path20));
20743
20776
  for (const [index, { entry }] of results.entries()) {
20744
20777
  const wanted = expected[index];
20745
20778
  if (entry.state !== wanted?.state || entry.contentDigest !== wanted.contentDigest || entry.byteLength !== wanted.byteLength)
@@ -21462,7 +21495,7 @@ var CodeIndexStore = class {
21462
21495
  const staged = this.stageUnits(buildRef, paths, linked);
21463
21496
  const reused = linked ? this.database.prepare(`SELECT path, unit_ref FROM project_map_version_units
21464
21497
  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) })) : [];
21465
- if (reused.length !== (linked?.paths.size ?? 0) || reused.some(({ path: path19 }) => !paths.has(path19)) || staged.some(({ path: path19 }) => linked?.paths.has(path19)))
21498
+ if (reused.length !== (linked?.paths.size ?? 0) || reused.some(({ path: path20 }) => !paths.has(path20)) || staged.some(({ path: path20 }) => linked?.paths.has(path20)))
21466
21499
  throw new MapReplayConflict();
21467
21500
  const units = [...staged, ...reused].sort(
21468
21501
  (left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0
@@ -21513,7 +21546,7 @@ var CodeIndexStore = class {
21513
21546
  const member = this.database.prepare(
21514
21547
  "INSERT INTO project_map_version_units VALUES (?, ?, ?)"
21515
21548
  );
21516
- for (const { path: path19, unit } of reused) member.run(version2.version, path19, unit);
21549
+ for (const { path: path20, unit } of reused) member.run(version2.version, path20, unit);
21517
21550
  this.database.prepare("INSERT INTO project_map_coverage VALUES (?, ?)").run(version2.version, canonicalJson(coverage));
21518
21551
  }
21519
21552
  this.database.exec(`DELETE FROM project_map_publish_objects;
@@ -21568,7 +21601,7 @@ var CodeIndexStore = class {
21568
21601
  corrupt2();
21569
21602
  }
21570
21603
  if (linked) {
21571
- const unlinked = database.prepare("SELECT path FROM project_map_version_units WHERE version_ref = ?").all(linked.version).map((row) => String(row.path)).filter((path19) => !linked.paths.has(path19));
21604
+ const unlinked = database.prepare("SELECT path FROM project_map_version_units WHERE version_ref = ?").all(linked.version).map((row) => String(row.path)).filter((path20) => !linked.paths.has(path20));
21572
21605
  if (database.prepare(`SELECT 1 FROM project_map_objects gone
21573
21606
  WHERE gone.version_ref = ? AND gone.path IN (SELECT value FROM json_each(?))
21574
21607
  AND gone.entity_ref NOT IN (SELECT entity_ref FROM project_map_publish_objects)
@@ -21590,17 +21623,17 @@ var CodeIndexStore = class {
21590
21623
  const units = [];
21591
21624
  for (const row of database.prepare(`SELECT path FROM project_map_publish_objects
21592
21625
  UNION SELECT path FROM project_map_publish_relations ORDER BY path`).all()) {
21593
- const path19 = String(row.path);
21594
- const hash2 = createHash4("sha256").update(path19).update("\0");
21626
+ const path20 = String(row.path);
21627
+ const hash2 = createHash4("sha256").update(path20).update("\0");
21595
21628
  for (const [mark, statement] of [
21596
21629
  ["object", objects2],
21597
21630
  ["relation", relations],
21598
21631
  ["note", pathNotes]
21599
21632
  ])
21600
- for (const fact of statement.all(path19))
21633
+ for (const fact of statement.all(path20))
21601
21634
  for (const value of Object.values(fact))
21602
21635
  hash2.update(mark).update("\0").update(String(value)).update("\0");
21603
- units.push({ path: path19, unit: hash2.digest("hex") });
21636
+ units.push({ path: path20, unit: hash2.digest("hex") });
21604
21637
  }
21605
21638
  return units;
21606
21639
  }
@@ -21618,13 +21651,13 @@ var CodeIndexStore = class {
21618
21651
  "INSERT INTO project_map_unit_notes SELECT ?, * FROM project_map_publish_notes WHERE path = ?"
21619
21652
  );
21620
21653
  const member = database.prepare("INSERT INTO project_map_version_units VALUES (?, ?, ?)");
21621
- for (const { path: path19, unit } of units) {
21622
- if (insertUnit.run(unit, path19).changes) {
21623
- unitObjects.run(unit, path19);
21624
- unitRelations.run(unit, path19);
21625
- unitNotes.run(unit, path19);
21654
+ for (const { path: path20, unit } of units) {
21655
+ if (insertUnit.run(unit, path20).changes) {
21656
+ unitObjects.run(unit, path20);
21657
+ unitRelations.run(unit, path20);
21658
+ unitNotes.run(unit, path20);
21626
21659
  }
21627
- member.run(version2, path19, unit);
21660
+ member.run(version2, path20, unit);
21628
21661
  }
21629
21662
  }
21630
21663
  /**
@@ -21886,19 +21919,19 @@ function replayableContexts(parent, digests, claims) {
21886
21919
  const { analysis, paths } = parent.shell(ref);
21887
21920
  const files = /* @__PURE__ */ new Set([...codeFiles(context, analysis.parsedFiles, claims), ...paths ?? []]);
21888
21921
  factFiles.set(ref, files);
21889
- for (const path19 of files) {
21890
- const refs = sharing.get(path19) ?? /* @__PURE__ */ new Set();
21922
+ for (const path20 of files) {
21923
+ const refs = sharing.get(path20) ?? /* @__PURE__ */ new Set();
21891
21924
  refs.add(ref);
21892
- sharing.set(path19, refs);
21925
+ sharing.set(path20, refs);
21893
21926
  }
21894
21927
  if (!paths || !contextFiles(context).every(
21895
- (path19) => digests.get(path19) !== void 0 && digests.get(path19) === parent.entries.get(path19)
21928
+ (path20) => digests.get(path20) !== void 0 && digests.get(path20) === parent.entries.get(path20)
21896
21929
  ))
21897
21930
  analyzed.add(ref);
21898
21931
  }
21899
21932
  for (const ref of analyzed)
21900
- for (const path19 of factFiles.get(ref) ?? [])
21901
- for (const other of sharing.get(path19) ?? []) analyzed.add(other);
21933
+ for (const path20 of factFiles.get(ref) ?? [])
21934
+ for (const other of sharing.get(path20) ?? []) analyzed.add(other);
21902
21935
  const replayable = new Set([...parent.contexts.keys()].filter((ref) => !analyzed.has(ref)));
21903
21936
  return { replayable, sharing, factFiles };
21904
21937
  }
@@ -21930,8 +21963,8 @@ var ProjectMapAnalyzer = class {
21930
21963
  languages;
21931
21964
  observe;
21932
21965
  id;
21933
- claims(path19) {
21934
- return this.languages.some((language) => language.claims(path19));
21966
+ claims(path20) {
21967
+ return this.languages.some((language) => language.claims(path20));
21935
21968
  }
21936
21969
  // A context holds one language's code, so its requests are that language's.
21937
21970
  async references(input, references, signal, until) {
@@ -21940,8 +21973,8 @@ var ProjectMapAnalyzer = class {
21940
21973
  return language?.references ? language.references(input, references, signal, this.observe, until) : { pages: references.map(() => null), requiredFiles: [] };
21941
21974
  }
21942
21975
  // A context's compiler diagnostics, undefined for a language without a compiler to ask.
21943
- diagnostics(input, path19, signal) {
21944
- return this.languages.find((language) => language.claims(path19))?.diagnostics?.(input, signal, this.observe);
21976
+ diagnostics(input, path20, signal) {
21977
+ return this.languages.find((language) => language.claims(path20))?.diagnostics?.(input, signal, this.observe);
21945
21978
  }
21946
21979
  async analyze(reader, entries, installed, signal, consume, parent) {
21947
21980
  const result = {
@@ -21965,7 +21998,7 @@ var ProjectMapAnalyzer = class {
21965
21998
  const digests = /* @__PURE__ */ new Map();
21966
21999
  for (const entry of entries)
21967
22000
  if (entry.contentDigest) digests.set(entry.path, entry.contentDigest);
21968
- const claims = (path19) => this.claims(path19);
22001
+ const claims = (path20) => this.claims(path20);
21969
22002
  const { replayable, sharing, factFiles } = parent ? replayableContexts(parent, digests, claims) : {
21970
22003
  replayable: /* @__PURE__ */ new Set(),
21971
22004
  sharing: /* @__PURE__ */ new Map(),
@@ -21977,7 +22010,7 @@ var ProjectMapAnalyzer = class {
21977
22010
  const linked = /* @__PURE__ */ new Set();
21978
22011
  const analyzedFiles = /* @__PURE__ */ new Set();
21979
22012
  const stagedPaths = /* @__PURE__ */ new Set();
21980
- const requestDigest = (request, files2) => digestValue({ request, files: files2.map((path19) => [path19, digests.get(path19) ?? null]) });
22013
+ const requestDigest = (request, files2) => digestValue({ request, files: files2.map((path20) => [path20, digests.get(path20) ?? null]) });
21981
22014
  const replaysDigest = (contextRef2, digest) => parent !== void 0 && replayable.has(contextRef2) && parent.contexts.get(contextRef2)?.requestDigest === digest;
21982
22015
  const replays = (contextRef2, request, files2) => replaysDigest(contextRef2, requestDigest(request, files2));
21983
22016
  const reuse = (contextRef2, request, files2) => {
@@ -22018,7 +22051,7 @@ var ProjectMapAnalyzer = class {
22018
22051
  const ref = analysis.contexts[0]?.ref ?? "";
22019
22052
  if (options?.linked?.length) {
22020
22053
  if (!parent || analysis.contexts.length !== 1) return invalidParent();
22021
- for (const path19 of options.linked) linked.add(path19);
22054
+ for (const path20 of options.linked) linked.add(path20);
22022
22055
  this.observe?.({
22023
22056
  operation: "LINK",
22024
22057
  phase: "FINISHED",
@@ -22045,7 +22078,7 @@ var ProjectMapAnalyzer = class {
22045
22078
  });
22046
22079
  for (const file2 of analysis.parsedFiles) parsed.add(file2);
22047
22080
  const staged = factPaths(analysis);
22048
- for (const path19 of staged) stagedPaths.add(path19);
22081
+ for (const path20 of staged) stagedPaths.add(path20);
22049
22082
  for (const context of analysis.contexts) {
22050
22083
  for (const file2 of context.configurationFiles) configurationInputs.add(file2);
22051
22084
  if (!replayed.has(context.ref))
@@ -22076,7 +22109,7 @@ var ProjectMapAnalyzer = class {
22076
22109
  reuse,
22077
22110
  replays,
22078
22111
  previous,
22079
- configuration: (path19) => configurationInputs.add(path19),
22112
+ configuration: (path20) => configurationInputs.add(path20),
22080
22113
  observe: this.observe
22081
22114
  },
22082
22115
  signal
@@ -22113,12 +22146,12 @@ var ProjectMapAnalyzer = class {
22113
22146
  if (files.objects.length) accept(files);
22114
22147
  if (parent && (replayed.size || linked.size)) {
22115
22148
  for (const ref of replayed.keys())
22116
- for (const path19 of factFiles.get(ref) ?? invalidParent())
22117
- if (analyzedFiles.has(path19) || [...sharing.get(path19) ?? []].some((other) => !replayed.has(other)))
22149
+ for (const path20 of factFiles.get(ref) ?? invalidParent())
22150
+ if (analyzedFiles.has(path20) || [...sharing.get(path20) ?? []].some((other) => !replayed.has(other)))
22118
22151
  throw new MapReplayConflict();
22119
- for (const paths of replayed.values()) for (const path19 of paths) linked.add(path19);
22120
- for (const path19 of linked)
22121
- if (analyzedFiles.has(path19) || stagedPaths.has(path19)) throw new MapReplayConflict();
22152
+ for (const paths of replayed.values()) for (const path20 of paths) linked.add(path20);
22153
+ for (const path20 of linked)
22154
+ if (analyzedFiles.has(path20) || stagedPaths.has(path20)) throw new MapReplayConflict();
22122
22155
  parent.link([...linked]);
22123
22156
  }
22124
22157
  result.parsedFiles = [...parsed].sort();
@@ -22155,12 +22188,12 @@ var ProjectMapReferenceQuery = class {
22155
22188
  return source;
22156
22189
  }
22157
22190
  // The compiler contexts a file is in.
22158
- contexts(version2, path19) {
22191
+ contexts(version2, path20) {
22159
22192
  return this.store.database.prepare(`SELECT DISTINCT c.context_ref, c.context_json
22160
22193
  FROM project_map_contexts c, json_each(c.context_json, '$.inputFiles') f
22161
22194
  WHERE c.version_ref = ? AND f.value = ?
22162
22195
  AND json_extract(c.context_json, '$.mode') != 'SYNTAX_ONLY'
22163
- ORDER BY c.context_ref`).all(version2, path19).map((value) => MapContextSchema.parse(JSON.parse(String(value.context_json))));
22196
+ ORDER BY c.context_ref`).all(version2, path20).map((value) => MapContextSchema.parse(JSON.parse(String(value.context_json))));
22164
22197
  }
22165
22198
  // A context's sources, and the request for its compile.
22166
22199
  async open(version2, source, context, signal) {
@@ -22198,7 +22231,7 @@ var ProjectMapReferenceQuery = class {
22198
22231
  /** The configurations of the contexts a version's files are in. */
22199
22232
  contextConfigurations(version2, paths) {
22200
22233
  return paths.flatMap(
22201
- (path19) => this.contexts(version2, path19).flatMap((context) => context.configPath ?? [])
22234
+ (path20) => this.contexts(version2, path20).flatMap((context) => context.configPath ?? [])
22202
22235
  );
22203
22236
  }
22204
22237
  /**
@@ -22224,9 +22257,9 @@ var ProjectMapReferenceQuery = class {
22224
22257
  unchecked.push(configPath);
22225
22258
  continue;
22226
22259
  }
22227
- const [path19] = context.rootFiles ?? context.inputFiles;
22260
+ const [path20] = context.rootFiles ?? context.inputFiles;
22228
22261
  const { reader, request } = await this.open(input.version, source, context, signal);
22229
- const result = path19 === void 0 ? void 0 : await this.analyzer.diagnostics(request, path19, signal);
22262
+ const result = path20 === void 0 ? void 0 : await this.analyzer.diagnostics(request, path20, signal);
22230
22263
  await reader.assertStable();
22231
22264
  if (!result) continue;
22232
22265
  if (result.requiredFiles.length)
@@ -22260,9 +22293,9 @@ var ProjectMapReferenceQuery = class {
22260
22293
  const compiles = /* @__PURE__ */ new Map();
22261
22294
  for (const ref of input.refs) {
22262
22295
  const object2 = requireMapObject(this.store, input.version, { entityRef: ref }, ["."]);
22263
- const path19 = object2.anchor.path;
22264
- const contexts = contextsOf.get(path19) ?? this.contexts(input.version, path19);
22265
- contextsOf.set(path19, contexts);
22296
+ const path20 = object2.anchor.path;
22297
+ const contexts = contextsOf.get(path20) ?? this.contexts(input.version, path20);
22298
+ contextsOf.set(path20, contexts);
22266
22299
  const readable = object2.symbolStart === void 0 ? [] : contexts;
22267
22300
  found.set(ref, {
22268
22301
  uses: [],
@@ -22326,16 +22359,31 @@ var ProjectMapReferenceQuery = class {
22326
22359
  );
22327
22360
  if (!prefixes.length || prefixes.length > 64)
22328
22361
  throw new ProjectEvidenceError("PROJECT_READ_INPUT_INVALID", false);
22329
- const selection = mapQuerySelection(input, MapReferenceKindSchema.options);
22330
- const query = { path: selection.path, kinds: [...selection.kinds] };
22331
- const object2 = requireMapObject(this.store, input.version, input, prefixes);
22362
+ const { path: path20, name, line, entityRef, locator } = input;
22363
+ if (path20 === void 0 !== (name === void 0) || line !== void 0 && name === void 0)
22364
+ throw new ProjectEvidenceError("PROJECT_READ_INPUT_INVALID", false);
22365
+ const selection = mapQuerySelection(
22366
+ { path: input.within, kinds: input.kinds },
22367
+ MapReferenceKindSchema.options
22368
+ );
22369
+ const query = { within: selection.path, kinds: [...selection.kinds] };
22370
+ const object2 = requireMapObject(
22371
+ this.store,
22372
+ input.version,
22373
+ {
22374
+ entityRef,
22375
+ locator,
22376
+ symbol: path20 !== void 0 && name !== void 0 ? { path: path20, name, ...line === void 0 ? {} : { line } } : void 0
22377
+ },
22378
+ prefixes
22379
+ );
22332
22380
  if (object2.symbolStart === void 0)
22333
22381
  throw new ProjectEvidenceError("PROJECT_MAP_REFERENCE_TARGET_UNAVAILABLE", false);
22334
22382
  const availableContexts = this.contexts(input.version, object2.anchor.path);
22335
22383
  if (!availableContexts.length)
22336
22384
  throw new ProjectEvidenceError("PROJECT_MAP_REFERENCE_CONTEXT_UNAVAILABLE", false);
22337
22385
  const contexts = availableContexts.filter(
22338
- (context2) => context2.inputFiles.some((file2) => mapQueryPathMatches(file2, query.path))
22386
+ (context2) => context2.inputFiles.some((file2) => mapQueryPathMatches(file2, query.within))
22339
22387
  );
22340
22388
  if (contexts.some((context2) => context2.inputFiles.some((file2) => !mapPathAllowed(file2, prefixes))))
22341
22389
  throw new ProjectEvidenceError("PROJECT_MAP_REFERENCE_CONTEXT_NOT_AUTHORIZED", false);
@@ -22400,7 +22448,7 @@ ${scope}`, input.cursor, 2) : [];
22400
22448
  const locations = /* @__PURE__ */ new Set();
22401
22449
  for (const reference of page.references) {
22402
22450
  const location2 = canonicalJson(reference.anchor);
22403
- if (!anchored(reference, files) || !mapPathAllowed(reference.anchor.path, prefixes) || !mapQueryPathMatches(reference.anchor.path, query.path) || !query.kinds.includes(reference.kind) || locations.has(location2))
22451
+ if (!anchored(reference, files) || !mapPathAllowed(reference.anchor.path, prefixes) || !mapQueryPathMatches(reference.anchor.path, query.within) || !query.kinds.includes(reference.kind) || locations.has(location2))
22404
22452
  throw invalidProtocol();
22405
22453
  locations.add(location2);
22406
22454
  const owner = this.owner(input.version, reference.anchor);
@@ -22574,8 +22622,8 @@ var CodeIndex = class {
22574
22622
  for (const entry of this.store.listEntries(candidate))
22575
22623
  if (entry.contentDigest) entries2.set(entry.path, entry.contentDigest);
22576
22624
  let changed = 0;
22577
- for (const [path19, digest] of digests) if (entries2.get(path19) !== digest) changed++;
22578
- for (const path19 of entries2.keys()) if (!digests.has(path19)) changed++;
22625
+ for (const [path20, digest] of digests) if (entries2.get(path20) !== digest) changed++;
22626
+ for (const path20 of entries2.keys()) if (!digests.has(path20)) changed++;
22579
22627
  if (!best || changed < best.changed) best = { version: candidate, entries: entries2, changed };
22580
22628
  }
22581
22629
  if (!best) return void 0;
@@ -22733,12 +22781,12 @@ var CodeIndex = class {
22733
22781
  };
22734
22782
 
22735
22783
  // src/project-map-change-diff.ts
22736
- import { open as open2 } from "node:fs/promises";
22737
- import path11 from "node:path";
22784
+ import { lstat as lstat3, open as open2 } from "node:fs/promises";
22785
+ import path12 from "node:path";
22738
22786
 
22739
22787
  // src/project-map-names.ts
22740
22788
  import { readFile } from "node:fs/promises";
22741
- import path10 from "node:path";
22789
+ import path11 from "node:path";
22742
22790
  var CONFIG_KEY = /^\s*(?:export\s+|-\s+)?["']?([A-Za-z_][\w.-]*)["']?\s*(?:=|:(?:\s|$))/u;
22743
22791
  var CODE_READS = [
22744
22792
  // process.env.NAME, import.meta.env.NAME
@@ -22784,7 +22832,7 @@ async function strandedNames(project, files, configuration, git2, options) {
22784
22832
  if (key) names2.add(key);
22785
22833
  for (const match of line.matchAll(PLACEHOLDER)) if (match[1]) names2.add(match[1]);
22786
22834
  } else for (const name of codeReads(line, file2.path)) names2.add(name);
22787
- const text = await readFile(path10.join(project, file2.path), "utf8").catch(() => void 0);
22835
+ const text = await readFile(path11.join(project, file2.path), "utf8").catch(() => void 0);
22788
22836
  if (text === void 0) continue;
22789
22837
  for (const name of names2)
22790
22838
  if (NAME.test(name) && !PLATFORM.test(name) && !from.has(name) && !wholeName(name).test(text))
@@ -22885,7 +22933,7 @@ async function readMapChanges(project, base, signal, options = { names: true })
22885
22933
  ...file2,
22886
22934
  baseText: (await git.run(["show", `${commit}:${file2.basePath}`], gitOptions(project, signal))).stdout.toString("utf8")
22887
22935
  };
22888
- const untracked = (await git.run(["ls-files", "--others", "--exclude-standard", "-z"], gitOptions(project, signal))).stdout.toString("utf8").split("\0").filter((path19) => path19 && !inExcludedDirectory(path19));
22936
+ const untracked = (await git.run(["ls-files", "--others", "--exclude-standard", "-z"], gitOptions(project, signal))).stdout.toString("utf8").split("\0").filter((path20) => path20 && !inExcludedDirectory(path20));
22889
22937
  for (const file2 of untracked)
22890
22938
  files.push({
22891
22939
  path: file2,
@@ -22896,7 +22944,7 @@ async function readMapChanges(project, base, signal, options = { names: true })
22896
22944
  removed: [],
22897
22945
  // git diff says which tracked files are binary; an untracked one in a language the map does
22898
22946
  // not analyze is told the way git tells it, by a NUL in its first 8000 bytes.
22899
- binary: !mapLanguageOf(file2) && await startsBinary(path11.join(project, file2))
22947
+ binary: !mapLanguageOf(file2) && await startsBinary(path12.join(project, file2))
22900
22948
  });
22901
22949
  const stranded = options.names ? await strandedNames(
22902
22950
  project,
@@ -22908,6 +22956,7 @@ async function readMapChanges(project, base, signal, options = { names: true })
22908
22956
  return { base, commit, files, quoted: parsed.quoted, stranded };
22909
22957
  }
22910
22958
  async function startsBinary(file2) {
22959
+ if (!(await lstat3(file2).catch(() => void 0))?.isFile()) return false;
22911
22960
  const handle = await open2(file2, "r").catch(() => void 0);
22912
22961
  if (!handle) return false;
22913
22962
  try {
@@ -22996,7 +23045,7 @@ function mapPathNow(files) {
22996
23045
  (file2) => file2.basePath !== void 0 && file2.status !== "DELETED" ? [[file2.basePath, file2.path]] : []
22997
23046
  )
22998
23047
  );
22999
- return (path19) => moved.get(path19) ?? path19;
23048
+ return (path20) => moved.get(path20) ?? path20;
23000
23049
  }
23001
23050
  var overlaps = (lines, start, end) => lines.some(([from, to]) => from <= end && start <= to);
23002
23051
  var workingLine = (file2, line) => {
@@ -23020,17 +23069,19 @@ var NON_CODE = [
23020
23069
  [/(?:^|\/)\.env[^/]*$|\.(?:ya?ml|toml|ini|properties|conf|cfg)$/iu, "configuration"],
23021
23070
  [/\.(?:html?|jinja2?|j2|hbs|ejs|tmpl|tpl|gohtml|vue|svelte|wxml)$/iu, "template"]
23022
23071
  ];
23023
- var nonCodeKind = (path19) => NON_CODE.find(([pattern]) => pattern.test(path19))?.[1];
23072
+ var nonCodeKind = (path20) => NON_CODE.find(([pattern]) => pattern.test(path20))?.[1];
23024
23073
  var UNANALYZED = [
23025
23074
  [/\.(?:sh|bash|zsh|fish|ps1|bat|cmd)$/iu, "shell script"],
23026
- [/\.(?:css|scss|sass|less|styl|wxss|acss)$/iu, "style sheet"]
23075
+ [/\.(?:css|scss|sass|less|styl|wxss|acss)$/iu, "style sheet"],
23076
+ // Git lists a repository nested in the project by its directory, and nothing inside it.
23077
+ [/\/$/u, "nested repository"]
23027
23078
  ];
23028
23079
  var DOCUMENTATION = /\.(?:md|mdx|markdown|rst|adoc)$|(?:^|\/)(?:LICENSE|NOTICE)[^/]*$/iu;
23029
- var unmappedKind = (path19, binary) => nonCodeKind(path19) ?? (binary ? "binary file" : DOCUMENTATION.test(path19) ? void 0 : UNANALYZED.find(([pattern]) => pattern.test(path19))?.[1] ?? "unanalyzed file");
23080
+ var unmappedKind = (path20, binary) => nonCodeKind(path20) ?? (binary ? "binary file" : DOCUMENTATION.test(path20) ? void 0 : UNANALYZED.find(([pattern]) => pattern.test(path20))?.[1] ?? "unanalyzed file");
23030
23081
 
23031
23082
  // src/project-map-changes.ts
23032
23083
  import { readFile as readFile3 } from "node:fs/promises";
23033
- import path13 from "node:path";
23084
+ import path14 from "node:path";
23034
23085
 
23035
23086
  // src/project-map-change-types.ts
23036
23087
  var LIMITS = Object.freeze({
@@ -23091,7 +23142,7 @@ var LITERAL = /(["'`])((?:\\.|(?!\1)[^\\])*)\1/gu;
23091
23142
  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;
23092
23143
  var LIMIT2 = Object.freeze({ routes: 40, clients: 5 });
23093
23144
  var ROUTE = /^(?:[A-Z]+(?:\|[A-Z]+)* +)?\/\S*$/u;
23094
- var segments = (path19) => path19.split("/").filter(Boolean).map((text) => ({ text, param: PARAM.test(text) || /[{}$<>%]/u.test(text) }));
23145
+ var segments = (path20) => path20.split("/").filter(Boolean).map((text) => ({ text, param: PARAM.test(text) || /[{}$<>%]/u.test(text) }));
23095
23146
  function mapRouteLabel(label) {
23096
23147
  const match = /^([A-Z]+(?:\|[A-Z]+)*) +(\S.*)$/u.exec(label);
23097
23148
  return match ? { methods: (match[1] ?? "").split("|"), path: match[2] ?? "" } : { path: label };
@@ -23124,10 +23175,10 @@ function requestedPath(literal3, joined) {
23124
23175
  const match = /^(?:https?:\/\/[^/\s]+|(?:\$\{[^}]*\})+|@\{|redirect:|forward:)?(\/[^\s?#()"'`,;|]*)/u.exec(
23125
23176
  literal3
23126
23177
  ) ?? void 0;
23127
- const path19 = match?.[1];
23128
- if (!path19 || path19.startsWith("//") || path19.length < 3) return void 0;
23129
- const parts = segments(path19);
23130
- if (joined && path19.endsWith("/")) parts.push({ text: "*", param: true });
23178
+ const path20 = match?.[1];
23179
+ if (!path20 || path20.startsWith("//") || path20.length < 3) return void 0;
23180
+ const parts = segments(path20);
23181
+ if (joined && path20.endsWith("/")) parts.push({ text: "*", param: true });
23131
23182
  return parts;
23132
23183
  }
23133
23184
  var same = (route, requested) => route.param || !requested.param && route.text === requested.text;
@@ -23280,12 +23331,11 @@ var USED_BY = {
23280
23331
  OVERRIDES: "overridden"
23281
23332
  };
23282
23333
  var runsTarget = (relation) => CALLER_KINDS.has(relation.kind) && !relation.event;
23283
- var IMPORT_KINDS2 = /* @__PURE__ */ new Set(["IMPORTS", "TEST_IMPORTS"]);
23284
- var changeUnits = (graph, path19) => mapMiniprogramTemplate(path19) ? graph.objectsAt(path19).filter((object2) => mapIsModule(object2) && object2.parsing === "PARSED") : graph.declarationsAt(path19);
23285
- function changedUnits(graph, path19, lines) {
23334
+ var changeUnits = (graph, path20) => mapMiniprogramTemplate(path20) ? graph.objectsAt(path20).filter((object2) => mapIsModule(object2) && object2.parsing === "PARSED") : graph.declarationsAt(path20);
23335
+ function changedUnits(graph, path20, lines) {
23286
23336
  const refs = /* @__PURE__ */ new Set();
23287
23337
  let topLevel = false;
23288
- const inFile = changeUnits(graph, path19);
23338
+ const inFile = changeUnits(graph, path20);
23289
23339
  for (const [from, to] of lines) {
23290
23340
  const containing = inFile.filter(
23291
23341
  (object2) => object2.anchor.startLine <= to && from <= object2.anchor.endLine
@@ -23799,12 +23849,12 @@ var Tracer = class {
23799
23849
  this.mentions.set(route, (this.mentions.get(route) ?? /* @__PURE__ */ new Set()).add(file2));
23800
23850
  }
23801
23851
  /** A related test file; the closest relation (lowest rank) explains it. */
23802
- test(path19, name, why, rank2) {
23803
- if (!mapRunnableTest(path19)) return;
23804
- const known = this.tests.get(path19) ?? { names: /* @__PURE__ */ new Set(), why, rank: rank2 };
23852
+ test(path20, name, why, rank2) {
23853
+ if (!mapRunnableTest(path20)) return;
23854
+ const known = this.tests.get(path20) ?? { names: /* @__PURE__ */ new Set(), why, rank: rank2 };
23805
23855
  if (rank2 < known.rank) Object.assign(known, { why, rank: rank2 });
23806
23856
  if (name && !name.startsWith("<")) known.names.add(name);
23807
- this.tests.set(path19, known);
23857
+ this.tests.set(path20, known);
23808
23858
  }
23809
23859
  };
23810
23860
  var entriesOf = /* @__PURE__ */ new WeakMap();
@@ -23853,19 +23903,19 @@ function findTestEntries(graph, ref) {
23853
23903
  }
23854
23904
 
23855
23905
  // src/project-map-change-edges.ts
23856
- var same2 = (path19) => path19;
23906
+ var same2 = (path20) => path20;
23857
23907
  var compare = (left, right) => left < right ? -1 : left > right ? 1 : 0;
23858
- function linksOf(side, path19) {
23908
+ function linksOf(side, path20) {
23859
23909
  const imports = /* @__PURE__ */ new Map();
23860
23910
  const calls = /* @__PURE__ */ new Map();
23861
- if (path19 === void 0) return { imports, calls };
23911
+ if (path20 === void 0) return { imports, calls };
23862
23912
  const { graph } = side;
23863
- for (const relation of graph.relationsFrom(graph.objectsAt(path19).map((object2) => object2.id))) {
23913
+ for (const relation of graph.relationsFrom(graph.objectsAt(path20).map((object2) => object2.id))) {
23864
23914
  const line = relation.anchor.startLine;
23865
- if (relation.to === void 0 || !side.counts(path19, line)) continue;
23866
- if (IMPORT_KINDS2.has(relation.kind)) {
23915
+ if (relation.to === void 0 || !side.counts(path20, line)) continue;
23916
+ if (relation.kind === "IMPORTS") {
23867
23917
  const target = graph.object(relation.to).anchor.path;
23868
- if (target === path19) continue;
23918
+ if (target === path20) continue;
23869
23919
  const to = side.pathNow(target);
23870
23920
  const found = imports.get(to) ?? { to, lines: [] };
23871
23921
  found.lines.push(line);
@@ -23873,7 +23923,7 @@ function linksOf(side, path19) {
23873
23923
  } else if (CALLER_KINDS.has(relation.kind)) {
23874
23924
  const ref = graph.owner(relation.to);
23875
23925
  const owner = graph.object(ref);
23876
- if (owner.anchor.path === path19 || mapIsModule(owner)) continue;
23926
+ if (owner.anchor.path === path20 || mapIsModule(owner)) continue;
23877
23927
  const to = side.pathNow(owner.anchor.path);
23878
23928
  const key = `${to}\0${graph.declarationKey(owner)}`;
23879
23929
  const found = calls.get(key) ?? { to, lines: [], ref };
@@ -23904,17 +23954,17 @@ function mapChangeLinks(store, working, base, files) {
23904
23954
  counts: always,
23905
23955
  pathOf,
23906
23956
  declaration: (file2, ref) => {
23907
- const path19 = pathOf(file2);
23908
- if (path19 === void 0) return void 0;
23909
- let keys = declared.get(path19);
23957
+ const path20 = pathOf(file2);
23958
+ if (path20 === void 0) return void 0;
23959
+ let keys = declared.get(path20);
23910
23960
  if (!keys) {
23911
23961
  keys = new Map(
23912
- changeUnits(baseGraph, path19).map((object2) => [
23962
+ changeUnits(baseGraph, path20).map((object2) => [
23913
23963
  baseGraph.declarationKey(object2),
23914
23964
  object2.id
23915
23965
  ])
23916
23966
  );
23917
- declared.set(path19, keys);
23967
+ declared.set(path20, keys);
23918
23968
  }
23919
23969
  return keys.get(graph.declarationKey(graph.object(ref)));
23920
23970
  }
@@ -23924,8 +23974,8 @@ function mapChangeLinks(store, working, base, files) {
23924
23974
  before = {
23925
23975
  graph,
23926
23976
  pathNow: same2,
23927
- counts: (path19, line) => {
23928
- const file2 = changedAt.get(path19);
23977
+ counts: (path20, line) => {
23978
+ const file2 = changedAt.get(path20);
23929
23979
  return !file2 || !overlaps(file2.lines, line, line);
23930
23980
  },
23931
23981
  pathOf: (file2) => file2.status === "ADDED" ? void 0 : file2.path,
@@ -23959,9 +24009,9 @@ function callersOf(side, ref) {
23959
24009
  const home = side.graph.object(ref).anchor.path;
23960
24010
  const files = /* @__PURE__ */ new Set();
23961
24011
  for (const relation of side.graph.relationsTo([ref])) {
23962
- const path19 = relation.anchor.path;
23963
- if (!CALLER_KINDS.has(relation.kind) || path19 === home || mapTestPath(path19)) continue;
23964
- if (side.counts(path19, relation.anchor.startLine)) files.add(side.pathNow(path19));
24012
+ const path20 = relation.anchor.path;
24013
+ if (!CALLER_KINDS.has(relation.kind) || path20 === home || mapTestPath(path20)) continue;
24014
+ if (side.counts(path20, relation.anchor.startLine)) files.add(side.pathNow(path20));
23965
24015
  }
23966
24016
  return [...files].sort();
23967
24017
  }
@@ -24023,7 +24073,7 @@ function mapChangeEdges(links) {
24023
24073
 
24024
24074
  // src/project-map-change-tests.ts
24025
24075
  import { readFile as readFile2 } from "node:fs/promises";
24026
- import path12 from "node:path";
24076
+ import path13 from "node:path";
24027
24077
 
24028
24078
  // src/project-map-route-paths.ts
24029
24079
  import {
@@ -24078,7 +24128,7 @@ var MAP_PATH_PARAMETER = "{}";
24078
24128
  async function existingTestsChanged(before, after, file2, project) {
24079
24129
  if (!file2.basePath || file2.baseText === void 0) return [];
24080
24130
  const baseLines = file2.baseText.split("\n");
24081
- const workingLines = file2.status !== "DELETED" && project ? (await readFile2(path12.join(project, file2.path), "utf8").catch(() => void 0))?.split(
24131
+ const workingLines = file2.status !== "DELETED" && project ? (await readFile2(path13.join(project, file2.path), "utf8").catch(() => void 0))?.split(
24082
24132
  "\n"
24083
24133
  ) ?? [] : [];
24084
24134
  const body = (lines, object2) => lines.slice(object2.anchor.startLine - 1, object2.anchor.endLine).map((line) => line.trimEnd());
@@ -24106,7 +24156,7 @@ function importerTests(graph, objects2, tracer, importers) {
24106
24156
  const unread = modules.filter((module) => !importers.has(module));
24107
24157
  for (const module of unread) importers.set(module, []);
24108
24158
  for (const relation of graph.relationsTo(unread)) {
24109
- if (!IMPORT_KINDS2.has(relation.kind) || !relation.to) continue;
24159
+ if (relation.kind !== "IMPORTS" || !relation.to) continue;
24110
24160
  const importer = graph.object(relation.from);
24111
24161
  importers.get(relation.to)?.push({
24112
24162
  path: relation.anchor.path,
@@ -24115,10 +24165,10 @@ function importerTests(graph, objects2, tracer, importers) {
24115
24165
  }
24116
24166
  const next = [];
24117
24167
  for (const imported of modules)
24118
- for (const { path: path19, module } of importers.get(imported) ?? [])
24119
- if (mapTestPath(path19))
24168
+ for (const { path: path20, module } of importers.get(imported) ?? [])
24169
+ if (mapTestPath(path20))
24120
24170
  tracer.test(
24121
- path19,
24171
+ path20,
24122
24172
  void 0,
24123
24173
  hop ? "imports a changed file indirectly" : "imports a changed file",
24124
24174
  hop ? 4 : 2
@@ -24143,17 +24193,17 @@ function supportTests(store, version2, tracer) {
24143
24193
  function mapPathIndex(paths) {
24144
24194
  const testsIn = /* @__PURE__ */ new Map();
24145
24195
  const under = /* @__PURE__ */ new Map();
24146
- const add = (map2, key, path19) => {
24196
+ const add = (map2, key, path20) => {
24147
24197
  const found = map2.get(key);
24148
- if (found) found.push(path19);
24149
- else map2.set(key, [path19]);
24198
+ if (found) found.push(path20);
24199
+ else map2.set(key, [path20]);
24150
24200
  };
24151
- for (const path19 of paths) {
24152
- const slash = path19.lastIndexOf("/");
24153
- const directory = slash < 0 ? "" : path19.slice(0, slash + 1);
24154
- if (mapTestPath(path19)) add(testsIn, directory, path19);
24201
+ for (const path20 of paths) {
24202
+ const slash = path20.lastIndexOf("/");
24203
+ const directory = slash < 0 ? "" : path20.slice(0, slash + 1);
24204
+ if (mapTestPath(path20)) add(testsIn, directory, path20);
24155
24205
  const name = directory.slice(directory.lastIndexOf("/", directory.length - 2) + 1, -1);
24156
- if (name) add(under, name, path19);
24206
+ if (name) add(under, name, path20);
24157
24207
  }
24158
24208
  return { testsIn, under };
24159
24209
  }
@@ -24246,7 +24296,7 @@ var RouteRequests = class {
24246
24296
  }
24247
24297
  const batch = this.candidates.slice(at, at + READ_BATCH);
24248
24298
  const texts = await Promise.all(
24249
- batch.map((file2) => readFile2(path12.join(project, file2), "utf8").catch(() => void 0))
24299
+ batch.map((file2) => readFile2(path13.join(project, file2), "utf8").catch(() => void 0))
24250
24300
  );
24251
24301
  for (const [index, text] of texts.entries())
24252
24302
  if (text !== void 0) yield [batch[index], text];
@@ -24287,9 +24337,9 @@ async function routeTests(requests, entries, tracer) {
24287
24337
  }
24288
24338
  return requested;
24289
24339
  }
24290
- function wholePath(text, path19) {
24291
- for (let at = text.indexOf(path19); at >= 0; at = text.indexOf(path19, at + 1))
24292
- if (!/[\w./-]/u.test(text[at + path19.length] ?? "")) return true;
24340
+ function wholePath(text, path20) {
24341
+ for (let at = text.indexOf(path20); at >= 0; at = text.indexOf(path20, at + 1))
24342
+ if (!/[\w./-]/u.test(text[at + path20.length] ?? "")) return true;
24293
24343
  return false;
24294
24344
  }
24295
24345
  async function unworkedRequests(requests, tracer, reaching) {
@@ -24310,14 +24360,14 @@ async function unworkedRequests(requests, tracer, reaching) {
24310
24360
  }
24311
24361
  }
24312
24362
  }
24313
- function sameDirectoryTests(paths, path19, tracer) {
24314
- const slash = path19.lastIndexOf("/");
24315
- for (const candidate of paths.testsIn.get(slash < 0 ? "" : path19.slice(0, slash + 1)) ?? [])
24363
+ function sameDirectoryTests(paths, path20, tracer) {
24364
+ const slash = path20.lastIndexOf("/");
24365
+ for (const candidate of paths.testsIn.get(slash < 0 ? "" : path20.slice(0, slash + 1)) ?? [])
24316
24366
  tracer.test(candidate, void 0, "in the same directory", 3);
24317
24367
  }
24318
- function routesIn(graph, path19) {
24368
+ function routesIn(graph, path20) {
24319
24369
  const routes = /* @__PURE__ */ new Set();
24320
- for (const relation of graph.relationsFrom(graph.objectsAt(path19).map((object2) => object2.id))) {
24370
+ for (const relation of graph.relationsFrom(graph.objectsAt(path20).map((object2) => object2.id))) {
24321
24371
  const route = mapRegisteredRoute(relation);
24322
24372
  if (route) routes.add(route);
24323
24373
  }
@@ -24355,9 +24405,9 @@ async function mapRemovedImpact(input) {
24355
24405
  new MapShapeUses(before, input.shapes, input.until)
24356
24406
  );
24357
24407
  const changedIn = changedInBase(changes.files);
24358
- const pathNow = (path19) => {
24359
- const file2 = changedIn.get(path19);
24360
- return file2?.status === "DELETED" ? void 0 : file2?.path ?? path19;
24408
+ const pathNow = (path20) => {
24409
+ const file2 = changedIn.get(path20);
24410
+ return file2?.status === "DELETED" ? void 0 : file2?.path ?? path20;
24361
24411
  };
24362
24412
  const nowAt = (anchor) => {
24363
24413
  const file2 = changedIn.get(anchor.path);
@@ -24372,11 +24422,11 @@ async function mapRemovedImpact(input) {
24372
24422
  const samePlace = (anchor, place) => anchor.path === place.path && anchor.startLine === place.startLine && anchor.endLine === place.endLine;
24373
24423
  const replaces = (now, removed2) => now.kind === removed2.kind && now.name === removed2.name;
24374
24424
  const relationsNow = /* @__PURE__ */ new Map();
24375
- const relationsIn = (path19) => {
24376
- let found = relationsNow.get(path19);
24425
+ const relationsIn = (path20) => {
24426
+ let found = relationsNow.get(path20);
24377
24427
  if (!found) {
24378
- found = graph.relationsFrom(graph.objectsAt(path19).map((object2) => object2.id));
24379
- relationsNow.set(path19, found);
24428
+ found = graph.relationsFrom(graph.objectsAt(path20).map((object2) => object2.id));
24429
+ relationsNow.set(path20, found);
24380
24430
  }
24381
24431
  return found;
24382
24432
  };
@@ -24485,13 +24535,13 @@ async function mapRemovedImpact(input) {
24485
24535
  );
24486
24536
  const lost = /* @__PURE__ */ new Map();
24487
24537
  const changedAt = changedInWorkingTree(changes.files);
24488
- for (const path19 of input.mappedPaths().filter(mapMiniprogramTemplate)) {
24489
- const template = graph.objectsAt(path19).find((object2) => mapIsModule(object2));
24538
+ for (const path20 of input.mappedPaths().filter(mapMiniprogramTemplate)) {
24539
+ const template = graph.objectsAt(path20).find((object2) => mapIsModule(object2));
24490
24540
  if (!template) continue;
24491
24541
  const broken = graph.relationsFrom(graph.scope(template.id).refs).filter((relation) => relation.to === void 0 && NAMING_KINDS.has(relation.kind));
24492
24542
  if (!broken.length) continue;
24493
- const file2 = changedAt.get(path19);
24494
- const basePath = file2 ? file2.basePath : path19;
24543
+ const file2 = changedAt.get(path20);
24544
+ const basePath = file2 ? file2.basePath : path20;
24495
24545
  const was = basePath === void 0 ? void 0 : before.objectsAt(basePath).find(mapIsModule);
24496
24546
  const links = was ? before.relationsFrom(before.scope(was.id).refs) : [];
24497
24547
  for (const relation of broken) {
@@ -24500,7 +24550,7 @@ async function mapRemovedImpact(input) {
24500
24550
  );
24501
24551
  if (earlier.some((link) => link.to === void 0)) continue;
24502
24552
  const event = miniprogramEventOf(relation.target);
24503
- const at = `${path19}:${relation.anchor.startLine}`;
24553
+ const at = `${path20}:${relation.anchor.startLine}`;
24504
24554
  if (file2 && overlaps(file2.lines, relation.anchor.startLine, relation.anchor.endLine)) {
24505
24555
  unclear.push(
24506
24556
  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`
@@ -24512,7 +24562,7 @@ async function mapRemovedImpact(input) {
24512
24562
  const object2 = before.object(reached);
24513
24563
  const name = mapIsModule(object2) ? `${object2.anchor.path} (template)${event ? `: ${event.event} event` : ""}` : `${object2.anchor.path}: ${before.qualifiedName(reached)} ${mapDeclarationLabel(object2)}`;
24514
24564
  const users = lost.get(name) ?? /* @__PURE__ */ new Set();
24515
- users.add(`${path19} (template)`);
24565
+ users.add(`${path20} (template)`);
24516
24566
  lost.set(name, users);
24517
24567
  }
24518
24568
  }
@@ -24554,15 +24604,15 @@ async function mapRemovedImpact(input) {
24554
24604
  ...removed2 ? { removed: true } : {}
24555
24605
  });
24556
24606
  }
24557
- for (const [path19, test] of beforeTracer.tests) {
24558
- const now = pathNow(path19);
24607
+ for (const [path20, test] of beforeTracer.tests) {
24608
+ const now = pathNow(path20);
24559
24609
  if (now === void 0) continue;
24560
24610
  tracer.test(now, void 0, test.why, test.rank);
24561
24611
  for (const name of test.names) tracer.test(now, name, test.why, test.rank);
24562
24612
  }
24563
24613
  for (const [area, known] of beforeTracer.areas)
24564
- for (const [path19, names] of known.tests) {
24565
- const now = pathNow(path19);
24614
+ for (const [path20, names] of known.tests) {
24615
+ const now = pathNow(path20);
24566
24616
  const place = pathNow(area);
24567
24617
  if (now !== void 0 && place !== void 0)
24568
24618
  tracer.shareArea(place, known.through, now, names);
@@ -24585,24 +24635,24 @@ async function mapRemovedImpact(input) {
24585
24635
  for (const ref of called) {
24586
24636
  const object2 = before.object(ref);
24587
24637
  if (mapIsModule(object2) || mapTestPath(object2.anchor.path) || gone2.has(ref)) continue;
24588
- const path19 = pathNow(object2.anchor.path);
24589
- if (path19 === void 0) continue;
24638
+ const path20 = pathNow(object2.anchor.path);
24639
+ if (path20 === void 0) continue;
24590
24640
  const key = before.declarationKey(object2);
24591
- const now = graph.declarationsAt(path19).find((candidate) => graph.declarationKey(candidate) === key);
24641
+ const now = graph.declarationsAt(path20).find((candidate) => graph.declarationKey(candidate) === key);
24592
24642
  if (!now) continue;
24593
24643
  const calls = tracer.callers(now.id).filter((caller) => !caller.uses);
24594
24644
  if (outsideTests(calls, graph).length || tracer.usesWithoutCalls(now.id).length) continue;
24595
24645
  if (!outsideTests(beforeTracer.callers(ref), before).length) continue;
24596
- candidates.push({ path: path19, name: before.qualifiedName(ref), now, tested: calls.length > 0 });
24646
+ candidates.push({ path: path20, name: before.qualifiedName(ref), now, tested: calls.length > 0 });
24597
24647
  }
24598
24648
  await tracer.shapes.read(candidates.map(({ now }) => now.id));
24599
24649
  const uncalled = [];
24600
24650
  const unknown2 = [];
24601
- for (const { path: path19, name, now, tested } of candidates) {
24651
+ for (const { path: path20, name, now, tested } of candidates) {
24602
24652
  if (tracer.shapes.unread.has(now.id)) unknown2.push(name);
24603
24653
  else if (!tracer.shapes.uses.get(now.id)?.some(({ owner, write }) => !write && !mapTestPath(graph.object(owner).anchor.path))) {
24604
24654
  uncalled.push(
24605
- `${path19}: ${name} ${mapDeclarationLabel(now)}${tested ? " (only tests call it now)" : ""}`
24655
+ `${path20}: ${name} ${mapDeclarationLabel(now)}${tested ? " (only tests call it now)" : ""}`
24606
24656
  );
24607
24657
  }
24608
24658
  }
@@ -24893,9 +24943,9 @@ function pathBetween(edges, from, to) {
24893
24943
  if (via.has(target)) continue;
24894
24944
  via.set(target, module);
24895
24945
  if (target === to) {
24896
- const path19 = [to];
24897
- for (let step = module; step !== from; step = via.get(step) ?? from) path19.unshift(step);
24898
- return [from, ...path19];
24946
+ const path20 = [to];
24947
+ for (let step = module; step !== from; step = via.get(step) ?? from) path20.unshift(step);
24948
+ return [from, ...path20];
24899
24949
  }
24900
24950
  next.push(target);
24901
24951
  }
@@ -24948,11 +24998,11 @@ function newModuleDependencies(store, cache, working, files, links) {
24948
24998
  );
24949
24999
  }
24950
25000
  var MANIFEST = /(?:^|\/)(?:package\.json|go\.mod|pom\.xml|build\.gradle(?:\.kts)?|pyproject\.toml|setup\.py|setup\.cfg)$/u;
24951
- var directoryOf3 = (path19) => path19.slice(0, Math.max(path19.lastIndexOf("/"), 0));
25001
+ var directoryOf3 = (path20) => path20.slice(0, Math.max(path20.lastIndexOf("/"), 0));
24952
25002
  var directoryLabel = (directory) => directory ? `${directory}/` : "./";
24953
25003
  function mapReuseImports(store, cache, working) {
24954
25004
  const roots = store.listEntries(working).filter((entry) => MANIFEST.test(entry.path)).map((entry) => directoryOf3(entry.path)).sort((left, right) => right.length - left.length);
24955
- const packageOf = (path19) => roots.find((root) => !root || path19.startsWith(`${root}/`)) ?? "";
25005
+ const packageOf = (path20) => roots.find((root) => !root || path20.startsWith(`${root}/`)) ?? "";
24956
25006
  const directories = /* @__PURE__ */ new Map();
24957
25007
  const packages = /* @__PURE__ */ new Map();
24958
25008
  const files = /* @__PURE__ */ new Set();
@@ -24985,21 +25035,21 @@ function mapReuseImports(store, cache, working) {
24985
25035
  };
24986
25036
  const graph = new MapViewGraph(store, working);
24987
25037
  const usedFrom = /* @__PURE__ */ new Map();
24988
- const used = (path19) => {
24989
- let found = usedFrom.get(path19);
25038
+ const used = (path20) => {
25039
+ let found = usedFrom.get(path20);
24990
25040
  if (found === void 0) {
24991
- found = graph.relationsTo(graph.objectsAt(path19).map((object2) => object2.id)).some((relation) => graph.object(relation.from).anchor.path !== path19);
24992
- usedFrom.set(path19, found);
25041
+ found = graph.relationsTo(graph.objectsAt(path20).map((object2) => object2.id)).some((relation) => graph.object(relation.from).anchor.path !== path20);
25042
+ usedFrom.set(path20, found);
24993
25043
  }
24994
25044
  return found;
24995
25045
  };
24996
- return (path19, existing) => {
24997
- const added = [directoryOf3(path19), packageOf(path19)];
25046
+ return (path20, existing) => {
25047
+ const added = [directoryOf3(path20), packageOf(path20)];
24998
25048
  const old = [directoryOf3(existing), packageOf(existing)];
24999
25049
  const ahead = use("NEW", added, old);
25000
- if (files.has(`${path19}\0${existing}`)) return ahead;
25001
- if (files.has(`${existing}\0${path19}`))
25002
- return { ...use("EXISTING", old, added), from: existing, to: path19 };
25050
+ if (files.has(`${path20}\0${existing}`)) return ahead;
25051
+ if (files.has(`${existing}\0${path20}`))
25052
+ return { ...use("EXISTING", old, added), from: existing, to: path20 };
25003
25053
  const usable = used(existing);
25004
25054
  if (usable && ahead.imported) return ahead;
25005
25055
  if (directories.get(old[0])?.has(added[0])) return use("EXISTING", old, added);
@@ -25021,9 +25071,9 @@ var KEYWORDS = new Set(
25021
25071
  );
25022
25072
  var ROWS = `SELECT entity_ref AS id, path, name, kind, object_json AS object
25023
25073
  FROM project_map_objects WHERE version_ref = ? AND kind <> 'PROPERTY'`;
25024
- function rows(store, version2, path19) {
25025
- const statement = store.database.prepare(path19 === void 0 ? ROWS : `${ROWS} AND path = ?`);
25026
- return (path19 === void 0 ? statement.all(version2) : statement.all(version2, path19)).map((row) => {
25074
+ function rows(store, version2, path20) {
25075
+ const statement = store.database.prepare(path20 === void 0 ? ROWS : `${ROWS} AND path = ?`);
25076
+ return (path20 === void 0 ? statement.all(version2) : statement.all(version2, path20)).map((row) => {
25027
25077
  const { anchor } = JSON.parse(String(row.object));
25028
25078
  return {
25029
25079
  id: String(row.id),
@@ -25065,10 +25115,10 @@ function lineWords(line) {
25065
25115
  var within2 = (lines, declaration) => lines.some(([from, to]) => from <= declaration.startLine && declaration.endLine <= to);
25066
25116
  var copyText = (code) => code.replace(/^export\s+(?:default\s+)?/u, "").replace(/\s+/gu, " ").trim();
25067
25117
  async function similarCode(store, working, base, files, read) {
25068
- const code = (path19) => mapCodePath(path19) && !mapTestPath(path19) && !MAP_MIGRATION_PATH.test(path19);
25118
+ const code = (path20) => mapCodePath(path20) && !mapTestPath(path20) && !MAP_MIGRATION_PATH.test(path20);
25069
25119
  const changed = files.filter((file2) => file2.status !== "DELETED" && code(file2.path));
25070
25120
  if (!changed.length) return [];
25071
- const names = (version2, path19) => new Set(declarations(rows(store, version2, path19)).map((item) => item.qualifiedName));
25121
+ const names = (version2, path20) => new Set(declarations(rows(store, version2, path20)).map((item) => item.qualifiedName));
25072
25122
  const movedOut = /* @__PURE__ */ new Set();
25073
25123
  if (base !== void 0)
25074
25124
  for (const file2 of files) {
@@ -25100,11 +25150,11 @@ async function similarCode(store, working, base, files, read) {
25100
25150
  const all = [];
25101
25151
  const shortCopies = /* @__PURE__ */ new Map();
25102
25152
  const texts = await Promise.all(
25103
- [...byPath].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(async ([path19, inFile]) => {
25153
+ [...byPath].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(async ([path20, inFile]) => {
25104
25154
  const found2 = declarations(inFile).filter(
25105
25155
  (item) => KINDS2.has(item.kind) && (long(item) ? longAdded : shortNames.has(item.qualifiedName))
25106
25156
  );
25107
- return { found: found2, text: found2.length ? await read(path19) : void 0 };
25157
+ return { found: found2, text: found2.length ? await read(path20) : void 0 };
25108
25158
  })
25109
25159
  );
25110
25160
  for (const { found: found2, text } of texts) {
@@ -25205,10 +25255,9 @@ async function similarCode(store, working, base, files, read) {
25205
25255
  }
25206
25256
 
25207
25257
  // src/project-map-changes.ts
25208
- async function mapChangeImpact(store, working, base, changes, links, shapes, until, project, tests) {
25258
+ async function mapChangeImpact(store, views, working, base, changes, links, shapes, until, project, tests) {
25209
25259
  const graph = new MapViewGraph(store, working);
25210
- const cache = new MapViewCache();
25211
- const memberCalls = cache.memberCalls(store, working);
25260
+ const memberCalls = views.memberCalls(store, working);
25212
25261
  const tracer = new Tracer(
25213
25262
  graph,
25214
25263
  memberCalls,
@@ -25238,8 +25287,8 @@ async function mapChangeImpact(store, working, base, changes, links, shapes, unt
25238
25287
  const mappedPaths = () => mapped ??= store.database.prepare("SELECT DISTINCT path FROM project_map_objects WHERE version_ref = ?").all(working).map((row) => String(row.path));
25239
25288
  let paths;
25240
25289
  const pathIndex = () => paths ??= mapPathIndex(mappedPaths());
25241
- const topLevelChanged = (path19) => {
25242
- const note = `top-level code of ${path19} changed (imports, constants or registrations)`;
25290
+ const topLevelChanged = (path20) => {
25291
+ const note = `top-level code of ${path20} changed (imports, constants or registrations)`;
25243
25292
  if (!unclear.includes(note)) unclear.push(note);
25244
25293
  };
25245
25294
  for (const file2 of changes.files) {
@@ -25350,7 +25399,7 @@ async function mapChangeImpact(store, working, base, changes, links, shapes, unt
25350
25399
  supportTests(store, working, tracer);
25351
25400
  const taken = base ? await mapRemovedImpact({
25352
25401
  store,
25353
- cache,
25402
+ cache: views,
25354
25403
  base,
25355
25404
  graph,
25356
25405
  tracer,
@@ -25360,15 +25409,15 @@ async function mapChangeImpact(store, working, base, changes, links, shapes, unt
25360
25409
  project,
25361
25410
  mappedPaths
25362
25411
  }) : void 0;
25363
- for (const path19 of taken?.topLevel ?? []) topLevelChanged(path19);
25412
+ for (const path20 of taken?.topLevel ?? []) topLevelChanged(path20);
25364
25413
  unclear.push(...taken?.unclear ?? []);
25365
25414
  return {
25366
25415
  changed,
25367
25416
  removed: taken?.removed ?? [],
25368
25417
  rewrittenTests: taken?.rewrittenTests ?? [],
25369
25418
  entries: [...tracer.entries.values()].sort(entryOrder),
25370
- tests: [...tracer.tests].map(([path19, test]) => ({
25371
- path: path19,
25419
+ tests: [...tracer.tests].map(([path20, test]) => ({
25420
+ path: path20,
25372
25421
  names: [...test.names].sort(),
25373
25422
  why: test.why,
25374
25423
  rank: test.rank
@@ -25378,7 +25427,7 @@ async function mapChangeImpact(store, working, base, changes, links, shapes, unt
25378
25427
  areas: [...tracer.areas].map(([area, known]) => ({
25379
25428
  area,
25380
25429
  through: [...known.through].sort(),
25381
- tests: [...known.tests].map(([path19, names]) => ({ path: path19, names: [...names].sort() })).sort((left, right) => right.names.length - left.names.length)
25430
+ tests: [...known.tests].map(([path20, names]) => ({ path: path20, names: [...names].sort() })).sort((left, right) => right.names.length - left.names.length)
25382
25431
  })).sort((left, right) => right.tests.length - left.tests.length),
25383
25432
  unclear: [.../* @__PURE__ */ new Set([...unclear, ...tracer.unclear])],
25384
25433
  incomplete: [
@@ -25390,7 +25439,7 @@ async function mapChangeImpact(store, working, base, changes, links, shapes, unt
25390
25439
  unmapped,
25391
25440
  removedRoutes: taken?.removedRoutes ?? [],
25392
25441
  uncalled: taken?.uncalled ?? [],
25393
- dependencies: newModuleDependencies(store, cache, working, changes.files, links.files),
25442
+ dependencies: newModuleDependencies(store, views, working, changes.files, links.files),
25394
25443
  ...untested ? { untested } : {},
25395
25444
  truncated: tracer.truncated
25396
25445
  };
@@ -25461,9 +25510,9 @@ function mapChangesData(changes, impact, edges) {
25461
25510
  return {
25462
25511
  base: changes.base,
25463
25512
  commit: changes.commit,
25464
- files: changes.files.map(({ path: path19, basePath, status }) => ({
25465
- path: path19,
25466
- ...basePath !== void 0 && basePath !== path19 ? { basePath } : {},
25513
+ files: changes.files.map(({ path: path20, basePath, status }) => ({
25514
+ path: path20,
25515
+ ...basePath !== void 0 && basePath !== path20 ? { basePath } : {},
25467
25516
  status
25468
25517
  })),
25469
25518
  tests: impact.tests,
@@ -25477,13 +25526,23 @@ function mapChangesData(changes, impact, edges) {
25477
25526
  }
25478
25527
  async function checkMapChanges(input, signal) {
25479
25528
  const { index, project, working } = input;
25529
+ const phase = input.phase ?? (() => {
25530
+ });
25531
+ const baseVersion = async (commit, then) => {
25532
+ phase("BASE");
25533
+ const version2 = await input.baseVersion(commit, signal);
25534
+ phase(then);
25535
+ return version2;
25536
+ };
25537
+ phase("DIFF");
25480
25538
  const changes = await readMapChanges(project, input.base, signal, {
25481
25539
  names: input.format !== "json"
25482
25540
  });
25483
25541
  await index.ensureIndex(working, signal);
25484
25542
  const base = changes.files.some(
25485
25543
  (file2) => file2.basePath !== void 0 && (file2.baseLines.length || file2.baseText !== void 0 || file2.status === "RENAMED")
25486
- ) ? await input.baseVersion(changes.commit, signal) : void 0;
25544
+ ) ? await baseVersion(changes.commit, "TRACE") : void 0;
25545
+ if (!base) phase("TRACE");
25487
25546
  const usesIn = (version2, source) => async (refs, until2) => {
25488
25547
  const found = await index.findUses(
25489
25548
  { version: version2, source, refs, until: until2, maxResults: MAP_REFERENCES_MAX },
@@ -25503,8 +25562,10 @@ async function checkMapChanges(input, signal) {
25503
25562
  };
25504
25563
  const until = mapShapeDeadline();
25505
25564
  const links = mapChangeLinks(index.store, working, base, changes.files);
25565
+ const views = new MapViewCache();
25506
25566
  const impact = await mapChangeImpact(
25507
25567
  index.store,
25568
+ views,
25508
25569
  working,
25509
25570
  base,
25510
25571
  changes,
@@ -25519,6 +25580,7 @@ async function checkMapChanges(input, signal) {
25519
25580
  );
25520
25581
  const data = mapChangesData(changes, impact, mapChangeEdges(links));
25521
25582
  if (input.format === "json") return { text: JSON.stringify(data), data };
25583
+ phase("REPORT");
25522
25584
  return {
25523
25585
  data,
25524
25586
  text: mapChangesText(
@@ -25527,22 +25589,23 @@ async function checkMapChanges(input, signal) {
25527
25589
  await mapRouteClients(project, index.store, working, impact, signal),
25528
25590
  reusable(
25529
25591
  index.store,
25592
+ views,
25530
25593
  working,
25531
25594
  await similarCode(
25532
25595
  index.store,
25533
25596
  working,
25534
25597
  base,
25535
25598
  changes.files,
25536
- (file2) => readFile3(path13.join(project, file2), "utf8").catch(() => void 0)
25599
+ (file2) => readFile3(path14.join(project, file2), "utf8").catch(() => void 0)
25537
25600
  )
25538
25601
  ),
25539
- changes.files.length ? await compileBreaks(input, changes, base, until, signal) : void 0
25602
+ changes.files.length ? await compileBreaks(input, views, changes, base, until, signal, phase, baseVersion) : void 0
25540
25603
  )
25541
25604
  };
25542
25605
  }
25543
- function reusable(store, working, similar) {
25606
+ function reusable(store, views, working, similar) {
25544
25607
  if (!similar.length) return [];
25545
- const importsFor = mapReuseImports(store, new MapViewCache(), working);
25608
+ const importsFor = mapReuseImports(store, views, working);
25546
25609
  return similar.flatMap((item) => {
25547
25610
  const imports = importsFor(item.path, item.like.path);
25548
25611
  return imports ? [{ ...item, imports }] : [];
@@ -25564,8 +25627,9 @@ async function mapRouteClients(project, store, working, impact, signal) {
25564
25627
  if (!routes.length) return { routes: [] };
25565
25628
  return routeClients(routes, registrations, git, gitOptions(project, signal));
25566
25629
  }
25567
- async function compileBreaks(input, changes, base, until, signal) {
25630
+ async function compileBreaks(input, views, changes, base, until, signal, phase, baseVersion) {
25568
25631
  const { index, working } = input;
25632
+ phase("COMPILE");
25569
25633
  const present = changes.files.filter((file2) => file2.status !== "DELETED").map((file2) => file2.path);
25570
25634
  const gone2 = changes.files.flatMap((file2) => file2.basePath ? [file2.basePath] : []);
25571
25635
  const after = await index.findDiagnostics(
@@ -25583,7 +25647,6 @@ async function compileBreaks(input, changes, base, until, signal) {
25583
25647
  signal
25584
25648
  );
25585
25649
  const missing = new Set(after.contexts.flatMap((context) => context.missing));
25586
- const views = new MapViewCache();
25587
25650
  const { notInstalled } = views.coverageNotes(index.store, working);
25588
25651
  if (notInstalled.length) {
25589
25652
  for (const { source, target, specifier } of views.imports(index.store, working))
@@ -25602,7 +25665,7 @@ async function compileBreaks(input, changes, base, until, signal) {
25602
25665
  });
25603
25666
  const before = onUnchanged.length && Date.now() <= until ? await index.findDiagnostics(
25604
25667
  {
25605
- version: base ?? await input.baseVersion(changes.commit, signal),
25668
+ version: base ?? await baseVersion(changes.commit, "COMPILE"),
25606
25669
  source: { ...input.source, kind: "COMMIT", commit: changes.commit },
25607
25670
  configurations: onUnchanged.map(({ configPath }) => configPath),
25608
25671
  until
@@ -25610,7 +25673,7 @@ async function compileBreaks(input, changes, base, until, signal) {
25610
25673
  signal
25611
25674
  ) : { contexts: [], unchecked: [] };
25612
25675
  const inBase = changedInBase(changes.files);
25613
- const named = (path19, item) => `${path19}\0${item.code}\0${item.span}\0${item.text}`;
25676
+ const named = (path20, item) => `${path20}\0${item.code}\0${item.span}\0${item.text}`;
25614
25677
  const compiled = new Map(before.contexts.map((context) => [context.configPath, context.errors]));
25615
25678
  const unchecked = new Set(after.unchecked);
25616
25679
  const errors = /* @__PURE__ */ new Set();
@@ -25670,7 +25733,7 @@ CREATE INDEX layermap_commit_version ON layermap_commit_versions(version_ref);
25670
25733
  `;
25671
25734
  var schemaVersion = (database) => Number(database.prepare("PRAGMA user_version").get()?.user_version ?? 0);
25672
25735
  function openMapDatabase(file2) {
25673
- mkdirSync(path14.dirname(file2), { recursive: true, mode: 448 });
25736
+ mkdirSync(path15.dirname(file2), { recursive: true, mode: 448 });
25674
25737
  const database = new DatabaseSync(file2);
25675
25738
  try {
25676
25739
  database.exec(BUSY_TIMEOUT);
@@ -25727,7 +25790,7 @@ async function lockMapBuilds(file2, signal) {
25727
25790
  throw error51;
25728
25791
  }
25729
25792
  }
25730
- var mapDatabasePath = (cacheDirectory2, canonicalProject) => path14.join(
25793
+ var mapDatabasePath = (cacheDirectory2, canonicalProject) => path15.join(
25731
25794
  cacheDirectory2,
25732
25795
  "projects",
25733
25796
  createHash5("sha256").update(canonicalProject).digest("hex").slice(0, 24),
@@ -25759,12 +25822,12 @@ var LayerMap = class _LayerMap {
25759
25822
  closed = false;
25760
25823
  static async open(options) {
25761
25824
  const project = await realpath2(options.project);
25762
- const stat3 = await lstat3(project, { bigint: true });
25763
- if (!stat3.isDirectory()) throw new ProjectEvidenceError("PROJECT_PATH_INVALID", false);
25825
+ const stat4 = await lstat4(project, { bigint: true });
25826
+ if (!stat4.isDirectory()) throw new ProjectEvidenceError("PROJECT_PATH_INVALID", false);
25764
25827
  const source = {
25765
25828
  kind: "WORKTREE",
25766
25829
  projectRef: `layermap:${createHash5("sha256").update(project).digest("hex").slice(0, 24)}`,
25767
- directory: { canonicalPath: project, device: String(stat3.dev), inode: String(stat3.ino) }
25830
+ directory: { canonicalPath: project, device: String(stat4.dev), inode: String(stat4.ino) }
25768
25831
  };
25769
25832
  const file2 = mapDatabasePath(options.cacheDirectory, project);
25770
25833
  const store = new CodeIndexStore(
@@ -25785,7 +25848,7 @@ var LayerMap = class _LayerMap {
25785
25848
  store,
25786
25849
  void 0,
25787
25850
  analyzer,
25788
- (signal) => lockMapBuilds(path14.join(path14.dirname(file2), "build.lock"), signal)
25851
+ (signal) => lockMapBuilds(path15.join(path15.dirname(file2), "build.lock"), signal)
25789
25852
  ),
25790
25853
  analyzer.id,
25791
25854
  { maxBytes: options.maxOutputBytes ?? 96 * 1024, envelopeBytes: 0 },
@@ -25992,6 +26055,12 @@ var LayerMap = class _LayerMap {
25992
26055
  )
25993
26056
  );
25994
26057
  }
26058
+ /** Every import of the directory as it is now, by file of the project, test files apart. */
26059
+ imports(signal) {
26060
+ return this.using(
26061
+ async (hold) => mapProjectImports(loadMapImports(this.store, await this.current(signal, hold)))
26062
+ );
26063
+ }
25995
26064
  /**
25996
26065
  * What the working tree's changes against a commit (HEAD by default) affect: the changed and
25997
26066
  * removed declarations, the entry points and tests their callers reach, and what the map cannot
@@ -25999,8 +26068,9 @@ var LayerMap = class _LayerMap {
25999
26068
  * The base commit's map is built only when the diff removes or changes lines there.
26000
26069
  */
26001
26070
  checkChanges(input, signal) {
26002
- return this.using(
26003
- async (hold) => checkMapChanges(
26071
+ return this.using(async (hold) => {
26072
+ input.phase?.("MAP");
26073
+ return checkMapChanges(
26004
26074
  {
26005
26075
  index: this.index,
26006
26076
  project: this.project,
@@ -26009,11 +26079,12 @@ var LayerMap = class _LayerMap {
26009
26079
  base: input.base ?? "HEAD",
26010
26080
  baseVersion: (commit, baseSignal) => this.versionAt(commit, baseSignal, hold),
26011
26081
  ...input.tests ? { tests: input.tests } : {},
26012
- ...input.format ? { format: input.format } : {}
26082
+ ...input.format ? { format: input.format } : {},
26083
+ ...input.phase ? { phase: input.phase } : {}
26013
26084
  },
26014
26085
  signal
26015
- )
26016
- );
26086
+ );
26087
+ });
26017
26088
  }
26018
26089
  /**
26019
26090
  * Builds the map of a base commit (HEAD by default) ahead of a change check, so the check after an
@@ -26036,25 +26107,25 @@ var LayerMap = class _LayerMap {
26036
26107
 
26037
26108
  // src/agent/environment.ts
26038
26109
  var packageRoot = (() => {
26039
- for (let directory = path15.dirname(fileURLToPath(import.meta.url)); ; ) {
26040
- const manifest = path15.join(directory, "package.json");
26110
+ for (let directory = path16.dirname(fileURLToPath(import.meta.url)); ; ) {
26111
+ const manifest = path16.join(directory, "package.json");
26041
26112
  if (existsSync6(manifest) && JSON.parse(readFileSync3(manifest, "utf8")).name === "layermap")
26042
26113
  return directory;
26043
- if (path15.dirname(directory) === directory) throw new Error("LayerMap cannot find its package.");
26044
- directory = path15.dirname(directory);
26114
+ if (path16.dirname(directory) === directory) throw new Error("LayerMap cannot find its package.");
26115
+ directory = path16.dirname(directory);
26045
26116
  }
26046
26117
  })();
26047
- var packageVersion = async () => JSON.parse(await readFile4(path15.join(packageRoot, "package.json"), "utf8")).version;
26118
+ var packageVersion = async () => JSON.parse(await readFile4(path16.join(packageRoot, "package.json"), "utf8")).version;
26048
26119
  var cacheDirectory = (env = process.env) => {
26049
- if (env.LAYERMAP_CACHE) return path15.resolve(env.LAYERMAP_CACHE);
26050
- if (process.platform === "darwin") return path15.join(homedir(), "Library", "Caches", "layermap");
26120
+ if (env.LAYERMAP_CACHE) return path16.resolve(env.LAYERMAP_CACHE);
26121
+ if (process.platform === "darwin") return path16.join(homedir(), "Library", "Caches", "layermap");
26051
26122
  if (process.platform === "win32")
26052
- return path15.join(
26053
- env.LOCALAPPDATA || path15.join(homedir(), "AppData", "Local"),
26123
+ return path16.join(
26124
+ env.LOCALAPPDATA || path16.join(homedir(), "AppData", "Local"),
26054
26125
  "layermap",
26055
26126
  "Cache"
26056
26127
  );
26057
- return path15.join(env.XDG_CACHE_HOME || path15.join(homedir(), ".cache"), "layermap");
26128
+ return path16.join(env.XDG_CACHE_HOME || path16.join(homedir(), ".cache"), "layermap");
26058
26129
  };
26059
26130
  var projectDirectory = async (directory) => {
26060
26131
  try {
@@ -26064,7 +26135,7 @@ var projectDirectory = async (directory) => {
26064
26135
  });
26065
26136
  return { directory: stdout.toString().trim(), git: true };
26066
26137
  } catch {
26067
- return { directory: path15.resolve(directory), git: false };
26138
+ return { directory: path16.resolve(directory), git: false };
26068
26139
  }
26069
26140
  };
26070
26141
  var relativeTo = (directory, value) => Object.fromEntries(
@@ -26073,7 +26144,7 @@ var relativeTo = (directory, value) => Object.fromEntries(
26073
26144
  Object.fromEntries(
26074
26145
  Object.entries(resources).map(([key, field]) => [
26075
26146
  key,
26076
- key.endsWith("Path") && typeof field === "string" && field.startsWith(directory) ? path15.relative(directory, field) : field
26147
+ key.endsWith("Path") && typeof field === "string" && field.startsWith(directory) ? path16.relative(directory, field) : field
26077
26148
  ])
26078
26149
  )
26079
26150
  ])
@@ -26084,7 +26155,7 @@ var resolvePlaceholder = (field) => {
26084
26155
  createRequire(import.meta.url).resolve("typescript/package.json")
26085
26156
  );
26086
26157
  const native = `@typescript/typescript-${process.platform}-${process.arch}/package.json`;
26087
- return path15.join(path15.dirname(compiler.resolve(native)), "lib", executableName("tsc"));
26158
+ return path16.join(path16.dirname(compiler.resolve(native)), "lib", executableName("tsc"));
26088
26159
  }
26089
26160
  const resolved = field.replaceAll("{platform}", process.platform).replaceAll("{arch}", process.arch);
26090
26161
  return field.includes("{platform}") ? executableName(resolved) : resolved;
@@ -26096,42 +26167,42 @@ var absoluteIn = (directory, value) => Object.fromEntries(
26096
26167
  Object.entries(resources).map(([key, field]) => {
26097
26168
  if (!key.endsWith("Path") || typeof field !== "string") return [key, field];
26098
26169
  const resolved = resolvePlaceholder(field);
26099
- return [key, path15.isAbsolute(resolved) ? resolved : path15.join(directory, resolved)];
26170
+ return [key, path16.isAbsolute(resolved) ? resolved : path16.join(directory, resolved)];
26100
26171
  })
26101
26172
  )
26102
26173
  ])
26103
26174
  );
26104
26175
  var readAnalyzers = async (directory) => {
26105
- const file2 = path15.join(directory, "analyzers.json");
26176
+ const file2 = path16.join(directory, "analyzers.json");
26106
26177
  if (!existsSync6(file2)) return void 0;
26107
26178
  const analyzers = absoluteIn(directory, JSON.parse(await readFile4(file2, "utf8")));
26108
26179
  return analyzers.java.runtimePath ? analyzers : { ...analyzers, java: { ...analyzers.java, ...discoverJavaRuntime() } };
26109
26180
  };
26110
26181
  var sourceDigest = async () => {
26111
- const hash2 = createHash6("sha256").update(await readFile4(path15.join(packageRoot, "package.json")));
26182
+ const hash2 = createHash6("sha256").update(await readFile4(path16.join(packageRoot, "package.json")));
26112
26183
  for (const part of ["src", "go-map", "java-map", "scripts"]) {
26113
- const directory = path15.join(packageRoot, part);
26184
+ const directory = path16.join(packageRoot, part);
26114
26185
  if (!existsSync6(directory)) continue;
26115
26186
  for (const entry of (await readdir(directory, { recursive: true })).sort()) {
26116
- const file2 = path15.join(directory, entry);
26117
- const info = await stat(file2);
26187
+ const file2 = path16.join(directory, entry);
26188
+ const info = await stat2(file2);
26118
26189
  if (info.isFile()) hash2.update(`${part}/${entry}\0${info.size}\0${info.mtimeMs}\0`);
26119
26190
  }
26120
26191
  }
26121
26192
  return hash2.digest("hex").slice(0, 16);
26122
26193
  };
26123
26194
  async function resolveAnalyzers(cache, log2, env = process.env) {
26124
- for (const directory2 of [env.LAYERMAP_ANALYZERS, path15.join(packageRoot, "analyzers")]) {
26125
- const analyzers = directory2 && await readAnalyzers(path15.resolve(directory2));
26195
+ for (const directory2 of [env.LAYERMAP_ANALYZERS, path16.join(packageRoot, "analyzers")]) {
26196
+ const analyzers = directory2 && await readAnalyzers(path16.resolve(directory2));
26126
26197
  if (analyzers) return analyzers;
26127
26198
  }
26128
- const directory = path15.join(cache, "analyzers", await sourceDigest());
26199
+ const directory = path16.join(cache, "analyzers", await sourceDigest());
26129
26200
  const built = await readAnalyzers(directory);
26130
26201
  if (built) return built;
26131
26202
  log2("Building the language analyzers (once per LayerMap version)...");
26132
26203
  const staging = `${directory}.${process.pid}`;
26133
26204
  await rm(staging, { recursive: true, force: true });
26134
- await mkdir(staging, { recursive: true, mode: 448 });
26205
+ await mkdir2(staging, { recursive: true, mode: 448 });
26135
26206
  const builder = new URL("../../scripts/build.mjs", import.meta.url).href;
26136
26207
  const { buildProjectMapParser } = await import(builder);
26137
26208
  const parser = await buildProjectMapParser(staging);
@@ -26141,81 +26212,81 @@ async function resolveAnalyzers(cache, log2, env = process.env) {
26141
26212
  python: parser.pythonResources,
26142
26213
  java: parser.javaResources
26143
26214
  });
26144
- await writeFile(path15.join(staging, "analyzers.json"), `${JSON.stringify(stored, null, 2)}
26215
+ await writeFile(path16.join(staging, "analyzers.json"), `${JSON.stringify(stored, null, 2)}
26145
26216
  `);
26146
- await rename(staging, directory).catch(() => rm(staging, { recursive: true, force: true }));
26217
+ await rename2(staging, directory).catch(() => rm(staging, { recursive: true, force: true }));
26147
26218
  return await readAnalyzers(directory);
26148
26219
  }
26149
26220
  var DAY = 24 * 60 * 60 * 1e3;
26150
26221
  async function pruneCache(cache, project, now = Date.now(), installed = packageRoot, env = process.env) {
26151
- const used = path15.join(path15.dirname(mapDatabasePath(cache, project)), "last-used");
26152
- await mkdir(path15.dirname(used), { recursive: true, mode: 448 });
26222
+ const used = path16.join(path16.dirname(mapDatabasePath(cache, project)), "last-used");
26223
+ await mkdir2(path16.dirname(used), { recursive: true, mode: 448 });
26153
26224
  await writeFile(used, project);
26154
26225
  await utimes(used, now / 1e3, now / 1e3);
26155
- const projects = path15.join(cache, "projects");
26226
+ const projects = path16.join(cache, "projects");
26156
26227
  for (const name of await readdir(projects).catch(() => [])) {
26157
- const directory = path15.join(projects, name);
26158
- const marker = path15.join(directory, "last-used");
26159
- const last = (await stat(existsSync6(marker) ? marker : directory).catch(() => void 0))?.mtimeMs;
26228
+ const directory = path16.join(projects, name);
26229
+ const marker = path16.join(directory, "last-used");
26230
+ const last = (await stat2(existsSync6(marker) ? marker : directory).catch(() => void 0))?.mtimeMs;
26160
26231
  const owner = await readFile4(marker, "utf8").catch(() => "");
26161
26232
  if (last !== void 0 && now - last > 30 * DAY || owner !== "" && await gone(owner))
26162
26233
  await rm(directory, { recursive: true, force: true });
26163
26234
  }
26164
- const builds = path15.join(cache, "analyzers");
26235
+ const builds = path16.join(cache, "analyzers");
26165
26236
  const current = await sourceDigest();
26166
26237
  for (const name of await readdir(builds).catch(() => [])) {
26167
26238
  if (name === current) continue;
26168
- const built = (await stat(path15.join(builds, name)).catch(() => void 0))?.mtimeMs;
26239
+ const built = (await stat2(path16.join(builds, name)).catch(() => void 0))?.mtimeMs;
26169
26240
  if (built !== void 0 && now - built > (name.includes(".") ? DAY / 24 : DAY))
26170
- await rm(path15.join(builds, name), { recursive: true, force: true });
26241
+ await rm(path16.join(builds, name), { recursive: true, force: true });
26171
26242
  }
26172
- const own = path15.dirname(path15.dirname(installed));
26173
- const versions = path15.join(cache, "versions");
26174
- const launched = path15.dirname(own) === versions;
26243
+ const own = path16.dirname(path16.dirname(installed));
26244
+ const versions = path16.join(cache, "versions");
26245
+ const launched = path16.dirname(own) === versions;
26175
26246
  if (launched) await pruneVersions(versions, own, now);
26176
- const npx = launched ? path15.join(
26177
- env.npm_config_cache || (process.platform === "win32" ? path15.join(env.LOCALAPPDATA || path15.join(homedir(), "AppData", "Local"), "npm-cache") : path15.join(homedir(), ".npm")),
26247
+ const npx = launched ? path16.join(
26248
+ env.npm_config_cache || (process.platform === "win32" ? path16.join(env.LOCALAPPDATA || path16.join(homedir(), "AppData", "Local"), "npm-cache") : path16.join(homedir(), ".npm")),
26178
26249
  "_npx"
26179
- ) : path15.dirname(own);
26180
- if (path15.basename(path15.dirname(installed)) === "node_modules" && path15.basename(npx) === "_npx")
26250
+ ) : path16.dirname(own);
26251
+ if (path16.basename(path16.dirname(installed)) === "node_modules" && path16.basename(npx) === "_npx")
26181
26252
  await pruneNpxInstalls(npx, installed, now);
26182
26253
  }
26183
- var gone = (directory) => stat(directory).then(
26254
+ var gone = (directory) => stat2(directory).then(
26184
26255
  () => false,
26185
26256
  (error51) => error51.code === "ENOENT"
26186
26257
  );
26187
26258
  async function pruneVersions(versions, own, now) {
26188
- const used = path15.join(own, "last-used");
26259
+ const used = path16.join(own, "last-used");
26189
26260
  await writeFile(used, "");
26190
26261
  await utimes(used, now / 1e3, now / 1e3);
26191
26262
  for (const name of await readdir(versions).catch(() => [])) {
26192
- const directory = path15.join(versions, name);
26193
- const marker = path15.join(directory, "last-used");
26194
- const last = (await stat(existsSync6(marker) ? marker : directory).catch(() => void 0))?.mtimeMs;
26263
+ const directory = path16.join(versions, name);
26264
+ const marker = path16.join(directory, "last-used");
26265
+ const last = (await stat2(existsSync6(marker) ? marker : directory).catch(() => void 0))?.mtimeMs;
26195
26266
  if (last !== void 0 && now - last > (name.startsWith(".") ? DAY / 24 : 7 * DAY))
26196
26267
  await rm(directory, { recursive: true, force: true });
26197
26268
  }
26198
26269
  }
26199
26270
  async function pruneNpxInstalls(npx, installed, now) {
26200
- const own = path15.dirname(path15.dirname(installed));
26271
+ const own = path16.dirname(path16.dirname(installed));
26201
26272
  const manifest = async (file2) => JSON.parse(await readFile4(file2, "utf8").catch(() => "{}"));
26202
26273
  const parts = (version2) => version2?.split(".").map(Number) ?? [];
26203
- const current = parts((await manifest(path15.join(installed, "package.json"))).version);
26274
+ const current = parts((await manifest(path16.join(installed, "package.json"))).version);
26204
26275
  const older = (version2) => {
26205
26276
  for (let index = 0; index < 3; index++)
26206
26277
  if (version2[index] !== current[index]) return (version2[index] ?? 0) < (current[index] ?? 0);
26207
26278
  return false;
26208
26279
  };
26209
26280
  for (const name of await readdir(npx).catch(() => [])) {
26210
- const directory = path15.join(npx, name);
26281
+ const directory = path16.join(npx, name);
26211
26282
  if (directory === own) continue;
26212
- const requested = (await manifest(path15.join(directory, "package.json"))).dependencies ?? {};
26283
+ const requested = (await manifest(path16.join(directory, "package.json"))).dependencies ?? {};
26213
26284
  if (Object.keys(requested).join() !== "layermap") continue;
26214
26285
  const version2 = parts(
26215
- (await manifest(path15.join(directory, "node_modules", "layermap", "package.json"))).version
26286
+ (await manifest(path16.join(directory, "node_modules", "layermap", "package.json"))).version
26216
26287
  );
26217
26288
  if (version2.length !== 3 || version2.some(Number.isNaN) || !older(version2)) continue;
26218
- const at = (await stat(directory).catch(() => void 0))?.mtimeMs;
26289
+ const at = (await stat2(directory).catch(() => void 0))?.mtimeMs;
26219
26290
  if (at !== void 0 && now - at > 7 * DAY)
26220
26291
  await rm(directory, { recursive: true, force: true });
26221
26292
  }
@@ -26226,15 +26297,6 @@ import { createInterface } from "node:readline";
26226
26297
  import { setTimeout as delay2 } from "node:timers/promises";
26227
26298
  import { fileURLToPath as fileURLToPath2 } from "node:url";
26228
26299
 
26229
- // src/agent/notes.ts
26230
- 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.";
26231
- var projectHeading = (project) => `Project ${project} (paths are relative to it)`;
26232
-
26233
- // src/agent/projects.ts
26234
- import { existsSync as existsSync7 } from "node:fs";
26235
- import { readdir as readdir2, realpath as realpath3, stat as stat2 } from "node:fs/promises";
26236
- import path16 from "node:path";
26237
-
26238
26300
  // src/tools.ts
26239
26301
  var AGENT_MAP_TOOL_HOST = Object.freeze({
26240
26302
  readResult: "read its line range in the file",
@@ -26257,7 +26319,7 @@ var MAP_TOOL_NAMES = Object.freeze({
26257
26319
  references: "project_find_references",
26258
26320
  check: "project_check_changes"
26259
26321
  });
26260
- var mapDirectoryPath = (path19) => path19.length > 1 && path19.endsWith("/") && !path19.endsWith("//") ? path19.slice(0, -1) : path19;
26322
+ var mapDirectoryPath = (path20) => path20.length > 1 && path20.endsWith("/") && !path20.endsWith("//") ? path20.slice(0, -1) : path20;
26261
26323
  var ProjectMapSearchInputSchema = external_exports.object({
26262
26324
  path: external_exports.string().default("."),
26263
26325
  query: external_exports.string().min(1).max(256),
@@ -26297,20 +26359,20 @@ var locatorSchema = MapObjectLocatorSchema.describe(
26297
26359
  "Declaration location: path and UTF-16 start offset; include kind to distinguish declarations at the same offset."
26298
26360
  );
26299
26361
  var mapReferencesInputSchema = (host) => external_exports.object({
26300
- symbol: MapSymbolSelectorSchema.optional().describe(
26301
- "Declaration as printed by the map: file path, name or Container.member, and start line when names repeat."
26302
- ),
26362
+ path: external_exports.string().min(1).optional().describe("The file declaring it, as for project_explore_map."),
26363
+ name: MapSymbolSelectorSchema.shape.name.optional().describe("Declaration name or Container.member in the file, as printed by the map."),
26364
+ line: MapSymbolSelectorSchema.shape.line.describe("Start line of a same-named declaration."),
26303
26365
  entityRef: external_exports.string().min(1).max(128).optional(),
26304
26366
  locator: locatorSchema.optional(),
26305
- path: external_exports.string().default(".").describe(
26306
- `Filter usage locations; compiler inputs and declarations may lie elsewhere in the ${host.scope}.`
26367
+ within: external_exports.string().default(".").describe(
26368
+ `Only usages in this file or directory; compiler inputs and declarations may lie elsewhere in the ${host.scope}.`
26307
26369
  ),
26308
26370
  kinds: external_exports.array(MapReferenceKindSchema).min(1).max(MapReferenceKindSchema.options.length).optional(),
26309
26371
  maxResults: external_exports.number().int().min(1).max(200).default(20),
26310
26372
  cursor: external_exports.string().max(2048).optional()
26311
26373
  }).strict().refine(
26312
- (input) => [input.symbol, input.entityRef, input.locator].filter((value) => value !== void 0).length === 1,
26313
- "Provide exactly one symbol, entityRef or locator."
26374
+ (input) => [input.name, input.entityRef, input.locator].filter((value) => value !== void 0).length === 1 && input.name === void 0 === (input.path === void 0 && input.line === void 0),
26375
+ "Select the declaration with path and name (and line when names repeat), as for project_explore_map, or with an entityRef or locator alone."
26314
26376
  );
26315
26377
  var mapToolDescriptions = (host) => {
26316
26378
  const lead = (tool) => host.lead?.[tool] ? `${host.lead[tool]} ` : "";
@@ -26318,48 +26380,54 @@ var mapToolDescriptions = (host) => {
26318
26380
  search: `${lead("search")}Find declarations and files whose names, paths or source documentation match query terms. ANY (default) matches any term, ALL requires every term, LITERAL matches the exact text. Results are ranked by relevance and grouped by file with the declaration name, kind, 1-based line range and matched fields (${MAP_KINDS_LEGEND}). Zoom into a result with project_explore_map({path,name}) or ${host.readResult}. This is not a full-text search and does not prove absence; ${host.textSearch}. Continue with offset and unchanged conditions.`,
26319
26381
  explore: `${lead("explore")}Read the static project map, zooming from the whole project to one declaration. path "." or a directory lists modules, module imports, external packages and its files: with exported declarations when the listing is small, as file names and line counts by directory when larger, and as modules only when very large. Start here to see what exists before searching or reading. A file path lists its declarations and members, imports, importers and top-level statements. A file path with name (or Container.member), optionally narrowed by its start line, or with a line alone, shows that declaration's calls, callers (including uses as a value), writes, heritage, decorators and members, aggregated per related declaration with @line sites; closures and locals are folded into their named container. depth also expands the related declarations hop by hop: up to 8 in one direction, which traces callers up to entry points (INCOMING) or callees down (OUTGOING), and up to 3 for BOTH. To find what a change affects, select the declaration with direction INCOMING and a depth up to 8, continue from any NOT EXPANDED declarations the view names, then confirm the entry points in source. Test files and standard-library call targets are hidden and counted by default; includeTests and includeUnresolved show them. Views use ${MAP_KINDS_LEGEND}. In a declaration view, ${MAP_DECLARATION_LEGEND} ${host.readSource} The map is static: trace stops, possible callers by name, framework wiring and unresolved targets need source reading, and a missing relationship does not prove absence. When a page reports more entries, continue with offset and otherwise unchanged arguments.`,
26320
26382
  check: `${lead("check")}Compares the working tree with a commit (HEAD by default, so uncommitted and untracked changes), finds the declarations the diff changed, removed or renamed, and follows their callers, and the code using a field or type, up to 8 levels. It reports, conclusion first: AFFECTED ENTRY POINTS reached through resolved calls, each route with its HTTP methods and full path and the chain to the change; POSSIBLY AFFECTED ones reached only through a call on an interface or base member, or through code that uses a changed field or type; REQUESTED BY, the code and templates outside the tests that request the path of a route whose handler the change reaches or a route it removed, found by text; EXISTING TESTS CHANGED, the tests that existed before the diff and whose code it changed or removed; SHARED BY, when tests reach the changed code through more than one area (package or module), so a change meant for one feature may change others; NAMES STILL USED ELSEWHERE, environment variables and configuration keys the diff removed from a file that other files still read or set, found by text; NEW MODULE DEPENDENCIES, imports between the modules of the project overview that the base did not have, and those that make two modules depend on each other, for you to judge against the project's layers; NEW COMPILE ERRORS, what the compiler reports on lines the diff left unchanged and did not report before, in code a tsconfig covers; PACKAGES NOT FOUND, packages the changed code needs that are not installed in this directory, whose types the trace then lacks; EXISTING CODE LIKE THE NEW CODE, declarations the diff adds whose code reads almost the same as code the project already has; LEFT WITHOUT CALLERS, declarations whose last callers outside the tests the diff removed or changed, and that nothing extends, implements, overrides or wires with a decorator; CHECK BY HAND for what a static map cannot follow (changed configuration, templates, migrations or dependency files, changed route registrations, declarations with no callers, calls by name on receivers of unknown type); and RELATED TESTS, closest first, the existing test files the diff changed, that call or use the changed code, request a route it reaches, may request one through a path the map does not work out, spell out a stretch of such a route's path in their text, may call it through a receiver of unknown type or through a test support file beside or above them, import a changed file, are named for its module or sit beside it; given tests, NOT REACHED BY THE GIVEN TESTS, the changed declarations none of them calls or requests through a route, or uses when it is a field or type, with the entry points above them, the other tests of the project that run them, and those the given tests may run through a request whose path the map does not work out. It does not run or write tests: run the related ones if the change needs verifying; a failing or rewritten test of a feature the request is not about means the change leaked, so restore the test and narrow the change; a new dependency that runs against the layers or closes a cycle means moving what both modules need down rather than importing upward; new code like existing code means using the existing code, removing the old if the new replaces it, or having the existing code use the new where it is the one that can, unless the two are meant to differ, and changing existing code only where it is part of the task while telling the user of the rest; code left without callers means deleting it, with the tests that only test it, when the change replaced it; call it once when the edits are done; and confirm the entry points in source, since an empty list does not prove a change safe.`,
26321
- references: `${lead("references")}Compute usages of a mapped declaration from current source, including aliases, re-exports and non-call references. Select it with symbol {path,name,line?} as printed by project_explore_map or project_search_map (line is its start line when names repeat), or with an entityRef or locator {path,start,kind}. Broader and more expensive than the cached callers in project_explore_map; file or unsupported declarations may lack a reference target. path and kinds filter usage locations before paging. ${host.grantRules}objects contains compact declarations; targetRef and reference ownerRef identify them. ${host.readReference} A file that several compiler contexts read (such as packages of one workspace) lists its references once per context, each with that context's configPath. Continue with nextCursor and unchanged conditions, including after an empty partial page. Filtered exhaustion and missing results do not prove absence.`
26383
+ references: `${lead("references")}Compute usages of a mapped declaration from current source, including aliases, re-exports and non-call references. Select it as project_explore_map does, with path (its file) and name as printed by project_explore_map or project_search_map, and line (its start line) when names repeat; or with an entityRef or locator {path,start,kind}. Broader and more expensive than the cached callers in project_explore_map; file or unsupported declarations may lack a reference target. within and kinds filter usage locations before paging. ${host.grantRules}objects contains compact declarations; targetRef and reference ownerRef identify them. ${host.readReference} A file that several compiler contexts read (such as packages of one workspace) lists its references once per context, each with that context's configPath. Continue with nextCursor and unchanged conditions, including after an empty partial page. Filtered exhaustion and missing results do not prove absence.`
26322
26384
  });
26323
26385
  };
26324
26386
 
26387
+ // src/agent/notes.ts
26388
+ 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.";
26389
+ var projectHeading = (project) => `Project ${project} (paths are relative to it)`;
26390
+
26325
26391
  // src/agent/projects.ts
26392
+ import { existsSync as existsSync7 } from "node:fs";
26393
+ import { readdir as readdir2, realpath as realpath3, stat as stat3 } from "node:fs/promises";
26394
+ import path17 from "node:path";
26326
26395
  var escapes = (relative) => {
26327
- const normal = path16.normalize(relative);
26328
- return normal === ".." || normal.startsWith(`..${path16.sep}`);
26396
+ const normal = path17.normalize(relative);
26397
+ return normal === ".." || normal.startsWith(`..${path17.sep}`);
26329
26398
  };
26330
26399
  async function locate(start, given) {
26331
- if (start.git && !path16.isAbsolute(given) && !escapes(given))
26400
+ if (start.git && !path17.isAbsolute(given) && !escapes(given))
26332
26401
  return { project: start.directory, path: given };
26333
- const absolute = path16.resolve(start.directory, given);
26402
+ const absolute = path17.resolve(start.directory, given);
26334
26403
  let directory = absolute;
26335
- while (!(await stat2(directory).catch(() => void 0))?.isDirectory()) {
26336
- if (path16.dirname(directory) === directory) return void 0;
26337
- directory = path16.dirname(directory);
26404
+ while (!(await stat3(directory).catch(() => void 0))?.isDirectory()) {
26405
+ if (path17.dirname(directory) === directory) return void 0;
26406
+ directory = path17.dirname(directory);
26338
26407
  }
26339
- const real = path16.join(await realpath3(directory), path16.relative(directory, absolute));
26408
+ const real = path17.join(await realpath3(directory), path17.relative(directory, absolute));
26340
26409
  const { directory: project, git: git2 } = await projectDirectory(directory);
26341
26410
  if (!git2) return void 0;
26342
- const relative = path16.relative(project, real);
26411
+ const relative = path17.relative(project, real);
26343
26412
  if (escapes(relative)) return void 0;
26344
- return { project, path: relative ? relative.split(path16.sep).join("/") : "." };
26413
+ return { project, path: relative ? relative.split(path17.sep).join("/") : "." };
26345
26414
  }
26346
26415
  async function repositoriesIn(directory) {
26347
26416
  const entries = await readdir2(directory, { withFileTypes: true }).catch(() => []);
26348
- return entries.filter((entry) => entry.isDirectory() && existsSync7(path16.join(directory, entry.name, ".git"))).map((entry) => `${entry.name}/`).sort();
26417
+ return entries.filter((entry) => entry.isDirectory() && existsSync7(path17.join(directory, entry.name, ".git"))).map((entry) => `${entry.name}/`).sort();
26349
26418
  }
26350
26419
  async function routeMapCall(start, { name, args }) {
26351
- const holder = ["symbol", "locator"].find(
26352
- (key) => name === MAP_TOOL_NAMES.references && args[key] !== void 0
26353
- );
26354
- const value = holder ? args[holder].path : args.path;
26420
+ const references = name === MAP_TOOL_NAMES.references;
26421
+ const locator = references ? args.locator : void 0;
26422
+ const value = locator?.path ?? args.path ?? (references && args.within !== "." ? args.within : void 0);
26355
26423
  const named = value || ".";
26356
26424
  const located = await locate(start, named);
26357
26425
  if (!located) {
26358
26426
  const repositories = start.git ? [] : await repositoriesIn(start.directory);
26359
26427
  const such = repositories.length ? `, such as ${repositories.join(", ")}` : "";
26360
- 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: ${path16.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}`}.`;
26428
+ 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: ${path17.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}`}.`;
26361
26429
  }
26362
- if (!holder) {
26430
+ if (!references) {
26363
26431
  const routed2 = value === void 0 ? args : { ...args, path: located.path };
26364
26432
  if (!Array.isArray(args.tests)) return { project: located.project, args: routed2 };
26365
26433
  const tests = [];
@@ -26371,16 +26439,13 @@ async function routeMapCall(start, { name, args }) {
26371
26439
  }
26372
26440
  return { project: located.project, args: { ...routed2, tests } };
26373
26441
  }
26374
- const routed = {
26375
- ...args,
26376
- [holder]: { ...args[holder], path: located.path }
26377
- };
26378
- const filter = args.path;
26442
+ const routed = locator ? { ...args, locator: { ...locator, path: located.path } } : args.path !== void 0 ? { ...args, path: located.path } : args;
26443
+ const filter = args.within;
26379
26444
  if (filter === ".") return { project: located.project, args: routed };
26380
26445
  const within3 = await locate(start, filter);
26381
26446
  if (within3?.project !== located.project)
26382
- return `PROJECT_PATH_INVALID: path ${filter} is not in ${located.project}, the repository of the declaration.`;
26383
- return { project: located.project, args: { ...routed, path: within3.path } };
26447
+ return `PROJECT_PATH_INVALID: within ${filter} is not in ${located.project}, the repository of the declaration.`;
26448
+ return { project: located.project, args: { ...routed, within: within3.path } };
26384
26449
  }
26385
26450
 
26386
26451
  // src/agent/tools.ts
@@ -26419,7 +26484,7 @@ var more = (nextOffset) => nextOffset === void 0 ? "" : `
26419
26484
 
26420
26485
  [More entries: call again with offset ${nextOffset} and otherwise the same arguments.]`;
26421
26486
  var HINTS = {
26422
- PROJECT_MAP_OBJECT_NOT_FOUND: "No such path or declaration in the map. Explore the parent directory or the file to see what it contains.",
26487
+ PROJECT_MAP_OBJECT_NOT_FOUND: 'No such path or declaration in the map. path names a file or directory, and name a declaration in it (as {path: "src/a.ts", name: "run"}); explore the parent directory or the file to see what it contains.',
26423
26488
  PROJECT_FILE_CHANGED: "Files kept changing while the map was updating. Call again.",
26424
26489
  PROJECT_FILE_UNIVERSE_CHANGED: "Files kept changing while the map was updating. Call again.",
26425
26490
  PROJECT_READ_SOURCE_CHANGED: "Files kept changing while the map was updating. Call again.",
@@ -26435,18 +26500,23 @@ var HINTS = {
26435
26500
  LAYERMAP_NOT_A_GIT_REPOSITORY: "LayerMap maps Git repositories. Run it in one, or name one with --project."
26436
26501
  };
26437
26502
  var describeMapError = (error51) => error51 instanceof ProjectEvidenceError ? `${error51.code}${HINTS[error51.code] ? `: ${HINTS[error51.code]}` : ""}` : void 0;
26503
+ var EXAMPLES = {
26504
+ [MAP_TOOL_NAMES.explore]: '{"path": "src/billing/tax.ts", "name": "calculateTax", "direction": "INCOMING", "depth": 8}',
26505
+ [MAP_TOOL_NAMES.references]: '{"path": "src/billing/tax.ts", "name": "calculateTax"}',
26506
+ [MAP_TOOL_NAMES.search]: '{"query": "tax"}'
26507
+ };
26438
26508
  function parseMapToolCall(name, args) {
26439
26509
  const tool = agentMapTools.find((candidate) => candidate.name === name);
26440
26510
  if (!tool) return { text: `Unknown tool ${name}.`, isError: true };
26441
26511
  const parsed = tool.schema.safeParse(args ?? {});
26442
26512
  if (!parsed.success)
26443
26513
  return {
26444
- text: `Invalid arguments: ${parsed.error.issues.map((issue2) => `${issue2.path.join(".") || "(arguments)"}: ${issue2.message}`).join("; ")}`,
26514
+ text: `Invalid arguments: ${parsed.error.issues.map((issue2) => `${issue2.path.join(".") || "(arguments)"}: ${issue2.message}`).join("; ")}${EXAMPLES[name] ? `. For example: ${EXAMPLES[name]}` : ""}`,
26445
26515
  isError: true
26446
26516
  };
26447
26517
  return { name, args: parsed.data };
26448
26518
  }
26449
- async function runMapTool(map2, { name, args }, signal) {
26519
+ async function runMapTool(map2, { name, args }, signal, phase) {
26450
26520
  try {
26451
26521
  if (name === MAP_TOOL_NAMES.explore) {
26452
26522
  const input2 = args;
@@ -26469,7 +26539,11 @@ async function runMapTool(map2, { name, args }, signal) {
26469
26539
  const input2 = args;
26470
26540
  return {
26471
26541
  text: (await map2.checkChanges(
26472
- { base: input2.base, ...input2.tests ? { tests: input2.tests } : {} },
26542
+ {
26543
+ base: input2.base,
26544
+ ...input2.tests ? { tests: input2.tests } : {},
26545
+ ...phase ? { phase } : {}
26546
+ },
26473
26547
  signal
26474
26548
  )).text,
26475
26549
  isError: false
@@ -26492,6 +26566,17 @@ var AGENT_MAP_INSTRUCTIONS = `Use the LayerMap tools instead of grep whenever a
26492
26566
 
26493
26567
  // src/agent/mcp.ts
26494
26568
  var ROOTS_WAIT_MS = 5e3;
26569
+ var PROGRESS_EVERY_MS = 15e3;
26570
+ var PHASE_TEXT = {
26571
+ WAIT: "Waiting for the first build of the project's map",
26572
+ READ: "Reading the map",
26573
+ MAP: "Updating the map of the working tree",
26574
+ DIFF: "Reading the diff",
26575
+ BASE: "Building the map of the base commit",
26576
+ TRACE: "Tracing what the change reaches",
26577
+ REPORT: "Finding the code the report names",
26578
+ COMPILE: "Compiling the changed code"
26579
+ };
26495
26580
  function serveMcp(options) {
26496
26581
  const output = options.output ?? process.stdout;
26497
26582
  const log2 = options.log ?? ((line) => process.stderr.write(`${line}
@@ -26546,20 +26631,72 @@ function serveMcp(options) {
26546
26631
  calls.set(id2, controller);
26547
26632
  const name = String(params.name);
26548
26633
  let project;
26549
- const respond = (text, isError) => send({
26550
- id: id2,
26551
- result: {
26552
- content: [
26553
- {
26554
- type: "text",
26555
- text: project ? `${projectHeading(project)}
26634
+ const token = params._meta?.progressToken;
26635
+ const started = performance.now();
26636
+ const phases = {};
26637
+ let current = "WAIT";
26638
+ let since = started;
26639
+ let progress = 0;
26640
+ const notify = (message) => {
26641
+ if (typeof token !== "string" && typeof token !== "number") return;
26642
+ send({
26643
+ method: "notifications/progress",
26644
+ params: { progressToken: token, progress: ++progress, message }
26645
+ });
26646
+ };
26647
+ const tally = () => {
26648
+ const now = performance.now();
26649
+ phases[current] = (phases[current] ?? 0) + now - since;
26650
+ since = now;
26651
+ };
26652
+ const enter = (next) => {
26653
+ tally();
26654
+ current = next;
26655
+ notify(PHASE_TEXT[next]);
26656
+ };
26657
+ const beat = setInterval(
26658
+ () => notify(
26659
+ `${PHASE_TEXT[current]} (${Math.round((performance.now() - started) / 1e3)} s so far)`
26660
+ ),
26661
+ PROGRESS_EVERY_MS
26662
+ );
26663
+ let answered = false;
26664
+ const finish = (text, isError, cancelled) => {
26665
+ tally();
26666
+ void options.record?.({
26667
+ at: (/* @__PURE__ */ new Date()).toISOString(),
26668
+ version: options.version,
26669
+ tool: name,
26670
+ ...project ? { project } : {},
26671
+ ...params.arguments === void 0 ? {} : { arguments: params.arguments },
26672
+ ms: Math.round(performance.now() - started),
26673
+ phases: Object.fromEntries(
26674
+ Object.entries(phases).map(([phase, ms]) => [phase, Math.round(ms)])
26675
+ ),
26676
+ chars: text.length,
26677
+ head: text.split("\n", 1)[0]?.slice(0, 300) ?? "",
26678
+ isError,
26679
+ ...cancelled ? { cancelled } : {}
26680
+ });
26681
+ };
26682
+ const respond = (text, isError) => {
26683
+ answered = true;
26684
+ finish(text, isError, false);
26685
+ send({
26686
+ id: id2,
26687
+ result: {
26688
+ content: [
26689
+ {
26690
+ type: "text",
26691
+ text: project ? `${projectHeading(project)}
26556
26692
 
26557
26693
  ${text}` : text
26558
- }
26559
- ],
26560
- isError
26561
- }
26562
- });
26694
+ }
26695
+ ],
26696
+ isError
26697
+ }
26698
+ });
26699
+ };
26563
26700
  try {
26564
26701
  const parsed = parseMapToolCall(name, params.arguments);
26565
26702
  if ("text" in parsed) return respond(parsed.text, parsed.isError);
@@ -26577,7 +26714,8 @@ ${text}` : text
26577
26714
  ]);
26578
26715
  timer.abort();
26579
26716
  if (controller.signal.aborted) return;
26580
- const result = ready ? await runMapTool(await opened, { name, args: routed.args }, controller.signal) : {
26717
+ if (ready && name !== MAP_TOOL_NAMES.check) enter("READ");
26718
+ const result = ready ? await runMapTool(await opened, { name, args: routed.args }, controller.signal, enter) : {
26581
26719
  text: `LayerMap is still building this project's map (a first build can take minutes on a large repository). Call ${name} again shortly, or read source meanwhile.`,
26582
26720
  isError: false
26583
26721
  };
@@ -26586,6 +26724,8 @@ ${text}` : text
26586
26724
  if (controller.signal.aborted) return;
26587
26725
  respond(describeMapError(error51) ?? `LayerMap failed: ${String(error51)}`, true);
26588
26726
  } finally {
26727
+ clearInterval(beat);
26728
+ if (!answered) finish("", false, true);
26589
26729
  calls.delete(id2);
26590
26730
  }
26591
26731
  };
@@ -26675,9 +26815,9 @@ ${text}` : text
26675
26815
  // src/agent/setup.ts
26676
26816
  import { execFile } from "node:child_process";
26677
26817
  import { existsSync as existsSync8 } from "node:fs";
26678
- import { mkdir as mkdir2, readFile as readFile5, rename as rename2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
26818
+ import { mkdir as mkdir3, readFile as readFile5, rename as rename3, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
26679
26819
  import { homedir as homedir2 } from "node:os";
26680
- import path17 from "node:path";
26820
+ import path18 from "node:path";
26681
26821
  var SERVER = "layermap";
26682
26822
  var SETUP_RULE = `mcp__${SERVER}`;
26683
26823
  var PLUGIN_RULE = `mcp__plugin_${SERVER}_${SERVER}`;
@@ -26685,11 +26825,11 @@ var BEGIN = "<!-- layermap:begin -->";
26685
26825
  var END = "<!-- layermap:end -->";
26686
26826
  var launcherScript = (template, version2, args = '["mcp"]') => `// Generated from scripts/launcher.mjs.
26687
26827
  ${template.replace("__VERSION__", JSON.stringify(version2)).replace("__ARGUMENTS__", args)}`;
26688
- var PUBLISHED_LAUNCHER = path17.join(packageRoot, "dist", "launcher.mjs");
26689
- var launcherFile = (env = process.env) => path17.join(cacheDirectory(env), "server.mjs");
26828
+ var PUBLISHED_LAUNCHER = path18.join(packageRoot, "dist", "launcher.mjs");
26829
+ var launcherFile = (env = process.env) => path18.join(cacheDirectory(env), "server.mjs");
26690
26830
  var mcpLaunchCommand = (env = process.env, published = existsSync8(PUBLISHED_LAUNCHER)) => {
26691
26831
  if (published) return ["node", launcherFile(env)];
26692
- const script = path17.resolve(process.argv[1] ?? "");
26832
+ const script = path18.resolve(process.argv[1] ?? "");
26693
26833
  const execArgv = [];
26694
26834
  for (let index = 0; index < process.execArgv.length; index++) {
26695
26835
  const argument = process.execArgv[index];
@@ -26725,7 +26865,7 @@ async function allowInClaudeSettings(file2, rule = SETUP_RULE) {
26725
26865
  throw new Error(`${file2} has permissions.allow that is not a list.`);
26726
26866
  if (settings.permissions.allow.includes(rule)) return false;
26727
26867
  settings.permissions.allow.push(rule);
26728
- await mkdir2(path17.dirname(file2), { recursive: true });
26868
+ await mkdir3(path18.dirname(file2), { recursive: true });
26729
26869
  await writeFile2(file2, `${JSON.stringify(settings, null, 2)}
26730
26870
  `);
26731
26871
  return true;
@@ -26761,7 +26901,7 @@ ${END}`;
26761
26901
  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}
26762
26902
  `;
26763
26903
  if (next === text) return;
26764
- await mkdir2(path17.dirname(file2), { recursive: true });
26904
+ await mkdir3(path18.dirname(file2), { recursive: true });
26765
26905
  await writeFile2(file2, next);
26766
26906
  }
26767
26907
  async function removeInstructionNote(file2) {
@@ -26789,11 +26929,11 @@ async function disallowInClaudeSettings(file2) {
26789
26929
  }
26790
26930
  var YAML_BEGIN = "# layermap:begin";
26791
26931
  var YAML_END = "# layermap:end";
26792
- var nodeDirectory = (env = process.env) => (env.PATH ?? "").split(path17.delimiter).find((directory) => path17.isAbsolute(directory) && existsSync8(path17.join(directory, "node"))) ?? path17.dirname(process.execPath);
26932
+ var nodeDirectory = (env = process.env) => (env.PATH ?? "").split(path18.delimiter).find((directory) => path18.isAbsolute(directory) && existsSync8(path18.join(directory, "node"))) ?? path18.dirname(process.execPath);
26793
26933
  var dshPatchBlock = (command, env) => {
26794
26934
  const node = nodeDirectory(env);
26795
- const [program = "", ...args] = command[0] === "node" ? [path17.join(node, "node"), ...command.slice(1)] : command;
26796
- const searchPath2 = `${JSON.stringify(`${node}${path17.delimiter}`)} + process.env.PATH`;
26935
+ const [program = "", ...args] = command[0] === "node" ? [path18.join(node, "node"), ...command.slice(1)] : command;
26936
+ const searchPath2 = `${JSON.stringify(`${node}${path18.delimiter}`)} + process.env.PATH`;
26797
26937
  return [
26798
26938
  `${YAML_BEGIN} (written by \`layermap setup dsh\`; \`layermap remove dsh\` deletes it)`,
26799
26939
  "- insert:",
@@ -26828,7 +26968,7 @@ async function writeDshPatch(file2, block) {
26828
26968
  `;
26829
26969
  }
26830
26970
  if (next === text) return;
26831
- await mkdir2(path17.dirname(file2), { recursive: true });
26971
+ await mkdir3(path18.dirname(file2), { recursive: true });
26832
26972
  await writeFile2(file2, next);
26833
26973
  }
26834
26974
  async function removeDshPatch(file2) {
@@ -26846,31 +26986,31 @@ async function removeDshPatch(file2) {
26846
26986
  var agentFiles = (options) => {
26847
26987
  const env = options.env ?? process.env;
26848
26988
  if (options.agent === "dsh") {
26849
- const home = env.DSH_HOME || path17.join(homedir2(), ".dsh");
26989
+ const home = env.DSH_HOME || path18.join(homedir2(), ".dsh");
26850
26990
  return {
26851
- settings: path17.join(home, "cordis.patch.yml"),
26852
- instructions: path17.join(home, "AGENTS.md")
26991
+ settings: path18.join(home, "cordis.patch.yml"),
26992
+ instructions: path18.join(home, "AGENTS.md")
26853
26993
  };
26854
26994
  }
26855
26995
  if (options.agent === "codex") {
26856
- const home = env.CODEX_HOME ?? path17.join(homedir2(), ".codex");
26857
- return { settings: path17.join(home, "config.toml"), instructions: path17.join(home, "AGENTS.md") };
26996
+ const home = env.CODEX_HOME ?? path18.join(homedir2(), ".codex");
26997
+ return { settings: path18.join(home, "config.toml"), instructions: path18.join(home, "AGENTS.md") };
26858
26998
  }
26859
26999
  if (options.scope === "user") {
26860
- const home = env.CLAUDE_CONFIG_DIR ?? path17.join(homedir2(), ".claude");
27000
+ const home = env.CLAUDE_CONFIG_DIR ?? path18.join(homedir2(), ".claude");
26861
27001
  return {
26862
- settings: path17.join(home, "settings.json"),
26863
- instructions: path17.join(home, "CLAUDE.md")
27002
+ settings: path18.join(home, "settings.json"),
27003
+ instructions: path18.join(home, "CLAUDE.md")
26864
27004
  };
26865
27005
  }
26866
27006
  const local = options.scope === "local";
26867
27007
  return {
26868
- settings: path17.join(
27008
+ settings: path18.join(
26869
27009
  options.project,
26870
27010
  ".claude",
26871
27011
  local ? "settings.local.json" : "settings.json"
26872
27012
  ),
26873
- instructions: path17.join(options.project, local ? "CLAUDE.local.md" : "CLAUDE.md")
27013
+ instructions: path18.join(options.project, local ? "CLAUDE.local.md" : "CLAUDE.md")
26874
27014
  };
26875
27015
  };
26876
27016
  async function setupAgent(options) {
@@ -26890,12 +27030,12 @@ async function setupAgent(options) {
26890
27030
  const writeLauncher = async () => {
26891
27031
  if (!published) return;
26892
27032
  const file2 = launcherFile(env);
26893
- await mkdir2(path17.dirname(file2), { recursive: true, mode: 448 });
27033
+ await mkdir3(path18.dirname(file2), { recursive: true, mode: 448 });
26894
27034
  await writeFile2(
26895
27035
  `${file2}.${process.pid}`,
26896
27036
  launcherScript(await readFile5(PUBLISHED_LAUNCHER, "utf8"), options.version)
26897
27037
  );
26898
- await rename2(`${file2}.${process.pid}`, file2);
27038
+ await rename3(`${file2}.${process.pid}`, file2);
26899
27039
  };
26900
27040
  if (published) log2(`write the launcher of LayerMap ${options.version} to ${launcherFile(env)}`);
26901
27041
  if (options.agent === "dsh") {
@@ -26996,12 +27136,15 @@ Usage:
26996
27136
  layermap explore [PATH] [--name NAME] [--line N] [--direction INCOMING|OUTGOING|BOTH]
26997
27137
  [--depth N] [--tests] [--unresolved] [--offset N]
26998
27138
  layermap search QUERY [--path DIR] [--mode ANY|ALL|LITERAL] [--max N] [--offset N]
26999
- layermap refs PATH NAME [--line N] [--path DIR] [--max N] [--cursor C]
27139
+ layermap refs PATH NAME [--line N] [--within DIR] [--max N] [--cursor C]
27000
27140
  layermap check [--base REF] [--json] [TEST...]
27001
27141
  what the uncommitted changes (or those since REF) affect,
27002
27142
  and what of them the test files given do not run; --json
27003
27143
  prints the related tests by rank and what the map cannot
27004
27144
  follow, for a program choosing which tests to run
27145
+ layermap imports [--json] every import of the project as it is now, test files
27146
+ apart: the file and line importing, the file imported,
27147
+ and the imports with no file of the project, with why
27005
27148
 
27006
27149
  The project is the Git work tree around the current directory unless --project names one; the MCP
27007
27150
  server also maps any other repository a tool call's path names.
@@ -27011,10 +27154,10 @@ var log = (line) => process.stderr.write(`${line}
27011
27154
  async function checkedTests(project, tests) {
27012
27155
  const here = await realpath4(process.cwd());
27013
27156
  return tests.map((test) => {
27014
- const relative = path18.relative(project, path18.resolve(here, test));
27015
- if (!relative || relative === ".." || relative.startsWith(`..${path18.sep}`) || path18.isAbsolute(relative))
27157
+ const relative = path19.relative(project, path19.resolve(here, test));
27158
+ if (!relative || relative === ".." || relative.startsWith(`..${path19.sep}`) || path19.isAbsolute(relative))
27016
27159
  throw new Error(`${test} is not in ${project}.`);
27017
- return relative.split(path18.sep).join("/");
27160
+ return relative.split(path19.sep).join("/");
27018
27161
  });
27019
27162
  }
27020
27163
  var usage = (code) => {
@@ -27040,6 +27183,7 @@ async function main(argv) {
27040
27183
  unresolved: { type: "boolean", default: false },
27041
27184
  offset: { type: "string" },
27042
27185
  path: { type: "string" },
27186
+ within: { type: "string" },
27043
27187
  mode: { type: "string" },
27044
27188
  max: { type: "string" },
27045
27189
  cursor: { type: "string" },
@@ -27056,7 +27200,7 @@ async function main(argv) {
27056
27200
  return 0;
27057
27201
  }
27058
27202
  if (values.help || !command) return usage(command ? 0 : 1);
27059
- if (values.json && command !== "check") return usage(1);
27203
+ if (values.json && command !== "check" && command !== "imports") return usage(1);
27060
27204
  const { directory: project, git: git2 } = await projectDirectory(values.project ?? process.cwd());
27061
27205
  const cache = cacheDirectory();
27062
27206
  const open3 = async (directory) => {
@@ -27086,7 +27230,13 @@ async function main(argv) {
27086
27230
  return done ? 0 : 1;
27087
27231
  }
27088
27232
  if (command === "mcp") {
27089
- await serveMcp({ version: version2, start: { directory: project, git: git2 }, open: open3, log });
27233
+ await serveMcp({
27234
+ version: version2,
27235
+ start: { directory: project, git: git2 },
27236
+ open: open3,
27237
+ log,
27238
+ record: mapCallLog(cache)
27239
+ });
27090
27240
  return 0;
27091
27241
  }
27092
27242
  const number4 = (value) => value === void 0 ? void 0 : Number(value);
@@ -27112,6 +27262,22 @@ async function main(argv) {
27112
27262
  `);
27113
27263
  return 0;
27114
27264
  }
27265
+ if (command === "imports") {
27266
+ const imports = await map2.imports(signal);
27267
+ process.stdout.write(
27268
+ values.json ? `${JSON.stringify(imports)}
27269
+ ` : [
27270
+ `IMPORTS (${imports.imports.length})`,
27271
+ ...imports.imports.map((item) => `${item.from}:${item.line} \u2192 ${item.to}`),
27272
+ `UNRESOLVED IMPORTS (${imports.unresolved.length})`,
27273
+ ...imports.unresolved.map(
27274
+ (item) => `${item.from}:${item.line} ${item.specifier} ${item.reason}`
27275
+ ),
27276
+ ""
27277
+ ].join("\n")
27278
+ );
27279
+ return 0;
27280
+ }
27115
27281
  const call = {
27116
27282
  explore: [
27117
27283
  MAP_TOOL_NAMES.explore,
@@ -27146,8 +27312,10 @@ async function main(argv) {
27146
27312
  refs: [
27147
27313
  MAP_TOOL_NAMES.references,
27148
27314
  {
27149
- symbol: { path: rest[0], name: rest[1], line: number4(values.line) },
27150
- path: values.path,
27315
+ path: rest[0],
27316
+ name: rest[1],
27317
+ line: number4(values.line),
27318
+ within: values.within,
27151
27319
  maxResults: number4(values.max),
27152
27320
  cursor: values.cursor
27153
27321
  }