layermap 0.1.21 → 0.1.24

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
@@ -160,7 +160,11 @@ from a file, the check names the files that still read or set the old name. In t
160
160
  the change reaches a route's handler or renames a route, it names the code and templates that
161
161
  request that path: a frontend's fetch, a generated API client, a redirect or a link. When the change adds
162
162
  an import between two modules of the project overview, it names it, and says when the two now
163
- depend on each other; whether that direction suits the project's layers is for the agent to judge. It never writes or runs tests. In Claude Code and
163
+ depend on each other; whether that direction suits the project's layers is for the agent to judge. When a
164
+ declaration the change adds reads almost the same as code the project already has, it names both, so
165
+ the agent can use the existing code instead of a copy. When the change takes away the last call to a
166
+ declaration, as when new code replaces old, it names that declaration, so the agent can delete what
167
+ the change left behind. It never writes or runs tests. In Claude Code and
164
168
  CodeBuddy Code the plugin asks the agent once, before it finishes, to run this check for each repository it edited code in
165
169
  and has not checked since, whether through its edit tools or shell commands (changes another session makes in the same
166
170
  work tree do not count); the Pi extension does the same after the agent's own edits. Set `LAYERMAP_STOP_CHECK=0` to turn that
@@ -198,7 +202,7 @@ nothing anywhere ([privacy](https://github.com/coffeecoproject/layermap/blob/mai
198
202
  | `project_explore_map` | A directory, a file, or a declaration's callers and callees (`direction` INCOMING or OUTGOING, `depth` up to 8). |
199
203
  | `project_search_map` | Find declarations by words in their names, paths or documentation. |
200
204
  | `project_find_references` | Every usage of a declaration, compiled from current source. |
201
- | `project_check_changes` | What the uncommitted changes (or those since `base`) affect: changed and removed declarations, the routes, jobs and commands they reach, the areas that share the changed code, environment variables and configuration keys it removed that other files still use, code and templates that request the affected routes, new dependencies between modules and the cycles they close, what to check by hand, and related tests. |
205
+ | `project_check_changes` | What the uncommitted changes (or those since `base`) affect: changed and removed declarations, the routes, jobs and commands they reach, the areas that share the changed code, environment variables and configuration keys it removed that other files still use, code and templates that request the affected routes, new dependencies between modules and the cycles they close, new code that repeats existing code, what to check by hand, and related tests. |
202
206
 
203
207
  The same from the command line:
204
208
 
package/dist/cli.mjs CHANGED
@@ -7,13 +7,14 @@ var __export = (target, all) => {
7
7
  };
8
8
 
9
9
  // src/cli.ts
10
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
10
11
  import { parseArgs } from "node:util";
11
12
 
12
13
  // src/agent/environment.ts
13
14
  import { execFile } from "node:child_process";
14
15
  import { createHash as createHash5 } from "node:crypto";
15
16
  import { existsSync as existsSync5, readFileSync as readFileSync4 } from "node:fs";
16
- import { mkdir, readdir, readFile, rename, rm, stat, utimes, writeFile } from "node:fs/promises";
17
+ import { mkdir, readdir, readFile as readFile2, rename, rm, stat, utimes, writeFile } from "node:fs/promises";
17
18
  import { createRequire } from "node:module";
18
19
  import { homedir } from "node:os";
19
20
  import path11 from "node:path";
@@ -21,7 +22,7 @@ import { fileURLToPath } from "node:url";
21
22
 
22
23
  // src/layermap.ts
23
24
  import { createHash as createHash4 } from "node:crypto";
24
- import { mkdirSync } from "node:fs";
25
+ import { mkdirSync, statSync } from "node:fs";
25
26
  import { lstat as lstat2, realpath as realpath2 } from "node:fs/promises";
26
27
  import path10 from "node:path";
27
28
  import { DatabaseSync } from "@photostructure/sqlite";
@@ -15481,7 +15482,11 @@ var excludedSegments = Object.freeze([
15481
15482
  "vendor",
15482
15483
  ".venv",
15483
15484
  "__pycache__",
15484
- "site-packages"
15485
+ "site-packages",
15486
+ ".claude",
15487
+ ".codex",
15488
+ ".cursor",
15489
+ ".pi"
15485
15490
  ]);
15486
15491
  var SOURCE_POLICY = Object.freeze({
15487
15492
  sourceExtensions,
@@ -15507,6 +15512,7 @@ var SOURCE_POLICY = Object.freeze({
15507
15512
  });
15508
15513
  var extensions = new Set(sourceExtensions);
15509
15514
  var excluded = new Set(excludedSegments);
15515
+ var inExcludedDirectory = (relativePath) => relativePath.toLowerCase().split("/").slice(0, -1).some((segment) => excluded.has(segment));
15510
15516
  var includesInitialEvidencePath = (relativePath, scope) => {
15511
15517
  try {
15512
15518
  assertProjectEvidencePathNotSensitive(relativePath);
@@ -15517,10 +15523,9 @@ var includesInitialEvidencePath = (relativePath, scope) => {
15517
15523
  (prefix) => prefix === "." || relativePath === prefix || relativePath.startsWith(`${prefix}/`)
15518
15524
  ))
15519
15525
  return false;
15520
- if (isProjectEvidenceTraversalExcluded(relativePath)) return false;
15521
- const segments2 = relativePath.toLowerCase().split("/");
15522
- if (segments2.slice(0, -1).some((segment) => excluded.has(segment))) return false;
15523
- const basename = segments2.at(-1) ?? "";
15526
+ if (isProjectEvidenceTraversalExcluded(relativePath) || inExcludedDirectory(relativePath))
15527
+ return false;
15528
+ const basename = relativePath.toLowerCase().split("/").at(-1) ?? "";
15524
15529
  return extensions.has(path6.posix.extname(basename)) || SOURCE_POLICY.documentationFiles.includes(basename) || SOURCE_POLICY.configurationFiles.includes(basename) || SOURCE_POLICY.workspaceFiles.includes(relativePath);
15525
15530
  };
15526
15531
 
@@ -15970,7 +15975,7 @@ function encodeMapText(graph) {
15970
15975
  const at = (anchor) => `${file2(anchor.path)}:${anchor.startLine}-${anchor.endLine}@${anchor.start}-${anchor.end}`;
15971
15976
  const nodes = new Map(graph.objects.map((object2, index) => [object2.id, `N${index + 1}`]));
15972
15977
  const node = (id2) => nodes.get(id2) ?? failed();
15973
- const rows = graph.objects.map(
15978
+ const rows2 = graph.objects.map(
15974
15979
  (object2) => [
15975
15980
  node(object2.id),
15976
15981
  JSON.stringify(object2.name),
@@ -15982,7 +15987,7 @@ function encodeMapText(graph) {
15982
15987
  );
15983
15988
  for (const { relation } of graph.relations) {
15984
15989
  const { id: id2, ...semantic } = relation;
15985
- rows.push(
15990
+ rows2.push(
15986
15991
  [
15987
15992
  "R",
15988
15993
  `${node(relation.from)} \u2192 ${relation.to === void 0 ? "-" : node(relation.to)}`,
@@ -15996,7 +16001,7 @@ function encodeMapText(graph) {
15996
16001
  );
15997
16002
  }
15998
16003
  for (const note of graph.notes)
15999
- rows.push(
16004
+ rows2.push(
16000
16005
  [
16001
16006
  "D",
16002
16007
  node(note.entityRef),
@@ -16006,13 +16011,13 @@ function encodeMapText(graph) {
16006
16011
  JSON.stringify(note.text)
16007
16012
  ].join(" ")
16008
16013
  );
16009
- if (graph.targetRef !== void 0) rows.push(`T ${node(graph.targetRef)}`);
16014
+ if (graph.targetRef !== void 0) rows2.push(`T ${node(graph.targetRef)}`);
16010
16015
  for (const frontier of graph.traversal.frontier)
16011
- rows.push(`B ${node(frontier.entityRef)} ${frontier.direction}`);
16016
+ rows2.push(`B ${node(frontier.entityRef)} ${frontier.direction}`);
16012
16017
  return [
16013
16018
  ...header,
16014
16019
  ...[...files].map(([path14, ref]) => `${ref} ${JSON.stringify(path14)}`),
16015
- ...rows
16020
+ ...rows2
16016
16021
  ].join("\n");
16017
16022
  }
16018
16023
  function decodeMapText(text) {
@@ -16371,9 +16376,9 @@ var MapViewGraph = class {
16371
16376
  parent(ref) {
16372
16377
  let parent = this.parents.get(ref);
16373
16378
  if (parent === void 0) {
16374
- const rows = this.statements.parent.all(this.version, ref);
16375
- if (rows.length > 1) return corrupt();
16376
- parent = rows[0] ? String(rows[0].from_ref) : null;
16379
+ const rows2 = this.statements.parent.all(this.version, ref);
16380
+ if (rows2.length > 1) return corrupt();
16381
+ parent = rows2[0] ? String(rows2[0].from_ref) : null;
16377
16382
  this.parents.set(ref, parent);
16378
16383
  }
16379
16384
  return parent ?? void 0;
@@ -16518,23 +16523,23 @@ function requireMapObject(store, version2, selector, prefixes) {
16518
16523
  if (!object3) throw new ProjectEvidenceError("PROJECT_MAP_OBJECT_NOT_FOUND", false);
16519
16524
  return object3;
16520
16525
  }
16521
- let rows;
16526
+ let rows2;
16522
16527
  if (locator) {
16523
16528
  const path14 = normalizeProjectEvidencePath(locator.path);
16524
16529
  if (!Number.isSafeInteger(locator.start) || locator.start < 0 || locator.kind !== void 0 && !MapObjectKindSchema.safeParse(locator.kind).success)
16525
16530
  throw new ProjectEvidenceError("PROJECT_READ_INPUT_INVALID", false);
16526
16531
  if (!mapPathAllowed(path14, prefixes))
16527
16532
  throw new ProjectEvidenceError("PROJECT_MAP_OBJECT_NOT_FOUND", false);
16528
- rows = store.database.prepare(`SELECT object_json FROM project_map_objects
16533
+ rows2 = store.database.prepare(`SELECT object_json FROM project_map_objects
16529
16534
  WHERE version_ref = ? AND path = ? AND json_extract(object_json, '$.anchor.start') = ?
16530
16535
  AND (? IS NULL OR kind = ?) LIMIT 2`).all(version2, path14, locator.start, locator.kind ?? null, locator.kind ?? null);
16531
16536
  } else {
16532
- rows = store.database.prepare(
16537
+ rows2 = store.database.prepare(
16533
16538
  "SELECT object_json FROM project_map_objects WHERE version_ref = ? AND entity_ref = ?"
16534
16539
  ).all(version2, entityRef);
16535
16540
  }
16536
- if (rows.length > 1) throw new ProjectEvidenceError("PROJECT_READ_INPUT_INVALID", false);
16537
- const object2 = rows[0] ? MapObjectSchema.parse(JSON.parse(String(rows[0].object_json))) : void 0;
16541
+ if (rows2.length > 1) throw new ProjectEvidenceError("PROJECT_READ_INPUT_INVALID", false);
16542
+ const object2 = rows2[0] ? MapObjectSchema.parse(JSON.parse(String(rows2[0].object_json))) : void 0;
16538
16543
  if (!object2 || !mapPathAllowed(object2.anchor.path, prefixes))
16539
16544
  throw new ProjectEvidenceError("PROJECT_MAP_OBJECT_NOT_FOUND", false);
16540
16545
  return object2;
@@ -16822,7 +16827,7 @@ function mapSearchRows(store, input, query, scope, offset, signal) {
16822
16827
  AND ${mapSearchAllowedSql("json_extract(note.note_json, '$.anchor.path')")}
16823
16828
  ) AS documentation
16824
16829
  FROM candidate_objects object`);
16825
- const rows = [];
16830
+ const rows2 = [];
16826
16831
  for (const row of statement.iterate(
16827
16832
  ...candidates.parameters,
16828
16833
  input.version,
@@ -16847,11 +16852,11 @@ function mapSearchRows(store, input, query, scope, offset, signal) {
16847
16852
  query,
16848
16853
  focus.get(object2.id)
16849
16854
  );
16850
- if (ranking) rows.push({ object: object2, ranking });
16855
+ if (ranking) rows2.push({ object: object2, ranking });
16851
16856
  }
16852
- rows.sort(compareRows);
16857
+ rows2.sort(compareRows);
16853
16858
  const perPath = /* @__PURE__ */ new Map();
16854
- const diversified = rows.map(({ object: object2, ranking }) => {
16859
+ const diversified = rows2.map(({ object: object2, ranking }) => {
16855
16860
  const pathRank = (perPath.get(object2.anchor.path) ?? 0) + 1;
16856
16861
  perPath.set(object2.anchor.path, pathRank);
16857
16862
  return {
@@ -16872,9 +16877,9 @@ var MapSearchViewPageSchema = external_exports.object({
16872
16877
  pageExhausted: external_exports.boolean()
16873
16878
  }).strict();
16874
16879
  var FIELDS = { NAME: "name", PATH: "path", DOCUMENTATION: "doc" };
16875
- function mapSearchView(store, version2, query, rows, offset, maxResults, budget) {
16880
+ function mapSearchView(store, version2, query, rows2, offset, maxResults, budget) {
16876
16881
  const graph = new MapViewGraph(store, version2);
16877
- const results = rows.slice(0, maxResults).map(({ object: object2, ranking }) => ({
16882
+ const results = rows2.slice(0, maxResults).map(({ object: object2, ranking }) => ({
16878
16883
  path: object2.anchor.path,
16879
16884
  text: `${mapIsModule(object2) ? `(file) ${object2.anchor.endLine}L` : `${graph.qualifiedName(object2.id)} ${mapDeclarationLabel(object2)}`} [${ranking.matchedFields.map((field) => FIELDS[field]).join(",")}]`
16880
16885
  }));
@@ -16883,7 +16888,7 @@ function mapSearchView(store, version2, query, rows, offset, maxResults, budget)
16883
16888
  ...query.kinds.length < MapObjectKindSchema.options.length ? [`kinds ${query.kinds.join(",")}`] : []
16884
16889
  ];
16885
16890
  const materialize = (count) => {
16886
- const more2 = rows.length > count;
16891
+ const more2 = rows2.length > count;
16887
16892
  const lines = [];
16888
16893
  let current;
16889
16894
  for (const result of results.slice(0, count)) {
@@ -17039,9 +17044,9 @@ function mapExplorePageRows(store, version2) {
17039
17044
  };
17040
17045
  };
17041
17046
  }
17042
- function mapPageFrontier(frontier, rows) {
17047
+ function mapPageFrontier(frontier, rows2) {
17043
17048
  const visible = new Set(
17044
- rows.flatMap(({ relation }) => [relation.from, ...relation.to ? [relation.to] : []])
17049
+ rows2.flatMap(({ relation }) => [relation.from, ...relation.to ? [relation.to] : []])
17045
17050
  );
17046
17051
  return frontier.filter(({ entityRef }) => visible.has(entityRef)).map((node) => ({ ...node }));
17047
17052
  }
@@ -19069,7 +19074,7 @@ function loadImports(store, version2) {
19069
19074
  }
19070
19075
  function loadDirectoryFacts(store, version2) {
19071
19076
  const files = /* @__PURE__ */ new Map();
19072
- const declarations = [];
19077
+ const declarations2 = [];
19073
19078
  for (const row of store.database.prepare(`SELECT entity_ref, path, kind, name,
19074
19079
  json_extract(object_json, '$.anchor.startLine') AS start_line,
19075
19080
  json_extract(object_json, '$.anchor.endLine') AS end_line,
@@ -19087,7 +19092,7 @@ function loadDirectoryFacts(store, version2) {
19087
19092
  ...row.language ? { language: String(row.language) } : {}
19088
19093
  });
19089
19094
  else
19090
- declarations.push({
19095
+ declarations2.push({
19091
19096
  ref: String(row.entity_ref),
19092
19097
  path: String(row.path),
19093
19098
  kind,
@@ -19098,7 +19103,7 @@ function loadDirectoryFacts(store, version2) {
19098
19103
  });
19099
19104
  }
19100
19105
  const decorators = /* @__PURE__ */ new Map();
19101
- const classes = declarations.filter((item) => item.kind === "CLASS").map((item) => item.ref);
19106
+ const classes = declarations2.filter((item) => item.kind === "CLASS").map((item) => item.ref);
19102
19107
  const decoratorQuery = store.database.prepare(`SELECT from_ref,
19103
19108
  json_extract(relation_json, '$.target') AS target,
19104
19109
  json_extract(relation_json, '$.argument') AS argument,
@@ -19120,7 +19125,7 @@ function loadDirectoryFacts(store, version2) {
19120
19125
  )
19121
19126
  ]);
19122
19127
  const exported = /* @__PURE__ */ new Map();
19123
- for (const item of declarations) {
19128
+ for (const item of declarations2) {
19124
19129
  const endLine = item.kind === "TYPE" || item.kind === "VARIABLE" ? item.startLine : item.endLine;
19125
19130
  const label = mapDeclarationLabel({
19126
19131
  kind: item.kind,
@@ -19366,10 +19371,10 @@ function directoryView(facts, coverage, entries, input, directory, prefixes) {
19366
19371
  }
19367
19372
  const detailed = [
19368
19373
  ...code.map((path14) => {
19369
- const declarations = (facts.exported.get(path14) ?? []).map(({ text: text2 }) => text2);
19374
+ const declarations2 = (facts.exported.get(path14) ?? []).map(({ text: text2 }) => text2);
19370
19375
  return [
19371
19376
  path14,
19372
- `${path14} ${lineCount(path14)}${declarations.length ? `: ${declarations.join(", ")}` : ""}`
19377
+ `${path14} ${lineCount(path14)}${declarations2.length ? `: ${declarations2.join(", ")}` : ""}`
19373
19378
  ];
19374
19379
  }),
19375
19380
  ...listedOther.map((entry) => [
@@ -19741,14 +19746,14 @@ function fileView(store, coverage, graph, input, path14, prefixes) {
19741
19746
  `${object2.name} ${mapDeclarationLabel(object2)}${object2.anchor.path === path14 ? "" : ` (${object2.anchor.path})`}`,
19742
19747
  ...tags.get(object2.id) ?? []
19743
19748
  ].join(" ");
19744
- const declarations = [];
19749
+ const declarations2 = [];
19745
19750
  for (const member of members) {
19746
- declarations.push(`${member.exported ? "*" : " "}${describe3(member)}`);
19751
+ declarations2.push(`${member.exported ? "*" : " "}${describe3(member)}`);
19747
19752
  const children = nested.get(member.id) ?? [];
19748
19753
  const listed = member.kind === "CLASS" ? children : children.filter((child) => child.kind === "METHOD");
19749
19754
  const fields2 = children.length - listed.length;
19750
19755
  if (listed.length || fields2)
19751
- declarations.push(
19756
+ declarations2.push(
19752
19757
  ` ${[...listed.map(describe3), ...fields2 ? [`${fields2} fields`] : []].join(", ")}`
19753
19758
  );
19754
19759
  }
@@ -19765,10 +19770,10 @@ function fileView(store, coverage, graph, input, path14, prefixes) {
19765
19770
  for (const [parent, list] of [...elsewhere].sort(
19766
19771
  ([, left], [, right]) => Math.min(...left.map((object2) => object2.anchor.start)) - Math.min(...right.map((object2) => object2.anchor.start))
19767
19772
  ))
19768
- declarations.push(
19773
+ declarations2.push(
19769
19774
  ` ${graph.qualifiedName(parent)} (${graph.object(parent).anchor.path}): ${list.sort((left, right) => left.anchor.start - right.anchor.start).map((object2) => `${object2.name} ${mapDeclarationLabel(object2)}`).join(", ")}`
19770
19775
  );
19771
- if (declarations.length) blocks.push(["DECLARATIONS (* exported)", ...declarations].join("\n"));
19776
+ if (declarations2.length) blocks.push(["DECLARATIONS (* exported)", ...declarations2].join("\n"));
19772
19777
  const imports2 = /* @__PURE__ */ new Set();
19773
19778
  const external = /* @__PURE__ */ new Set();
19774
19779
  const fileObjects = graph.objectsAt(path14).map((object2) => object2.id);
@@ -19959,18 +19964,18 @@ var ProjectMapQuery = class {
19959
19964
  throw new ProjectEvidenceError("PROJECT_EVIDENCE_INDEX_UNAVAILABLE", true);
19960
19965
  const { offset, scope, prefixes } = admission(input);
19961
19966
  const query = mapSearchQuery(input);
19962
- const rows = mapSearchRows(this.store, input, query, scope, offset, signal);
19967
+ const rows2 = mapSearchRows(this.store, input, query, scope, offset, signal);
19963
19968
  const metadata = { ...MAP_QUERY_GUIDANCE, query, gaps: this.gaps(input.version, prefixes) };
19964
19969
  return mapQueryPage(
19965
- Math.min(rows.length, input.maxResults),
19970
+ Math.min(rows2.length, input.maxResults),
19966
19971
  (count) => {
19967
- const selected = rows.slice(0, count);
19972
+ const selected = rows2.slice(0, count);
19968
19973
  return {
19969
19974
  ...metadata,
19970
19975
  objects: selected.map((row) => row.object),
19971
19976
  rankings: selected.map((row) => row.ranking),
19972
- ...rows.length > count ? { nextOffset: offset + count } : {},
19973
- pageExhausted: rows.length <= count
19977
+ ...rows2.length > count ? { nextOffset: offset + count } : {},
19978
+ pageExhausted: rows2.length <= count
19974
19979
  };
19975
19980
  },
19976
19981
  mapSearchNavigation,
@@ -19981,12 +19986,12 @@ var ProjectMapQuery = class {
19981
19986
  this.requireReadableMap(input.version, signal);
19982
19987
  const { offset, scope } = admission(input);
19983
19988
  const query = mapSearchQuery(input);
19984
- const rows = mapSearchRows(this.store, input, query, scope, offset, signal);
19989
+ const rows2 = mapSearchRows(this.store, input, query, scope, offset, signal);
19985
19990
  return mapSearchView(
19986
19991
  this.store,
19987
19992
  input.version,
19988
19993
  query,
19989
- rows,
19994
+ rows2,
19990
19995
  offset,
19991
19996
  input.maxResults,
19992
19997
  input.outputBudget
@@ -20060,10 +20065,10 @@ var ProjectMapQuery = class {
20060
20065
  notesTruncated: notes.length > selectedNotes.length,
20061
20066
  gaps: this.gaps(input.version, prefixes)
20062
20067
  };
20063
- const rows = [];
20068
+ const rows2 = [];
20064
20069
  const materialize = (count) => ({
20065
20070
  ...metadata,
20066
- relations: rows.slice(0, count),
20071
+ relations: rows2.slice(0, count),
20067
20072
  coverage: {
20068
20073
  totalRelations,
20069
20074
  returnedRelations: count,
@@ -20071,7 +20076,7 @@ var ProjectMapQuery = class {
20071
20076
  },
20072
20077
  traversal: {
20073
20078
  semantics: "STATIC_RELATIONSHIPS",
20074
- frontier: mapPageFrontier(frontier, rows.slice(0, count))
20079
+ frontier: mapPageFrontier(frontier, rows2.slice(0, count))
20075
20080
  },
20076
20081
  ...totalRelations > offset + count ? { nextOffset: offset + count } : {},
20077
20082
  pageExhausted: totalRelations <= offset + count
@@ -20084,13 +20089,13 @@ var ProjectMapQuery = class {
20084
20089
  const ref = relationRefs[position];
20085
20090
  if (ref === void 0)
20086
20091
  throw new ProjectEvidenceError("PROJECT_EVIDENCE_STORE_CORRUPT", false);
20087
- rows.push(readRow(ref));
20092
+ rows2.push(readRow(ref));
20088
20093
  }
20089
20094
  await setImmediate3();
20090
20095
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
20091
20096
  if (position === end) break;
20092
20097
  const { nextOffset: _nextOffset, ...minimum } = mapExploreNavigation(
20093
- materialize(rows.length)
20098
+ materialize(rows2.length)
20094
20099
  );
20095
20100
  const minimumBytes = Buffer.byteLength(
20096
20101
  canonicalJson({
@@ -20103,7 +20108,7 @@ var ProjectMapQuery = class {
20103
20108
  if (minimumBytes + (input.outputBudget?.envelopeBytes ?? 0) > (input.outputBudget?.maxBytes ?? PROJECT_MAP_LIMITS.queryBytes))
20104
20109
  break;
20105
20110
  }
20106
- const page = mapQueryPage(rows.length, materialize, mapExploreNavigation, input.outputBudget);
20111
+ const page = mapQueryPage(rows2.length, materialize, mapExploreNavigation, input.outputBudget);
20107
20112
  await setImmediate3();
20108
20113
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
20109
20114
  this.rememberTraversal(traversalKey, traversal);
@@ -21984,6 +21989,7 @@ var CodeIndex = class {
21984
21989
 
21985
21990
  // src/project-map-changes.ts
21986
21991
  import { readFileSync as readFileSync3 } from "node:fs";
21992
+ import { readFile } from "node:fs/promises";
21987
21993
  import path9 from "node:path";
21988
21994
 
21989
21995
  // src/project-map-clients.ts
@@ -22365,6 +22371,176 @@ async function strandedNames(project, diff, files, configuration, git2, options)
22365
22371
  }
22366
22372
  var strandedNameLine = ({ name, from, mentions }) => `${name}, gone from ${from}: ${mentions.slice(0, LIMIT2.mentions).join(", ")}${mentions.length > LIMIT2.mentions ? `, +${mentions.length - LIMIT2.mentions} more` : ""}`;
22367
22373
 
22374
+ // src/project-map-reuse.ts
22375
+ var MODULES = /* @__PURE__ */ new Set(["FILE", "PACKAGE", "CONFIG"]);
22376
+ var MEMBER_CONTAINERS2 = /* @__PURE__ */ new Set(["CLASS", "INTERFACE", "TYPE", "ENUM"]);
22377
+ var KINDS = /* @__PURE__ */ new Set(["FUNCTION", "METHOD", "CLASS", "VARIABLE"]);
22378
+ var MIN_LINES = 3;
22379
+ var ALIKE = 0.8;
22380
+ var SIBLINGS_ALIKE = 0.95;
22381
+ var KEYWORDS = new Set(
22382
+ "abstract and any as assert async await boolean break case catch chan class const continue def default defer del delete do elif else enum except export extends false final finally for from func function go if implements import in instanceof interface is keyof lambda let map new nil none not null number object of or package pass private protected public raise range readonly return self static string struct super switch this throw throws true try type typeof undefined unknown var void while with yield".split(" ")
22383
+ );
22384
+ var ROWS = `SELECT entity_ref AS id, path, name, kind, object_json AS object
22385
+ FROM project_map_objects WHERE version_ref = ? AND kind <> 'PROPERTY'`;
22386
+ function rows(store, version2, path14) {
22387
+ const statement = store.database.prepare(path14 === void 0 ? ROWS : `${ROWS} AND path = ?`);
22388
+ return (path14 === void 0 ? statement.all(version2) : statement.all(version2, path14)).map((row) => {
22389
+ const { anchor } = JSON.parse(String(row.object));
22390
+ return {
22391
+ id: String(row.id),
22392
+ path: String(row.path),
22393
+ name: String(row.name),
22394
+ kind: String(row.kind),
22395
+ start: anchor.start,
22396
+ end: anchor.end,
22397
+ startLine: anchor.startLine,
22398
+ endLine: anchor.endLine
22399
+ };
22400
+ });
22401
+ }
22402
+ function declarations(inFile) {
22403
+ const sorted = inFile.filter((row) => !MODULES.has(row.kind)).sort((left, right) => left.start - right.start || right.end - left.end);
22404
+ const found = [];
22405
+ const open2 = [];
22406
+ for (const row of sorted) {
22407
+ while (open2.length && open2.at(-1).row.end <= row.start) open2.pop();
22408
+ const around = open2.at(-1);
22409
+ let declaration;
22410
+ if (!row.name.startsWith("<")) {
22411
+ if (!around) declaration = { ...row, qualifiedName: row.name };
22412
+ else if (around.declaration && row.kind === "METHOD" && !around.parent && (MEMBER_CONTAINERS2.has(around.row.kind) || around.row.kind === "VARIABLE"))
22413
+ declaration = {
22414
+ ...row,
22415
+ qualifiedName: `${around.row.name}.${row.name}`,
22416
+ container: around.row.id
22417
+ };
22418
+ }
22419
+ if (declaration) found.push(declaration);
22420
+ open2.push({ row, declaration, parent: around?.row });
22421
+ }
22422
+ return found;
22423
+ }
22424
+ function lineWords(line) {
22425
+ return (line.replace(/([A-Z])([A-Z][a-z])/g, "$1 $2").replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().match(/[a-z][a-z0-9]+/g) ?? []).filter((word) => !KEYWORDS.has(word));
22426
+ }
22427
+ var within2 = (lines, declaration) => lines.some(([from, to]) => from <= declaration.startLine && declaration.endLine <= to);
22428
+ async function similarCode(store, working, base, files, read) {
22429
+ const code = (path14) => mapCodePath(path14) !== void 0 && !mapTestPath(path14);
22430
+ const changed = files.filter((file2) => file2.status !== "DELETED" && code(file2.path));
22431
+ if (!changed.length) return [];
22432
+ const names = (version2, path14) => new Set(declarations(rows(store, version2, path14)).map((item) => item.qualifiedName));
22433
+ const movedOut = /* @__PURE__ */ new Set();
22434
+ if (base !== void 0)
22435
+ for (const file2 of files) {
22436
+ if (!file2.basePath || file2.status === "ADDED") continue;
22437
+ const now = file2.status === "DELETED" ? /* @__PURE__ */ new Set() : names(working, file2.path);
22438
+ for (const name of names(base, file2.basePath)) if (!now.has(name)) movedOut.add(name);
22439
+ }
22440
+ const eligible = (item) => KINDS.has(item.kind) && item.endLine - item.startLine + 1 >= MIN_LINES;
22441
+ const added = /* @__PURE__ */ new Set();
22442
+ for (const file2 of changed) {
22443
+ const had = base !== void 0 && file2.basePath && file2.status !== "ADDED" ? names(base, file2.basePath) : void 0;
22444
+ for (const item of declarations(rows(store, working, file2.path)))
22445
+ if (eligible(item) && within2(file2.lines, item) && !had?.has(item.qualifiedName) && !movedOut.has(item.qualifiedName))
22446
+ added.add(item.id);
22447
+ }
22448
+ if (!added.size) return [];
22449
+ const byPath = /* @__PURE__ */ new Map();
22450
+ for (const row of rows(store, working)) {
22451
+ if (!code(row.path)) continue;
22452
+ const inFile = byPath.get(row.path) ?? [];
22453
+ inFile.push(row);
22454
+ byPath.set(row.path, inFile);
22455
+ }
22456
+ const all = [];
22457
+ await Promise.all(
22458
+ [...byPath].map(async ([path14, inFile]) => {
22459
+ const found2 = declarations(inFile).filter(eligible);
22460
+ if (!found2.length) return;
22461
+ const text = await read(path14);
22462
+ if (text === void 0) return;
22463
+ const lines = text.split("\n").map(lineWords);
22464
+ for (const declaration of found2) {
22465
+ const words = /* @__PURE__ */ new Map();
22466
+ for (const line of lines.slice(declaration.startLine - 1, declaration.endLine))
22467
+ for (const word of line) words.set(word, (words.get(word) ?? 0) + 1);
22468
+ all.push({ declaration, words });
22469
+ }
22470
+ })
22471
+ );
22472
+ const frequency = /* @__PURE__ */ new Map();
22473
+ for (const { words } of all)
22474
+ for (const word of words.keys()) frequency.set(word, (frequency.get(word) ?? 0) + 1);
22475
+ const weight = (word) => Math.log((all.length + 1) / ((frequency.get(word) ?? 0) + 1));
22476
+ const vector = (words) => {
22477
+ const weighted = /* @__PURE__ */ new Map();
22478
+ let length = 0;
22479
+ for (const [word, count] of words) {
22480
+ const value = (1 + Math.log(count)) * weight(word);
22481
+ weighted.set(word, value);
22482
+ length += value * value;
22483
+ }
22484
+ length = Math.sqrt(length) || 1;
22485
+ for (const [word, value] of weighted) weighted.set(word, value / length);
22486
+ return weighted;
22487
+ };
22488
+ const holders = /* @__PURE__ */ new Map();
22489
+ for (const item of all) {
22490
+ if (added.has(item.declaration.id)) continue;
22491
+ for (const [word, value] of vector(item.words)) {
22492
+ const holding = holders.get(word) ?? [];
22493
+ holding.push({ item, value });
22494
+ holders.set(word, holding);
22495
+ }
22496
+ }
22497
+ const graph = new MapViewGraph(store, working);
22498
+ const label = (row) => mapDeclarationLabel({
22499
+ kind: row.kind,
22500
+ anchor: { startLine: row.startLine, endLine: row.endLine }
22501
+ });
22502
+ const found = [];
22503
+ for (const item of all) {
22504
+ const declaration = item.declaration;
22505
+ if (!added.has(declaration.id)) continue;
22506
+ const scores = /* @__PURE__ */ new Map();
22507
+ for (const [word, value] of vector(item.words))
22508
+ for (const other of holders.get(word) ?? [])
22509
+ scores.set(other.item, (scores.get(other.item) ?? 0) + value * other.value);
22510
+ const alike = [...scores].filter(([other, score]) => {
22511
+ const them = other.declaration;
22512
+ if (them.path === declaration.path && them.start < declaration.end && declaration.start < them.end)
22513
+ return false;
22514
+ const siblings = declaration.container !== void 0 && them.container === declaration.container;
22515
+ return score >= (siblings ? SIBLINGS_ALIKE : ALIKE);
22516
+ }).sort(([, left], [, right]) => right - left);
22517
+ if (!alike.length) continue;
22518
+ const scope = graph.scope(declaration.id).refs;
22519
+ const linked = /* @__PURE__ */ new Set([
22520
+ ...graph.relationsFrom(scope).flatMap((relation) => relation.to ? [graph.owner(relation.to)] : []),
22521
+ ...graph.relationsTo(scope).map((relation) => graph.owner(relation.from))
22522
+ ]);
22523
+ const unlinked = alike.filter(([other]) => !linked.has(other.declaration.id));
22524
+ const best = unlinked[0];
22525
+ if (!best) continue;
22526
+ found.push({
22527
+ path: declaration.path,
22528
+ name: declaration.qualifiedName,
22529
+ label: label(declaration),
22530
+ like: {
22531
+ path: best[0].declaration.path,
22532
+ name: best[0].declaration.qualifiedName,
22533
+ label: label(best[0].declaration)
22534
+ },
22535
+ others: unlinked.length - 1,
22536
+ score: best[1]
22537
+ });
22538
+ }
22539
+ return found.sort(
22540
+ (left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0) || right.score - left.score
22541
+ ).map(({ score: _score, ...similar }) => similar);
22542
+ }
22543
+
22368
22544
  // src/project-map-changes.ts
22369
22545
  var git = new GitRunner();
22370
22546
  var gitOptions = (cwd, signal) => ({
@@ -22409,14 +22585,14 @@ async function readMapChanges(project, base, signal) {
22409
22585
  ],
22410
22586
  gitOptions(project, signal)
22411
22587
  )).stdout.toString("utf8");
22412
- const files = parseMapDiff(diff);
22588
+ const files = parseMapDiff(diff).filter((file2) => !inExcludedDirectory(file2.path));
22413
22589
  for (const [index, file2] of files.entries())
22414
22590
  if (file2.basePath && file2.status !== "ADDED" && !file2.binary && testCode(file2.basePath))
22415
22591
  files[index] = {
22416
22592
  ...file2,
22417
22593
  baseText: (await git.run(["show", `${commit}:${file2.basePath}`], gitOptions(project, signal))).stdout.toString("utf8")
22418
22594
  };
22419
- const untracked = (await git.run(["ls-files", "--others", "--exclude-standard", "-z"], gitOptions(project, signal))).stdout.toString("utf8").split("\0").filter(Boolean);
22595
+ const untracked = (await git.run(["ls-files", "--others", "--exclude-standard", "-z"], gitOptions(project, signal))).stdout.toString("utf8").split("\0").filter((path14) => path14 && !inExcludedDirectory(path14));
22420
22596
  for (const path14 of untracked)
22421
22597
  files.push({ path: path14, status: "ADDED", lines: [EVERYTHING], baseLines: [], binary: false });
22422
22598
  const stranded = await strandedNames(
@@ -22709,9 +22885,12 @@ function mapChangeImpact(store, working, base, changes, project) {
22709
22885
  const changed = [];
22710
22886
  const unclear = [];
22711
22887
  const removed = [];
22712
- const declarations = (g, path14) => g.objectsAt(path14).filter((object2) => !mapIsModule(object2) && g.isAddressable(object2));
22888
+ const declarations2 = (g, path14) => g.objectsAt(path14).filter((object2) => !mapIsModule(object2) && g.isAddressable(object2));
22713
22889
  let changedCount = 0;
22714
22890
  const starts = [];
22891
+ const importers = /* @__PURE__ */ new Map();
22892
+ let mapped;
22893
+ const mappedPaths = () => mapped ??= store.database.prepare("SELECT DISTINCT path FROM project_map_objects WHERE version_ref = ?").all(working).map((row) => String(row.path));
22715
22894
  for (const file2 of changes.files) {
22716
22895
  if (file2.binary) continue;
22717
22896
  const kind = nonCodeKind(file2.path);
@@ -22726,7 +22905,7 @@ function mapChangeImpact(store, working, base, changes, project) {
22726
22905
  if (!objects2.length) continue;
22727
22906
  const hits = /* @__PURE__ */ new Set();
22728
22907
  let topLevel = false;
22729
- const inFile = declarations(graph, file2.path);
22908
+ const inFile = declarations2(graph, file2.path);
22730
22909
  for (const [from, to] of file2.lines) {
22731
22910
  const containing = inFile.filter(
22732
22911
  (object2) => object2.anchor.startLine <= to && from <= object2.anchor.endLine
@@ -22756,15 +22935,16 @@ function mapChangeImpact(store, working, base, changes, project) {
22756
22935
  );
22757
22936
  if (analyzed && topLevel && file2.status !== "ADDED")
22758
22937
  unclear.push(`top-level code of ${file2.path} changed (imports, constants or registrations)`);
22759
- importerTests(graph, objects2, tracer);
22760
- sameDirectoryTests(store, working, file2.path, tracer);
22761
- mirroredTests(store, working, file2.path, tracer);
22938
+ importerTests(graph, objects2, tracer, importers);
22939
+ sameDirectoryTests(mappedPaths(), file2.path, tracer);
22940
+ mirroredTests(mappedPaths(), file2.path, tracer);
22762
22941
  }
22763
22942
  tracer.trace(starts);
22764
22943
  if (project) routeTests(project, store, working, [...tracer.entries.values()], tracer);
22765
22944
  supportTests(store, working, tracer);
22766
22945
  const rewrittenTests = [];
22767
22946
  const removedRoutes = [];
22947
+ const uncalled = [];
22768
22948
  if (base) {
22769
22949
  const before = new MapViewGraph(store, base);
22770
22950
  const registered = /* @__PURE__ */ new Set();
@@ -22787,11 +22967,11 @@ function mapChangeImpact(store, working, base, changes, project) {
22787
22967
  if (!file2.basePath || !file2.baseLines.length || file2.binary || testCode(file2.basePath))
22788
22968
  continue;
22789
22969
  const now = new Set(
22790
- file2.status === "DELETED" ? [] : declarations(graph, file2.path).map(
22970
+ file2.status === "DELETED" ? [] : declarations2(graph, file2.path).map(
22791
22971
  (o) => `${o.kind}\0${graph.qualifiedName(o.id)}`
22792
22972
  )
22793
22973
  );
22794
- for (const object2 of declarations(before, file2.basePath)) {
22974
+ for (const object2 of declarations2(before, file2.basePath)) {
22795
22975
  if (!overlaps(file2.baseLines, object2.anchor.startLine, object2.anchor.endLine)) continue;
22796
22976
  if (now.has(`${object2.kind}\0${before.qualifiedName(object2.id)}`)) continue;
22797
22977
  const parent = before.parent(object2.id);
@@ -22823,6 +23003,39 @@ function mapChangeImpact(store, working, base, changes, project) {
22823
23003
  unclear.push(...beforeTracer.unclear.filter((line) => !line.includes("has no callers")));
22824
23004
  if (beforeTracer.truncated) tracer.truncated = true;
22825
23005
  }
23006
+ const moved = new Map(
23007
+ changes.files.flatMap(
23008
+ (file2) => file2.basePath ? [[file2.basePath, file2.status === "DELETED" ? void 0 : file2.path]] : []
23009
+ )
23010
+ );
23011
+ const called = /* @__PURE__ */ new Set();
23012
+ for (const file2 of changes.files) {
23013
+ if (!file2.basePath || !file2.baseLines.length || file2.binary || testCode(file2.basePath))
23014
+ continue;
23015
+ for (const relation of before.relationsFrom(
23016
+ before.objectsAt(file2.basePath).map((object2) => object2.id)
23017
+ ))
23018
+ if (CALLER_KINDS.has(relation.kind) && relation.to !== void 0 && overlaps(file2.baseLines, relation.anchor.startLine, relation.anchor.endLine))
23019
+ called.add(before.owner(relation.to));
23020
+ }
23021
+ const outsideTests = (callers, g) => callers.filter((caller) => !testCode(g.object(caller.ref).anchor.path));
23022
+ for (const ref of called) {
23023
+ const object2 = before.object(ref);
23024
+ if (mapIsModule(object2) || testCode(object2.anchor.path) || gone.includes(ref)) continue;
23025
+ const path14 = moved.has(object2.anchor.path) ? moved.get(object2.anchor.path) : object2.anchor.path;
23026
+ if (path14 === void 0) continue;
23027
+ const name = before.qualifiedName(ref);
23028
+ const now = declarations2(graph, path14).find(
23029
+ (candidate) => candidate.kind === object2.kind && graph.qualifiedName(candidate.id) === name
23030
+ );
23031
+ if (!now || outsideTests(tracer.callers(now.id), graph).length) continue;
23032
+ if (!outsideTests(beforeTracer.callers(ref), before).length) continue;
23033
+ const tested = tracer.callers(now.id).length > 0;
23034
+ uncalled.push(
23035
+ `${path14}: ${name} ${mapDeclarationLabel(now)}${tested ? " (only tests call it now)" : ""}`
23036
+ );
23037
+ }
23038
+ uncalled.sort();
22826
23039
  }
22827
23040
  return {
22828
23041
  changed,
@@ -22846,6 +23059,7 @@ function mapChangeImpact(store, working, base, changes, project) {
22846
23059
  })).sort((left, right) => right.tests.length - left.tests.length),
22847
23060
  unclear: [.../* @__PURE__ */ new Set([...unclear, ...tracer.unclear])],
22848
23061
  removedRoutes,
23062
+ uncalled,
22849
23063
  dependencies: newModuleDependencies(store, cache, working, base, changes.files),
22850
23064
  truncated: tracer.truncated
22851
23065
  };
@@ -22879,27 +23093,34 @@ function existingTestsChanged(before, after, file2, project) {
22879
23093
  )
22880
23094
  ).map((object2) => before.qualifiedName(object2.id)).sort();
22881
23095
  }
22882
- function importerTests(graph, objects2, tracer) {
23096
+ function importerTests(graph, objects2, tracer, importers) {
22883
23097
  let modules = objects2.filter((object2) => mapIsModule(object2)).map((object2) => object2.id);
22884
23098
  const seen = new Set(modules);
22885
23099
  for (let hop = 0; hop < 3 && modules.length; hop++) {
22886
- const next = [];
22887
- for (const relation of graph.relationsTo(modules)) {
22888
- if (!IMPORT_KINDS3.has(relation.kind)) continue;
23100
+ const unread = modules.filter((module) => !importers.has(module));
23101
+ for (const module of unread) importers.set(module, []);
23102
+ for (const relation of graph.relationsTo(unread)) {
23103
+ if (!IMPORT_KINDS3.has(relation.kind) || !relation.to) continue;
22889
23104
  const importer = graph.object(relation.from);
22890
- const module = mapIsModule(importer) ? importer.id : graph.owner(relation.from);
22891
- if (testCode(relation.anchor.path))
22892
- tracer.test(
22893
- relation.anchor.path,
22894
- void 0,
22895
- hop ? "imports a changed file indirectly" : "imports a changed file",
22896
- hop ? 4 : 2
22897
- );
22898
- else if (!seen.has(module)) {
22899
- seen.add(module);
22900
- next.push(module);
22901
- }
23105
+ importers.get(relation.to)?.push({
23106
+ path: relation.anchor.path,
23107
+ module: mapIsModule(importer) ? importer.id : graph.owner(relation.from)
23108
+ });
22902
23109
  }
23110
+ const next = [];
23111
+ for (const imported of modules)
23112
+ for (const { path: path14, module } of importers.get(imported) ?? [])
23113
+ if (testCode(path14))
23114
+ tracer.test(
23115
+ path14,
23116
+ void 0,
23117
+ hop ? "imports a changed file indirectly" : "imports a changed file",
23118
+ hop ? 4 : 2
23119
+ );
23120
+ else if (!seen.has(module)) {
23121
+ seen.add(module);
23122
+ next.push(module);
23123
+ }
22903
23124
  modules = next;
22904
23125
  }
22905
23126
  }
@@ -22913,14 +23134,12 @@ function supportTests(store, version2, tracer) {
22913
23134
  tracer.test(String(row.path), void 0, `may use it through ${file2}`, 3.5);
22914
23135
  }
22915
23136
  }
22916
- function mirroredTests(store, version2, file2, tracer) {
23137
+ function mirroredTests(paths, file2, tracer) {
22917
23138
  const directories = file2.split("/").slice(0, -1);
22918
23139
  const module = directories.at(-1);
22919
23140
  if (!module || directories.length < 1) return;
22920
- for (const row of store.database.prepare(
22921
- "SELECT DISTINCT path FROM project_map_objects WHERE version_ref = ? AND instr(path, ?) > 0"
22922
- ).all(version2, `/${module}/`)) {
22923
- const candidate = String(row.path);
23141
+ for (const candidate of paths) {
23142
+ if (!candidate.includes(`/${module}/`)) continue;
22924
23143
  const parts = candidate.split("/");
22925
23144
  const at = parts.lastIndexOf(module);
22926
23145
  if (at < 1 || at !== parts.length - 2) continue;
@@ -22961,13 +23180,11 @@ function routeTests(project, store, version2, entries, tracer) {
22961
23180
  }
22962
23181
  }
22963
23182
  }
22964
- function sameDirectoryTests(store, version2, path14, tracer) {
23183
+ function sameDirectoryTests(paths, path14, tracer) {
22965
23184
  const slash = path14.lastIndexOf("/");
22966
23185
  const directory = slash < 0 ? "" : path14.slice(0, slash + 1);
22967
- for (const row of store.database.prepare(
22968
- "SELECT DISTINCT path FROM project_map_objects WHERE version_ref = ? AND path LIKE ? ESCAPE '\\'"
22969
- ).all(version2, `${directory.replace(/[\\%_]/gu, (c) => `\\${c}`)}%`)) {
22970
- const candidate = String(row.path);
23186
+ for (const candidate of paths) {
23187
+ if (!candidate.startsWith(directory)) continue;
22971
23188
  if (candidate.slice(directory.length).includes("/") || !mapTestPath(candidate)) continue;
22972
23189
  tracer.test(candidate, void 0, "in the same directory", 3);
22973
23190
  }
@@ -22992,7 +23209,9 @@ var LIST = Object.freeze({
22992
23209
  areaNames: 3,
22993
23210
  through: 2,
22994
23211
  dependencies: 12,
22995
- sites: 2
23212
+ sites: 2,
23213
+ similar: 10,
23214
+ similarNames: 3
22996
23215
  });
22997
23216
  function routesIn(graph, path14) {
22998
23217
  const routes = /* @__PURE__ */ new Set();
@@ -23015,7 +23234,14 @@ async function checkMapChanges(input, signal) {
23015
23234
  text: mapChangesText(
23016
23235
  changes,
23017
23236
  impact,
23018
- await mapRouteClients(project, index.store, working, impact, signal)
23237
+ await mapRouteClients(project, index.store, working, impact, signal),
23238
+ await similarCode(
23239
+ index.store,
23240
+ working,
23241
+ base,
23242
+ changes.files,
23243
+ (file2) => readFile(path9.join(project, file2), "utf8").catch(() => void 0)
23244
+ )
23019
23245
  )
23020
23246
  };
23021
23247
  }
@@ -23035,7 +23261,7 @@ async function mapRouteClients(project, store, working, impact, signal) {
23035
23261
  if (!routes.length) return [];
23036
23262
  return routeClients(routes, registrations, git, gitOptions(project, signal));
23037
23263
  }
23038
- function mapChangesText(changes, impact, clients = []) {
23264
+ function mapChangesText(changes, impact, clients = [], similar = []) {
23039
23265
  const files = changes.files.length;
23040
23266
  const direct = impact.tests.filter((test) => test.rank < 4);
23041
23267
  const indirect = impact.tests.filter((test) => test.rank >= 4);
@@ -23056,6 +23282,15 @@ Nothing changed against ${changes.base}.`;
23056
23282
  impact.removed,
23057
23283
  LIST.changed
23058
23284
  );
23285
+ list(
23286
+ "LEFT WITHOUT CALLERS (the diff removed or changed their last callers; nothing outside tests calls them now)",
23287
+ impact.uncalled,
23288
+ LIST.changed
23289
+ );
23290
+ if (impact.uncalled.length)
23291
+ lines.push(
23292
+ "If the change replaced them, delete them and the tests that only test them; keep them only if something the map cannot see uses them, such as another package, a framework or a dynamic call."
23293
+ );
23059
23294
  if (changes.stranded.length) {
23060
23295
  list(
23061
23296
  "NAMES STILL USED ELSEWHERE (environment variables and configuration keys the diff removed from a file, found by text)",
@@ -23115,6 +23350,32 @@ Nothing changed against ${changes.base}.`;
23115
23350
  `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.`
23116
23351
  );
23117
23352
  }
23353
+ if (similar.length) {
23354
+ const declaration = (item) => `${item.path}: ${item.name} ${item.label}`;
23355
+ const pairs = /* @__PURE__ */ new Map();
23356
+ for (const item of similar) {
23357
+ const key = `${item.path}\0${item.like.path}`;
23358
+ pairs.set(key, [...pairs.get(key) ?? [], item]);
23359
+ }
23360
+ list(
23361
+ "EXISTING CODE LIKE THE NEW CODE (declarations the diff adds whose code reads almost the same as code the project already has)",
23362
+ [...pairs.values()].flatMap((items) => {
23363
+ const [first] = items;
23364
+ if (items.length < 3)
23365
+ return items.map(
23366
+ (item) => `${declaration(item)} ~ ${declaration(item.like)}${item.others ? ` (+${item.others} more alike)` : ""}`
23367
+ );
23368
+ const names = items.slice(0, LIST.similarNames).map((item) => `${item.name} ~ ${item.like.name}`);
23369
+ return [
23370
+ `${first.path} repeats ${first.like.path} in ${items.length} declarations: ${names.join(", ")}${items.length > LIST.similarNames ? ", \u2026" : ""}`
23371
+ ];
23372
+ }),
23373
+ LIST.similar
23374
+ );
23375
+ lines.push(
23376
+ "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."
23377
+ );
23378
+ }
23118
23379
  const entry = (item) => `${item.route ? JSON.stringify(item.label) : item.label}${item.chain.length ? ` \u2192 ${item.chain.join(" \u2192 ")}` : ""}${item.site ? ` (registered at ${item.site})` : ""}`;
23119
23380
  list(
23120
23381
  "AFFECTED ENTRY POINTS (through resolved calls)",
@@ -23170,11 +23431,13 @@ Nothing changed against ${changes.base}.`;
23170
23431
  // src/layermap.ts
23171
23432
  var SCHEMA_VERSION = 2;
23172
23433
  var KEEP_VERSIONS = 3;
23434
+ var BUSY_TIMEOUT = "PRAGMA busy_timeout = 30000;";
23435
+ var JOURNAL_LIMIT = 32 * 1024 * 1024;
23173
23436
  function openMapDatabase(file2) {
23174
23437
  mkdirSync(path10.dirname(file2), { recursive: true, mode: 448 });
23175
23438
  const database = new DatabaseSync(file2);
23176
23439
  try {
23177
- database.exec("PRAGMA busy_timeout = 30000;");
23440
+ database.exec(BUSY_TIMEOUT);
23178
23441
  const version2 = Number(database.prepare("PRAGMA user_version").get()?.user_version ?? 0);
23179
23442
  if (version2 > SCHEMA_VERSION) throw new ProjectEvidenceError("LAYERMAP_DATABASE_NEWER", false);
23180
23443
  if (version2 === 0) database.exec("PRAGMA auto_vacuum = INCREMENTAL;");
@@ -23215,18 +23478,20 @@ var mapDatabasePath = (cacheDirectory2, canonicalProject) => path10.join(
23215
23478
  "map.sqlite"
23216
23479
  );
23217
23480
  var LayerMap = class _LayerMap {
23218
- constructor(project, source, store, index, budget) {
23481
+ constructor(project, source, store, index, budget, journal) {
23219
23482
  this.project = project;
23220
23483
  this.source = source;
23221
23484
  this.store = store;
23222
23485
  this.index = index;
23223
23486
  this.budget = budget;
23487
+ this.journal = journal;
23224
23488
  }
23225
23489
  project;
23226
23490
  source;
23227
23491
  store;
23228
23492
  index;
23229
23493
  budget;
23494
+ journal;
23230
23495
  refreshing;
23231
23496
  static async open(options) {
23232
23497
  const project = await realpath2(options.project);
@@ -23237,10 +23502,9 @@ var LayerMap = class _LayerMap {
23237
23502
  projectRef: `layermap:${createHash4("sha256").update(project).digest("hex").slice(0, 24)}`,
23238
23503
  directory: { canonicalPath: project, device: String(stat3.dev), inode: String(stat3.ino) }
23239
23504
  };
23505
+ const file2 = mapDatabasePath(options.cacheDirectory, project);
23240
23506
  const store = new CodeIndexStore(
23241
- openMapDatabase(
23242
- mapDatabasePath(options.cacheDirectory, project)
23243
- )
23507
+ openMapDatabase(file2)
23244
23508
  );
23245
23509
  const { typescript, go, python, java } = options.analyzers;
23246
23510
  const index = new CodeIndex(
@@ -23253,10 +23517,14 @@ var LayerMap = class _LayerMap {
23253
23517
  new JavaMapAnalyzer(java)
23254
23518
  ])
23255
23519
  );
23256
- return new _LayerMap(project, source, store, index, {
23257
- maxBytes: options.maxOutputBytes ?? 96 * 1024,
23258
- envelopeBytes: 0
23259
- });
23520
+ return new _LayerMap(
23521
+ project,
23522
+ source,
23523
+ store,
23524
+ index,
23525
+ { maxBytes: options.maxOutputBytes ?? 96 * 1024, envelopeBytes: 0 },
23526
+ `${file2}-wal`
23527
+ );
23260
23528
  }
23261
23529
  /** The map version of the directory as it is now, built or updated if needed. */
23262
23530
  refresh(signal) {
@@ -23265,6 +23533,7 @@ var LayerMap = class _LayerMap {
23265
23533
  initialScope: DEFAULT_INITIAL_EVIDENCE_SCOPE
23266
23534
  });
23267
23535
  this.prune(version2);
23536
+ this.tidyJournal();
23268
23537
  return version2.version;
23269
23538
  });
23270
23539
  }
@@ -23295,6 +23564,20 @@ var LayerMap = class _LayerMap {
23295
23564
  ]);
23296
23565
  this.store.database.exec("PRAGMA incremental_vacuum;");
23297
23566
  }
23567
+ // SQLite leaves the write-ahead log at the size of the largest capture written through it, often
23568
+ // hundreds of megabytes after a build. Once that capture is in the database the log is emptied,
23569
+ // unless another process is reading or writing the map, in which case a later capture empties it.
23570
+ tidyJournal() {
23571
+ if ((statSync(this.journal, { throwIfNoEntry: false })?.size ?? 0) <= JOURNAL_LIMIT) return;
23572
+ const database = this.store.database;
23573
+ database.exec("PRAGMA busy_timeout = 0;");
23574
+ try {
23575
+ database.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get();
23576
+ } catch {
23577
+ } finally {
23578
+ database.exec(BUSY_TIMEOUT);
23579
+ }
23580
+ }
23298
23581
  async explore(input, signal) {
23299
23582
  const version2 = await this.refresh(signal);
23300
23583
  return this.index.query.viewMap(
@@ -23365,7 +23648,7 @@ var packageRoot = (() => {
23365
23648
  directory = path11.dirname(directory);
23366
23649
  }
23367
23650
  })();
23368
- var packageVersion = async () => JSON.parse(await readFile(path11.join(packageRoot, "package.json"), "utf8")).version;
23651
+ var packageVersion = async () => JSON.parse(await readFile2(path11.join(packageRoot, "package.json"), "utf8")).version;
23369
23652
  var cacheDirectory = (env = process.env) => {
23370
23653
  if (env.LAYERMAP_CACHE) return path11.resolve(env.LAYERMAP_CACHE);
23371
23654
  if (process.platform === "darwin") return path11.join(homedir(), "Library", "Caches", "layermap");
@@ -23424,11 +23707,11 @@ var absoluteIn = (directory, value) => Object.fromEntries(
23424
23707
  var readAnalyzers = async (directory) => {
23425
23708
  const file2 = path11.join(directory, "analyzers.json");
23426
23709
  if (!existsSync5(file2)) return void 0;
23427
- const analyzers = absoluteIn(directory, JSON.parse(await readFile(file2, "utf8")));
23710
+ const analyzers = absoluteIn(directory, JSON.parse(await readFile2(file2, "utf8")));
23428
23711
  return analyzers.java.runtimePath ? analyzers : { ...analyzers, java: { ...analyzers.java, ...discoverJavaRuntime() } };
23429
23712
  };
23430
23713
  var sourceDigest = async () => {
23431
- const hash2 = createHash5("sha256").update(await readFile(path11.join(packageRoot, "package.json")));
23714
+ const hash2 = createHash5("sha256").update(await readFile2(path11.join(packageRoot, "package.json")));
23432
23715
  for (const part of ["src", "go-map", "java-map", "scripts"]) {
23433
23716
  const directory = path11.join(packageRoot, part);
23434
23717
  if (!existsSync5(directory)) continue;
@@ -23467,7 +23750,7 @@ async function resolveAnalyzers(cache, log2, env = process.env) {
23467
23750
  return await readAnalyzers(directory);
23468
23751
  }
23469
23752
  var DAY = 24 * 60 * 60 * 1e3;
23470
- async function pruneCache(cache, project, now = Date.now()) {
23753
+ async function pruneCache(cache, project, now = Date.now(), installed = packageRoot) {
23471
23754
  const used = path11.join(path11.dirname(mapDatabasePath(cache, project)), "last-used");
23472
23755
  await mkdir(path11.dirname(used), { recursive: true, mode: 448 });
23473
23756
  await writeFile(used, "");
@@ -23488,11 +23771,40 @@ async function pruneCache(cache, project, now = Date.now()) {
23488
23771
  if (built !== void 0 && now - built > (name.includes(".") ? DAY / 24 : DAY))
23489
23772
  await rm(path11.join(builds, name), { recursive: true, force: true });
23490
23773
  }
23774
+ await pruneNpxInstalls(installed, now);
23775
+ }
23776
+ async function pruneNpxInstalls(installed, now) {
23777
+ const own = path11.dirname(path11.dirname(installed));
23778
+ const npx = path11.dirname(own);
23779
+ if (path11.basename(path11.dirname(installed)) !== "node_modules" || path11.basename(npx) !== "_npx")
23780
+ return;
23781
+ const manifest = async (file2) => JSON.parse(await readFile2(file2, "utf8").catch(() => "{}"));
23782
+ const parts = (version2) => version2?.split(".").map(Number) ?? [];
23783
+ const current = parts((await manifest(path11.join(installed, "package.json"))).version);
23784
+ const older = (version2) => {
23785
+ for (let index = 0; index < 3; index++)
23786
+ if (version2[index] !== current[index]) return (version2[index] ?? 0) < (current[index] ?? 0);
23787
+ return false;
23788
+ };
23789
+ for (const name of await readdir(npx).catch(() => [])) {
23790
+ const directory = path11.join(npx, name);
23791
+ if (directory === own) continue;
23792
+ const requested = (await manifest(path11.join(directory, "package.json"))).dependencies ?? {};
23793
+ if (Object.keys(requested).join() !== "layermap") continue;
23794
+ const version2 = parts(
23795
+ (await manifest(path11.join(directory, "node_modules", "layermap", "package.json"))).version
23796
+ );
23797
+ if (version2.length !== 3 || version2.some(Number.isNaN) || !older(version2)) continue;
23798
+ const at = (await stat(directory).catch(() => void 0))?.mtimeMs;
23799
+ if (at !== void 0 && now - at > 7 * DAY)
23800
+ await rm(directory, { recursive: true, force: true });
23801
+ }
23491
23802
  }
23492
23803
 
23493
23804
  // src/agent/mcp.ts
23494
23805
  import { createInterface } from "node:readline";
23495
23806
  import { setTimeout as delay } from "node:timers/promises";
23807
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
23496
23808
 
23497
23809
  // src/agent/projects.ts
23498
23810
  import { existsSync as existsSync6 } from "node:fs";
@@ -23578,7 +23890,7 @@ var mapToolDescriptions = (host) => {
23578
23890
  return Object.freeze({
23579
23891
  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.`,
23580
23892
  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.`,
23581
- check: `${lead("check")}Compares the working tree with a commit (HEAD by default, so uncommitted and untracked changes), finds the declarations the diff changed, removed or renamed, and follows their callers up to 8 levels. It reports, conclusion first: AFFECTED ENTRY POINTS reached through resolved calls, each route with its HTTP methods and full path and the chain to the change; POSSIBLY AFFECTED ones reached only through a call on an interface or base member; REQUESTED BY, the code and templates outside the tests that request the path of a route whose handler the change reaches or a route it removed, found by text; EXISTING TESTS CHANGED, the tests that existed before the diff and whose code it changed or removed; SHARED BY, when tests reach the changed code through more than one area (package or module), so a change meant for one feature may change others; NAMES STILL USED ELSEWHERE, environment variables and configuration keys the diff removed from a file that other files still read or set, found by text; NEW MODULE DEPENDENCIES, imports between the modules of the project overview that the base did not have, and those that make two modules depend on each other, for you to judge against the project's layers; CHECK BY HAND for what a static map cannot follow (changed configuration, templates, migrations or dependency files, changed route registrations, declarations with no callers, calls by name on receivers of unknown type); and RELATED TESTS, the existing test files that call the changed code, import a changed file or sit beside it. It does not run or write tests: run the related ones if the change needs verifying; a failing or rewritten test of a feature the request is not about means the change leaked, so restore the test and narrow the change; a new dependency that runs against the layers or closes a cycle means moving what both modules need down rather than importing upward; 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.`,
23893
+ check: `${lead("check")}Compares the working tree with a commit (HEAD by default, so uncommitted and untracked changes), finds the declarations the diff changed, removed or renamed, and follows their callers up to 8 levels. It reports, conclusion first: AFFECTED ENTRY POINTS reached through resolved calls, each route with its HTTP methods and full path and the chain to the change; POSSIBLY AFFECTED ones reached only through a call on an interface or base member; REQUESTED BY, the code and templates outside the tests that request the path of a route whose handler the change reaches or a route it removed, found by text; EXISTING TESTS CHANGED, the tests that existed before the diff and whose code it changed or removed; SHARED BY, when tests reach the changed code through more than one area (package or module), so a change meant for one feature may change others; NAMES STILL USED ELSEWHERE, environment variables and configuration keys the diff removed from a file that other files still read or set, found by text; NEW MODULE DEPENDENCIES, imports between the modules of the project overview that the base did not have, and those that make two modules depend on each other, for you to judge against the project's layers; EXISTING CODE LIKE THE NEW CODE, declarations the diff adds whose code reads almost the same as code the project already has; LEFT WITHOUT CALLERS, declarations whose last callers outside the tests the diff removed or changed; CHECK BY HAND for what a static map cannot follow (changed configuration, templates, migrations or dependency files, changed route registrations, declarations with no callers, calls by name on receivers of unknown type); and RELATED TESTS, the existing test files that call the changed code, import a changed file or sit beside it. It does not run or write tests: run the related ones if the change needs verifying; a failing or rewritten test of a feature the request is not about means the change leaked, so restore the test and narrow the change; a new dependency that runs against the layers or closes a cycle means moving what both modules need down rather than importing upward; new code like existing code means using the existing code, or removing the old if the new replaces it; code left without callers means deleting it, with the tests that only test it, when the change replaced it; call it once when the edits are done; and confirm the entry points in source, since an empty list does not prove a change safe.`,
23582
23894
  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.`
23583
23895
  });
23584
23896
  };
@@ -23631,10 +23943,10 @@ async function routeMapCall(start, { name, args }) {
23631
23943
  };
23632
23944
  const filter = args.path;
23633
23945
  if (filter === ".") return { project: located.project, args: routed };
23634
- const within2 = await locate(start, filter);
23635
- if (within2?.project !== located.project)
23946
+ const within3 = await locate(start, filter);
23947
+ if (within3?.project !== located.project)
23636
23948
  return `PROJECT_PATH_INVALID: path ${filter} is not in ${located.project}, the repository of the declaration.`;
23637
- return { project: located.project, args: { ...routed, path: within2.path } };
23949
+ return { project: located.project, args: { ...routed, path: within3.path } };
23638
23950
  }
23639
23951
 
23640
23952
  // src/agent/tools.ts
@@ -23737,6 +24049,7 @@ var AGENT_MAP_INSTRUCTIONS = `Use the LayerMap tools instead of grep whenever a
23737
24049
  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.";
23738
24050
 
23739
24051
  // src/agent/mcp.ts
24052
+ var ROOTS_WAIT_MS = 5e3;
23740
24053
  function serveMcp(options) {
23741
24054
  const output = options.output ?? process.stdout;
23742
24055
  const log2 = options.log ?? ((line) => process.stderr.write(`${line}
@@ -23746,6 +24059,26 @@ function serveMcp(options) {
23746
24059
  const calls = /* @__PURE__ */ new Map();
23747
24060
  const maps = /* @__PURE__ */ new Map();
23748
24061
  const session = new AbortController();
24062
+ let start = options.start;
24063
+ let rooted = Promise.resolve();
24064
+ let listsRoots = false;
24065
+ const replies = /* @__PURE__ */ new Map();
24066
+ let requested = 0;
24067
+ const readRoots = () => {
24068
+ const id2 = `layermap-roots-${++requested}`;
24069
+ const reply = new Promise((resolve) => replies.set(id2, resolve));
24070
+ send({ id: id2, method: "roots/list" });
24071
+ rooted = Promise.race([reply, delay(ROOTS_WAIT_MS, void 0, { ref: false })]).then(async (message) => {
24072
+ replies.delete(id2);
24073
+ const roots = message?.result?.roots;
24074
+ const root = Array.isArray(roots) ? roots.find((item) => typeof item?.uri === "string" && item.uri.startsWith("file:")) : void 0;
24075
+ if (!root) return;
24076
+ const directory = await projectDirectory(fileURLToPath2(root.uri));
24077
+ if (id2 === `layermap-roots-${requested}`) start = directory;
24078
+ }).catch(() => {
24079
+ });
24080
+ return rooted;
24081
+ };
23749
24082
  const map2 = (project) => {
23750
24083
  let entry = maps.get(project);
23751
24084
  if (!entry) {
@@ -23784,7 +24117,8 @@ ${text}` : text
23784
24117
  try {
23785
24118
  const parsed = parseMapToolCall(name, params.arguments);
23786
24119
  if ("text" in parsed) return respond(parsed.text, parsed.isError);
23787
- const routed = await routeMapCall(options.start, parsed);
24120
+ await rooted;
24121
+ const routed = await routeMapCall(start, parsed);
23788
24122
  if (typeof routed === "string") return respond(routed, true);
23789
24123
  project = routed.project;
23790
24124
  const { opened, built } = map2(project);
@@ -23811,15 +24145,23 @@ ${text}` : text
23811
24145
  };
23812
24146
  const handle = (message) => {
23813
24147
  const { id: id2, method, params = {} } = message;
23814
- if (method === void 0) return;
24148
+ if (method === void 0) {
24149
+ if (id2 !== void 0 && id2 !== null) replies.get(id2)?.(message);
24150
+ return;
24151
+ }
23815
24152
  if (id2 === void 0 || id2 === null) {
23816
- if (method === "notifications/initialized" && options.start.git) map2(options.start.directory);
24153
+ if (method === "notifications/initialized")
24154
+ void (listsRoots ? readRoots() : rooted).then(() => {
24155
+ if (start.git) map2(start.directory);
24156
+ });
24157
+ if (method === "notifications/roots/list_changed" && listsRoots) void readRoots();
23817
24158
  if (method === "notifications/cancelled")
23818
24159
  calls.get(params.requestId)?.abort();
23819
24160
  return;
23820
24161
  }
23821
24162
  switch (method) {
23822
24163
  case "initialize":
24164
+ listsRoots = Boolean(params.capabilities?.roots);
23823
24165
  return send({
23824
24166
  id: id2,
23825
24167
  result: {
@@ -23887,7 +24229,7 @@ ${text}` : text
23887
24229
  // src/agent/setup.ts
23888
24230
  import { execFile as execFile2 } from "node:child_process";
23889
24231
  import { existsSync as existsSync7 } from "node:fs";
23890
- import { mkdir as mkdir2, readFile as readFile2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
24232
+ import { mkdir as mkdir2, readFile as readFile3, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
23891
24233
  import { homedir as homedir2 } from "node:os";
23892
24234
  import path13 from "node:path";
23893
24235
  var SERVER = "layermap";
@@ -23931,7 +24273,7 @@ var run = (command, args, env) => new Promise((resolve) => {
23931
24273
  );
23932
24274
  });
23933
24275
  async function allowInClaudeSettings(file2, rule = SETUP_RULE) {
23934
- const settings = existsSync7(file2) ? JSON.parse(await readFile2(file2, "utf8")) : {};
24276
+ const settings = existsSync7(file2) ? JSON.parse(await readFile3(file2, "utf8")) : {};
23935
24277
  if (typeof settings !== "object" || settings === null || Array.isArray(settings))
23936
24278
  throw new Error(`${file2} is not a settings object.`);
23937
24279
  settings.permissions ??= {};
@@ -23946,7 +24288,7 @@ async function allowInClaudeSettings(file2, rule = SETUP_RULE) {
23946
24288
  return true;
23947
24289
  }
23948
24290
  async function configureCodexServer(file2) {
23949
- const lines = (await readFile2(file2, "utf8")).split("\n");
24291
+ const lines = (await readFile3(file2, "utf8")).split("\n");
23950
24292
  const header2 = lines.findIndex((line) => line.trim() === `[mcp_servers.${SERVER}]`);
23951
24293
  if (header2 < 0) throw new Error(`${file2} has no [mcp_servers.${SERVER}] table.`);
23952
24294
  let end = header2 + 1;
@@ -23968,7 +24310,7 @@ async function writeInstructionNote(file2, note = AGENT_MAP_NOTE) {
23968
24310
  const block = `${BEGIN}
23969
24311
  ${note}
23970
24312
  ${END}`;
23971
- const text = existsSync7(file2) ? await readFile2(file2, "utf8") : "";
24313
+ const text = existsSync7(file2) ? await readFile3(file2, "utf8") : "";
23972
24314
  const start = text.indexOf(BEGIN);
23973
24315
  const end = text.indexOf(END);
23974
24316
  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}
@@ -23979,7 +24321,7 @@ ${END}`;
23979
24321
  }
23980
24322
  async function removeInstructionNote(file2) {
23981
24323
  if (!existsSync7(file2)) return;
23982
- const text = await readFile2(file2, "utf8");
24324
+ const text = await readFile3(file2, "utf8");
23983
24325
  const start = text.indexOf(BEGIN);
23984
24326
  const end = text.indexOf(END);
23985
24327
  if (start < 0 || end < start) return;
@@ -23990,7 +24332,7 @@ async function removeInstructionNote(file2) {
23990
24332
  }
23991
24333
  async function disallowInClaudeSettings(file2) {
23992
24334
  if (!existsSync7(file2)) return;
23993
- const settings = JSON.parse(await readFile2(file2, "utf8"));
24335
+ const settings = JSON.parse(await readFile3(file2, "utf8"));
23994
24336
  const allow = settings?.permissions?.allow;
23995
24337
  const ours = (rule) => rule === SETUP_RULE || rule === PLUGIN_RULE;
23996
24338
  if (!Array.isArray(allow) || !allow.some(ours)) return;
@@ -24028,7 +24370,7 @@ var dshPatchBlock = (command, env) => {
24028
24370
  ].join("\n");
24029
24371
  };
24030
24372
  async function writeDshPatch(file2, block) {
24031
- const text = existsSync7(file2) ? await readFile2(file2, "utf8") : "";
24373
+ const text = existsSync7(file2) ? await readFile3(file2, "utf8") : "";
24032
24374
  const start = text.indexOf(YAML_BEGIN);
24033
24375
  const end = text.indexOf(YAML_END);
24034
24376
  let next;
@@ -24049,7 +24391,7 @@ async function writeDshPatch(file2, block) {
24049
24391
  }
24050
24392
  async function removeDshPatch(file2) {
24051
24393
  if (!existsSync7(file2)) return;
24052
- const text = await readFile2(file2, "utf8");
24394
+ const text = await readFile3(file2, "utf8");
24053
24395
  const start = text.indexOf(YAML_BEGIN);
24054
24396
  const end = text.indexOf(YAML_END);
24055
24397
  if (start < 0 || end < start) return;
@@ -24232,6 +24574,11 @@ async function main(argv) {
24232
24574
  const version2 = await packageVersion();
24233
24575
  if (values.version) {
24234
24576
  process.stdout.write(`${version2}
24577
+ `);
24578
+ return 0;
24579
+ }
24580
+ if (command === "entry") {
24581
+ process.stdout.write(`${fileURLToPath3(import.meta.url)}
24235
24582
  `);
24236
24583
  return 0;
24237
24584
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "layermap",
3
- "version": "0.1.21",
3
+ "version": "0.1.24",
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
@@ -177,6 +177,9 @@ const fingerprint = (changed) =>
177
177
  .digest("hex")
178
178
  : "";
179
179
 
180
+ // How long a command runs (ms) before only the files it names count as its changes.
181
+ const LONG_COMMAND = 10_000;
182
+
180
183
  // The folders a shell command names that exist, relative to the directory it runs in.
181
184
  async function namedFolders(cwd, command) {
182
185
  const folders = new Set();
@@ -209,11 +212,15 @@ export default function layermap(pi) {
209
212
  // folders its command names and those already edited.
210
213
  // It compares a repository's uncommitted code changes with those it had before the session's
211
214
  // first such tool there and those the agent last checked in it, and all of them with those it
212
- // was last asked about; changes another session makes while this one reads do not count.
215
+ // was last asked about; changes another session makes while this one reads do not count. A
216
+ // command that ran longer than ten seconds (tests, builds, scripts) leaves time for another
217
+ // session to change the same work tree, so only the files it names count; one that writes code
218
+ // without naming the file, such as a generator or formatter, takes a few seconds.
213
219
  const edited = new Set();
214
220
  const before = new Map();
215
221
  const checked = new Map();
216
- // The code changes of each repository a running tool may change, by the tool call's id.
222
+ // The code changes of each repository a running tool may change, when it started and its
223
+ // command, by the tool call's id.
217
224
  const running = new Map();
218
225
  let askedAbout = "";
219
226
 
@@ -221,7 +228,7 @@ export default function layermap(pi) {
221
228
  if (server && !server.dead) return server;
222
229
  starting ??= (async () => {
223
230
  const next = new MapServer(cwd);
224
- const tools = await next.start("0.1.21");
231
+ const tools = await next.start("0.1.24");
225
232
  for (const tool of tools) {
226
233
  if (registered.has(tool.name)) continue;
227
234
  registered.add(tool.name);
@@ -295,17 +302,27 @@ export default function layermap(pi) {
295
302
  const changes = new Map();
296
303
  for (const repository of repositories)
297
304
  if (repository) changes.set(repository, await changedCode(repository));
298
- running.set(event.toolCallId, changes);
305
+ running.set(event.toolCallId, {
306
+ changes,
307
+ started: Date.now(),
308
+ command: typeof command === "string" ? command : "",
309
+ });
299
310
  });
300
311
 
301
312
  pi.on("tool_result", async (event) => {
302
- const changes = running.get(event.toolCallId);
303
- if (!changes) return;
313
+ const call = running.get(event.toolCallId);
314
+ if (!call) return;
304
315
  running.delete(event.toolCallId);
305
- for (const [repository, earlier] of changes) {
316
+ const long = Date.now() - call.started > LONG_COMMAND;
317
+ for (const [repository, earlier] of call.changes) {
306
318
  if (edited.has(repository)) continue;
307
319
  const now = await changedCode(repository);
308
- if ([...now].some(([file, content]) => earlier.get(file) !== content)) {
320
+ if (
321
+ [...now].some(
322
+ ([file, content]) =>
323
+ earlier.get(file) !== content && (!long || call.command.includes(path.basename(file))),
324
+ )
325
+ ) {
309
326
  edited.add(repository);
310
327
  before.set(repository, fingerprint(earlier));
311
328
  }