layermap 0.1.20 → 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/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
  }
@@ -19041,9 +19041,35 @@ function mapModules(directory, files) {
19041
19041
  (left, right) => compareText2(left.directory, right.directory) || Number(left.direct) - Number(right.direct)
19042
19042
  );
19043
19043
  }
19044
+ function mapProjectModules(entries) {
19045
+ const modules = mapModules(
19046
+ ".",
19047
+ entries.filter(
19048
+ (entry) => entry.state === "TEXT" && mapCodePath(entry.path) && !mapTestPath(entry.path)
19049
+ ).map((entry) => entry.path)
19050
+ );
19051
+ return (path14) => {
19052
+ if (mapTestPath(path14)) return void 0;
19053
+ const module = modules.find((candidate) => inModule(path14, candidate));
19054
+ return module && moduleLabel(module);
19055
+ };
19056
+ }
19057
+ function loadImports(store, version2) {
19058
+ return store.database.prepare(`SELECT r.path AS source, t.path AS target,
19059
+ json_extract(r.relation_json, '$.target') AS specifier, count(*) AS count
19060
+ FROM project_map_relations r NOT INDEXED
19061
+ LEFT JOIN project_map_objects t ON t.version_ref = r.version_ref AND t.entity_ref = r.to_ref
19062
+ WHERE r.version_ref = ? AND json_extract(r.relation_json, '$.kind') IN ('IMPORTS', 'TEST_IMPORTS')
19063
+ GROUP BY source, target, specifier`).all(version2).map((row) => ({
19064
+ source: String(row.source),
19065
+ target: row.target === null ? null : String(row.target),
19066
+ specifier: String(row.specifier),
19067
+ count: Number(row.count)
19068
+ }));
19069
+ }
19044
19070
  function loadDirectoryFacts(store, version2) {
19045
19071
  const files = /* @__PURE__ */ new Map();
19046
- const declarations = [];
19072
+ const declarations2 = [];
19047
19073
  for (const row of store.database.prepare(`SELECT entity_ref, path, kind, name,
19048
19074
  json_extract(object_json, '$.anchor.startLine') AS start_line,
19049
19075
  json_extract(object_json, '$.anchor.endLine') AS end_line,
@@ -19061,7 +19087,7 @@ function loadDirectoryFacts(store, version2) {
19061
19087
  ...row.language ? { language: String(row.language) } : {}
19062
19088
  });
19063
19089
  else
19064
- declarations.push({
19090
+ declarations2.push({
19065
19091
  ref: String(row.entity_ref),
19066
19092
  path: String(row.path),
19067
19093
  kind,
@@ -19072,7 +19098,7 @@ function loadDirectoryFacts(store, version2) {
19072
19098
  });
19073
19099
  }
19074
19100
  const decorators = /* @__PURE__ */ new Map();
19075
- 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);
19076
19102
  const decoratorQuery = store.database.prepare(`SELECT from_ref,
19077
19103
  json_extract(relation_json, '$.target') AS target,
19078
19104
  json_extract(relation_json, '$.argument') AS argument,
@@ -19094,7 +19120,7 @@ function loadDirectoryFacts(store, version2) {
19094
19120
  )
19095
19121
  ]);
19096
19122
  const exported = /* @__PURE__ */ new Map();
19097
- for (const item of declarations) {
19123
+ for (const item of declarations2) {
19098
19124
  const endLine = item.kind === "TYPE" || item.kind === "VARIABLE" ? item.startLine : item.endLine;
19099
19125
  const label = mapDeclarationLabel({
19100
19126
  kind: item.kind,
@@ -19109,17 +19135,7 @@ function loadDirectoryFacts(store, version2) {
19109
19135
  ]);
19110
19136
  }
19111
19137
  for (const list of exported.values()) list.sort((left, right) => left.start - right.start);
19112
- const imports = store.database.prepare(`SELECT r.path AS source, t.path AS target,
19113
- json_extract(r.relation_json, '$.target') AS specifier, count(*) AS count
19114
- FROM project_map_relations r NOT INDEXED
19115
- LEFT JOIN project_map_objects t ON t.version_ref = r.version_ref AND t.entity_ref = r.to_ref
19116
- WHERE r.version_ref = ? AND json_extract(r.relation_json, '$.kind') IN ('IMPORTS', 'TEST_IMPORTS')
19117
- GROUP BY source, target, specifier`).all(version2).map((row) => ({
19118
- source: String(row.source),
19119
- target: row.target === null ? null : String(row.target),
19120
- specifier: String(row.specifier),
19121
- count: Number(row.count)
19122
- }));
19138
+ const imports2 = loadImports(store, version2);
19123
19139
  const calls = /* @__PURE__ */ new Map();
19124
19140
  for (const row of store.database.prepare(`SELECT path, count(*) AS total, sum(to_ref IS NOT NULL) AS resolved,
19125
19141
  sum(to_ref IS NULL AND json_extract(relation_json, '$.unresolvedReason')
@@ -19135,7 +19151,7 @@ function loadDirectoryFacts(store, version2) {
19135
19151
  unresolved: Number(row.total) - resolved - external
19136
19152
  });
19137
19153
  }
19138
- return { files, calls, exported, imports };
19154
+ return { files, calls, exported, imports: imports2 };
19139
19155
  }
19140
19156
  var MEMBER_NAME = /\.([A-Za-z_$][\w$]*)$/u;
19141
19157
  var memberKey = (language, name) => `${language}\0${name}`;
@@ -19216,6 +19232,7 @@ function loadCoverageNotes(store, version2) {
19216
19232
  }
19217
19233
  var MapViewCache = class {
19218
19234
  facts = new VersionCache(loadDirectoryFacts);
19235
+ importRows = new VersionCache(loadImports);
19219
19236
  calls = new VersionCache(loadMemberCalls);
19220
19237
  coverage = new VersionCache(loadCoverageNotes);
19221
19238
  directoryFacts(store, version2) {
@@ -19224,11 +19241,15 @@ var MapViewCache = class {
19224
19241
  coverageNotes(store, version2) {
19225
19242
  return this.coverage.get(store, version2);
19226
19243
  }
19244
+ imports(store, version2) {
19245
+ return this.importRows.get(store, version2);
19246
+ }
19227
19247
  memberCalls(store, version2) {
19228
19248
  return this.calls.get(store, version2);
19229
19249
  }
19230
19250
  clear() {
19231
19251
  this.facts.clear();
19252
+ this.importRows.clear();
19232
19253
  this.calls.clear();
19233
19254
  this.coverage.clear();
19234
19255
  }
@@ -19345,10 +19366,10 @@ function directoryView(facts, coverage, entries, input, directory, prefixes) {
19345
19366
  }
19346
19367
  const detailed = [
19347
19368
  ...code.map((path14) => {
19348
- const declarations = (facts.exported.get(path14) ?? []).map(({ text: text2 }) => text2);
19369
+ const declarations2 = (facts.exported.get(path14) ?? []).map(({ text: text2 }) => text2);
19349
19370
  return [
19350
19371
  path14,
19351
- `${path14} ${lineCount(path14)}${declarations.length ? `: ${declarations.join(", ")}` : ""}`
19372
+ `${path14} ${lineCount(path14)}${declarations2.length ? `: ${declarations2.join(", ")}` : ""}`
19352
19373
  ];
19353
19374
  }),
19354
19375
  ...listedOther.map((entry) => [
@@ -19720,14 +19741,14 @@ function fileView(store, coverage, graph, input, path14, prefixes) {
19720
19741
  `${object2.name} ${mapDeclarationLabel(object2)}${object2.anchor.path === path14 ? "" : ` (${object2.anchor.path})`}`,
19721
19742
  ...tags.get(object2.id) ?? []
19722
19743
  ].join(" ");
19723
- const declarations = [];
19744
+ const declarations2 = [];
19724
19745
  for (const member of members) {
19725
- declarations.push(`${member.exported ? "*" : " "}${describe3(member)}`);
19746
+ declarations2.push(`${member.exported ? "*" : " "}${describe3(member)}`);
19726
19747
  const children = nested.get(member.id) ?? [];
19727
19748
  const listed = member.kind === "CLASS" ? children : children.filter((child) => child.kind === "METHOD");
19728
19749
  const fields2 = children.length - listed.length;
19729
19750
  if (listed.length || fields2)
19730
- declarations.push(
19751
+ declarations2.push(
19731
19752
  ` ${[...listed.map(describe3), ...fields2 ? [`${fields2} fields`] : []].join(", ")}`
19732
19753
  );
19733
19754
  }
@@ -19744,11 +19765,11 @@ function fileView(store, coverage, graph, input, path14, prefixes) {
19744
19765
  for (const [parent, list] of [...elsewhere].sort(
19745
19766
  ([, left], [, right]) => Math.min(...left.map((object2) => object2.anchor.start)) - Math.min(...right.map((object2) => object2.anchor.start))
19746
19767
  ))
19747
- declarations.push(
19768
+ declarations2.push(
19748
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(", ")}`
19749
19770
  );
19750
- if (declarations.length) blocks.push(["DECLARATIONS (* exported)", ...declarations].join("\n"));
19751
- const imports = /* @__PURE__ */ new Set();
19771
+ if (declarations2.length) blocks.push(["DECLARATIONS (* exported)", ...declarations2].join("\n"));
19772
+ const imports2 = /* @__PURE__ */ new Set();
19752
19773
  const external = /* @__PURE__ */ new Set();
19753
19774
  const fileObjects = graph.objectsAt(path14).map((object2) => object2.id);
19754
19775
  for (const relation of graph.relationsFrom(fileObjects)) {
@@ -19756,7 +19777,7 @@ function fileView(store, coverage, graph, input, path14, prefixes) {
19756
19777
  if (relation.to === void 0) external.add(relation.target);
19757
19778
  else {
19758
19779
  const target = graph.object(relation.to).anchor.path;
19759
- if (mapPathAllowed(target, prefixes)) imports.add(mapImportTarget(target));
19780
+ if (mapPathAllowed(target, prefixes)) imports2.add(mapImportTarget(target));
19760
19781
  }
19761
19782
  }
19762
19783
  const importers = /* @__PURE__ */ new Set();
@@ -19769,7 +19790,7 @@ function fileView(store, coverage, graph, input, path14, prefixes) {
19769
19790
  if (!mapPathAllowed(source, prefixes)) continue;
19770
19791
  (!showTests && mapTestPath(source) ? testImporters : importers).add(source);
19771
19792
  }
19772
- if (imports.size) blocks.push(`IMPORTS \u2192 ${[...imports].sort(compareText2).join(", ")}`);
19793
+ if (imports2.size) blocks.push(`IMPORTS \u2192 ${[...imports2].sort(compareText2).join(", ")}`);
19773
19794
  if (external.size)
19774
19795
  blocks.push(`UNRESOLVED IMPORTS: ${[...external].sort(compareText2).join(", ")}`);
19775
19796
  if (importers.size || testImporters.size)
@@ -19938,18 +19959,18 @@ var ProjectMapQuery = class {
19938
19959
  throw new ProjectEvidenceError("PROJECT_EVIDENCE_INDEX_UNAVAILABLE", true);
19939
19960
  const { offset, scope, prefixes } = admission(input);
19940
19961
  const query = mapSearchQuery(input);
19941
- const rows = mapSearchRows(this.store, input, query, scope, offset, signal);
19962
+ const rows2 = mapSearchRows(this.store, input, query, scope, offset, signal);
19942
19963
  const metadata = { ...MAP_QUERY_GUIDANCE, query, gaps: this.gaps(input.version, prefixes) };
19943
19964
  return mapQueryPage(
19944
- Math.min(rows.length, input.maxResults),
19965
+ Math.min(rows2.length, input.maxResults),
19945
19966
  (count) => {
19946
- const selected = rows.slice(0, count);
19967
+ const selected = rows2.slice(0, count);
19947
19968
  return {
19948
19969
  ...metadata,
19949
19970
  objects: selected.map((row) => row.object),
19950
19971
  rankings: selected.map((row) => row.ranking),
19951
- ...rows.length > count ? { nextOffset: offset + count } : {},
19952
- pageExhausted: rows.length <= count
19972
+ ...rows2.length > count ? { nextOffset: offset + count } : {},
19973
+ pageExhausted: rows2.length <= count
19953
19974
  };
19954
19975
  },
19955
19976
  mapSearchNavigation,
@@ -19960,12 +19981,12 @@ var ProjectMapQuery = class {
19960
19981
  this.requireReadableMap(input.version, signal);
19961
19982
  const { offset, scope } = admission(input);
19962
19983
  const query = mapSearchQuery(input);
19963
- const rows = mapSearchRows(this.store, input, query, scope, offset, signal);
19984
+ const rows2 = mapSearchRows(this.store, input, query, scope, offset, signal);
19964
19985
  return mapSearchView(
19965
19986
  this.store,
19966
19987
  input.version,
19967
19988
  query,
19968
- rows,
19989
+ rows2,
19969
19990
  offset,
19970
19991
  input.maxResults,
19971
19992
  input.outputBudget
@@ -20039,10 +20060,10 @@ var ProjectMapQuery = class {
20039
20060
  notesTruncated: notes.length > selectedNotes.length,
20040
20061
  gaps: this.gaps(input.version, prefixes)
20041
20062
  };
20042
- const rows = [];
20063
+ const rows2 = [];
20043
20064
  const materialize = (count) => ({
20044
20065
  ...metadata,
20045
- relations: rows.slice(0, count),
20066
+ relations: rows2.slice(0, count),
20046
20067
  coverage: {
20047
20068
  totalRelations,
20048
20069
  returnedRelations: count,
@@ -20050,7 +20071,7 @@ var ProjectMapQuery = class {
20050
20071
  },
20051
20072
  traversal: {
20052
20073
  semantics: "STATIC_RELATIONSHIPS",
20053
- frontier: mapPageFrontier(frontier, rows.slice(0, count))
20074
+ frontier: mapPageFrontier(frontier, rows2.slice(0, count))
20054
20075
  },
20055
20076
  ...totalRelations > offset + count ? { nextOffset: offset + count } : {},
20056
20077
  pageExhausted: totalRelations <= offset + count
@@ -20063,13 +20084,13 @@ var ProjectMapQuery = class {
20063
20084
  const ref = relationRefs[position];
20064
20085
  if (ref === void 0)
20065
20086
  throw new ProjectEvidenceError("PROJECT_EVIDENCE_STORE_CORRUPT", false);
20066
- rows.push(readRow(ref));
20087
+ rows2.push(readRow(ref));
20067
20088
  }
20068
20089
  await setImmediate3();
20069
20090
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
20070
20091
  if (position === end) break;
20071
20092
  const { nextOffset: _nextOffset, ...minimum } = mapExploreNavigation(
20072
- materialize(rows.length)
20093
+ materialize(rows2.length)
20073
20094
  );
20074
20095
  const minimumBytes = Buffer.byteLength(
20075
20096
  canonicalJson({
@@ -20082,7 +20103,7 @@ var ProjectMapQuery = class {
20082
20103
  if (minimumBytes + (input.outputBudget?.envelopeBytes ?? 0) > (input.outputBudget?.maxBytes ?? PROJECT_MAP_LIMITS.queryBytes))
20083
20104
  break;
20084
20105
  }
20085
- const page = mapQueryPage(rows.length, materialize, mapExploreNavigation, input.outputBudget);
20106
+ const page = mapQueryPage(rows2.length, materialize, mapExploreNavigation, input.outputBudget);
20086
20107
  await setImmediate3();
20087
20108
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
20088
20109
  this.rememberTraversal(traversalKey, traversal);
@@ -21963,6 +21984,7 @@ var CodeIndex = class {
21963
21984
 
21964
21985
  // src/project-map-changes.ts
21965
21986
  import { readFileSync as readFileSync3 } from "node:fs";
21987
+ import { readFile } from "node:fs/promises";
21966
21988
  import path9 from "node:path";
21967
21989
 
21968
21990
  // src/project-map-clients.ts
@@ -22113,6 +22135,90 @@ async function routeClients(routes, registrations, git2, options) {
22113
22135
  }
22114
22136
  var routeClientsLine = ({ route, removed, clients }) => `${JSON.stringify(route)}${removed ? " (removed or renamed)" : ""} \u2190 ${clients.slice(0, LIMIT.clients).join(", ")}${clients.length > LIMIT.clients ? `, +${clients.length - LIMIT.clients} more` : ""}`;
22115
22137
 
22138
+ // src/project-map-dependencies.ts
22139
+ var IMPORT_KINDS2 = /* @__PURE__ */ new Set(["IMPORTS", "TEST_IMPORTS"]);
22140
+ function imports(graph, path14) {
22141
+ const found = [];
22142
+ for (const relation of graph.relationsFrom(graph.objectsAt(path14).map((object2) => object2.id)))
22143
+ if (IMPORT_KINDS2.has(relation.kind) && relation.to !== void 0)
22144
+ found.push({
22145
+ target: graph.object(relation.to).anchor.path,
22146
+ line: relation.anchor.startLine
22147
+ });
22148
+ return found;
22149
+ }
22150
+ function pathBetween(edges, from, to) {
22151
+ const via = /* @__PURE__ */ new Map([[from, from]]);
22152
+ for (let frontier = [from]; frontier.length; ) {
22153
+ const next = [];
22154
+ for (const module of frontier)
22155
+ for (const target of edges.get(module)?.keys() ?? []) {
22156
+ if (via.has(target)) continue;
22157
+ via.set(target, module);
22158
+ if (target === to) {
22159
+ const path14 = [to];
22160
+ for (let step = module; step !== from; step = via.get(step) ?? from) path14.unshift(step);
22161
+ return [from, ...path14];
22162
+ }
22163
+ next.push(target);
22164
+ }
22165
+ frontier = next;
22166
+ }
22167
+ return void 0;
22168
+ }
22169
+ function newModuleDependencies(store, cache, working, base, files) {
22170
+ const entries = store.listEntries(working);
22171
+ const moduleOf = mapProjectModules(entries);
22172
+ const now = /* @__PURE__ */ new Map();
22173
+ const before = /* @__PURE__ */ new Map();
22174
+ const add = (edges, source, target, site) => {
22175
+ const from = moduleOf(source);
22176
+ const to = moduleOf(target);
22177
+ if (!from || !to || from === to) return;
22178
+ const targets = edges.get(from) ?? /* @__PURE__ */ new Map();
22179
+ const sites2 = targets.get(to) ?? [];
22180
+ if (site && !sites2.includes(site)) sites2.push(site);
22181
+ targets.set(to, sites2);
22182
+ edges.set(from, targets);
22183
+ };
22184
+ const changed = new Set(files.map((file2) => file2.path));
22185
+ for (const row of cache.imports(store, working))
22186
+ if (row.target !== null && !changed.has(row.source)) {
22187
+ add(now, row.source, row.target);
22188
+ add(before, row.source, row.target);
22189
+ }
22190
+ const graph = new MapViewGraph(store, working);
22191
+ const baseGraph = base === void 0 ? void 0 : new MapViewGraph(store, base);
22192
+ for (const file2 of files) {
22193
+ const current = file2.status === "DELETED" ? [] : imports(graph, file2.path);
22194
+ for (const { target, line } of current) add(now, file2.path, target, `${file2.path}:${line}`);
22195
+ if (!file2.basePath || file2.status === "ADDED") continue;
22196
+ if (baseGraph)
22197
+ for (const { target } of imports(baseGraph, file2.basePath)) add(before, file2.path, target);
22198
+ else
22199
+ for (const { target, line } of current)
22200
+ if (!file2.lines.some(([from, to]) => from <= line && line <= to))
22201
+ add(before, file2.path, target);
22202
+ }
22203
+ const added = new Set(files.filter((file2) => file2.status === "ADDED").map((file2) => file2.path));
22204
+ const kept = /* @__PURE__ */ new Set();
22205
+ for (const entry of entries) {
22206
+ const module = mapCodePath(entry.path) ? moduleOf(entry.path) : void 0;
22207
+ if (module && !added.has(entry.path)) kept.add(module);
22208
+ }
22209
+ const dependencies = [];
22210
+ for (const [from, targets] of now)
22211
+ for (const [to, sites2] of targets) {
22212
+ if (before.get(from)?.has(to)) continue;
22213
+ const back = pathBetween(now, to, from);
22214
+ const cycle = back && !(pathBetween(before, from, to) && pathBetween(before, to, from)) ? { back } : {};
22215
+ dependencies.push({ from, to, sites: sites2, ...cycle, added: !kept.has(from) });
22216
+ }
22217
+ return dependencies.sort(
22218
+ (left, right) => Number(right.back !== void 0) - Number(left.back !== void 0) || (left.from < right.from ? -1 : left.from > right.from ? 1 : 0) || (left.to < right.to ? -1 : left.to > right.to ? 1 : 0)
22219
+ );
22220
+ }
22221
+
22116
22222
  // src/project-map-names.ts
22117
22223
  import { readFileSync as readFileSync2 } from "node:fs";
22118
22224
  import path8 from "node:path";
@@ -22260,6 +22366,176 @@ async function strandedNames(project, diff, files, configuration, git2, options)
22260
22366
  }
22261
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` : ""}`;
22262
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
+
22263
22539
  // src/project-map-changes.ts
22264
22540
  var git = new GitRunner();
22265
22541
  var gitOptions = (cwd, signal) => ({
@@ -22394,7 +22670,7 @@ var NON_CODE = [
22394
22670
  var nonCodeKind = (path14) => NON_CODE.find(([pattern]) => pattern.test(path14))?.[1];
22395
22671
  var LIMITS = Object.freeze({ depth: 8, declarations: 800, changed: 200, chain: 3, byName: 40 });
22396
22672
  var CALLER_KINDS = /* @__PURE__ */ new Set(["CALLS", "REFERENCES"]);
22397
- var IMPORT_KINDS2 = /* @__PURE__ */ new Set(["IMPORTS", "TEST_IMPORTS"]);
22673
+ var IMPORT_KINDS3 = /* @__PURE__ */ new Set(["IMPORTS", "TEST_IMPORTS"]);
22398
22674
  var ROUTE2 = /^(?:[A-Z]+(?:\|[A-Z]+)* +)?\/\S*$/u;
22399
22675
  var areaOf = (file2) => /\.(?:go|java|kt)$/u.test(file2) ? file2.slice(0, file2.lastIndexOf("/") + 1) || "./" : file2;
22400
22676
  var Tracer = class {
@@ -22604,9 +22880,12 @@ function mapChangeImpact(store, working, base, changes, project) {
22604
22880
  const changed = [];
22605
22881
  const unclear = [];
22606
22882
  const removed = [];
22607
- 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));
22608
22884
  let changedCount = 0;
22609
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));
22610
22889
  for (const file2 of changes.files) {
22611
22890
  if (file2.binary) continue;
22612
22891
  const kind = nonCodeKind(file2.path);
@@ -22621,7 +22900,7 @@ function mapChangeImpact(store, working, base, changes, project) {
22621
22900
  if (!objects2.length) continue;
22622
22901
  const hits = /* @__PURE__ */ new Set();
22623
22902
  let topLevel = false;
22624
- const inFile = declarations(graph, file2.path);
22903
+ const inFile = declarations2(graph, file2.path);
22625
22904
  for (const [from, to] of file2.lines) {
22626
22905
  const containing = inFile.filter(
22627
22906
  (object2) => object2.anchor.startLine <= to && from <= object2.anchor.endLine
@@ -22651,9 +22930,9 @@ function mapChangeImpact(store, working, base, changes, project) {
22651
22930
  );
22652
22931
  if (analyzed && topLevel && file2.status !== "ADDED")
22653
22932
  unclear.push(`top-level code of ${file2.path} changed (imports, constants or registrations)`);
22654
- importerTests(graph, objects2, tracer);
22655
- sameDirectoryTests(store, working, file2.path, tracer);
22656
- mirroredTests(store, working, file2.path, tracer);
22933
+ importerTests(graph, objects2, tracer, importers);
22934
+ sameDirectoryTests(mappedPaths(), file2.path, tracer);
22935
+ mirroredTests(mappedPaths(), file2.path, tracer);
22657
22936
  }
22658
22937
  tracer.trace(starts);
22659
22938
  if (project) routeTests(project, store, working, [...tracer.entries.values()], tracer);
@@ -22682,11 +22961,11 @@ function mapChangeImpact(store, working, base, changes, project) {
22682
22961
  if (!file2.basePath || !file2.baseLines.length || file2.binary || testCode(file2.basePath))
22683
22962
  continue;
22684
22963
  const now = new Set(
22685
- file2.status === "DELETED" ? [] : declarations(graph, file2.path).map(
22964
+ file2.status === "DELETED" ? [] : declarations2(graph, file2.path).map(
22686
22965
  (o) => `${o.kind}\0${graph.qualifiedName(o.id)}`
22687
22966
  )
22688
22967
  );
22689
- for (const object2 of declarations(before, file2.basePath)) {
22968
+ for (const object2 of declarations2(before, file2.basePath)) {
22690
22969
  if (!overlaps(file2.baseLines, object2.anchor.startLine, object2.anchor.endLine)) continue;
22691
22970
  if (now.has(`${object2.kind}\0${before.qualifiedName(object2.id)}`)) continue;
22692
22971
  const parent = before.parent(object2.id);
@@ -22741,6 +23020,7 @@ function mapChangeImpact(store, working, base, changes, project) {
22741
23020
  })).sort((left, right) => right.tests.length - left.tests.length),
22742
23021
  unclear: [.../* @__PURE__ */ new Set([...unclear, ...tracer.unclear])],
22743
23022
  removedRoutes,
23023
+ dependencies: newModuleDependencies(store, cache, working, base, changes.files),
22744
23024
  truncated: tracer.truncated
22745
23025
  };
22746
23026
  }
@@ -22773,27 +23053,34 @@ function existingTestsChanged(before, after, file2, project) {
22773
23053
  )
22774
23054
  ).map((object2) => before.qualifiedName(object2.id)).sort();
22775
23055
  }
22776
- function importerTests(graph, objects2, tracer) {
23056
+ function importerTests(graph, objects2, tracer, importers) {
22777
23057
  let modules = objects2.filter((object2) => mapIsModule(object2)).map((object2) => object2.id);
22778
23058
  const seen = new Set(modules);
22779
23059
  for (let hop = 0; hop < 3 && modules.length; hop++) {
22780
- const next = [];
22781
- for (const relation of graph.relationsTo(modules)) {
22782
- if (!IMPORT_KINDS2.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;
22783
23064
  const importer = graph.object(relation.from);
22784
- const module = mapIsModule(importer) ? importer.id : graph.owner(relation.from);
22785
- if (testCode(relation.anchor.path))
22786
- tracer.test(
22787
- relation.anchor.path,
22788
- void 0,
22789
- hop ? "imports a changed file indirectly" : "imports a changed file",
22790
- hop ? 4 : 2
22791
- );
22792
- else if (!seen.has(module)) {
22793
- seen.add(module);
22794
- next.push(module);
22795
- }
23065
+ importers.get(relation.to)?.push({
23066
+ path: relation.anchor.path,
23067
+ module: mapIsModule(importer) ? importer.id : graph.owner(relation.from)
23068
+ });
22796
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
+ }
22797
23084
  modules = next;
22798
23085
  }
22799
23086
  }
@@ -22807,14 +23094,12 @@ function supportTests(store, version2, tracer) {
22807
23094
  tracer.test(String(row.path), void 0, `may use it through ${file2}`, 3.5);
22808
23095
  }
22809
23096
  }
22810
- function mirroredTests(store, version2, file2, tracer) {
23097
+ function mirroredTests(paths, file2, tracer) {
22811
23098
  const directories = file2.split("/").slice(0, -1);
22812
23099
  const module = directories.at(-1);
22813
23100
  if (!module || directories.length < 1) return;
22814
- for (const row of store.database.prepare(
22815
- "SELECT DISTINCT path FROM project_map_objects WHERE version_ref = ? AND instr(path, ?) > 0"
22816
- ).all(version2, `/${module}/`)) {
22817
- const candidate = String(row.path);
23101
+ for (const candidate of paths) {
23102
+ if (!candidate.includes(`/${module}/`)) continue;
22818
23103
  const parts = candidate.split("/");
22819
23104
  const at = parts.lastIndexOf(module);
22820
23105
  if (at < 1 || at !== parts.length - 2) continue;
@@ -22855,13 +23140,11 @@ function routeTests(project, store, version2, entries, tracer) {
22855
23140
  }
22856
23141
  }
22857
23142
  }
22858
- function sameDirectoryTests(store, version2, path14, tracer) {
23143
+ function sameDirectoryTests(paths, path14, tracer) {
22859
23144
  const slash = path14.lastIndexOf("/");
22860
23145
  const directory = slash < 0 ? "" : path14.slice(0, slash + 1);
22861
- for (const row of store.database.prepare(
22862
- "SELECT DISTINCT path FROM project_map_objects WHERE version_ref = ? AND path LIKE ? ESCAPE '\\'"
22863
- ).all(version2, `${directory.replace(/[\\%_]/gu, (c) => `\\${c}`)}%`)) {
22864
- const candidate = String(row.path);
23146
+ for (const candidate of paths) {
23147
+ if (!candidate.startsWith(directory)) continue;
22865
23148
  if (candidate.slice(directory.length).includes("/") || !mapTestPath(candidate)) continue;
22866
23149
  tracer.test(candidate, void 0, "in the same directory", 3);
22867
23150
  }
@@ -22884,7 +23167,11 @@ var LIST = Object.freeze({
22884
23167
  areas: 8,
22885
23168
  areaTests: 3,
22886
23169
  areaNames: 3,
22887
- through: 2
23170
+ through: 2,
23171
+ dependencies: 12,
23172
+ sites: 2,
23173
+ similar: 10,
23174
+ similarNames: 3
22888
23175
  });
22889
23176
  function routesIn(graph, path14) {
22890
23177
  const routes = /* @__PURE__ */ new Set();
@@ -22907,7 +23194,14 @@ async function checkMapChanges(input, signal) {
22907
23194
  text: mapChangesText(
22908
23195
  changes,
22909
23196
  impact,
22910
- 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
+ )
22911
23205
  )
22912
23206
  };
22913
23207
  }
@@ -22927,7 +23221,7 @@ async function mapRouteClients(project, store, working, impact, signal) {
22927
23221
  if (!routes.length) return [];
22928
23222
  return routeClients(routes, registrations, git, gitOptions(project, signal));
22929
23223
  }
22930
- function mapChangesText(changes, impact, clients = []) {
23224
+ function mapChangesText(changes, impact, clients = [], similar = []) {
22931
23225
  const files = changes.files.length;
22932
23226
  const direct = impact.tests.filter((test) => test.rank < 4);
22933
23227
  const indirect = impact.tests.filter((test) => test.rank >= 4);
@@ -22985,6 +23279,54 @@ Nothing changed against ${changes.base}.`;
22985
23279
  "Each area's tests pin its current behavior. Decide which areas the request is about: a failing test of another area means the change reached a feature the request may not cover; if it does not, narrow the change, for example to code only the requested area uses, rather than rewriting that test."
22986
23280
  );
22987
23281
  }
23282
+ if (impact.dependencies.length) {
23283
+ const sites2 = (dependency) => `${dependency.sites.slice(0, LIST.sites).join(", ")}${dependency.sites.length > LIST.sites ? `, +${dependency.sites.length - LIST.sites} more` : ""}`;
23284
+ const fresh = /* @__PURE__ */ new Map();
23285
+ for (const dependency of impact.dependencies)
23286
+ if (dependency.added && !dependency.back)
23287
+ fresh.set(dependency.from, [...fresh.get(dependency.from) ?? [], dependency.to]);
23288
+ list(
23289
+ "NEW MODULE DEPENDENCIES (imports between the modules of the project overview that the base did not have)",
23290
+ [
23291
+ ...impact.dependencies.filter((dependency) => !fresh.has(dependency.from) || dependency.back).map(
23292
+ (dependency) => `${dependency.from} \u2192 ${dependency.to} (${sites2(dependency)})${dependency.back ? `; now a cycle, back through ${dependency.back.join(" \u2192 ")}` : ""}`
23293
+ ),
23294
+ ...[...fresh].map(
23295
+ ([from, targets]) => `${from} (a module this diff adds) \u2192 ${targets.join(", ")}`
23296
+ )
23297
+ ],
23298
+ LIST.dependencies
23299
+ );
23300
+ lines.push(
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.`
23302
+ );
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
+ }
22988
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})` : ""}`;
22989
23331
  list(
22990
23332
  "AFFECTED ENTRY POINTS (through resolved calls)",
@@ -23235,7 +23577,7 @@ var packageRoot = (() => {
23235
23577
  directory = path11.dirname(directory);
23236
23578
  }
23237
23579
  })();
23238
- 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;
23239
23581
  var cacheDirectory = (env = process.env) => {
23240
23582
  if (env.LAYERMAP_CACHE) return path11.resolve(env.LAYERMAP_CACHE);
23241
23583
  if (process.platform === "darwin") return path11.join(homedir(), "Library", "Caches", "layermap");
@@ -23294,11 +23636,11 @@ var absoluteIn = (directory, value) => Object.fromEntries(
23294
23636
  var readAnalyzers = async (directory) => {
23295
23637
  const file2 = path11.join(directory, "analyzers.json");
23296
23638
  if (!existsSync5(file2)) return void 0;
23297
- const analyzers = absoluteIn(directory, JSON.parse(await readFile(file2, "utf8")));
23639
+ const analyzers = absoluteIn(directory, JSON.parse(await readFile2(file2, "utf8")));
23298
23640
  return analyzers.java.runtimePath ? analyzers : { ...analyzers, java: { ...analyzers.java, ...discoverJavaRuntime() } };
23299
23641
  };
23300
23642
  var sourceDigest = async () => {
23301
- 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")));
23302
23644
  for (const part of ["src", "go-map", "java-map", "scripts"]) {
23303
23645
  const directory = path11.join(packageRoot, part);
23304
23646
  if (!existsSync5(directory)) continue;
@@ -23363,6 +23705,7 @@ async function pruneCache(cache, project, now = Date.now()) {
23363
23705
  // src/agent/mcp.ts
23364
23706
  import { createInterface } from "node:readline";
23365
23707
  import { setTimeout as delay } from "node:timers/promises";
23708
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
23366
23709
 
23367
23710
  // src/agent/projects.ts
23368
23711
  import { existsSync as existsSync6 } from "node:fs";
@@ -23448,7 +23791,7 @@ var mapToolDescriptions = (host) => {
23448
23791
  return Object.freeze({
23449
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.`,
23450
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.`,
23451
- 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; 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; 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.`,
23452
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.`
23453
23796
  });
23454
23797
  };
@@ -23501,10 +23844,10 @@ async function routeMapCall(start, { name, args }) {
23501
23844
  };
23502
23845
  const filter = args.path;
23503
23846
  if (filter === ".") return { project: located.project, args: routed };
23504
- const within2 = await locate(start, filter);
23505
- if (within2?.project !== located.project)
23847
+ const within3 = await locate(start, filter);
23848
+ if (within3?.project !== located.project)
23506
23849
  return `PROJECT_PATH_INVALID: path ${filter} is not in ${located.project}, the repository of the declaration.`;
23507
- return { project: located.project, args: { ...routed, path: within2.path } };
23850
+ return { project: located.project, args: { ...routed, path: within3.path } };
23508
23851
  }
23509
23852
 
23510
23853
  // src/agent/tools.ts
@@ -23607,6 +23950,7 @@ var AGENT_MAP_INSTRUCTIONS = `Use the LayerMap tools instead of grep whenever a
23607
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.";
23608
23951
 
23609
23952
  // src/agent/mcp.ts
23953
+ var ROOTS_WAIT_MS = 5e3;
23610
23954
  function serveMcp(options) {
23611
23955
  const output = options.output ?? process.stdout;
23612
23956
  const log2 = options.log ?? ((line) => process.stderr.write(`${line}
@@ -23616,6 +23960,26 @@ function serveMcp(options) {
23616
23960
  const calls = /* @__PURE__ */ new Map();
23617
23961
  const maps = /* @__PURE__ */ new Map();
23618
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
+ };
23619
23983
  const map2 = (project) => {
23620
23984
  let entry = maps.get(project);
23621
23985
  if (!entry) {
@@ -23654,7 +24018,8 @@ ${text}` : text
23654
24018
  try {
23655
24019
  const parsed = parseMapToolCall(name, params.arguments);
23656
24020
  if ("text" in parsed) return respond(parsed.text, parsed.isError);
23657
- const routed = await routeMapCall(options.start, parsed);
24021
+ await rooted;
24022
+ const routed = await routeMapCall(start, parsed);
23658
24023
  if (typeof routed === "string") return respond(routed, true);
23659
24024
  project = routed.project;
23660
24025
  const { opened, built } = map2(project);
@@ -23681,15 +24046,23 @@ ${text}` : text
23681
24046
  };
23682
24047
  const handle = (message) => {
23683
24048
  const { id: id2, method, params = {} } = message;
23684
- if (method === void 0) return;
24049
+ if (method === void 0) {
24050
+ if (id2 !== void 0 && id2 !== null) replies.get(id2)?.(message);
24051
+ return;
24052
+ }
23685
24053
  if (id2 === void 0 || id2 === null) {
23686
- 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();
23687
24059
  if (method === "notifications/cancelled")
23688
24060
  calls.get(params.requestId)?.abort();
23689
24061
  return;
23690
24062
  }
23691
24063
  switch (method) {
23692
24064
  case "initialize":
24065
+ listsRoots = Boolean(params.capabilities?.roots);
23693
24066
  return send({
23694
24067
  id: id2,
23695
24068
  result: {
@@ -23757,7 +24130,7 @@ ${text}` : text
23757
24130
  // src/agent/setup.ts
23758
24131
  import { execFile as execFile2 } from "node:child_process";
23759
24132
  import { existsSync as existsSync7 } from "node:fs";
23760
- 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";
23761
24134
  import { homedir as homedir2 } from "node:os";
23762
24135
  import path13 from "node:path";
23763
24136
  var SERVER = "layermap";
@@ -23801,7 +24174,7 @@ var run = (command, args, env) => new Promise((resolve) => {
23801
24174
  );
23802
24175
  });
23803
24176
  async function allowInClaudeSettings(file2, rule = SETUP_RULE) {
23804
- const settings = existsSync7(file2) ? JSON.parse(await readFile2(file2, "utf8")) : {};
24177
+ const settings = existsSync7(file2) ? JSON.parse(await readFile3(file2, "utf8")) : {};
23805
24178
  if (typeof settings !== "object" || settings === null || Array.isArray(settings))
23806
24179
  throw new Error(`${file2} is not a settings object.`);
23807
24180
  settings.permissions ??= {};
@@ -23816,7 +24189,7 @@ async function allowInClaudeSettings(file2, rule = SETUP_RULE) {
23816
24189
  return true;
23817
24190
  }
23818
24191
  async function configureCodexServer(file2) {
23819
- const lines = (await readFile2(file2, "utf8")).split("\n");
24192
+ const lines = (await readFile3(file2, "utf8")).split("\n");
23820
24193
  const header2 = lines.findIndex((line) => line.trim() === `[mcp_servers.${SERVER}]`);
23821
24194
  if (header2 < 0) throw new Error(`${file2} has no [mcp_servers.${SERVER}] table.`);
23822
24195
  let end = header2 + 1;
@@ -23838,7 +24211,7 @@ async function writeInstructionNote(file2, note = AGENT_MAP_NOTE) {
23838
24211
  const block = `${BEGIN}
23839
24212
  ${note}
23840
24213
  ${END}`;
23841
- const text = existsSync7(file2) ? await readFile2(file2, "utf8") : "";
24214
+ const text = existsSync7(file2) ? await readFile3(file2, "utf8") : "";
23842
24215
  const start = text.indexOf(BEGIN);
23843
24216
  const end = text.indexOf(END);
23844
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}
@@ -23849,7 +24222,7 @@ ${END}`;
23849
24222
  }
23850
24223
  async function removeInstructionNote(file2) {
23851
24224
  if (!existsSync7(file2)) return;
23852
- const text = await readFile2(file2, "utf8");
24225
+ const text = await readFile3(file2, "utf8");
23853
24226
  const start = text.indexOf(BEGIN);
23854
24227
  const end = text.indexOf(END);
23855
24228
  if (start < 0 || end < start) return;
@@ -23860,7 +24233,7 @@ async function removeInstructionNote(file2) {
23860
24233
  }
23861
24234
  async function disallowInClaudeSettings(file2) {
23862
24235
  if (!existsSync7(file2)) return;
23863
- const settings = JSON.parse(await readFile2(file2, "utf8"));
24236
+ const settings = JSON.parse(await readFile3(file2, "utf8"));
23864
24237
  const allow = settings?.permissions?.allow;
23865
24238
  const ours = (rule) => rule === SETUP_RULE || rule === PLUGIN_RULE;
23866
24239
  if (!Array.isArray(allow) || !allow.some(ours)) return;
@@ -23898,7 +24271,7 @@ var dshPatchBlock = (command, env) => {
23898
24271
  ].join("\n");
23899
24272
  };
23900
24273
  async function writeDshPatch(file2, block) {
23901
- const text = existsSync7(file2) ? await readFile2(file2, "utf8") : "";
24274
+ const text = existsSync7(file2) ? await readFile3(file2, "utf8") : "";
23902
24275
  const start = text.indexOf(YAML_BEGIN);
23903
24276
  const end = text.indexOf(YAML_END);
23904
24277
  let next;
@@ -23919,7 +24292,7 @@ async function writeDshPatch(file2, block) {
23919
24292
  }
23920
24293
  async function removeDshPatch(file2) {
23921
24294
  if (!existsSync7(file2)) return;
23922
- const text = await readFile2(file2, "utf8");
24295
+ const text = await readFile3(file2, "utf8");
23923
24296
  const start = text.indexOf(YAML_BEGIN);
23924
24297
  const end = text.indexOf(YAML_END);
23925
24298
  if (start < 0 || end < start) return;