layermap 0.1.38 → 0.1.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -225,6 +225,7 @@ npx layermap search "invoice total"
225
225
  npx layermap refs src/billing/tax.ts calculateTax
226
226
  npx layermap check --base main
227
227
  npx layermap check test/billing.test.ts # also: what of the change this test does not run
228
+ npx layermap check --json # related tests by rank and what the map cannot follow, as JSON
228
229
  ```
229
230
 
230
231
  ## FAQ
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -14740,7 +14740,6 @@ process.once(
14740
14740
  helper.stdin.end(
14741
14741
  JSON.stringify({
14742
14742
  operation: message.operation,
14743
- modFile: message.modFile ?? "",
14744
14743
  files: message.files,
14745
14744
  ...message.targets ? { targets: message.targets } : {}
14746
14745
  })
@@ -15710,10 +15710,15 @@ var MapVirtualFiles = class {
15710
15710
  import path5 from "node:path";
15711
15711
  function pnpmPackages(text2) {
15712
15712
  const lines = text2.replace(/^\uFEFF/u, "").split(/\r?\n/u).filter((line) => line.trim() && !line.trimStart().startsWith("#"));
15713
- if (!/^packages:\s*(?:#.*)?$/u.test(lines[0] ?? "")) return void 0;
15713
+ const keys = lines.flatMap(
15714
+ (line, index) => /^packages:\s*(?:#.*)?$/u.test(line) ? [index] : []
15715
+ );
15716
+ if (keys.length !== 1 || keys[0] === void 0) return void 0;
15717
+ const after = lines.slice(keys[0] + 1);
15718
+ const end = after.findIndex((line) => !/^\s/u.test(line) && !line.startsWith("-"));
15714
15719
  const patterns = [];
15715
- for (const line of lines.slice(1)) {
15716
- const match = /^\s+-\s+("(?:[^"\\]|\\.)*"|'(?:[^']|'')*'|[^\s#]+)\s*(?:#.*)?$/u.exec(line);
15720
+ for (const line of end === -1 ? after : after.slice(0, end)) {
15721
+ const match = /^\s*-\s+("(?:[^"\\]|\\.)*"|'(?:[^']|'')*'|[^\s#]+)\s*(?:#.*)?$/u.exec(line);
15717
15722
  if (!match?.[1]) return void 0;
15718
15723
  const value = match[1];
15719
15724
  try {
@@ -15821,8 +15826,13 @@ async function discoverMapConfiguration(api, files) {
15821
15826
  const workspaceLinks = [...new Map(links.map((link) => [link.from, link])).values()];
15822
15827
  applyMapWorkspaceLinks(files, workspaceLinks);
15823
15828
  const outputs = /* @__PURE__ */ new Map();
15829
+ const members = /* @__PURE__ */ new Map();
15824
15830
  for (const configPath of Object.keys(files.input.files).filter((file2) => configuration.test(file2)).sort()) {
15825
15831
  const parsed = await api.parseConfigFile(mapVirtualPath(configPath));
15832
+ members.set(
15833
+ configPath,
15834
+ new Set(parsed.fileNames.flatMap((source) => mapRelativePath(source) ?? []))
15835
+ );
15826
15836
  const { rootDir, outDir, outFile, noEmit, declarationDir } = parsed.options;
15827
15837
  if (typeof rootDir !== "string" || typeof outDir !== "string" || outFile || noEmit) continue;
15828
15838
  for (const source of parsed.fileNames) {
@@ -15870,6 +15880,7 @@ async function discoverMapConfiguration(api, files) {
15870
15880
  applyMapWorkspaceContents(files, workspace);
15871
15881
  const openFiles = files.input.inventory.filter((file2) => /\.[cm]?[jt]sx?$/u.test(file2));
15872
15882
  const snapshot = await api.updateSnapshot({ openFiles: openFiles.map(mapVirtualPath) });
15883
+ let opened;
15873
15884
  try {
15874
15885
  const selected = /* @__PURE__ */ new Map();
15875
15886
  for (let start = 0; start < openFiles.length; start += 32) {
@@ -15892,6 +15903,26 @@ async function discoverMapConfiguration(api, files) {
15892
15903
  entry.rootFiles.push(file2);
15893
15904
  }
15894
15905
  }
15906
+ const inferred = selected.get("INFERRED");
15907
+ const candidates = inferred ? holders(members, selected) : /* @__PURE__ */ new Map();
15908
+ const held = /* @__PURE__ */ new Map();
15909
+ for (const file2 of inferred?.rootFiles ?? []) {
15910
+ const configPath = holder(candidates, file2);
15911
+ if (configPath) held.set(configPath, [...held.get(configPath) ?? [], file2]);
15912
+ }
15913
+ if (held.size && inferred) {
15914
+ opened = await api.updateSnapshot({ openProjects: [...held.keys()].map(mapVirtualPath) });
15915
+ for (const [configPath, rootFiles] of held) {
15916
+ const project = opened.getProject(mapVirtualPath(configPath));
15917
+ if (!project) continue;
15918
+ const entry = selected.get(configPath);
15919
+ if (entry) entry.rootFiles.push(...rootFiles);
15920
+ else selected.set(configPath, { configPath, rootFiles, project });
15921
+ const moved = new Set(rootFiles);
15922
+ inferred.rootFiles = inferred.rootFiles.filter((file2) => !moved.has(file2));
15923
+ }
15924
+ if (!inferred.rootFiles.length) selected.delete("INFERRED");
15925
+ }
15895
15926
  const projects = [];
15896
15927
  for (const { project, ...entry } of selected.values()) {
15897
15928
  const inputFiles = (await project.program.getSourceFileNames()).flatMap((file2) => {
@@ -15902,9 +15933,47 @@ async function discoverMapConfiguration(api, files) {
15902
15933
  }
15903
15934
  return { projects, workspace };
15904
15935
  } finally {
15936
+ await opened?.dispose();
15905
15937
  await snapshot.dispose();
15906
15938
  }
15907
15939
  }
15940
+ var directoryOf = (file2) => {
15941
+ const directory = path6.posix.dirname(file2);
15942
+ return directory === "." ? "" : directory;
15943
+ };
15944
+ var within = (directory, file2) => !directory || inside(directory, file2);
15945
+ function holders(members, selected) {
15946
+ const governing = /* @__PURE__ */ new Set();
15947
+ for (const key2 of selected.keys()) if (key2 !== "INFERRED") governing.add(directoryOf(key2));
15948
+ const governed = /* @__PURE__ */ new Map();
15949
+ for (const [key2, entry] of selected)
15950
+ if (key2 !== "INFERRED") for (const file2 of entry.rootFiles) governed.set(file2, key2);
15951
+ const candidates = /* @__PURE__ */ new Map();
15952
+ for (const [configPath, sources] of members) {
15953
+ const directory = directoryOf(configPath);
15954
+ const deeper = [...governing].filter((own) => own !== directory && within(directory, own));
15955
+ if (!deeper.length) {
15956
+ candidates.set(configPath, sources);
15957
+ continue;
15958
+ }
15959
+ const spans = [...sources].some((source) => {
15960
+ const owner = governed.get(source);
15961
+ return owner !== void 0 && deeper.includes(directoryOf(owner));
15962
+ });
15963
+ if (!spans) candidates.set(configPath, sources);
15964
+ }
15965
+ return candidates;
15966
+ }
15967
+ function holder(candidates, file2) {
15968
+ let best;
15969
+ for (const [configPath, sources] of candidates) {
15970
+ if (!sources.has(file2)) continue;
15971
+ const directory = directoryOf(configPath);
15972
+ const depth = !directory ? 0 : inside(directory, file2) ? directory.split("/").length : -1;
15973
+ if (!best || depth > best.depth) best = { configPath, depth };
15974
+ }
15975
+ return best?.configPath;
15976
+ }
15908
15977
  function applyMapWorkspace(files, workspace) {
15909
15978
  applyMapWorkspaceLinks(files, workspace.links);
15910
15979
  applyMapWorkspaceContents(files, workspace);
@@ -31979,11 +32048,11 @@ async function extractProjectMap(project, input, trace, read, installed) {
31979
32048
  await readState(symbol2);
31980
32049
  continue;
31981
32050
  }
31982
- const holder = callable && item.holder ? materialize(item.holder) : void 0;
31983
- if (holder && item.holder) callableHolders.add(key(item.holder));
32051
+ const holder2 = callable && item.holder ? materialize(item.holder) : void 0;
32052
+ if (holder2 && item.holder) callableHolders.add(key(item.holder));
31984
32053
  for (const destination of callable?.objects ?? [])
31985
32054
  collect.relation({
31986
- from: holder?.id ?? item.owner,
32055
+ from: holder2?.id ?? item.owner,
31987
32056
  to: destination.id,
31988
32057
  kind: item.kind,
31989
32058
  anchor: item.anchor,
package/dist/cli.mjs CHANGED
@@ -16055,6 +16055,7 @@ var mapPathAllowed = (relative, prefixes) => prefixes.some(
16055
16055
  var mapTestPath = (path17) => /(?:^|\/)(?:__tests__|tests?|fixtures?|e2e|testdata)(?:\/|$)|\.(?:spec|test)\.|_test\.(?:go|py)$|(?:^|\/)(?:test_[^/]*\.py|conftest\.py)$/iu.test(
16056
16056
  path17
16057
16057
  );
16058
+ var MAP_MIGRATION_PATH = /(?:^|\/)migrations?\/|\.sql$/iu;
16058
16059
 
16059
16060
  // src/project-map-reference-types.ts
16060
16061
  var MapReferenceKindSchema = external_exports.enum([
@@ -17239,6 +17240,7 @@ function mapPageFrontier(frontier, rows2) {
17239
17240
 
17240
17241
  // src/project-map-language-go.ts
17241
17242
  import { existsSync as existsSync4 } from "node:fs";
17243
+ import { posix } from "node:path";
17242
17244
 
17243
17245
  // src/project-map-analysis-validation.ts
17244
17246
  function validateMapAnalysis(analysis, input) {
@@ -17448,7 +17450,7 @@ function mapFactsAnalysis(facts, input, context) {
17448
17450
  optionsDigest: context.optionsDigest,
17449
17451
  mode: context.configPath ? "CONFIGURED" : "INFERRED",
17450
17452
  inputFiles: Object.keys(input.files).sort(),
17451
- configurationFiles: context.configPath ? [context.configPath] : []
17453
+ configurationFiles: context.configurationFiles ? [...context.configurationFiles] : context.configPath ? [context.configPath] : []
17452
17454
  }
17453
17455
  ],
17454
17456
  objects: [],
@@ -18037,11 +18039,12 @@ function runMapOperation(resources, input, schema, signal, observeTiming) {
18037
18039
 
18038
18040
  // src/project-map-language-go.ts
18039
18041
  var goModule = /(?:^|\/)go\.mod$/u;
18042
+ var goWork = /(?:^|\/)go\.work$/u;
18040
18043
  var codeHosts = /* @__PURE__ */ new Set(["github.com", "gitlab.com", "bitbucket.org"]);
18041
18044
  var GO_MAP_LANGUAGE = Object.freeze({
18042
- id: "go-1.24-map-v9",
18045
+ id: "go-1.24-map-v10",
18043
18046
  claims: (path17) => path17.endsWith(".go"),
18044
- reads: (path17) => goModule.test(path17),
18047
+ reads: (path17) => goModule.test(path17) || goWork.test(path17),
18045
18048
  // A module path, or the standard library, whose first path element has no dot.
18046
18049
  importName: (specifier) => {
18047
18050
  const parts = specifier.split("/");
@@ -18062,15 +18065,68 @@ var GO_GAPS = [
18062
18065
  "DETAILED_REFERENCES_AVAILABLE_ON_DEMAND",
18063
18066
  "LOCAL_BINDINGS_MAPPED_WHEN_LINKED"
18064
18067
  ];
18065
- var goMapAnalysis = (facts, input, modFile) => mapFactsAnalysis(facts, input, {
18068
+ var goMapAnalysis = (facts, input, configurations) => mapFactsAnalysis(facts, input, {
18066
18069
  language: "go",
18067
18070
  offsets: "UTF8_BYTES",
18068
- ...modFile ? { configPath: modFile } : {},
18071
+ ...input.configPath ? { configPath: input.configPath } : {},
18072
+ configurationFiles: configurations,
18069
18073
  optionsDigest: digestValue({ goos: "linux", goarch: "amd64", cgo: false }),
18070
- gaps: [...modFile ? [] : [{ code: "NO_GO_MODULE" }], ...GO_GAPS.map((code) => ({ code }))],
18074
+ gaps: [
18075
+ ...input.configPath ? [] : [{ code: "NO_GO_MODULE" }],
18076
+ ...GO_GAPS.map((code) => ({ code }))
18077
+ ],
18071
18078
  typeIssues: "GO_TYPE_CHECK_ISSUES",
18072
18079
  contract: "Declares a Go interface. This does not establish runtime enforcement or business authority."
18073
18080
  });
18081
+ var goLocalModules = (path17, text) => {
18082
+ const directive = goWork.test(path17) ? "use" : "replace";
18083
+ const found = [];
18084
+ let block = false;
18085
+ for (const raw of text.split("\n")) {
18086
+ const line = raw.replace(/\/\/.*$/u, "").trim();
18087
+ let entry;
18088
+ if (block) {
18089
+ if (line === ")") block = false;
18090
+ else entry = line;
18091
+ } else if (line === `${directive} (`) block = true;
18092
+ else if (line.startsWith(`${directive} `)) entry = line.slice(directive.length + 1);
18093
+ const target = directive === "use" ? entry : entry?.split("=>")[1];
18094
+ const directory = target?.trim().split(/\s+/u)[0]?.replace(/^(["`])(.*)\1$/u, "$2");
18095
+ if (!directory || !/^\.\.?(?:\/|$)/u.test(directory)) continue;
18096
+ const joined = posix.normalize(posix.join(posix.dirname(path17), directory)).replace(/\/$/u, "");
18097
+ if (joined !== ".." && !joined.startsWith("../")) found.push(joined);
18098
+ }
18099
+ return found;
18100
+ };
18101
+ var goModuleGroups = (files, text) => {
18102
+ const modules = files.filter((path17) => goModule.test(path17)).sort();
18103
+ const moduleAt = new Map(modules.map((path17) => [posix.dirname(path17), path17]));
18104
+ const parent = new Map(modules.map((path17) => [path17, path17]));
18105
+ const root = (path17) => {
18106
+ const up = parent.get(path17) ?? path17;
18107
+ return up === path17 ? path17 : root(up);
18108
+ };
18109
+ const works = [];
18110
+ for (const path17 of [...files].filter((file2) => goModule.test(file2) || goWork.test(file2)).sort()) {
18111
+ const linked = goLocalModules(path17, text(path17)).flatMap((dir) => moduleAt.get(dir) ?? []);
18112
+ const first = goWork.test(path17) ? linked[0] : path17;
18113
+ if (!first) continue;
18114
+ if (goWork.test(path17)) works.push([path17, first]);
18115
+ for (const module of linked) {
18116
+ const [low = first, high = module] = [root(first), root(module)].sort();
18117
+ if (low !== high) parent.set(high, low);
18118
+ }
18119
+ }
18120
+ const members = /* @__PURE__ */ new Map();
18121
+ for (const path17 of modules) members.set(root(path17), [...members.get(root(path17)) ?? [], path17]);
18122
+ const named = new Map(works.reverse().map(([work, module]) => [root(module), work]));
18123
+ return new Map(
18124
+ modules.map((path17) => [
18125
+ path17,
18126
+ { configPath: named.get(root(path17)) ?? root(path17), modules: members.get(root(path17)) ?? [] }
18127
+ ])
18128
+ );
18129
+ };
18074
18130
  var GoMapAnalyzer = class {
18075
18131
  constructor(resources = installedGoMapResources()) {
18076
18132
  this.resources = resources;
@@ -18096,28 +18152,37 @@ var GoMapAnalyzer = class {
18096
18152
  }
18097
18153
  }
18098
18154
  async analyze(session, signal) {
18099
- const modules = session.readable.map((entry) => entry.path).filter((path17) => goModule.test(path17)).sort();
18155
+ const paths = session.readable.map((entry) => entry.path);
18156
+ const groupOf = goModuleGroups(paths, (path17) => session.texts[path17] ?? "");
18100
18157
  const moduleOf = (path17) => {
18101
18158
  let best;
18102
- for (const modFile of modules) {
18159
+ for (const modFile of groupOf.keys()) {
18103
18160
  const directory = modFile.slice(0, modFile.lastIndexOf("/") + 1);
18104
18161
  if (path17.startsWith(directory) && (!best || directory.length > best.lastIndexOf("/") + 1))
18105
18162
  best = modFile;
18106
18163
  }
18107
18164
  return best;
18108
18165
  };
18109
- const groups = /* @__PURE__ */ new Map();
18110
- for (const entry of session.readable) {
18111
- if (!this.claims(entry.path)) continue;
18112
- const key = moduleOf(entry.path) ?? "";
18113
- const into = groups.get(key);
18114
- if (into) into.push(entry.path);
18115
- else groups.set(key, [entry.path]);
18166
+ const contexts = /* @__PURE__ */ new Map();
18167
+ for (const path17 of paths) {
18168
+ if (!this.claims(path17)) continue;
18169
+ const module = moduleOf(path17);
18170
+ const group = module ? groupOf.get(module) : void 0;
18171
+ const configPath = group?.configPath ?? "";
18172
+ const into = contexts.get(configPath);
18173
+ if (into) into.sources.push(path17);
18174
+ else
18175
+ contexts.set(configPath, {
18176
+ configurations: group ? [.../* @__PURE__ */ new Set([...group.modules, configPath])].sort() : [],
18177
+ sources: [path17]
18178
+ });
18116
18179
  }
18117
- for (const modFile of [...groups.keys()].sort()) {
18180
+ for (const [configPath, { configurations, sources }] of [...contexts].sort(
18181
+ ([left], [right]) => left < right ? -1 : left > right ? 1 : 0
18182
+ )) {
18118
18183
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
18119
18184
  const files = /* @__PURE__ */ Object.create(null);
18120
- for (const path17 of [...groups.get(modFile) ?? [], ...modFile ? [modFile] : []]) {
18185
+ for (const path17 of [...sources, ...configurations]) {
18121
18186
  const text = session.texts[path17];
18122
18187
  if (text === void 0)
18123
18188
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
@@ -18126,26 +18191,26 @@ var GoMapAnalyzer = class {
18126
18191
  const input = {
18127
18192
  contextRef: digestValue({
18128
18193
  analyzer: this.id,
18129
- configPath: modFile || null
18194
+ configPath: configPath || null
18130
18195
  }),
18131
- ...modFile ? { configPath: modFile } : {},
18196
+ ...configPath ? { configPath } : {},
18132
18197
  files,
18133
18198
  inventory: Object.keys(files).sort(),
18134
18199
  syntaxOnly: false
18135
18200
  };
18136
18201
  const built = existsSync4(this.resources.compilerPath);
18137
- const reused = session.reuse(input.contextRef, { modFile, built }, Object.keys(files));
18202
+ const reused = session.reuse(input.contextRef, { configurations, built }, Object.keys(files));
18138
18203
  if (reused) {
18139
18204
  session.accept(reused);
18140
18205
  continue;
18141
18206
  }
18142
18207
  const facts = built ? await this.operation(
18143
- { ...input, operation: "BUILD", modFile },
18208
+ { ...input, operation: "BUILD" },
18144
18209
  MapFactsSchema,
18145
18210
  signal,
18146
18211
  session.observe
18147
18212
  ) : { files: [], objects: [], relations: [], notes: [], typeErrors: 0 };
18148
- const analysis = goMapAnalysis(facts, input, modFile || void 0);
18213
+ const analysis = goMapAnalysis(facts, input, configurations);
18149
18214
  if (!built) analysis.gaps.push({ code: "GO_ANALYZER_NOT_BUILT" });
18150
18215
  validateMapAnalysis(analysis, input);
18151
18216
  session.accept(analysis);
@@ -18156,13 +18221,12 @@ var GoMapAnalyzer = class {
18156
18221
  return { pages: references.map(() => null), requiredFiles: [] };
18157
18222
  const files = /* @__PURE__ */ Object.create(null);
18158
18223
  for (const [path17, value] of Object.entries(input.files))
18159
- if (this.claims(path17) || goModule.test(path17)) files[path17] = value;
18224
+ if (this.claims(path17) || this.reads(path17)) files[path17] = value;
18160
18225
  const facts = await this.operation(
18161
18226
  {
18162
18227
  ...input,
18163
18228
  files,
18164
18229
  operation: "REFERENCES",
18165
- modFile: input.configPath ?? "",
18166
18230
  targets: references.map(({ targetPath, symbolStart }) => ({
18167
18231
  path: targetPath,
18168
18232
  offset: mapFactsOffset(input.files[targetPath] ?? "", symbolStart, "UTF8_BYTES")
@@ -18933,7 +18997,7 @@ var miniprogramEventOf = (target) => {
18933
18997
 
18934
18998
  // src/project-map-language-typescript.ts
18935
18999
  var TYPESCRIPT_MAP_LANGUAGE = Object.freeze({
18936
- id: "typescript-7.0.2-map-v24",
19000
+ id: "typescript-7.0.2-map-v25",
18937
19001
  claims: (path17) => /\.[cm]?[jt]sx?$/u.test(path17),
18938
19002
  reads: (path17) => path17.endsWith(".json") || path17.endsWith(".wxml") || path17 === "pnpm-workspace.yaml",
18939
19003
  create: () => new TypeScriptMapAnalyzer()
@@ -22712,6 +22776,66 @@ function newModuleDependencies(store, cache, working, base, files) {
22712
22776
  (left, right) => Number(right.back !== void 0) - Number(left.back !== void 0) || (left.from < right.from ? -1 : left.from > right.from ? 1 : 0) || (left.to < right.to ? -1 : left.to > right.to ? 1 : 0)
22713
22777
  );
22714
22778
  }
22779
+ var MANIFEST = /(?:^|\/)(?:package\.json|go\.mod|pom\.xml|build\.gradle(?:\.kts)?|pyproject\.toml|setup\.py|setup\.cfg)$/u;
22780
+ var directoryOf3 = (path17) => path17.slice(0, Math.max(path17.lastIndexOf("/"), 0));
22781
+ var directoryLabel = (directory) => directory ? `${directory}/` : "./";
22782
+ function mapReuseImports(store, cache, working) {
22783
+ const roots = store.listEntries(working).filter((entry) => MANIFEST.test(entry.path)).map((entry) => directoryOf3(entry.path)).sort((left, right) => right.length - left.length);
22784
+ const packageOf = (path17) => roots.find((root) => !root || path17.startsWith(`${root}/`)) ?? "";
22785
+ const directories = /* @__PURE__ */ new Map();
22786
+ const packages = /* @__PURE__ */ new Map();
22787
+ const files = /* @__PURE__ */ new Set();
22788
+ for (const { source, target } of cache.imports(store, working)) {
22789
+ if (target === null) continue;
22790
+ files.add(`${source}\0${target}`);
22791
+ if (mapTestPath(source)) continue;
22792
+ const from = directoryOf3(source);
22793
+ const to = directoryOf3(target);
22794
+ if (from !== to) {
22795
+ const targets = directories.get(from) ?? /* @__PURE__ */ new Map();
22796
+ targets.set(to, []);
22797
+ directories.set(from, targets);
22798
+ }
22799
+ const fromPackage = packageOf(source);
22800
+ const toPackage = packageOf(target);
22801
+ if (fromPackage !== toPackage)
22802
+ packages.set(fromPackage, (packages.get(fromPackage) ?? /* @__PURE__ */ new Set()).add(toPackage));
22803
+ }
22804
+ const use = (user, [from, fromPackage], [to, toPackage]) => {
22805
+ const imported = from === to || directories.get(from)?.has(to) === true;
22806
+ return {
22807
+ user,
22808
+ from: directoryLabel(from),
22809
+ to: directoryLabel(to),
22810
+ imported,
22811
+ cycle: !imported && pathBetween(directories, to, from) !== void 0,
22812
+ ...fromPackage === toPackage ? {} : { packages: [directoryLabel(fromPackage), directoryLabel(toPackage)] }
22813
+ };
22814
+ };
22815
+ const graph = new MapViewGraph(store, working);
22816
+ const usedFrom = /* @__PURE__ */ new Map();
22817
+ const used = (path17) => {
22818
+ let found = usedFrom.get(path17);
22819
+ if (found === void 0) {
22820
+ found = graph.relationsTo(graph.objectsAt(path17).map((object2) => object2.id)).some((relation) => graph.object(relation.from).anchor.path !== path17);
22821
+ usedFrom.set(path17, found);
22822
+ }
22823
+ return found;
22824
+ };
22825
+ return (path17, existing) => {
22826
+ const added = [directoryOf3(path17), packageOf(path17)];
22827
+ const old = [directoryOf3(existing), packageOf(existing)];
22828
+ const ahead = use("NEW", added, old);
22829
+ if (files.has(`${path17}\0${existing}`)) return ahead;
22830
+ if (files.has(`${existing}\0${path17}`))
22831
+ return { ...use("EXISTING", old, added), from: existing, to: path17 };
22832
+ const usable = used(existing);
22833
+ if (usable && ahead.imported) return ahead;
22834
+ if (directories.get(old[0])?.has(added[0])) return use("EXISTING", old, added);
22835
+ if (usable && (added[1] === old[1] || packages.get(added[1])?.has(old[1]))) return ahead;
22836
+ return packages.get(old[1])?.has(added[1]) ? use("EXISTING", old, added) : void 0;
22837
+ };
22838
+ }
22715
22839
 
22716
22840
  // src/project-map-names.ts
22717
22841
  import { readFileSync as readFileSync3 } from "node:fs";
@@ -22865,7 +22989,7 @@ var MODULES = /* @__PURE__ */ new Set(["FILE", "PACKAGE", "CONFIG"]);
22865
22989
  var MEMBER_CONTAINERS2 = /* @__PURE__ */ new Set(["CLASS", "INTERFACE", "TYPE", "ENUM"]);
22866
22990
  var KINDS = /* @__PURE__ */ new Set(["FUNCTION", "METHOD", "CLASS", "VARIABLE"]);
22867
22991
  var MIN_LINES = 3;
22868
- var SHORT_COPIES = 3;
22992
+ var CONVENTION = 3;
22869
22993
  var ALIKE = 0.8;
22870
22994
  var SIBLINGS_ALIKE = 0.95;
22871
22995
  var KEYWORDS = new Set(
@@ -22917,7 +23041,7 @@ function lineWords(line) {
22917
23041
  var within2 = (lines, declaration) => lines.some(([from, to]) => from <= declaration.startLine && declaration.endLine <= to);
22918
23042
  var copyText = (code) => code.replace(/^export\s+(?:default\s+)?/u, "").replace(/\s+/gu, " ").trim();
22919
23043
  async function similarCode(store, working, base, files, read) {
22920
- const code = (path17) => mapCodePath(path17) !== void 0 && !mapTestPath(path17);
23044
+ const code = (path17) => mapCodePath(path17) && !mapTestPath(path17) && !MAP_MIGRATION_PATH.test(path17);
22921
23045
  const changed = files.filter((file2) => file2.status !== "DELETED" && code(file2.path));
22922
23046
  if (!changed.length) return [];
22923
23047
  const names = (version2, path17) => new Set(declarations(rows(store, version2, path17)).map((item) => item.qualifiedName));
@@ -22951,28 +23075,29 @@ async function similarCode(store, working, base, files, read) {
22951
23075
  }
22952
23076
  const all = [];
22953
23077
  const shortCopies = /* @__PURE__ */ new Map();
22954
- await Promise.all(
22955
- [...byPath].map(async ([path17, inFile]) => {
23078
+ const texts = await Promise.all(
23079
+ [...byPath].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(async ([path17, inFile]) => {
22956
23080
  const found2 = declarations(inFile).filter(
22957
23081
  (item) => KINDS.has(item.kind) && (long(item) ? longAdded : shortNames.has(item.qualifiedName))
22958
23082
  );
22959
- if (!found2.length) return;
22960
- const text = await read(path17);
22961
- if (text === void 0) return;
22962
- const lines = text.split("\n").map(lineWords);
22963
- for (const declaration of found2) {
22964
- if (!long(declaration)) {
22965
- const key = `${declaration.qualifiedName}\0${copyText(text.slice(declaration.start, declaration.end))}`;
22966
- shortCopies.set(key, [...shortCopies.get(key) ?? [], declaration]);
22967
- continue;
22968
- }
22969
- const words = /* @__PURE__ */ new Map();
22970
- for (const line of lines.slice(declaration.startLine - 1, declaration.endLine))
22971
- for (const word of line) words.set(word, (words.get(word) ?? 0) + 1);
22972
- all.push({ declaration, words });
22973
- }
23083
+ return { found: found2, text: found2.length ? await read(path17) : void 0 };
22974
23084
  })
22975
23085
  );
23086
+ for (const { found: found2, text } of texts) {
23087
+ if (text === void 0) continue;
23088
+ const lines = text.split("\n").map(lineWords);
23089
+ for (const declaration of found2) {
23090
+ if (!long(declaration)) {
23091
+ const key = `${declaration.qualifiedName}\0${copyText(text.slice(declaration.start, declaration.end))}`;
23092
+ shortCopies.set(key, [...shortCopies.get(key) ?? [], declaration]);
23093
+ continue;
23094
+ }
23095
+ const words = /* @__PURE__ */ new Map();
23096
+ for (const line of lines.slice(declaration.startLine - 1, declaration.endLine))
23097
+ for (const word of line) words.set(word, (words.get(word) ?? 0) + 1);
23098
+ all.push({ declaration, words });
23099
+ }
23100
+ }
22976
23101
  const frequency = /* @__PURE__ */ new Map();
22977
23102
  for (const { words } of all)
22978
23103
  for (const word of words.keys()) frequency.set(word, (frequency.get(word) ?? 0) + 1);
@@ -23033,7 +23158,7 @@ async function similarCode(store, working, base, files, read) {
23033
23158
  const siblings = declaration.container !== void 0 && them.container === declaration.container;
23034
23159
  return score >= (siblings ? SIBLINGS_ALIKE : ALIKE);
23035
23160
  }).sort(([, left], [, right]) => right - left);
23036
- if (!alike.length) continue;
23161
+ if (!alike.length || alike.length > CONVENTION) continue;
23037
23162
  const linked = linkedTo(declaration);
23038
23163
  const unlinked = alike.filter(([other]) => !linked.has(other.declaration.id));
23039
23164
  const best = unlinked[0];
@@ -23041,7 +23166,7 @@ async function similarCode(store, working, base, files, read) {
23041
23166
  }
23042
23167
  for (const copies of shortCopies.values()) {
23043
23168
  const existing = copies.filter((copy) => !added.has(copy.id)).sort((left, right) => left.path < right.path ? -1 : 1);
23044
- if (!existing.length || existing.length > SHORT_COPIES) continue;
23169
+ if (!existing.length || existing.length > CONVENTION) continue;
23045
23170
  for (const declaration of copies) {
23046
23171
  if (!added.has(declaration.id)) continue;
23047
23172
  const linked = linkedTo(declaration);
@@ -23242,11 +23367,17 @@ var NON_CODE = [
23242
23367
  /(?:^|\/)(?:package\.json|go\.mod|pom\.xml|build\.gradle(?:\.kts)?|settings\.gradle(?:\.kts)?|pyproject\.toml|setup\.py|setup\.cfg|requirements[^/]*\.txt|Makefile|Dockerfile|tsconfig[^/]*\.json)$/u,
23243
23368
  "build or dependency file"
23244
23369
  ],
23245
- [/(?:^|\/)migrations?\/|\.sql$/iu, "database migration or schema"],
23370
+ [MAP_MIGRATION_PATH, "database migration or schema"],
23246
23371
  [/(?:^|\/)\.env[^/]*$|\.(?:ya?ml|toml|ini|properties|conf|cfg)$/iu, "configuration"],
23247
23372
  [/\.(?:html?|jinja2?|j2|hbs|ejs|tmpl|tpl|gohtml|vue|svelte|wxml)$/iu, "template"]
23248
23373
  ];
23249
23374
  var nonCodeKind = (path17) => NON_CODE.find(([pattern]) => pattern.test(path17))?.[1];
23375
+ var UNANALYZED = [
23376
+ [/\.(?:sh|bash|zsh|fish|ps1|bat|cmd)$/iu, "shell script"],
23377
+ [/\.(?:css|scss|sass|less|styl|wxss|acss)$/iu, "style sheet"]
23378
+ ];
23379
+ var DOCUMENTATION = /\.(?:md|mdx|markdown|rst|adoc)$|(?:^|\/)(?:LICENSE|NOTICE)[^/]*$/iu;
23380
+ var unmappedKind = (path17, binary) => nonCodeKind(path17) ?? (binary ? "binary file" : DOCUMENTATION.test(path17) ? void 0 : UNANALYZED.find(([pattern]) => pattern.test(path17))?.[1] ?? "unanalyzed file");
23250
23381
  var LIMITS = Object.freeze({
23251
23382
  depth: 8,
23252
23383
  declarations: 800,
@@ -23678,6 +23809,7 @@ async function mapChangeImpact(store, working, base, changes, shapes, until, pro
23678
23809
  const tracer = new Tracer(graph, memberCalls, new MapShapeUses(graph, shapes.working, until));
23679
23810
  const changed = [];
23680
23811
  const unclear = [];
23812
+ const unmapped = [];
23681
23813
  const removed = [];
23682
23814
  const declarations2 = (g, path17) => g.objectsAt(path17).filter((object2) => !mapIsModule(object2) && g.isAddressable(object2));
23683
23815
  const units = (g, path17) => mapMiniprogramTemplate(path17) ? g.objectsAt(path17).filter((object2) => mapIsModule(object2) && object2.parsing === "PARSED") : declarations2(g, path17);
@@ -23691,17 +23823,21 @@ async function mapChangeImpact(store, working, base, changes, shapes, until, pro
23691
23823
  if (!unclear.includes(note)) unclear.push(note);
23692
23824
  };
23693
23825
  for (const file2 of changes.files) {
23694
- if (file2.binary) continue;
23695
- const kind = nonCodeKind(file2.path);
23696
- const objects2 = file2.status === "DELETED" ? [] : graph.objectsAt(file2.path);
23826
+ const objects2 = file2.status === "DELETED" || file2.binary ? [] : graph.objectsAt(file2.path);
23697
23827
  if (testCode(file2.path)) {
23698
- if (file2.status !== "DELETED") tracer.test(file2.path, void 0, "changed in this diff", 1);
23828
+ if (file2.status !== "DELETED" && !file2.binary)
23829
+ tracer.test(file2.path, void 0, "changed in this diff", 1);
23699
23830
  continue;
23700
23831
  }
23701
23832
  const template = mapMiniprogramTemplate(file2.path);
23702
- const analyzed = objects2.length > 0 && (mapLanguageOf(file2.path) !== void 0 || template && objects2.some((object2) => object2.parsing === "PARSED"));
23703
- if (!analyzed && file2.status !== "DELETED" && kind)
23704
- unclear.push(`${file2.path} changed (${kind}): its effects are not mapped`);
23833
+ const analyzed = file2.status === "DELETED" ? !file2.binary && (mapLanguageOf(file2.path) !== void 0 || template) : objects2.length > 0 && (mapLanguageOf(file2.path) !== void 0 || template && objects2.some((object2) => object2.parsing === "PARSED"));
23834
+ const kind = !analyzed || MAP_MIGRATION_PATH.test(file2.path) ? unmappedKind(file2.path, file2.binary) : void 0;
23835
+ if (kind) {
23836
+ unclear.push(
23837
+ `${file2.path} ${file2.status === "DELETED" ? "deleted" : "changed"} (${kind}): its effects are not mapped`
23838
+ );
23839
+ unmapped.push({ path: file2.path, kind });
23840
+ }
23705
23841
  if (!objects2.length) continue;
23706
23842
  const hits = /* @__PURE__ */ new Set();
23707
23843
  let topLevel = false;
@@ -24048,6 +24184,7 @@ async function mapChangeImpact(store, working, base, changes, shapes, until, pro
24048
24184
  tests: [...known.tests].map(([path17, names]) => ({ path: path17, names: [...names].sort() })).sort((left, right) => right.names.length - left.names.length)
24049
24185
  })).sort((left, right) => right.tests.length - left.tests.length),
24050
24186
  unclear: [.../* @__PURE__ */ new Set([...unclear, ...tracer.unclear])],
24187
+ unmapped,
24051
24188
  removedRoutes,
24052
24189
  uncalled,
24053
24190
  dependencies: newModuleDependencies(store, cache, working, base, changes.files),
@@ -24262,6 +24399,22 @@ function routeFragment(label) {
24262
24399
  const longest = routePath(label).split(/\/(?:\{[^}]*\}|:[^/]+|<[^>]*>|\*)(?=\/|$)/u).sort((left, right) => right.length - left.length)[0];
24263
24400
  return longest && longest.replace(/\//gu, "").length >= 4 ? longest : void 0;
24264
24401
  }
24402
+ function mapChangesData(changes, impact) {
24403
+ return {
24404
+ base: changes.base,
24405
+ commit: changes.commit,
24406
+ files: changes.files.map(({ path: path17, basePath, status }) => ({
24407
+ path: path17,
24408
+ ...basePath !== void 0 && basePath !== path17 ? { basePath } : {},
24409
+ status
24410
+ })),
24411
+ tests: impact.tests,
24412
+ unmapped: impact.unmapped,
24413
+ checkByHand: impact.unclear,
24414
+ truncated: impact.truncated,
24415
+ ...impact.untested ? { untested: impact.untested } : {}
24416
+ };
24417
+ }
24265
24418
  async function checkMapChanges(input, signal) {
24266
24419
  const { index, project, working } = input;
24267
24420
  const changes = await readMapChanges(project, input.base, signal);
@@ -24300,22 +24453,35 @@ async function checkMapChanges(input, signal) {
24300
24453
  project,
24301
24454
  input.tests
24302
24455
  );
24456
+ if (input.format === "json") return { text: JSON.stringify(mapChangesData(changes, impact)) };
24303
24457
  return {
24304
24458
  text: mapChangesText(
24305
24459
  changes,
24306
24460
  impact,
24307
24461
  await mapRouteClients(project, index.store, working, impact, signal),
24308
- await similarCode(
24462
+ reusable(
24309
24463
  index.store,
24310
24464
  working,
24311
- base,
24312
- changes.files,
24313
- (file2) => readFile(path11.join(project, file2), "utf8").catch(() => void 0)
24465
+ await similarCode(
24466
+ index.store,
24467
+ working,
24468
+ base,
24469
+ changes.files,
24470
+ (file2) => readFile(path11.join(project, file2), "utf8").catch(() => void 0)
24471
+ )
24314
24472
  ),
24315
24473
  changes.files.length ? await compileBreaks(input, changes, base, until, signal) : void 0
24316
24474
  )
24317
24475
  };
24318
24476
  }
24477
+ function reusable(store, working, similar) {
24478
+ if (!similar.length) return [];
24479
+ const importsFor = mapReuseImports(store, new MapViewCache(), working);
24480
+ return similar.flatMap((item) => {
24481
+ const imports2 = importsFor(item.path, item.like.path);
24482
+ return imports2 ? [{ ...item, imports: imports2 }] : [];
24483
+ });
24484
+ }
24319
24485
  async function mapRouteClients(project, store, working, impact, signal) {
24320
24486
  const affected = impact.entries.filter(
24321
24487
  (entry) => entry.route && entry.certain && entry.chain.length <= 2
@@ -24515,32 +24681,6 @@ Nothing changed against ${changes.base}.`;
24515
24681
  `Decide for each whether it runs the way the project's layers do: code others build on (shared types, storage, utilities) should not import the features or interfaces built on it.${impact.dependencies.some((dependency) => dependency.back) ? " A cycle ties the modules together, so neither can change or be tested alone." : ""} If one runs the wrong way, move what both need into the lower module or pass it in, rather than import upward.`
24516
24682
  );
24517
24683
  }
24518
- if (similar.length) {
24519
- const declaration = (item) => `${item.path}: ${item.name} ${item.label}`;
24520
- const pairs = /* @__PURE__ */ new Map();
24521
- for (const item of similar) {
24522
- const key = `${item.path}\0${item.like.path}`;
24523
- pairs.set(key, [...pairs.get(key) ?? [], item]);
24524
- }
24525
- list(
24526
- "EXISTING CODE LIKE THE NEW CODE (declarations the diff adds whose code reads almost the same as code the project already has)",
24527
- [...pairs.values()].flatMap((items) => {
24528
- const [first] = items;
24529
- if (items.length < 3)
24530
- return items.map(
24531
- (item) => `${declaration(item)} ~ ${declaration(item.like)}${item.others ? ` (+${item.others} more alike)` : ""}`
24532
- );
24533
- const names = items.slice(0, LIST.similarNames).map((item) => `${item.name} ~ ${item.like.name}`);
24534
- return [
24535
- `${first.path} repeats ${first.like.path} in ${items.length} declarations: ${names.join(", ")}${items.length > LIST.similarNames ? ", \u2026" : ""}`
24536
- ];
24537
- }),
24538
- LIST.similar
24539
- );
24540
- lines.push(
24541
- "Use the existing code rather than a copy, or, if the new code replaces it, remove the old; keep both only when they are meant to differ. Code that does the same in other words is not found."
24542
- );
24543
- }
24544
24684
  const entry = (item) => `${item.route ? JSON.stringify(item.label) : item.label}${item.chain.length ? ` \u2192 ${item.chain.join(" \u2192 ")}` : ""}${item.removed ? ` (the diff removes it${item.site ? `; registered at ${item.site} before` : ""})` : item.site ? ` (registered at ${item.site})` : ""}`;
24545
24685
  list(
24546
24686
  "AFFECTED ENTRY POINTS (through resolved calls)",
@@ -24627,6 +24767,38 @@ Nothing changed against ${changes.base}.`;
24627
24767
  lines.push(
24628
24768
  "Static estimate: calls through dependency injection, reflection, string dispatch, configuration and database coupling are not mapped, so an empty list does not prove the change is safe; confirm the entry points in source."
24629
24769
  );
24770
+ if (similar.length) {
24771
+ const declaration = (item) => `${item.path}: ${item.name} ${item.label}`;
24772
+ const reach = ({ user, from, to, imported, cycle, packages }) => {
24773
+ const using = user === "NEW" ? "using it" : "the existing code using the new";
24774
+ if (imported)
24775
+ return user === "NEW" ? "no new import" : `the existing code can use the new with no new import: ${from} already imports ${to}`;
24776
+ return `${using} imports ${to} from ${from} for the first time${packages ? `, in ${packages[1]}, which ${packages[0]} already imports` : ""}${cycle ? `; ${to} already reaches ${from}, so the import closes a cycle` : ""}`;
24777
+ };
24778
+ const pairs = /* @__PURE__ */ new Map();
24779
+ for (const item of similar) {
24780
+ const key = `${item.path}\0${item.like.path}`;
24781
+ pairs.set(key, [...pairs.get(key) ?? [], item]);
24782
+ }
24783
+ list(
24784
+ "EXISTING CODE LIKE THE NEW CODE (declarations the diff adds whose code reads almost the same as code the project already has; weigh them after everything above)",
24785
+ [...pairs.values()].flatMap((items) => {
24786
+ const [first] = items;
24787
+ if (items.length < 3)
24788
+ return items.map(
24789
+ (item) => `${declaration(item)} ~ ${declaration(item.like)} (${item.others ? `+${item.others} more alike; ` : ""}${reach(item.imports)})`
24790
+ );
24791
+ const names = items.slice(0, LIST.similarNames).map((item) => `${item.name} ~ ${item.like.name}`);
24792
+ return [
24793
+ `${first.path} repeats ${first.like.path} in ${items.length} declarations: ${names.join(", ")}${items.length > LIST.similarNames ? ", \u2026" : ""} (${reach(first.imports)})`
24794
+ ];
24795
+ }),
24796
+ LIST.similar
24797
+ );
24798
+ lines.push(
24799
+ "Where it needs no new import, or only one that runs the way the project's layers do, and both copies must stay the same, keep one; code alike for another feature, layer or table is often meant to differ, so keep both. Change existing code only where it is part of the task; tell the user of the rest."
24800
+ );
24801
+ }
24630
24802
  return lines.join("\n");
24631
24803
  }
24632
24804
 
@@ -25001,7 +25173,8 @@ var LayerMap = class _LayerMap {
25001
25173
  working: await this.current(signal, hold),
25002
25174
  base: input.base ?? "HEAD",
25003
25175
  baseVersion: (commit, baseSignal) => this.versionAt(commit, baseSignal, hold),
25004
- ...input.tests ? { tests: input.tests } : {}
25176
+ ...input.tests ? { tests: input.tests } : {},
25177
+ ...input.format ? { format: input.format } : {}
25005
25178
  },
25006
25179
  signal
25007
25180
  )
@@ -25304,7 +25477,7 @@ var mapToolDescriptions = (host) => {
25304
25477
  return Object.freeze({
25305
25478
  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.`,
25306
25479
  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.`,
25307
- 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, the existing test files that call the changed code, import a changed file 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. It does not run or write tests: run the related ones if the change needs verifying; a failing or rewritten test of a feature the request is not about means the change leaked, so restore the test and narrow the change; a new dependency that runs against the layers or closes a cycle means moving what both modules need down rather than importing upward; new code like existing code means using the existing code, or removing the old if the new replaces it; code left without callers means deleting it, with the tests that only test it, when the change replaced it; call it once when the edits are done; and confirm the entry points in source, since an empty list does not prove a change safe.`,
25480
+ 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, the existing test files that call the changed code, import a changed file 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. 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.`,
25308
25481
  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.`
25309
25482
  });
25310
25483
  };
@@ -25669,8 +25842,8 @@ var SETUP_RULE = `mcp__${SERVER}`;
25669
25842
  var PLUGIN_RULE = `mcp__plugin_${SERVER}_${SERVER}`;
25670
25843
  var BEGIN = "<!-- layermap:begin -->";
25671
25844
  var END = "<!-- layermap:end -->";
25672
- var launcherScript = (template, version2) => `// Generated from scripts/launcher.mjs.
25673
- ${template.replace("__VERSION__", JSON.stringify(version2))}`;
25845
+ var launcherScript = (template, version2, args = '["mcp"]') => `// Generated from scripts/launcher.mjs.
25846
+ ${template.replace("__VERSION__", JSON.stringify(version2)).replace("__ARGUMENTS__", args)}`;
25674
25847
  var PUBLISHED_LAUNCHER = path15.join(packageRoot, "dist", "launcher.mjs");
25675
25848
  var launcherFile = (env = process.env) => path15.join(cacheDirectory(env), "server.mjs");
25676
25849
  var mcpLaunchCommand = (env = process.env, published = existsSync8(PUBLISHED_LAUNCHER)) => {
@@ -25983,8 +26156,11 @@ Usage:
25983
26156
  [--depth N] [--tests] [--unresolved] [--offset N]
25984
26157
  layermap search QUERY [--path DIR] [--mode ANY|ALL|LITERAL] [--max N] [--offset N]
25985
26158
  layermap refs PATH NAME [--line N] [--path DIR] [--max N] [--cursor C]
25986
- layermap check [--base REF] [TEST...] what the uncommitted changes (or those since REF) affect,
25987
- and what of them the test files given do not run
26159
+ layermap check [--base REF] [--json] [TEST...]
26160
+ what the uncommitted changes (or those since REF) affect,
26161
+ and what of them the test files given do not run; --json
26162
+ prints the related tests by rank and what the map cannot
26163
+ follow, for a program choosing which tests to run
25988
26164
 
25989
26165
  The project is the Git work tree around the current directory unless --project names one; the MCP
25990
26166
  server also maps any other repository a tool call's path names.
@@ -26026,6 +26202,7 @@ async function main(argv) {
26026
26202
  mode: { type: "string" },
26027
26203
  max: { type: "string" },
26028
26204
  cursor: { type: "string" },
26205
+ json: { type: "boolean", default: false },
26029
26206
  help: { type: "boolean", short: "h", default: false },
26030
26207
  version: { type: "boolean", short: "v", default: false }
26031
26208
  }
@@ -26038,6 +26215,7 @@ async function main(argv) {
26038
26215
  return 0;
26039
26216
  }
26040
26217
  if (values.help || !command) return usage(command ? 0 : 1);
26218
+ if (values.json && command !== "check") return usage(1);
26041
26219
  const { directory: project, git: git2 } = await projectDirectory(values.project ?? process.cwd());
26042
26220
  const cache = cacheDirectory();
26043
26221
  const open2 = async (directory) => {
@@ -26083,6 +26261,16 @@ async function main(argv) {
26083
26261
  );
26084
26262
  return 0;
26085
26263
  }
26264
+ if (command === "check" && values.json) {
26265
+ const tests = rest.length ? await checkedTests(project, rest) : void 0;
26266
+ const { text } = await map2.checkChanges(
26267
+ { base: values.base, ...tests ? { tests } : {}, format: "json" },
26268
+ signal
26269
+ );
26270
+ process.stdout.write(`${text}
26271
+ `);
26272
+ return 0;
26273
+ }
26086
26274
  const call = {
26087
26275
  explore: [
26088
26276
  MAP_TOOL_NAMES.explore,
package/dist/launcher.mjs CHANGED
@@ -1,4 +1,5 @@
1
- // Starts one LayerMap version's MCP server in this process. The version is installed once into
1
+ // Runs one LayerMap version in this process: its MCP server, or, for the layermap command of the
2
+ // Claude Code plugin, its command line with the arguments given. The version is installed once into
2
3
  // LayerMap's cache, from where every later start runs without npm or a network. The agent starts
3
4
  // this in the project, which stays the working directory the server maps; npm runs in the cache,
4
5
  // so the project's own npm settings and packages play no part in what gets installed.
@@ -17,6 +18,7 @@ import path from "node:path";
17
18
  import { pathToFileURL } from "node:url";
18
19
 
19
20
  const VERSION = __VERSION__;
21
+ const ARGUMENTS = __ARGUMENTS__;
20
22
 
21
23
  // The same directory as cacheDirectory in src/agent/environment.ts.
22
24
  const env = process.env;
@@ -95,7 +97,7 @@ try {
95
97
  // LayerMap removes a version from its cache once nothing has started it for a week.
96
98
  writeFileSync(path.join(home, "last-used"), "");
97
99
  const entry = path.join(installed, JSON.parse(readFileSync(manifest, "utf8")).bin.layermap);
98
- process.argv = [process.argv[0], entry, "mcp"];
100
+ process.argv = [process.argv[0], entry, ...ARGUMENTS];
99
101
  await import(pathToFileURL(entry).href);
100
102
  } catch (error) {
101
103
  process.stderr.write(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "layermap",
3
- "version": "0.1.38",
3
+ "version": "0.1.40",
4
4
  "mcpName": "io.github.coffeecoproject/layermap",
5
5
  "description": "A layered map of a codebase for coding agents: directories, modules and call chains across TypeScript, JavaScript, Go, Python and Java.",
6
6
  "license": "Apache-2.0",
package/pi/layermap.mjs CHANGED
@@ -293,7 +293,7 @@ function layermap(pi) {
293
293
  if (server && !server.dead) return server;
294
294
  starting ??= (async () => {
295
295
  const next = new MapServer(cwd);
296
- const tools = await next.start("0.1.38");
296
+ const tools = await next.start("0.1.40");
297
297
  for (const tool of tools) {
298
298
  if (registered.has(tool.name)) continue;
299
299
  registered.add(tool.name);