layermap 0.1.21 → 0.1.22

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,9 @@ 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. It never writes or runs tests. In Claude Code and
164
166
  CodeBuddy Code the plugin asks the agent once, before it finishes, to run this check for each repository it edited code in
165
167
  and has not checked since, whether through its edit tools or shell commands (changes another session makes in the same
166
168
  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 +200,7 @@ nothing anywhere ([privacy](https://github.com/coffeecoproject/layermap/blob/mai
198
200
  | `project_explore_map` | A directory, a file, or a declaration's callers and callees (`direction` INCOMING or OUTGOING, `depth` up to 8). |
199
201
  | `project_search_map` | Find declarations by words in their names, paths or documentation. |
200
202
  | `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. |
203
+ | `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
204
 
203
205
  The same from the command line:
204
206
 
package/dist/cli.mjs CHANGED
@@ -13,7 +13,7 @@ import { parseArgs } from "node:util";
13
13
  import { execFile } from "node:child_process";
14
14
  import { createHash as createHash5 } from "node:crypto";
15
15
  import { existsSync as existsSync5, readFileSync as readFileSync4 } from "node:fs";
16
- import { mkdir, readdir, readFile, rename, rm, stat, utimes, writeFile } from "node:fs/promises";
16
+ import { mkdir, readdir, readFile as readFile2, rename, rm, stat, utimes, writeFile } from "node:fs/promises";
17
17
  import { createRequire } from "node:module";
18
18
  import { homedir } from "node:os";
19
19
  import path11 from "node:path";
@@ -15970,7 +15970,7 @@ function encodeMapText(graph) {
15970
15970
  const at = (anchor) => `${file2(anchor.path)}:${anchor.startLine}-${anchor.endLine}@${anchor.start}-${anchor.end}`;
15971
15971
  const nodes = new Map(graph.objects.map((object2, index) => [object2.id, `N${index + 1}`]));
15972
15972
  const node = (id2) => nodes.get(id2) ?? failed();
15973
- const rows = graph.objects.map(
15973
+ const rows2 = graph.objects.map(
15974
15974
  (object2) => [
15975
15975
  node(object2.id),
15976
15976
  JSON.stringify(object2.name),
@@ -15982,7 +15982,7 @@ function encodeMapText(graph) {
15982
15982
  );
15983
15983
  for (const { relation } of graph.relations) {
15984
15984
  const { id: id2, ...semantic } = relation;
15985
- rows.push(
15985
+ rows2.push(
15986
15986
  [
15987
15987
  "R",
15988
15988
  `${node(relation.from)} \u2192 ${relation.to === void 0 ? "-" : node(relation.to)}`,
@@ -15996,7 +15996,7 @@ function encodeMapText(graph) {
15996
15996
  );
15997
15997
  }
15998
15998
  for (const note of graph.notes)
15999
- rows.push(
15999
+ rows2.push(
16000
16000
  [
16001
16001
  "D",
16002
16002
  node(note.entityRef),
@@ -16006,13 +16006,13 @@ function encodeMapText(graph) {
16006
16006
  JSON.stringify(note.text)
16007
16007
  ].join(" ")
16008
16008
  );
16009
- if (graph.targetRef !== void 0) rows.push(`T ${node(graph.targetRef)}`);
16009
+ if (graph.targetRef !== void 0) rows2.push(`T ${node(graph.targetRef)}`);
16010
16010
  for (const frontier of graph.traversal.frontier)
16011
- rows.push(`B ${node(frontier.entityRef)} ${frontier.direction}`);
16011
+ rows2.push(`B ${node(frontier.entityRef)} ${frontier.direction}`);
16012
16012
  return [
16013
16013
  ...header,
16014
16014
  ...[...files].map(([path14, ref]) => `${ref} ${JSON.stringify(path14)}`),
16015
- ...rows
16015
+ ...rows2
16016
16016
  ].join("\n");
16017
16017
  }
16018
16018
  function decodeMapText(text) {
@@ -16371,9 +16371,9 @@ var MapViewGraph = class {
16371
16371
  parent(ref) {
16372
16372
  let parent = this.parents.get(ref);
16373
16373
  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;
16374
+ const rows2 = this.statements.parent.all(this.version, ref);
16375
+ if (rows2.length > 1) return corrupt();
16376
+ parent = rows2[0] ? String(rows2[0].from_ref) : null;
16377
16377
  this.parents.set(ref, parent);
16378
16378
  }
16379
16379
  return parent ?? void 0;
@@ -16518,23 +16518,23 @@ function requireMapObject(store, version2, selector, prefixes) {
16518
16518
  if (!object3) throw new ProjectEvidenceError("PROJECT_MAP_OBJECT_NOT_FOUND", false);
16519
16519
  return object3;
16520
16520
  }
16521
- let rows;
16521
+ let rows2;
16522
16522
  if (locator) {
16523
16523
  const path14 = normalizeProjectEvidencePath(locator.path);
16524
16524
  if (!Number.isSafeInteger(locator.start) || locator.start < 0 || locator.kind !== void 0 && !MapObjectKindSchema.safeParse(locator.kind).success)
16525
16525
  throw new ProjectEvidenceError("PROJECT_READ_INPUT_INVALID", false);
16526
16526
  if (!mapPathAllowed(path14, prefixes))
16527
16527
  throw new ProjectEvidenceError("PROJECT_MAP_OBJECT_NOT_FOUND", false);
16528
- rows = store.database.prepare(`SELECT object_json FROM project_map_objects
16528
+ rows2 = store.database.prepare(`SELECT object_json FROM project_map_objects
16529
16529
  WHERE version_ref = ? AND path = ? AND json_extract(object_json, '$.anchor.start') = ?
16530
16530
  AND (? IS NULL OR kind = ?) LIMIT 2`).all(version2, path14, locator.start, locator.kind ?? null, locator.kind ?? null);
16531
16531
  } else {
16532
- rows = store.database.prepare(
16532
+ rows2 = store.database.prepare(
16533
16533
  "SELECT object_json FROM project_map_objects WHERE version_ref = ? AND entity_ref = ?"
16534
16534
  ).all(version2, entityRef);
16535
16535
  }
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;
16536
+ if (rows2.length > 1) throw new ProjectEvidenceError("PROJECT_READ_INPUT_INVALID", false);
16537
+ const object2 = rows2[0] ? MapObjectSchema.parse(JSON.parse(String(rows2[0].object_json))) : void 0;
16538
16538
  if (!object2 || !mapPathAllowed(object2.anchor.path, prefixes))
16539
16539
  throw new ProjectEvidenceError("PROJECT_MAP_OBJECT_NOT_FOUND", false);
16540
16540
  return object2;
@@ -16822,7 +16822,7 @@ function mapSearchRows(store, input, query, scope, offset, signal) {
16822
16822
  AND ${mapSearchAllowedSql("json_extract(note.note_json, '$.anchor.path')")}
16823
16823
  ) AS documentation
16824
16824
  FROM candidate_objects object`);
16825
- const rows = [];
16825
+ const rows2 = [];
16826
16826
  for (const row of statement.iterate(
16827
16827
  ...candidates.parameters,
16828
16828
  input.version,
@@ -16847,11 +16847,11 @@ function mapSearchRows(store, input, query, scope, offset, signal) {
16847
16847
  query,
16848
16848
  focus.get(object2.id)
16849
16849
  );
16850
- if (ranking) rows.push({ object: object2, ranking });
16850
+ if (ranking) rows2.push({ object: object2, ranking });
16851
16851
  }
16852
- rows.sort(compareRows);
16852
+ rows2.sort(compareRows);
16853
16853
  const perPath = /* @__PURE__ */ new Map();
16854
- const diversified = rows.map(({ object: object2, ranking }) => {
16854
+ const diversified = rows2.map(({ object: object2, ranking }) => {
16855
16855
  const pathRank = (perPath.get(object2.anchor.path) ?? 0) + 1;
16856
16856
  perPath.set(object2.anchor.path, pathRank);
16857
16857
  return {
@@ -16872,9 +16872,9 @@ var MapSearchViewPageSchema = external_exports.object({
16872
16872
  pageExhausted: external_exports.boolean()
16873
16873
  }).strict();
16874
16874
  var FIELDS = { NAME: "name", PATH: "path", DOCUMENTATION: "doc" };
16875
- function mapSearchView(store, version2, query, rows, offset, maxResults, budget) {
16875
+ function mapSearchView(store, version2, query, rows2, offset, maxResults, budget) {
16876
16876
  const graph = new MapViewGraph(store, version2);
16877
- const results = rows.slice(0, maxResults).map(({ object: object2, ranking }) => ({
16877
+ const results = rows2.slice(0, maxResults).map(({ object: object2, ranking }) => ({
16878
16878
  path: object2.anchor.path,
16879
16879
  text: `${mapIsModule(object2) ? `(file) ${object2.anchor.endLine}L` : `${graph.qualifiedName(object2.id)} ${mapDeclarationLabel(object2)}`} [${ranking.matchedFields.map((field) => FIELDS[field]).join(",")}]`
16880
16880
  }));
@@ -16883,7 +16883,7 @@ function mapSearchView(store, version2, query, rows, offset, maxResults, budget)
16883
16883
  ...query.kinds.length < MapObjectKindSchema.options.length ? [`kinds ${query.kinds.join(",")}`] : []
16884
16884
  ];
16885
16885
  const materialize = (count) => {
16886
- const more2 = rows.length > count;
16886
+ const more2 = rows2.length > count;
16887
16887
  const lines = [];
16888
16888
  let current;
16889
16889
  for (const result of results.slice(0, count)) {
@@ -17039,9 +17039,9 @@ function mapExplorePageRows(store, version2) {
17039
17039
  };
17040
17040
  };
17041
17041
  }
17042
- function mapPageFrontier(frontier, rows) {
17042
+ function mapPageFrontier(frontier, rows2) {
17043
17043
  const visible = new Set(
17044
- rows.flatMap(({ relation }) => [relation.from, ...relation.to ? [relation.to] : []])
17044
+ rows2.flatMap(({ relation }) => [relation.from, ...relation.to ? [relation.to] : []])
17045
17045
  );
17046
17046
  return frontier.filter(({ entityRef }) => visible.has(entityRef)).map((node) => ({ ...node }));
17047
17047
  }
@@ -19069,7 +19069,7 @@ function loadImports(store, version2) {
19069
19069
  }
19070
19070
  function loadDirectoryFacts(store, version2) {
19071
19071
  const files = /* @__PURE__ */ new Map();
19072
- const declarations = [];
19072
+ const declarations2 = [];
19073
19073
  for (const row of store.database.prepare(`SELECT entity_ref, path, kind, name,
19074
19074
  json_extract(object_json, '$.anchor.startLine') AS start_line,
19075
19075
  json_extract(object_json, '$.anchor.endLine') AS end_line,
@@ -19087,7 +19087,7 @@ function loadDirectoryFacts(store, version2) {
19087
19087
  ...row.language ? { language: String(row.language) } : {}
19088
19088
  });
19089
19089
  else
19090
- declarations.push({
19090
+ declarations2.push({
19091
19091
  ref: String(row.entity_ref),
19092
19092
  path: String(row.path),
19093
19093
  kind,
@@ -19098,7 +19098,7 @@ function loadDirectoryFacts(store, version2) {
19098
19098
  });
19099
19099
  }
19100
19100
  const decorators = /* @__PURE__ */ new Map();
19101
- const classes = declarations.filter((item) => item.kind === "CLASS").map((item) => item.ref);
19101
+ const classes = declarations2.filter((item) => item.kind === "CLASS").map((item) => item.ref);
19102
19102
  const decoratorQuery = store.database.prepare(`SELECT from_ref,
19103
19103
  json_extract(relation_json, '$.target') AS target,
19104
19104
  json_extract(relation_json, '$.argument') AS argument,
@@ -19120,7 +19120,7 @@ function loadDirectoryFacts(store, version2) {
19120
19120
  )
19121
19121
  ]);
19122
19122
  const exported = /* @__PURE__ */ new Map();
19123
- for (const item of declarations) {
19123
+ for (const item of declarations2) {
19124
19124
  const endLine = item.kind === "TYPE" || item.kind === "VARIABLE" ? item.startLine : item.endLine;
19125
19125
  const label = mapDeclarationLabel({
19126
19126
  kind: item.kind,
@@ -19366,10 +19366,10 @@ function directoryView(facts, coverage, entries, input, directory, prefixes) {
19366
19366
  }
19367
19367
  const detailed = [
19368
19368
  ...code.map((path14) => {
19369
- const declarations = (facts.exported.get(path14) ?? []).map(({ text: text2 }) => text2);
19369
+ const declarations2 = (facts.exported.get(path14) ?? []).map(({ text: text2 }) => text2);
19370
19370
  return [
19371
19371
  path14,
19372
- `${path14} ${lineCount(path14)}${declarations.length ? `: ${declarations.join(", ")}` : ""}`
19372
+ `${path14} ${lineCount(path14)}${declarations2.length ? `: ${declarations2.join(", ")}` : ""}`
19373
19373
  ];
19374
19374
  }),
19375
19375
  ...listedOther.map((entry) => [
@@ -19741,14 +19741,14 @@ function fileView(store, coverage, graph, input, path14, prefixes) {
19741
19741
  `${object2.name} ${mapDeclarationLabel(object2)}${object2.anchor.path === path14 ? "" : ` (${object2.anchor.path})`}`,
19742
19742
  ...tags.get(object2.id) ?? []
19743
19743
  ].join(" ");
19744
- const declarations = [];
19744
+ const declarations2 = [];
19745
19745
  for (const member of members) {
19746
- declarations.push(`${member.exported ? "*" : " "}${describe3(member)}`);
19746
+ declarations2.push(`${member.exported ? "*" : " "}${describe3(member)}`);
19747
19747
  const children = nested.get(member.id) ?? [];
19748
19748
  const listed = member.kind === "CLASS" ? children : children.filter((child) => child.kind === "METHOD");
19749
19749
  const fields2 = children.length - listed.length;
19750
19750
  if (listed.length || fields2)
19751
- declarations.push(
19751
+ declarations2.push(
19752
19752
  ` ${[...listed.map(describe3), ...fields2 ? [`${fields2} fields`] : []].join(", ")}`
19753
19753
  );
19754
19754
  }
@@ -19765,10 +19765,10 @@ function fileView(store, coverage, graph, input, path14, prefixes) {
19765
19765
  for (const [parent, list] of [...elsewhere].sort(
19766
19766
  ([, left], [, right]) => Math.min(...left.map((object2) => object2.anchor.start)) - Math.min(...right.map((object2) => object2.anchor.start))
19767
19767
  ))
19768
- declarations.push(
19768
+ declarations2.push(
19769
19769
  ` ${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
19770
  );
19771
- if (declarations.length) blocks.push(["DECLARATIONS (* exported)", ...declarations].join("\n"));
19771
+ if (declarations2.length) blocks.push(["DECLARATIONS (* exported)", ...declarations2].join("\n"));
19772
19772
  const imports2 = /* @__PURE__ */ new Set();
19773
19773
  const external = /* @__PURE__ */ new Set();
19774
19774
  const fileObjects = graph.objectsAt(path14).map((object2) => object2.id);
@@ -19959,18 +19959,18 @@ var ProjectMapQuery = class {
19959
19959
  throw new ProjectEvidenceError("PROJECT_EVIDENCE_INDEX_UNAVAILABLE", true);
19960
19960
  const { offset, scope, prefixes } = admission(input);
19961
19961
  const query = mapSearchQuery(input);
19962
- const rows = mapSearchRows(this.store, input, query, scope, offset, signal);
19962
+ const rows2 = mapSearchRows(this.store, input, query, scope, offset, signal);
19963
19963
  const metadata = { ...MAP_QUERY_GUIDANCE, query, gaps: this.gaps(input.version, prefixes) };
19964
19964
  return mapQueryPage(
19965
- Math.min(rows.length, input.maxResults),
19965
+ Math.min(rows2.length, input.maxResults),
19966
19966
  (count) => {
19967
- const selected = rows.slice(0, count);
19967
+ const selected = rows2.slice(0, count);
19968
19968
  return {
19969
19969
  ...metadata,
19970
19970
  objects: selected.map((row) => row.object),
19971
19971
  rankings: selected.map((row) => row.ranking),
19972
- ...rows.length > count ? { nextOffset: offset + count } : {},
19973
- pageExhausted: rows.length <= count
19972
+ ...rows2.length > count ? { nextOffset: offset + count } : {},
19973
+ pageExhausted: rows2.length <= count
19974
19974
  };
19975
19975
  },
19976
19976
  mapSearchNavigation,
@@ -19981,12 +19981,12 @@ var ProjectMapQuery = class {
19981
19981
  this.requireReadableMap(input.version, signal);
19982
19982
  const { offset, scope } = admission(input);
19983
19983
  const query = mapSearchQuery(input);
19984
- const rows = mapSearchRows(this.store, input, query, scope, offset, signal);
19984
+ const rows2 = mapSearchRows(this.store, input, query, scope, offset, signal);
19985
19985
  return mapSearchView(
19986
19986
  this.store,
19987
19987
  input.version,
19988
19988
  query,
19989
- rows,
19989
+ rows2,
19990
19990
  offset,
19991
19991
  input.maxResults,
19992
19992
  input.outputBudget
@@ -20060,10 +20060,10 @@ var ProjectMapQuery = class {
20060
20060
  notesTruncated: notes.length > selectedNotes.length,
20061
20061
  gaps: this.gaps(input.version, prefixes)
20062
20062
  };
20063
- const rows = [];
20063
+ const rows2 = [];
20064
20064
  const materialize = (count) => ({
20065
20065
  ...metadata,
20066
- relations: rows.slice(0, count),
20066
+ relations: rows2.slice(0, count),
20067
20067
  coverage: {
20068
20068
  totalRelations,
20069
20069
  returnedRelations: count,
@@ -20071,7 +20071,7 @@ var ProjectMapQuery = class {
20071
20071
  },
20072
20072
  traversal: {
20073
20073
  semantics: "STATIC_RELATIONSHIPS",
20074
- frontier: mapPageFrontier(frontier, rows.slice(0, count))
20074
+ frontier: mapPageFrontier(frontier, rows2.slice(0, count))
20075
20075
  },
20076
20076
  ...totalRelations > offset + count ? { nextOffset: offset + count } : {},
20077
20077
  pageExhausted: totalRelations <= offset + count
@@ -20084,13 +20084,13 @@ var ProjectMapQuery = class {
20084
20084
  const ref = relationRefs[position];
20085
20085
  if (ref === void 0)
20086
20086
  throw new ProjectEvidenceError("PROJECT_EVIDENCE_STORE_CORRUPT", false);
20087
- rows.push(readRow(ref));
20087
+ rows2.push(readRow(ref));
20088
20088
  }
20089
20089
  await setImmediate3();
20090
20090
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
20091
20091
  if (position === end) break;
20092
20092
  const { nextOffset: _nextOffset, ...minimum } = mapExploreNavigation(
20093
- materialize(rows.length)
20093
+ materialize(rows2.length)
20094
20094
  );
20095
20095
  const minimumBytes = Buffer.byteLength(
20096
20096
  canonicalJson({
@@ -20103,7 +20103,7 @@ var ProjectMapQuery = class {
20103
20103
  if (minimumBytes + (input.outputBudget?.envelopeBytes ?? 0) > (input.outputBudget?.maxBytes ?? PROJECT_MAP_LIMITS.queryBytes))
20104
20104
  break;
20105
20105
  }
20106
- const page = mapQueryPage(rows.length, materialize, mapExploreNavigation, input.outputBudget);
20106
+ const page = mapQueryPage(rows2.length, materialize, mapExploreNavigation, input.outputBudget);
20107
20107
  await setImmediate3();
20108
20108
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
20109
20109
  this.rememberTraversal(traversalKey, traversal);
@@ -21984,6 +21984,7 @@ var CodeIndex = class {
21984
21984
 
21985
21985
  // src/project-map-changes.ts
21986
21986
  import { readFileSync as readFileSync3 } from "node:fs";
21987
+ import { readFile } from "node:fs/promises";
21987
21988
  import path9 from "node:path";
21988
21989
 
21989
21990
  // src/project-map-clients.ts
@@ -22365,6 +22366,176 @@ async function strandedNames(project, diff, files, configuration, git2, options)
22365
22366
  }
22366
22367
  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
22368
 
22369
+ // src/project-map-reuse.ts
22370
+ var MODULES = /* @__PURE__ */ new Set(["FILE", "PACKAGE", "CONFIG"]);
22371
+ var MEMBER_CONTAINERS2 = /* @__PURE__ */ new Set(["CLASS", "INTERFACE", "TYPE", "ENUM"]);
22372
+ var KINDS = /* @__PURE__ */ new Set(["FUNCTION", "METHOD", "CLASS", "VARIABLE"]);
22373
+ var MIN_LINES = 3;
22374
+ var ALIKE = 0.8;
22375
+ var SIBLINGS_ALIKE = 0.95;
22376
+ var KEYWORDS = new Set(
22377
+ "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(" ")
22378
+ );
22379
+ var ROWS = `SELECT entity_ref AS id, path, name, kind, object_json AS object
22380
+ FROM project_map_objects WHERE version_ref = ? AND kind <> 'PROPERTY'`;
22381
+ function rows(store, version2, path14) {
22382
+ const statement = store.database.prepare(path14 === void 0 ? ROWS : `${ROWS} AND path = ?`);
22383
+ return (path14 === void 0 ? statement.all(version2) : statement.all(version2, path14)).map((row) => {
22384
+ const { anchor } = JSON.parse(String(row.object));
22385
+ return {
22386
+ id: String(row.id),
22387
+ path: String(row.path),
22388
+ name: String(row.name),
22389
+ kind: String(row.kind),
22390
+ start: anchor.start,
22391
+ end: anchor.end,
22392
+ startLine: anchor.startLine,
22393
+ endLine: anchor.endLine
22394
+ };
22395
+ });
22396
+ }
22397
+ function declarations(inFile) {
22398
+ const sorted = inFile.filter((row) => !MODULES.has(row.kind)).sort((left, right) => left.start - right.start || right.end - left.end);
22399
+ const found = [];
22400
+ const open2 = [];
22401
+ for (const row of sorted) {
22402
+ while (open2.length && open2.at(-1).row.end <= row.start) open2.pop();
22403
+ const around = open2.at(-1);
22404
+ let declaration;
22405
+ if (!row.name.startsWith("<")) {
22406
+ if (!around) declaration = { ...row, qualifiedName: row.name };
22407
+ else if (around.declaration && row.kind === "METHOD" && !around.parent && (MEMBER_CONTAINERS2.has(around.row.kind) || around.row.kind === "VARIABLE"))
22408
+ declaration = {
22409
+ ...row,
22410
+ qualifiedName: `${around.row.name}.${row.name}`,
22411
+ container: around.row.id
22412
+ };
22413
+ }
22414
+ if (declaration) found.push(declaration);
22415
+ open2.push({ row, declaration, parent: around?.row });
22416
+ }
22417
+ return found;
22418
+ }
22419
+ function lineWords(line) {
22420
+ 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));
22421
+ }
22422
+ var within2 = (lines, declaration) => lines.some(([from, to]) => from <= declaration.startLine && declaration.endLine <= to);
22423
+ async function similarCode(store, working, base, files, read) {
22424
+ const code = (path14) => mapCodePath(path14) !== void 0 && !mapTestPath(path14);
22425
+ const changed = files.filter((file2) => file2.status !== "DELETED" && code(file2.path));
22426
+ if (!changed.length) return [];
22427
+ const names = (version2, path14) => new Set(declarations(rows(store, version2, path14)).map((item) => item.qualifiedName));
22428
+ const movedOut = /* @__PURE__ */ new Set();
22429
+ if (base !== void 0)
22430
+ for (const file2 of files) {
22431
+ if (!file2.basePath || file2.status === "ADDED") continue;
22432
+ const now = file2.status === "DELETED" ? /* @__PURE__ */ new Set() : names(working, file2.path);
22433
+ for (const name of names(base, file2.basePath)) if (!now.has(name)) movedOut.add(name);
22434
+ }
22435
+ const eligible = (item) => KINDS.has(item.kind) && item.endLine - item.startLine + 1 >= MIN_LINES;
22436
+ const added = /* @__PURE__ */ new Set();
22437
+ for (const file2 of changed) {
22438
+ const had = base !== void 0 && file2.basePath && file2.status !== "ADDED" ? names(base, file2.basePath) : void 0;
22439
+ for (const item of declarations(rows(store, working, file2.path)))
22440
+ if (eligible(item) && within2(file2.lines, item) && !had?.has(item.qualifiedName) && !movedOut.has(item.qualifiedName))
22441
+ added.add(item.id);
22442
+ }
22443
+ if (!added.size) return [];
22444
+ const byPath = /* @__PURE__ */ new Map();
22445
+ for (const row of rows(store, working)) {
22446
+ if (!code(row.path)) continue;
22447
+ const inFile = byPath.get(row.path) ?? [];
22448
+ inFile.push(row);
22449
+ byPath.set(row.path, inFile);
22450
+ }
22451
+ const all = [];
22452
+ await Promise.all(
22453
+ [...byPath].map(async ([path14, inFile]) => {
22454
+ const found2 = declarations(inFile).filter(eligible);
22455
+ if (!found2.length) return;
22456
+ const text = await read(path14);
22457
+ if (text === void 0) return;
22458
+ const lines = text.split("\n").map(lineWords);
22459
+ for (const declaration of found2) {
22460
+ const words = /* @__PURE__ */ new Map();
22461
+ for (const line of lines.slice(declaration.startLine - 1, declaration.endLine))
22462
+ for (const word of line) words.set(word, (words.get(word) ?? 0) + 1);
22463
+ all.push({ declaration, words });
22464
+ }
22465
+ })
22466
+ );
22467
+ const frequency = /* @__PURE__ */ new Map();
22468
+ for (const { words } of all)
22469
+ for (const word of words.keys()) frequency.set(word, (frequency.get(word) ?? 0) + 1);
22470
+ const weight = (word) => Math.log((all.length + 1) / ((frequency.get(word) ?? 0) + 1));
22471
+ const vector = (words) => {
22472
+ const weighted = /* @__PURE__ */ new Map();
22473
+ let length = 0;
22474
+ for (const [word, count] of words) {
22475
+ const value = (1 + Math.log(count)) * weight(word);
22476
+ weighted.set(word, value);
22477
+ length += value * value;
22478
+ }
22479
+ length = Math.sqrt(length) || 1;
22480
+ for (const [word, value] of weighted) weighted.set(word, value / length);
22481
+ return weighted;
22482
+ };
22483
+ const holders = /* @__PURE__ */ new Map();
22484
+ for (const item of all) {
22485
+ if (added.has(item.declaration.id)) continue;
22486
+ for (const [word, value] of vector(item.words)) {
22487
+ const holding = holders.get(word) ?? [];
22488
+ holding.push({ item, value });
22489
+ holders.set(word, holding);
22490
+ }
22491
+ }
22492
+ const graph = new MapViewGraph(store, working);
22493
+ const label = (row) => mapDeclarationLabel({
22494
+ kind: row.kind,
22495
+ anchor: { startLine: row.startLine, endLine: row.endLine }
22496
+ });
22497
+ const found = [];
22498
+ for (const item of all) {
22499
+ const declaration = item.declaration;
22500
+ if (!added.has(declaration.id)) continue;
22501
+ const scores = /* @__PURE__ */ new Map();
22502
+ for (const [word, value] of vector(item.words))
22503
+ for (const other of holders.get(word) ?? [])
22504
+ scores.set(other.item, (scores.get(other.item) ?? 0) + value * other.value);
22505
+ const alike = [...scores].filter(([other, score]) => {
22506
+ const them = other.declaration;
22507
+ if (them.path === declaration.path && them.start < declaration.end && declaration.start < them.end)
22508
+ return false;
22509
+ const siblings = declaration.container !== void 0 && them.container === declaration.container;
22510
+ return score >= (siblings ? SIBLINGS_ALIKE : ALIKE);
22511
+ }).sort(([, left], [, right]) => right - left);
22512
+ if (!alike.length) continue;
22513
+ const scope = graph.scope(declaration.id).refs;
22514
+ const linked = /* @__PURE__ */ new Set([
22515
+ ...graph.relationsFrom(scope).flatMap((relation) => relation.to ? [graph.owner(relation.to)] : []),
22516
+ ...graph.relationsTo(scope).map((relation) => graph.owner(relation.from))
22517
+ ]);
22518
+ const unlinked = alike.filter(([other]) => !linked.has(other.declaration.id));
22519
+ const best = unlinked[0];
22520
+ if (!best) continue;
22521
+ found.push({
22522
+ path: declaration.path,
22523
+ name: declaration.qualifiedName,
22524
+ label: label(declaration),
22525
+ like: {
22526
+ path: best[0].declaration.path,
22527
+ name: best[0].declaration.qualifiedName,
22528
+ label: label(best[0].declaration)
22529
+ },
22530
+ others: unlinked.length - 1,
22531
+ score: best[1]
22532
+ });
22533
+ }
22534
+ return found.sort(
22535
+ (left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0) || right.score - left.score
22536
+ ).map(({ score: _score, ...similar }) => similar);
22537
+ }
22538
+
22368
22539
  // src/project-map-changes.ts
22369
22540
  var git = new GitRunner();
22370
22541
  var gitOptions = (cwd, signal) => ({
@@ -22709,9 +22880,12 @@ function mapChangeImpact(store, working, base, changes, project) {
22709
22880
  const changed = [];
22710
22881
  const unclear = [];
22711
22882
  const removed = [];
22712
- const declarations = (g, path14) => g.objectsAt(path14).filter((object2) => !mapIsModule(object2) && g.isAddressable(object2));
22883
+ const declarations2 = (g, path14) => g.objectsAt(path14).filter((object2) => !mapIsModule(object2) && g.isAddressable(object2));
22713
22884
  let changedCount = 0;
22714
22885
  const starts = [];
22886
+ const importers = /* @__PURE__ */ new Map();
22887
+ let mapped;
22888
+ const mappedPaths = () => mapped ??= store.database.prepare("SELECT DISTINCT path FROM project_map_objects WHERE version_ref = ?").all(working).map((row) => String(row.path));
22715
22889
  for (const file2 of changes.files) {
22716
22890
  if (file2.binary) continue;
22717
22891
  const kind = nonCodeKind(file2.path);
@@ -22726,7 +22900,7 @@ function mapChangeImpact(store, working, base, changes, project) {
22726
22900
  if (!objects2.length) continue;
22727
22901
  const hits = /* @__PURE__ */ new Set();
22728
22902
  let topLevel = false;
22729
- const inFile = declarations(graph, file2.path);
22903
+ const inFile = declarations2(graph, file2.path);
22730
22904
  for (const [from, to] of file2.lines) {
22731
22905
  const containing = inFile.filter(
22732
22906
  (object2) => object2.anchor.startLine <= to && from <= object2.anchor.endLine
@@ -22756,9 +22930,9 @@ function mapChangeImpact(store, working, base, changes, project) {
22756
22930
  );
22757
22931
  if (analyzed && topLevel && file2.status !== "ADDED")
22758
22932
  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);
22933
+ importerTests(graph, objects2, tracer, importers);
22934
+ sameDirectoryTests(mappedPaths(), file2.path, tracer);
22935
+ mirroredTests(mappedPaths(), file2.path, tracer);
22762
22936
  }
22763
22937
  tracer.trace(starts);
22764
22938
  if (project) routeTests(project, store, working, [...tracer.entries.values()], tracer);
@@ -22787,11 +22961,11 @@ function mapChangeImpact(store, working, base, changes, project) {
22787
22961
  if (!file2.basePath || !file2.baseLines.length || file2.binary || testCode(file2.basePath))
22788
22962
  continue;
22789
22963
  const now = new Set(
22790
- file2.status === "DELETED" ? [] : declarations(graph, file2.path).map(
22964
+ file2.status === "DELETED" ? [] : declarations2(graph, file2.path).map(
22791
22965
  (o) => `${o.kind}\0${graph.qualifiedName(o.id)}`
22792
22966
  )
22793
22967
  );
22794
- for (const object2 of declarations(before, file2.basePath)) {
22968
+ for (const object2 of declarations2(before, file2.basePath)) {
22795
22969
  if (!overlaps(file2.baseLines, object2.anchor.startLine, object2.anchor.endLine)) continue;
22796
22970
  if (now.has(`${object2.kind}\0${before.qualifiedName(object2.id)}`)) continue;
22797
22971
  const parent = before.parent(object2.id);
@@ -22879,27 +23053,34 @@ function existingTestsChanged(before, after, file2, project) {
22879
23053
  )
22880
23054
  ).map((object2) => before.qualifiedName(object2.id)).sort();
22881
23055
  }
22882
- function importerTests(graph, objects2, tracer) {
23056
+ function importerTests(graph, objects2, tracer, importers) {
22883
23057
  let modules = objects2.filter((object2) => mapIsModule(object2)).map((object2) => object2.id);
22884
23058
  const seen = new Set(modules);
22885
23059
  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;
23060
+ const unread = modules.filter((module) => !importers.has(module));
23061
+ for (const module of unread) importers.set(module, []);
23062
+ for (const relation of graph.relationsTo(unread)) {
23063
+ if (!IMPORT_KINDS3.has(relation.kind) || !relation.to) continue;
22889
23064
  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
- }
23065
+ importers.get(relation.to)?.push({
23066
+ path: relation.anchor.path,
23067
+ module: mapIsModule(importer) ? importer.id : graph.owner(relation.from)
23068
+ });
22902
23069
  }
23070
+ const next = [];
23071
+ for (const imported of modules)
23072
+ for (const { path: path14, module } of importers.get(imported) ?? [])
23073
+ if (testCode(path14))
23074
+ tracer.test(
23075
+ path14,
23076
+ void 0,
23077
+ hop ? "imports a changed file indirectly" : "imports a changed file",
23078
+ hop ? 4 : 2
23079
+ );
23080
+ else if (!seen.has(module)) {
23081
+ seen.add(module);
23082
+ next.push(module);
23083
+ }
22903
23084
  modules = next;
22904
23085
  }
22905
23086
  }
@@ -22913,14 +23094,12 @@ function supportTests(store, version2, tracer) {
22913
23094
  tracer.test(String(row.path), void 0, `may use it through ${file2}`, 3.5);
22914
23095
  }
22915
23096
  }
22916
- function mirroredTests(store, version2, file2, tracer) {
23097
+ function mirroredTests(paths, file2, tracer) {
22917
23098
  const directories = file2.split("/").slice(0, -1);
22918
23099
  const module = directories.at(-1);
22919
23100
  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);
23101
+ for (const candidate of paths) {
23102
+ if (!candidate.includes(`/${module}/`)) continue;
22924
23103
  const parts = candidate.split("/");
22925
23104
  const at = parts.lastIndexOf(module);
22926
23105
  if (at < 1 || at !== parts.length - 2) continue;
@@ -22961,13 +23140,11 @@ function routeTests(project, store, version2, entries, tracer) {
22961
23140
  }
22962
23141
  }
22963
23142
  }
22964
- function sameDirectoryTests(store, version2, path14, tracer) {
23143
+ function sameDirectoryTests(paths, path14, tracer) {
22965
23144
  const slash = path14.lastIndexOf("/");
22966
23145
  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);
23146
+ for (const candidate of paths) {
23147
+ if (!candidate.startsWith(directory)) continue;
22971
23148
  if (candidate.slice(directory.length).includes("/") || !mapTestPath(candidate)) continue;
22972
23149
  tracer.test(candidate, void 0, "in the same directory", 3);
22973
23150
  }
@@ -22992,7 +23169,9 @@ var LIST = Object.freeze({
22992
23169
  areaNames: 3,
22993
23170
  through: 2,
22994
23171
  dependencies: 12,
22995
- sites: 2
23172
+ sites: 2,
23173
+ similar: 10,
23174
+ similarNames: 3
22996
23175
  });
22997
23176
  function routesIn(graph, path14) {
22998
23177
  const routes = /* @__PURE__ */ new Set();
@@ -23015,7 +23194,14 @@ async function checkMapChanges(input, signal) {
23015
23194
  text: mapChangesText(
23016
23195
  changes,
23017
23196
  impact,
23018
- await mapRouteClients(project, index.store, working, impact, signal)
23197
+ await mapRouteClients(project, index.store, working, impact, signal),
23198
+ await similarCode(
23199
+ index.store,
23200
+ working,
23201
+ base,
23202
+ changes.files,
23203
+ (file2) => readFile(path9.join(project, file2), "utf8").catch(() => void 0)
23204
+ )
23019
23205
  )
23020
23206
  };
23021
23207
  }
@@ -23035,7 +23221,7 @@ async function mapRouteClients(project, store, working, impact, signal) {
23035
23221
  if (!routes.length) return [];
23036
23222
  return routeClients(routes, registrations, git, gitOptions(project, signal));
23037
23223
  }
23038
- function mapChangesText(changes, impact, clients = []) {
23224
+ function mapChangesText(changes, impact, clients = [], similar = []) {
23039
23225
  const files = changes.files.length;
23040
23226
  const direct = impact.tests.filter((test) => test.rank < 4);
23041
23227
  const indirect = impact.tests.filter((test) => test.rank >= 4);
@@ -23115,6 +23301,32 @@ Nothing changed against ${changes.base}.`;
23115
23301
  `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
23302
  );
23117
23303
  }
23304
+ if (similar.length) {
23305
+ const declaration = (item) => `${item.path}: ${item.name} ${item.label}`;
23306
+ const pairs = /* @__PURE__ */ new Map();
23307
+ for (const item of similar) {
23308
+ const key = `${item.path}\0${item.like.path}`;
23309
+ pairs.set(key, [...pairs.get(key) ?? [], item]);
23310
+ }
23311
+ list(
23312
+ "EXISTING CODE LIKE THE NEW CODE (declarations the diff adds whose code reads almost the same as code the project already has)",
23313
+ [...pairs.values()].flatMap((items) => {
23314
+ const [first] = items;
23315
+ if (items.length < 3)
23316
+ return items.map(
23317
+ (item) => `${declaration(item)} ~ ${declaration(item.like)}${item.others ? ` (+${item.others} more alike)` : ""}`
23318
+ );
23319
+ const names = items.slice(0, LIST.similarNames).map((item) => `${item.name} ~ ${item.like.name}`);
23320
+ return [
23321
+ `${first.path} repeats ${first.like.path} in ${items.length} declarations: ${names.join(", ")}${items.length > LIST.similarNames ? ", \u2026" : ""}`
23322
+ ];
23323
+ }),
23324
+ LIST.similar
23325
+ );
23326
+ lines.push(
23327
+ "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."
23328
+ );
23329
+ }
23118
23330
  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
23331
  list(
23120
23332
  "AFFECTED ENTRY POINTS (through resolved calls)",
@@ -23365,7 +23577,7 @@ var packageRoot = (() => {
23365
23577
  directory = path11.dirname(directory);
23366
23578
  }
23367
23579
  })();
23368
- var packageVersion = async () => JSON.parse(await readFile(path11.join(packageRoot, "package.json"), "utf8")).version;
23580
+ var packageVersion = async () => JSON.parse(await readFile2(path11.join(packageRoot, "package.json"), "utf8")).version;
23369
23581
  var cacheDirectory = (env = process.env) => {
23370
23582
  if (env.LAYERMAP_CACHE) return path11.resolve(env.LAYERMAP_CACHE);
23371
23583
  if (process.platform === "darwin") return path11.join(homedir(), "Library", "Caches", "layermap");
@@ -23424,11 +23636,11 @@ var absoluteIn = (directory, value) => Object.fromEntries(
23424
23636
  var readAnalyzers = async (directory) => {
23425
23637
  const file2 = path11.join(directory, "analyzers.json");
23426
23638
  if (!existsSync5(file2)) return void 0;
23427
- const analyzers = absoluteIn(directory, JSON.parse(await readFile(file2, "utf8")));
23639
+ const analyzers = absoluteIn(directory, JSON.parse(await readFile2(file2, "utf8")));
23428
23640
  return analyzers.java.runtimePath ? analyzers : { ...analyzers, java: { ...analyzers.java, ...discoverJavaRuntime() } };
23429
23641
  };
23430
23642
  var sourceDigest = async () => {
23431
- const hash2 = createHash5("sha256").update(await readFile(path11.join(packageRoot, "package.json")));
23643
+ const hash2 = createHash5("sha256").update(await readFile2(path11.join(packageRoot, "package.json")));
23432
23644
  for (const part of ["src", "go-map", "java-map", "scripts"]) {
23433
23645
  const directory = path11.join(packageRoot, part);
23434
23646
  if (!existsSync5(directory)) continue;
@@ -23493,6 +23705,7 @@ async function pruneCache(cache, project, now = Date.now()) {
23493
23705
  // src/agent/mcp.ts
23494
23706
  import { createInterface } from "node:readline";
23495
23707
  import { setTimeout as delay } from "node:timers/promises";
23708
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
23496
23709
 
23497
23710
  // src/agent/projects.ts
23498
23711
  import { existsSync as existsSync6 } from "node:fs";
@@ -23578,7 +23791,7 @@ var mapToolDescriptions = (host) => {
23578
23791
  return Object.freeze({
23579
23792
  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
23793
  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.`,
23794
+ 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; 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; 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
23795
  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
23796
  });
23584
23797
  };
@@ -23631,10 +23844,10 @@ async function routeMapCall(start, { name, args }) {
23631
23844
  };
23632
23845
  const filter = args.path;
23633
23846
  if (filter === ".") return { project: located.project, args: routed };
23634
- const within2 = await locate(start, filter);
23635
- if (within2?.project !== located.project)
23847
+ const within3 = await locate(start, filter);
23848
+ if (within3?.project !== located.project)
23636
23849
  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 } };
23850
+ return { project: located.project, args: { ...routed, path: within3.path } };
23638
23851
  }
23639
23852
 
23640
23853
  // src/agent/tools.ts
@@ -23737,6 +23950,7 @@ var AGENT_MAP_INSTRUCTIONS = `Use the LayerMap tools instead of grep whenever a
23737
23950
  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
23951
 
23739
23952
  // src/agent/mcp.ts
23953
+ var ROOTS_WAIT_MS = 5e3;
23740
23954
  function serveMcp(options) {
23741
23955
  const output = options.output ?? process.stdout;
23742
23956
  const log2 = options.log ?? ((line) => process.stderr.write(`${line}
@@ -23746,6 +23960,26 @@ function serveMcp(options) {
23746
23960
  const calls = /* @__PURE__ */ new Map();
23747
23961
  const maps = /* @__PURE__ */ new Map();
23748
23962
  const session = new AbortController();
23963
+ let start = options.start;
23964
+ let rooted = Promise.resolve();
23965
+ let listsRoots = false;
23966
+ const replies = /* @__PURE__ */ new Map();
23967
+ let requested = 0;
23968
+ const readRoots = () => {
23969
+ const id2 = `layermap-roots-${++requested}`;
23970
+ const reply = new Promise((resolve) => replies.set(id2, resolve));
23971
+ send({ id: id2, method: "roots/list" });
23972
+ rooted = Promise.race([reply, delay(ROOTS_WAIT_MS, void 0, { ref: false })]).then(async (message) => {
23973
+ replies.delete(id2);
23974
+ const roots = message?.result?.roots;
23975
+ const root = Array.isArray(roots) ? roots.find((item) => typeof item?.uri === "string" && item.uri.startsWith("file:")) : void 0;
23976
+ if (!root) return;
23977
+ const directory = await projectDirectory(fileURLToPath2(root.uri));
23978
+ if (id2 === `layermap-roots-${requested}`) start = directory;
23979
+ }).catch(() => {
23980
+ });
23981
+ return rooted;
23982
+ };
23749
23983
  const map2 = (project) => {
23750
23984
  let entry = maps.get(project);
23751
23985
  if (!entry) {
@@ -23784,7 +24018,8 @@ ${text}` : text
23784
24018
  try {
23785
24019
  const parsed = parseMapToolCall(name, params.arguments);
23786
24020
  if ("text" in parsed) return respond(parsed.text, parsed.isError);
23787
- const routed = await routeMapCall(options.start, parsed);
24021
+ await rooted;
24022
+ const routed = await routeMapCall(start, parsed);
23788
24023
  if (typeof routed === "string") return respond(routed, true);
23789
24024
  project = routed.project;
23790
24025
  const { opened, built } = map2(project);
@@ -23811,15 +24046,23 @@ ${text}` : text
23811
24046
  };
23812
24047
  const handle = (message) => {
23813
24048
  const { id: id2, method, params = {} } = message;
23814
- if (method === void 0) return;
24049
+ if (method === void 0) {
24050
+ if (id2 !== void 0 && id2 !== null) replies.get(id2)?.(message);
24051
+ return;
24052
+ }
23815
24053
  if (id2 === void 0 || id2 === null) {
23816
- if (method === "notifications/initialized" && options.start.git) map2(options.start.directory);
24054
+ if (method === "notifications/initialized")
24055
+ void (listsRoots ? readRoots() : rooted).then(() => {
24056
+ if (start.git) map2(start.directory);
24057
+ });
24058
+ if (method === "notifications/roots/list_changed" && listsRoots) void readRoots();
23817
24059
  if (method === "notifications/cancelled")
23818
24060
  calls.get(params.requestId)?.abort();
23819
24061
  return;
23820
24062
  }
23821
24063
  switch (method) {
23822
24064
  case "initialize":
24065
+ listsRoots = Boolean(params.capabilities?.roots);
23823
24066
  return send({
23824
24067
  id: id2,
23825
24068
  result: {
@@ -23887,7 +24130,7 @@ ${text}` : text
23887
24130
  // src/agent/setup.ts
23888
24131
  import { execFile as execFile2 } from "node:child_process";
23889
24132
  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";
24133
+ import { mkdir as mkdir2, readFile as readFile3, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
23891
24134
  import { homedir as homedir2 } from "node:os";
23892
24135
  import path13 from "node:path";
23893
24136
  var SERVER = "layermap";
@@ -23931,7 +24174,7 @@ var run = (command, args, env) => new Promise((resolve) => {
23931
24174
  );
23932
24175
  });
23933
24176
  async function allowInClaudeSettings(file2, rule = SETUP_RULE) {
23934
- const settings = existsSync7(file2) ? JSON.parse(await readFile2(file2, "utf8")) : {};
24177
+ const settings = existsSync7(file2) ? JSON.parse(await readFile3(file2, "utf8")) : {};
23935
24178
  if (typeof settings !== "object" || settings === null || Array.isArray(settings))
23936
24179
  throw new Error(`${file2} is not a settings object.`);
23937
24180
  settings.permissions ??= {};
@@ -23946,7 +24189,7 @@ async function allowInClaudeSettings(file2, rule = SETUP_RULE) {
23946
24189
  return true;
23947
24190
  }
23948
24191
  async function configureCodexServer(file2) {
23949
- const lines = (await readFile2(file2, "utf8")).split("\n");
24192
+ const lines = (await readFile3(file2, "utf8")).split("\n");
23950
24193
  const header2 = lines.findIndex((line) => line.trim() === `[mcp_servers.${SERVER}]`);
23951
24194
  if (header2 < 0) throw new Error(`${file2} has no [mcp_servers.${SERVER}] table.`);
23952
24195
  let end = header2 + 1;
@@ -23968,7 +24211,7 @@ async function writeInstructionNote(file2, note = AGENT_MAP_NOTE) {
23968
24211
  const block = `${BEGIN}
23969
24212
  ${note}
23970
24213
  ${END}`;
23971
- const text = existsSync7(file2) ? await readFile2(file2, "utf8") : "";
24214
+ const text = existsSync7(file2) ? await readFile3(file2, "utf8") : "";
23972
24215
  const start = text.indexOf(BEGIN);
23973
24216
  const end = text.indexOf(END);
23974
24217
  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 +24222,7 @@ ${END}`;
23979
24222
  }
23980
24223
  async function removeInstructionNote(file2) {
23981
24224
  if (!existsSync7(file2)) return;
23982
- const text = await readFile2(file2, "utf8");
24225
+ const text = await readFile3(file2, "utf8");
23983
24226
  const start = text.indexOf(BEGIN);
23984
24227
  const end = text.indexOf(END);
23985
24228
  if (start < 0 || end < start) return;
@@ -23990,7 +24233,7 @@ async function removeInstructionNote(file2) {
23990
24233
  }
23991
24234
  async function disallowInClaudeSettings(file2) {
23992
24235
  if (!existsSync7(file2)) return;
23993
- const settings = JSON.parse(await readFile2(file2, "utf8"));
24236
+ const settings = JSON.parse(await readFile3(file2, "utf8"));
23994
24237
  const allow = settings?.permissions?.allow;
23995
24238
  const ours = (rule) => rule === SETUP_RULE || rule === PLUGIN_RULE;
23996
24239
  if (!Array.isArray(allow) || !allow.some(ours)) return;
@@ -24028,7 +24271,7 @@ var dshPatchBlock = (command, env) => {
24028
24271
  ].join("\n");
24029
24272
  };
24030
24273
  async function writeDshPatch(file2, block) {
24031
- const text = existsSync7(file2) ? await readFile2(file2, "utf8") : "";
24274
+ const text = existsSync7(file2) ? await readFile3(file2, "utf8") : "";
24032
24275
  const start = text.indexOf(YAML_BEGIN);
24033
24276
  const end = text.indexOf(YAML_END);
24034
24277
  let next;
@@ -24049,7 +24292,7 @@ async function writeDshPatch(file2, block) {
24049
24292
  }
24050
24293
  async function removeDshPatch(file2) {
24051
24294
  if (!existsSync7(file2)) return;
24052
- const text = await readFile2(file2, "utf8");
24295
+ const text = await readFile3(file2, "utf8");
24053
24296
  const start = text.indexOf(YAML_BEGIN);
24054
24297
  const end = text.indexOf(YAML_END);
24055
24298
  if (start < 0 || end < start) return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "layermap",
3
- "version": "0.1.21",
3
+ "version": "0.1.22",
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 = 60_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,14 @@ 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 a minute (tests, builds, scripts) leaves time for another session
217
+ // to change the same work tree, so only the files it names count.
213
218
  const edited = new Set();
214
219
  const before = new Map();
215
220
  const checked = new Map();
216
- // The code changes of each repository a running tool may change, by the tool call's id.
221
+ // The code changes of each repository a running tool may change, when it started and its
222
+ // command, by the tool call's id.
217
223
  const running = new Map();
218
224
  let askedAbout = "";
219
225
 
@@ -221,7 +227,7 @@ export default function layermap(pi) {
221
227
  if (server && !server.dead) return server;
222
228
  starting ??= (async () => {
223
229
  const next = new MapServer(cwd);
224
- const tools = await next.start("0.1.21");
230
+ const tools = await next.start("0.1.22");
225
231
  for (const tool of tools) {
226
232
  if (registered.has(tool.name)) continue;
227
233
  registered.add(tool.name);
@@ -295,17 +301,27 @@ export default function layermap(pi) {
295
301
  const changes = new Map();
296
302
  for (const repository of repositories)
297
303
  if (repository) changes.set(repository, await changedCode(repository));
298
- running.set(event.toolCallId, changes);
304
+ running.set(event.toolCallId, {
305
+ changes,
306
+ started: Date.now(),
307
+ command: typeof command === "string" ? command : "",
308
+ });
299
309
  });
300
310
 
301
311
  pi.on("tool_result", async (event) => {
302
- const changes = running.get(event.toolCallId);
303
- if (!changes) return;
312
+ const call = running.get(event.toolCallId);
313
+ if (!call) return;
304
314
  running.delete(event.toolCallId);
305
- for (const [repository, earlier] of changes) {
315
+ const long = Date.now() - call.started > LONG_COMMAND;
316
+ for (const [repository, earlier] of call.changes) {
306
317
  if (edited.has(repository)) continue;
307
318
  const now = await changedCode(repository);
308
- if ([...now].some(([file, content]) => earlier.get(file) !== content)) {
319
+ if (
320
+ [...now].some(
321
+ ([file, content]) =>
322
+ earlier.get(file) !== content && (!long || call.command.includes(path.basename(file))),
323
+ )
324
+ ) {
309
325
  edited.add(repository);
310
326
  before.set(repository, fingerprint(earlier));
311
327
  }