layermap 0.1.20 → 0.1.21

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
@@ -158,10 +158,12 @@ a change meant for one feature does not quietly change the others. Environment v
158
158
  configuration keys are linked by name only, which no compiler sees, so when the diff removes one
159
159
  from a file, the check names the files that still read or set the old name. In the same way, when
160
160
  the change reaches a route's handler or renames a route, it names the code and templates that
161
- request that path: a frontend's fetch, a generated API client, a redirect or a link. It never writes or runs tests. In Claude Code and
161
+ request that path: a frontend's fetch, a generated API client, a redirect or a link. When the change adds
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
162
164
  CodeBuddy Code the plugin asks the agent once, before it finishes, to run this check for each repository it edited code in
163
- and has not checked since (changes another session makes in the same work tree do not count); the
164
- Pi extension does the same after the agent's own edits. Set `LAYERMAP_STOP_CHECK=0` to turn that
165
+ and has not checked since, whether through its edit tools or shell commands (changes another session makes in the same
166
+ 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
165
167
  off. Codex and DeepSeek Harness are told to run it.
166
168
 
167
169
  **Without plugins:** run `npx layermap setup claude` or `npx layermap setup codex`. Setup does three
@@ -196,7 +198,7 @@ nothing anywhere ([privacy](https://github.com/coffeecoproject/layermap/blob/mai
196
198
  | `project_explore_map` | A directory, a file, or a declaration's callers and callees (`direction` INCOMING or OUTGOING, `depth` up to 8). |
197
199
  | `project_search_map` | Find declarations by words in their names, paths or documentation. |
198
200
  | `project_find_references` | Every usage of a declaration, compiled from current source. |
199
- | `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, what to check by hand, and related tests. |
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. |
200
202
 
201
203
  The same from the command line:
202
204
 
package/dist/cli.mjs CHANGED
@@ -19041,6 +19041,32 @@ 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
19072
  const declarations = [];
@@ -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
  }
@@ -19748,7 +19769,7 @@ function fileView(store, coverage, graph, input, path14, prefixes) {
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
19771
  if (declarations.length) blocks.push(["DECLARATIONS (* exported)", ...declarations].join("\n"));
19751
- const imports = /* @__PURE__ */ new Set();
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)
@@ -22113,6 +22134,90 @@ async function routeClients(routes, registrations, git2, options) {
22113
22134
  }
22114
22135
  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
22136
 
22137
+ // src/project-map-dependencies.ts
22138
+ var IMPORT_KINDS2 = /* @__PURE__ */ new Set(["IMPORTS", "TEST_IMPORTS"]);
22139
+ function imports(graph, path14) {
22140
+ const found = [];
22141
+ for (const relation of graph.relationsFrom(graph.objectsAt(path14).map((object2) => object2.id)))
22142
+ if (IMPORT_KINDS2.has(relation.kind) && relation.to !== void 0)
22143
+ found.push({
22144
+ target: graph.object(relation.to).anchor.path,
22145
+ line: relation.anchor.startLine
22146
+ });
22147
+ return found;
22148
+ }
22149
+ function pathBetween(edges, from, to) {
22150
+ const via = /* @__PURE__ */ new Map([[from, from]]);
22151
+ for (let frontier = [from]; frontier.length; ) {
22152
+ const next = [];
22153
+ for (const module of frontier)
22154
+ for (const target of edges.get(module)?.keys() ?? []) {
22155
+ if (via.has(target)) continue;
22156
+ via.set(target, module);
22157
+ if (target === to) {
22158
+ const path14 = [to];
22159
+ for (let step = module; step !== from; step = via.get(step) ?? from) path14.unshift(step);
22160
+ return [from, ...path14];
22161
+ }
22162
+ next.push(target);
22163
+ }
22164
+ frontier = next;
22165
+ }
22166
+ return void 0;
22167
+ }
22168
+ function newModuleDependencies(store, cache, working, base, files) {
22169
+ const entries = store.listEntries(working);
22170
+ const moduleOf = mapProjectModules(entries);
22171
+ const now = /* @__PURE__ */ new Map();
22172
+ const before = /* @__PURE__ */ new Map();
22173
+ const add = (edges, source, target, site) => {
22174
+ const from = moduleOf(source);
22175
+ const to = moduleOf(target);
22176
+ if (!from || !to || from === to) return;
22177
+ const targets = edges.get(from) ?? /* @__PURE__ */ new Map();
22178
+ const sites2 = targets.get(to) ?? [];
22179
+ if (site && !sites2.includes(site)) sites2.push(site);
22180
+ targets.set(to, sites2);
22181
+ edges.set(from, targets);
22182
+ };
22183
+ const changed = new Set(files.map((file2) => file2.path));
22184
+ for (const row of cache.imports(store, working))
22185
+ if (row.target !== null && !changed.has(row.source)) {
22186
+ add(now, row.source, row.target);
22187
+ add(before, row.source, row.target);
22188
+ }
22189
+ const graph = new MapViewGraph(store, working);
22190
+ const baseGraph = base === void 0 ? void 0 : new MapViewGraph(store, base);
22191
+ for (const file2 of files) {
22192
+ const current = file2.status === "DELETED" ? [] : imports(graph, file2.path);
22193
+ for (const { target, line } of current) add(now, file2.path, target, `${file2.path}:${line}`);
22194
+ if (!file2.basePath || file2.status === "ADDED") continue;
22195
+ if (baseGraph)
22196
+ for (const { target } of imports(baseGraph, file2.basePath)) add(before, file2.path, target);
22197
+ else
22198
+ for (const { target, line } of current)
22199
+ if (!file2.lines.some(([from, to]) => from <= line && line <= to))
22200
+ add(before, file2.path, target);
22201
+ }
22202
+ const added = new Set(files.filter((file2) => file2.status === "ADDED").map((file2) => file2.path));
22203
+ const kept = /* @__PURE__ */ new Set();
22204
+ for (const entry of entries) {
22205
+ const module = mapCodePath(entry.path) ? moduleOf(entry.path) : void 0;
22206
+ if (module && !added.has(entry.path)) kept.add(module);
22207
+ }
22208
+ const dependencies = [];
22209
+ for (const [from, targets] of now)
22210
+ for (const [to, sites2] of targets) {
22211
+ if (before.get(from)?.has(to)) continue;
22212
+ const back = pathBetween(now, to, from);
22213
+ const cycle = back && !(pathBetween(before, from, to) && pathBetween(before, to, from)) ? { back } : {};
22214
+ dependencies.push({ from, to, sites: sites2, ...cycle, added: !kept.has(from) });
22215
+ }
22216
+ return dependencies.sort(
22217
+ (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)
22218
+ );
22219
+ }
22220
+
22116
22221
  // src/project-map-names.ts
22117
22222
  import { readFileSync as readFileSync2 } from "node:fs";
22118
22223
  import path8 from "node:path";
@@ -22394,7 +22499,7 @@ var NON_CODE = [
22394
22499
  var nonCodeKind = (path14) => NON_CODE.find(([pattern]) => pattern.test(path14))?.[1];
22395
22500
  var LIMITS = Object.freeze({ depth: 8, declarations: 800, changed: 200, chain: 3, byName: 40 });
22396
22501
  var CALLER_KINDS = /* @__PURE__ */ new Set(["CALLS", "REFERENCES"]);
22397
- var IMPORT_KINDS2 = /* @__PURE__ */ new Set(["IMPORTS", "TEST_IMPORTS"]);
22502
+ var IMPORT_KINDS3 = /* @__PURE__ */ new Set(["IMPORTS", "TEST_IMPORTS"]);
22398
22503
  var ROUTE2 = /^(?:[A-Z]+(?:\|[A-Z]+)* +)?\/\S*$/u;
22399
22504
  var areaOf = (file2) => /\.(?:go|java|kt)$/u.test(file2) ? file2.slice(0, file2.lastIndexOf("/") + 1) || "./" : file2;
22400
22505
  var Tracer = class {
@@ -22741,6 +22846,7 @@ function mapChangeImpact(store, working, base, changes, project) {
22741
22846
  })).sort((left, right) => right.tests.length - left.tests.length),
22742
22847
  unclear: [.../* @__PURE__ */ new Set([...unclear, ...tracer.unclear])],
22743
22848
  removedRoutes,
22849
+ dependencies: newModuleDependencies(store, cache, working, base, changes.files),
22744
22850
  truncated: tracer.truncated
22745
22851
  };
22746
22852
  }
@@ -22779,7 +22885,7 @@ function importerTests(graph, objects2, tracer) {
22779
22885
  for (let hop = 0; hop < 3 && modules.length; hop++) {
22780
22886
  const next = [];
22781
22887
  for (const relation of graph.relationsTo(modules)) {
22782
- if (!IMPORT_KINDS2.has(relation.kind)) continue;
22888
+ if (!IMPORT_KINDS3.has(relation.kind)) continue;
22783
22889
  const importer = graph.object(relation.from);
22784
22890
  const module = mapIsModule(importer) ? importer.id : graph.owner(relation.from);
22785
22891
  if (testCode(relation.anchor.path))
@@ -22884,7 +22990,9 @@ var LIST = Object.freeze({
22884
22990
  areas: 8,
22885
22991
  areaTests: 3,
22886
22992
  areaNames: 3,
22887
- through: 2
22993
+ through: 2,
22994
+ dependencies: 12,
22995
+ sites: 2
22888
22996
  });
22889
22997
  function routesIn(graph, path14) {
22890
22998
  const routes = /* @__PURE__ */ new Set();
@@ -22985,6 +23093,28 @@ Nothing changed against ${changes.base}.`;
22985
23093
  "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
23094
  );
22987
23095
  }
23096
+ if (impact.dependencies.length) {
23097
+ const sites2 = (dependency) => `${dependency.sites.slice(0, LIST.sites).join(", ")}${dependency.sites.length > LIST.sites ? `, +${dependency.sites.length - LIST.sites} more` : ""}`;
23098
+ const fresh = /* @__PURE__ */ new Map();
23099
+ for (const dependency of impact.dependencies)
23100
+ if (dependency.added && !dependency.back)
23101
+ fresh.set(dependency.from, [...fresh.get(dependency.from) ?? [], dependency.to]);
23102
+ list(
23103
+ "NEW MODULE DEPENDENCIES (imports between the modules of the project overview that the base did not have)",
23104
+ [
23105
+ ...impact.dependencies.filter((dependency) => !fresh.has(dependency.from) || dependency.back).map(
23106
+ (dependency) => `${dependency.from} \u2192 ${dependency.to} (${sites2(dependency)})${dependency.back ? `; now a cycle, back through ${dependency.back.join(" \u2192 ")}` : ""}`
23107
+ ),
23108
+ ...[...fresh].map(
23109
+ ([from, targets]) => `${from} (a module this diff adds) \u2192 ${targets.join(", ")}`
23110
+ )
23111
+ ],
23112
+ LIST.dependencies
23113
+ );
23114
+ lines.push(
23115
+ `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
+ );
23117
+ }
22988
23118
  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
23119
  list(
22990
23120
  "AFFECTED ENTRY POINTS (through resolved calls)",
@@ -23448,7 +23578,7 @@ var mapToolDescriptions = (host) => {
23448
23578
  return Object.freeze({
23449
23579
  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
23580
  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.`,
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.`,
23452
23582
  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
23583
  });
23454
23584
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "layermap",
3
- "version": "0.1.20",
3
+ "version": "0.1.21",
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
@@ -7,14 +7,15 @@
7
7
  // asks the agent once, before it settles, to check what its code edits affect.
8
8
  import { execFile, spawn } from "node:child_process";
9
9
  import { createHash } from "node:crypto";
10
- import { stat } from "node:fs/promises";
10
+ import { readFile, stat } from "node:fs/promises";
11
+ import os from "node:os";
11
12
  import path from "node:path";
12
13
  import { createInterface } from "node:readline";
13
14
  import { fileURLToPath } from "node:url";
14
15
  import { Type } from "typebox";
15
16
 
16
17
  const 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.";
17
- const STOP_CHECK = "Code changed in this session. Before finishing, call the LayerMap tool project_check_changes: it lists the routes, jobs and commands the changes reach and the existing tests related to them. Check the affected entry points in source, and run the related tests if the change needs verifying. If it lists EXISTING TESTS CHANGED or code SHARED BY several areas, decide which of them the request is about; for the others, restore their tests and narrow the change. If you already checked these changes, say so briefly and finish.";
18
+ const STOP_CHECK = "Code changed in this session. Before finishing, call the LayerMap tool project_check_changes: it lists the routes, jobs and commands the changes reach and the existing tests related to them. Check the affected entry points in source, and run the related tests if the change needs verifying. If it lists EXISTING TESTS CHANGED or code SHARED BY several areas, decide which of them the request is about; for the others, restore their tests and narrow the change. If it lists NEW MODULE DEPENDENCIES, check that each runs the way the project's layers do. If you already checked these changes, say so briefly and finish.";
18
19
  const STOP_CHECK_REPOSITORIES = "The changes are in more than one repository, or not in the one the session started in: call project_check_changes once for each, with its path set to the repository: ";
19
20
  const CHECK_TOOL = "project_check_changes";
20
21
  const CLI = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "dist", "cli.mjs");
@@ -134,16 +135,64 @@ function routedRepository(start, given) {
134
135
  return repositoryAt(path.resolve(start.directory, normal));
135
136
  }
136
137
 
137
- // The uncommitted code changes as one hash, empty when there are none or no repository.
138
- async function codeChanges(cwd) {
139
- if (!(await git(cwd, ["rev-parse", "--verify", "--quiet", "HEAD"]))) return "";
140
- const diff = await git(cwd, ["diff", "HEAD", "--no-ext-diff", "--no-color", "--", ...CODE_GLOBS]);
141
- const untracked = (
142
- await git(cwd, ["ls-files", "--others", "--exclude-standard", "--", ...CODE_GLOBS])
143
- ).trim();
144
- const listed = untracked ? await git(cwd, ["hash-object", "--", ...untracked.split("\n")]) : "";
145
- if (!diff && !untracked) return "";
146
- return createHash("sha256").update(diff).update(untracked).update(listed).digest("hex");
138
+ // A repository's uncommitted code files, each with a hash of its content ("" once deleted); empty
139
+ // without a commit.
140
+ async function changedCode(repository) {
141
+ const changed = new Map();
142
+ if (!(await git(repository, ["rev-parse", "--verify", "--quiet", "HEAD"]))) return changed;
143
+ const listed = await Promise.all([
144
+ git(repository, [
145
+ "-c",
146
+ "core.quotePath=false",
147
+ "diff",
148
+ "HEAD",
149
+ "--name-only",
150
+ "--no-renames",
151
+ "--",
152
+ ...CODE_GLOBS,
153
+ ]),
154
+ git(repository, [
155
+ "-c",
156
+ "core.quotePath=false",
157
+ "ls-files",
158
+ "--others",
159
+ "--exclude-standard",
160
+ "--",
161
+ ...CODE_GLOBS,
162
+ ]),
163
+ ]);
164
+ const files = [...new Set(listed.join("\n").split("\n").filter(Boolean))].sort();
165
+ for (const file of files) {
166
+ const content = await readFile(path.join(repository, file)).catch(() => undefined);
167
+ changed.set(file, content ? createHash("sha256").update(content).digest("hex") : "");
168
+ }
169
+ return changed;
170
+ }
171
+
172
+ // The changes as one hash, empty when there are none.
173
+ const fingerprint = (changed) =>
174
+ changed.size
175
+ ? createHash("sha256")
176
+ .update(JSON.stringify([...changed]))
177
+ .digest("hex")
178
+ : "";
179
+
180
+ // The folders a shell command names that exist, relative to the directory it runs in.
181
+ async function namedFolders(cwd, command) {
182
+ const folders = new Set();
183
+ for (const word of command.split(/[^A-Za-z0-9._/~:@+,%-]+/).slice(0, 300)) {
184
+ if (!word) continue;
185
+ const named = word.startsWith("~/")
186
+ ? path.join(os.homedir(), word.slice(2))
187
+ : path.resolve(cwd, word);
188
+ for (const folder of [named, path.dirname(named)])
189
+ if ((await stat(folder).catch(() => undefined))?.isDirectory()) {
190
+ folders.add(folder);
191
+ break;
192
+ }
193
+ if (folders.size >= 20) break;
194
+ }
195
+ return folders;
147
196
  }
148
197
 
149
198
  export default function layermap(pi) {
@@ -154,22 +203,25 @@ export default function layermap(pi) {
154
203
  // Where the server resolves relative paths from: the repository the session started in, or its
155
204
  // directory outside one.
156
205
  let start = { directory: "", git: false };
157
- // The stop check looks at each repository the agent may have changed files in: those of the
158
- // files an edit, write or patch names, and for any other tool that can change files the one the
159
- // session started in.
206
+ // The stop check looks at each repository the agent changed code in: those of the files an
207
+ // edit, write or patch names, and those in which any other tool that can change files (bash, …)
208
+ // changed code files while it ran, among the repository the session started in, those of the
209
+ // folders its command names and those already edited.
160
210
  // It compares a repository's uncommitted code changes with those it had before the session's
161
211
  // first such tool there and those the agent last checked in it, and all of them with those it
162
212
  // was last asked about; changes another session makes while this one reads do not count.
163
213
  const edited = new Set();
164
214
  const before = new Map();
165
215
  const checked = new Map();
216
+ // The code changes of each repository a running tool may change, by the tool call's id.
217
+ const running = new Map();
166
218
  let askedAbout = "";
167
219
 
168
220
  const ensureServer = async () => {
169
221
  if (server && !server.dead) return server;
170
222
  starting ??= (async () => {
171
223
  const next = new MapServer(cwd);
172
- const tools = await next.start("0.1.20");
224
+ const tools = await next.start("0.1.21");
173
225
  for (const tool of tools) {
174
226
  if (registered.has(tool.name)) continue;
175
227
  registered.add(tool.name);
@@ -191,7 +243,7 @@ export default function layermap(pi) {
191
243
  if (result.isError) throw new Error(text);
192
244
  if (tool.name === CHECK_TOOL) {
193
245
  const repository = await routedRepository(start, params?.path);
194
- if (repository) checked.set(repository, await codeChanges(repository));
246
+ if (repository) checked.set(repository, fingerprint(await changedCode(repository)));
195
247
  }
196
248
  return { content: [{ type: "text", text }], details: {} };
197
249
  },
@@ -212,6 +264,7 @@ export default function layermap(pi) {
212
264
  edited.clear();
213
265
  before.clear();
214
266
  checked.clear();
267
+ running.clear();
215
268
  askedAbout = "";
216
269
  await ensureServer().catch((error) =>
217
270
  ctx.ui?.notify?.(`LayerMap could not start: ${error.message}`, "warning"),
@@ -221,13 +274,41 @@ export default function layermap(pi) {
221
274
  pi.on("tool_call", async (event) => {
222
275
  if (READS.has(event.toolName) || registered.has(event.toolName) || !cwd) return;
223
276
  const files = namedFiles(event);
224
- const repositories = files.length
225
- ? await Promise.all(files.map((file) => repositoryAt(path.resolve(cwd, file))))
226
- : [start.git && start.directory];
227
- for (const repository of new Set(repositories)) {
228
- if (!repository || edited.has(repository)) continue;
229
- edited.add(repository);
230
- before.set(repository, await codeChanges(repository));
277
+ if (files.length) {
278
+ const repositories = await Promise.all(
279
+ files.map((file) => repositoryAt(path.resolve(cwd, file))),
280
+ );
281
+ for (const repository of new Set(repositories)) {
282
+ if (!repository || edited.has(repository)) continue;
283
+ edited.add(repository);
284
+ before.set(repository, fingerprint(await changedCode(repository)));
285
+ }
286
+ return;
287
+ }
288
+ const command = event.input?.command;
289
+ const folders = typeof command === "string" ? await namedFolders(cwd, command) : [];
290
+ const repositories = new Set([
291
+ ...(start.git ? [start.directory] : []),
292
+ ...(await Promise.all([...folders].map(repositoryAt))),
293
+ ...edited,
294
+ ]);
295
+ const changes = new Map();
296
+ for (const repository of repositories)
297
+ if (repository) changes.set(repository, await changedCode(repository));
298
+ running.set(event.toolCallId, changes);
299
+ });
300
+
301
+ pi.on("tool_result", async (event) => {
302
+ const changes = running.get(event.toolCallId);
303
+ if (!changes) return;
304
+ running.delete(event.toolCallId);
305
+ for (const [repository, earlier] of changes) {
306
+ if (edited.has(repository)) continue;
307
+ const now = await changedCode(repository);
308
+ if ([...now].some(([file, content]) => earlier.get(file) !== content)) {
309
+ edited.add(repository);
310
+ before.set(repository, fingerprint(earlier));
311
+ }
231
312
  }
232
313
  });
233
314
 
@@ -235,7 +316,7 @@ export default function layermap(pi) {
235
316
  if (process.env.LAYERMAP_STOP_CHECK === "0") return;
236
317
  const due = [];
237
318
  for (const repository of edited) {
238
- const changes = await codeChanges(repository);
319
+ const changes = fingerprint(await changedCode(repository));
239
320
  if (changes && changes !== before.get(repository) && changes !== checked.get(repository))
240
321
  due.push({ repository, changes });
241
322
  }