layermap 0.1.24 → 0.1.26

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
@@ -7,7 +7,6 @@ var __export = (target, all) => {
7
7
  };
8
8
 
9
9
  // src/cli.ts
10
- import { fileURLToPath as fileURLToPath3 } from "node:url";
11
10
  import { parseArgs } from "node:util";
12
11
 
13
12
  // src/agent/environment.ts
@@ -21,9 +20,9 @@ import path11 from "node:path";
21
20
  import { fileURLToPath } from "node:url";
22
21
 
23
22
  // src/layermap.ts
24
- import { createHash as createHash4 } from "node:crypto";
23
+ import { createHash as createHash4, randomUUID as randomUUID2 } from "node:crypto";
25
24
  import { mkdirSync, statSync } from "node:fs";
26
- import { lstat as lstat2, realpath as realpath2 } from "node:fs/promises";
25
+ import { lstat as lstat3, realpath as realpath2 } from "node:fs/promises";
27
26
  import path10 from "node:path";
28
27
  import { DatabaseSync } from "@photostructure/sqlite";
29
28
 
@@ -31,6 +30,7 @@ import { DatabaseSync } from "@photostructure/sqlite";
31
30
  import path3 from "node:path";
32
31
 
33
32
  // src/file-universe.ts
33
+ import { lstat } from "node:fs/promises";
34
34
  import path2 from "node:path";
35
35
 
36
36
  // src/git-runner.ts
@@ -154,17 +154,55 @@ function gitEnvironment() {
154
154
  });
155
155
  }
156
156
  var defaultGit = () => process.platform === "win32" ? findExecutable("git") ?? "git.exe" : "/usr/bin/git";
157
+ var FILTERING = /* @__PURE__ */ new Set(["diff", "status", "hash-object", "add", "stash", "update-index"]);
158
+ var subcommand = (args) => {
159
+ for (let index = 0; index < args.length; index++) {
160
+ if (args[index] === "-c" || args[index] === "-C") index++;
161
+ else if (!args[index]?.startsWith("-")) return args[index];
162
+ }
163
+ return void 0;
164
+ };
157
165
  var GitRunner = class {
158
166
  constructor(executable = defaultGit()) {
159
167
  this.executable = executable;
160
168
  }
161
169
  executable;
162
- run(args, options) {
163
- if (options.signal?.aborted) {
164
- return Promise.reject(new GitCommandError("Git command aborted."));
165
- }
170
+ async run(args, options) {
171
+ if (options.signal?.aborted) throw new GitCommandError("Git command aborted.");
166
172
  const readOnly = options.readOnly !== false;
167
- const finalArgs = readOnly ? ["--no-optional-locks", ...CONSTRAINED_CONFIG, ...args] : [...CONSTRAINED_CONFIG, ...args];
173
+ const config2 = [
174
+ ...CONSTRAINED_CONFIG,
175
+ ...FILTERING.has(subcommand(args) ?? "") ? await this.blankedFilters(options) : []
176
+ ];
177
+ return this.spawn(
178
+ readOnly ? ["--no-optional-locks", ...config2, ...args] : [...config2, ...args],
179
+ options
180
+ );
181
+ }
182
+ // Every filter driver the repository's config names, left with no program to run. Git reads its
183
+ // config without running anything; it lists none with status 1.
184
+ async blankedFilters(options) {
185
+ let listed;
186
+ try {
187
+ listed = (await this.spawn(
188
+ [...CONSTRAINED_CONFIG, "config", "--name-only", "--get-regexp", "^filter\\."],
189
+ { ...options, input: void 0 }
190
+ )).stdout.toString("utf8");
191
+ } catch (error51) {
192
+ if (error51 instanceof GitCommandError && error51.exitCode === 1) return [];
193
+ throw error51;
194
+ }
195
+ const drivers = new Set(
196
+ listed.split("\n").flatMap((key) => /^filter\.(.+)\.[^.]+$/su.exec(key)?.[1] ?? [])
197
+ );
198
+ return [...drivers].flatMap(
199
+ (driver) => ["clean=", "process=", "required=false"].flatMap((setting) => [
200
+ "-c",
201
+ `filter.${driver}.${setting}`
202
+ ])
203
+ );
204
+ }
205
+ spawn(finalArgs, options) {
168
206
  const timeoutMs = options.timeoutMs === void 0 ? 5e3 : options.timeoutMs;
169
207
  const maxOutputBytes = options.maxOutputBytes === void 0 ? 2 * 1024 * 1024 : options.maxOutputBytes;
170
208
  return new Promise((resolve, reject) => {
@@ -272,7 +310,6 @@ var FILE_UNIVERSE_ARGS = Object.freeze([
272
310
  "--",
273
311
  "."
274
312
  ]);
275
- var DELETED_FILE_ARGS = Object.freeze(["ls-files", "-z", "--deleted", "--", "."]);
276
313
  var PROJECT_EVIDENCE_FILE_UNIVERSE_POLICY = Object.freeze({
277
314
  kind: "GIT_TRACKED_AND_UNIGNORED_UNTRACKED",
278
315
  deletedPaths: "EXCLUDED",
@@ -319,52 +356,14 @@ var ProjectEvidenceFileUniverse = class {
319
356
  if (signal.aborted) {
320
357
  throw new ProjectEvidenceFileUniverseError("PROJECT_READ_CANCELLED");
321
358
  }
322
- let captured;
359
+ let listed;
323
360
  try {
324
- const stop = new AbortController();
325
- const combined = AbortSignal.any([signal, stop.signal]);
326
- let failed2 = false;
327
- let firstFailure;
328
- const results = await Promise.allSettled(
329
- [
330
- this.git.run(FILE_UNIVERSE_ARGS, {
331
- cwd: root,
332
- maxOutputBytes: null,
333
- signal: combined,
334
- timeoutMs: null
335
- }),
336
- this.git.run(DELETED_FILE_ARGS, {
337
- cwd: root,
338
- maxOutputBytes: null,
339
- signal: combined,
340
- timeoutMs: null
341
- })
342
- ].map(
343
- (work) => work.catch((error51) => {
344
- if (!failed2) {
345
- failed2 = true;
346
- firstFailure = error51;
347
- }
348
- stop.abort();
349
- throw error51;
350
- })
351
- )
352
- );
353
- const unconfirmed = results.find(
354
- (result) => result.status === "rejected" && result.reason instanceof GitCommandStopUnconfirmedError
355
- );
356
- if (unconfirmed?.status === "rejected") throw unconfirmed.reason;
357
- if (failed2) throw firstFailure;
358
- const [includedResult, deletedResult] = results;
359
- if (includedResult?.status !== "fulfilled") {
360
- throw includedResult?.status === "rejected" ? includedResult.reason : new Error("Missing file universe result.");
361
- }
362
- if (deletedResult?.status !== "fulfilled") {
363
- throw deletedResult?.status === "rejected" ? deletedResult.reason : new Error("Missing deleted-file result.");
364
- }
365
- const included = includedResult.value;
366
- const deleted2 = deletedResult.value;
367
- captured = { included: included.stdout, deleted: deleted2.stdout };
361
+ listed = (await this.git.run(FILE_UNIVERSE_ARGS, {
362
+ cwd: root,
363
+ maxOutputBytes: null,
364
+ signal,
365
+ timeoutMs: null
366
+ })).stdout;
368
367
  } catch (error51) {
369
368
  if (error51 instanceof GitCommandStopUnconfirmedError) throw error51;
370
369
  if (signal.aborted) {
@@ -372,14 +371,24 @@ var ProjectEvidenceFileUniverse = class {
372
371
  }
373
372
  throw new ProjectEvidenceFileUniverseError("PROJECT_FILE_UNIVERSE_UNAVAILABLE");
374
373
  }
374
+ const candidates = parseFileUniverse(listed);
375
+ const present = await Promise.all(
376
+ candidates.map(
377
+ (file2) => lstat(path2.join(root, ...file2.split("/"))).then(
378
+ () => true,
379
+ (error51) => {
380
+ if (error51.code === "ENOENT" || error51.code === "ENOTDIR") return false;
381
+ throw new ProjectEvidenceFileUniverseError("PROJECT_FILE_UNIVERSE_UNAVAILABLE");
382
+ }
383
+ )
384
+ )
385
+ );
375
386
  if (signal.aborted) {
376
387
  throw new ProjectEvidenceFileUniverseError("PROJECT_READ_CANCELLED");
377
388
  }
378
- const deleted = new Set(parseFileUniverse(captured.deleted));
379
- const files = Object.freeze(
380
- parseFileUniverse(captured.included).filter((candidate) => !deleted.has(candidate))
381
- );
382
- return Object.freeze({ files });
389
+ return Object.freeze({
390
+ files: Object.freeze(candidates.filter((_, index) => present[index]))
391
+ });
383
392
  }
384
393
  };
385
394
 
@@ -15131,6 +15140,8 @@ var canonicalJson = (value) => JSON.stringify(normalize(value, /* @__PURE__ */ n
15131
15140
  var digestValue = (value) => createHash("sha256").update(canonicalJson(value)).digest("hex");
15132
15141
 
15133
15142
  // src/code-commit-reader.ts
15143
+ var BATCH_BYTES = 16 * 1024 * 1024;
15144
+ var BATCH_BLOBS = 4096;
15134
15145
  var CodeCommitReader = class _CodeCommitReader {
15135
15146
  constructor(root, entries, git2, signal) {
15136
15147
  this.root = root;
@@ -15190,21 +15201,67 @@ var CodeCommitReader = class _CodeCommitReader {
15190
15201
  throw new ProjectEvidenceError("PROJECT_MAP_SOURCE_CHANGED", true);
15191
15202
  return new _CodeCommitReader(root, entries, git2, signal);
15192
15203
  }
15193
- async read(relativePath) {
15194
- const source = this.byPath.get(relativePath);
15195
- if (!source) throw new ProjectEvidenceError("PROJECT_CODE_TREE_INVALID", false);
15196
- const base = { path: relativePath, byteLength: source.bytes };
15197
- if (!isProjectEvidenceTextPath(relativePath))
15198
- return { entry: { ...base, state: "TYPE_RESTRICTED" } };
15199
- if (source.mode === "120000") return { entry: { ...base, state: "SYMLINK" } };
15200
- if (source.mode !== "100644" && source.mode !== "100755")
15201
- return { entry: { ...base, state: "UNSUPPORTED_ENTRY" } };
15202
- const content = (await this.git.run(["--no-replace-objects", "cat-file", "blob", source.object], {
15204
+ /**
15205
+ * Reads the files at the given paths in their order, many blobs to a Git process: one process
15206
+ * per blob made capturing a commit take seconds per thousand files.
15207
+ */
15208
+ async readAll(paths) {
15209
+ const reads = [];
15210
+ let batch = [];
15211
+ let bytes = 0;
15212
+ const flush = async () => {
15213
+ const contents = await this.blobs(batch.map(({ source }) => source.object));
15214
+ for (const [position, { index, source }] of batch.entries())
15215
+ reads[index] = this.blobRead(source, contents[position]);
15216
+ batch = [];
15217
+ bytes = 0;
15218
+ };
15219
+ for (const [index, relativePath] of paths.entries()) {
15220
+ const source = this.byPath.get(relativePath);
15221
+ if (!source) throw new ProjectEvidenceError("PROJECT_CODE_TREE_INVALID", false);
15222
+ const base = { path: relativePath, byteLength: source.bytes };
15223
+ if (!isProjectEvidenceTextPath(relativePath))
15224
+ reads[index] = { entry: { ...base, state: "TYPE_RESTRICTED" } };
15225
+ else if (source.mode === "120000") reads[index] = { entry: { ...base, state: "SYMLINK" } };
15226
+ else if (source.mode !== "100644" && source.mode !== "100755")
15227
+ reads[index] = { entry: { ...base, state: "UNSUPPORTED_ENTRY" } };
15228
+ else {
15229
+ if (batch.length && (bytes + source.bytes > BATCH_BYTES || batch.length === BATCH_BLOBS))
15230
+ await flush();
15231
+ batch.push({ index, source });
15232
+ bytes += source.bytes;
15233
+ }
15234
+ }
15235
+ if (batch.length) await flush();
15236
+ return reads;
15237
+ }
15238
+ // Git prints each blob as "<object> blob <size>", a newline, its bytes and a newline.
15239
+ async blobs(objects2) {
15240
+ const output = (await this.git.run(["--no-replace-objects", "cat-file", "--batch"], {
15203
15241
  cwd: this.root,
15242
+ input: Buffer.from(objects2.map((object2) => `${object2}
15243
+ `).join("")),
15204
15244
  signal: this.signal,
15205
15245
  timeoutMs: null,
15206
15246
  maxOutputBytes: null
15207
15247
  })).stdout;
15248
+ const contents = [];
15249
+ let offset = 0;
15250
+ for (const object2 of objects2) {
15251
+ const end = output.indexOf(10, offset);
15252
+ const header2 = /^([a-f0-9]+) blob ([0-9]+)$/u.exec(output.toString("utf8", offset, end));
15253
+ const start = end + 1;
15254
+ const size = Number(header2?.[2]);
15255
+ if (end < 0 || header2?.[1] !== object2 || output[start + size] !== 10)
15256
+ throw new ProjectEvidenceError("PROJECT_CODE_BLOB_INVALID", false);
15257
+ contents.push(output.subarray(start, start + size));
15258
+ offset = start + size + 1;
15259
+ }
15260
+ if (offset !== output.length)
15261
+ throw new ProjectEvidenceError("PROJECT_CODE_BLOB_INVALID", false);
15262
+ return contents;
15263
+ }
15264
+ blobRead(source, content) {
15208
15265
  const objectHash = createHash2(source.object.length === 64 ? "sha256" : "sha1").update(`blob ${content.byteLength}\0`).update(content).digest("hex");
15209
15266
  if (content.byteLength !== source.bytes || objectHash !== source.object)
15210
15267
  throw new ProjectEvidenceError("PROJECT_CODE_BLOB_INVALID", false);
@@ -15215,13 +15272,21 @@ var CodeCommitReader = class _CodeCommitReader {
15215
15272
  } catch {
15216
15273
  text = false;
15217
15274
  }
15218
- return { entry: { ...base, state: text ? "TEXT" : "NON_TEXT", contentDigest }, content };
15275
+ return {
15276
+ entry: {
15277
+ path: source.path,
15278
+ byteLength: source.bytes,
15279
+ state: text ? "TEXT" : "NON_TEXT",
15280
+ contentDigest
15281
+ },
15282
+ content
15283
+ };
15219
15284
  }
15220
15285
  };
15221
15286
 
15222
15287
  // src/code-worktree-reader.ts
15223
15288
  import { constants as fsConstants } from "node:fs";
15224
- import { lstat, open, realpath } from "node:fs/promises";
15289
+ import { lstat as lstat2, open, realpath } from "node:fs/promises";
15225
15290
  import path5 from "node:path";
15226
15291
  var fileSystemErrorCode = (error51) => {
15227
15292
  if (typeof error51 !== "object" || error51 === null || !("code" in error51)) return void 0;
@@ -15231,7 +15296,7 @@ var isInsideRoot = (root, candidate) => {
15231
15296
  const relative = path5.relative(root, candidate);
15232
15297
  return relative === "" || !relative.startsWith(`..${path5.sep}`) && relative !== "..";
15233
15298
  };
15234
- var stablePathFingerprint = (stats) => [
15299
+ var stablePathFingerprint = (stats) => (stats.isDirectory() ? ["directory", stats.dev, stats.ino] : [
15235
15300
  stats.dev,
15236
15301
  stats.ino,
15237
15302
  stats.mode,
@@ -15244,7 +15309,7 @@ var stablePathFingerprint = (stats) => [
15244
15309
  stats.blocks,
15245
15310
  stats.mtimeNs,
15246
15311
  stats.ctimeNs
15247
- ].map(String).join(":");
15312
+ ]).map(String).join(":");
15248
15313
  var StableProjectCaptureSession = class _StableProjectCaptureSession {
15249
15314
  constructor(root, rootDevice, rootInode, signal) {
15250
15315
  this.root = root;
@@ -15382,7 +15447,7 @@ var StableProjectCaptureSession = class _StableProjectCaptureSession {
15382
15447
  async assertStable() {
15383
15448
  for (const [absolutePath, expected] of this.pathFingerprints) {
15384
15449
  this.assertNotAborted();
15385
- const current = await lstat(absolutePath, { bigint: true }).catch(() => {
15450
+ const current = await lstat2(absolutePath, { bigint: true }).catch(() => {
15386
15451
  throw new ProjectEvidenceError(this.changeCode(absolutePath), true);
15387
15452
  });
15388
15453
  if (stablePathFingerprint(current) !== expected) {
@@ -15403,7 +15468,7 @@ var StableProjectCaptureSession = class _StableProjectCaptureSession {
15403
15468
  let finalStats;
15404
15469
  for (const [index, currentPath] of paths.entries()) {
15405
15470
  this.assertNotAborted();
15406
- const stats = await lstat(currentPath, { bigint: true }).catch(() => {
15471
+ const stats = await lstat2(currentPath, { bigint: true }).catch(() => {
15407
15472
  throw new ProjectEvidenceError(this.changeCode(currentPath), true);
15408
15473
  });
15409
15474
  const isFinal = index === paths.length - 1;
@@ -15579,7 +15644,7 @@ var CodeIndexCapture = class {
15579
15644
  if (relative === void 0) break;
15580
15645
  try {
15581
15646
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
15582
- const read = commit ? await commit.read(relative) : await session.captureFile(relative);
15647
+ const read = await session.captureFile(relative);
15583
15648
  capturedBytes += read.content?.byteLength ?? 0;
15584
15649
  entries.push(read.entry);
15585
15650
  processedFiles++;
@@ -15591,12 +15656,25 @@ var CodeIndexCapture = class {
15591
15656
  }
15592
15657
  }
15593
15658
  };
15594
- await Promise.all(
15595
- Array.from(
15596
- { length: Math.min(paths.length, PROJECT_EVIDENCE_POLICY_DESCRIPTOR.captureConcurrency) },
15597
- worker
15598
- )
15599
- );
15659
+ if (commit) {
15660
+ const reads = await commit.readAll(paths).catch((error51) => {
15661
+ if (signal.aborted && !(error51 instanceof GitCommandStopUnconfirmedError))
15662
+ throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
15663
+ throw error51;
15664
+ });
15665
+ for (const read of reads) {
15666
+ capturedBytes += read.content?.byteLength ?? 0;
15667
+ entries.push(read.entry);
15668
+ }
15669
+ processedFiles = paths.length;
15670
+ progress();
15671
+ } else
15672
+ await Promise.all(
15673
+ Array.from(
15674
+ { length: Math.min(paths.length, PROJECT_EVIDENCE_POLICY_DESCRIPTOR.captureConcurrency) },
15675
+ worker
15676
+ )
15677
+ );
15600
15678
  if (failed2) throw failure;
15601
15679
  await session.assertStable();
15602
15680
  if (snapshot) {
@@ -18699,7 +18777,7 @@ var PythonMapAnalyzer = class {
18699
18777
 
18700
18778
  // src/project-map-language-typescript.ts
18701
18779
  var TYPESCRIPT_MAP_LANGUAGE = Object.freeze({
18702
- id: "typescript-7.0.2-map-v17",
18780
+ id: "typescript-7.0.2-map-v18",
18703
18781
  claims: (path14) => /\.[cm]?[jt]sx?$/u.test(path14),
18704
18782
  reads: (path14) => path14.endsWith(".json") || path14 === "pnpm-workspace.yaml",
18705
18783
  create: () => new TypeScriptMapAnalyzer()
@@ -20166,16 +20244,14 @@ var ProjectMapQuery = class {
20166
20244
 
20167
20245
  // src/project-map-source.ts
20168
20246
  var ProjectMapSourceReader = class _ProjectMapSourceReader {
20169
- constructor(session, commit, universe, snapshot, signal) {
20247
+ constructor(session, commit, snapshot, signal) {
20170
20248
  this.session = session;
20171
20249
  this.commit = commit;
20172
- this.universe = universe;
20173
20250
  this.snapshot = snapshot;
20174
20251
  this.signal = signal;
20175
20252
  }
20176
20253
  session;
20177
20254
  commit;
20178
- universe;
20179
20255
  snapshot;
20180
20256
  signal;
20181
20257
  static async open(source, signal, enumerate = true, selectedPath) {
@@ -20188,33 +20264,47 @@ var ProjectMapSourceReader = class _ProjectMapSourceReader {
20188
20264
  source.directory.inode,
20189
20265
  signal
20190
20266
  );
20191
- const universe = new ProjectEvidenceFileUniverse();
20192
20267
  const commit = source.kind === "COMMIT" ? await CodeCommitReader.open(session.root, source.commit, signal, selectedPath) : void 0;
20193
- const snapshot = source.kind === "WORKTREE" && enumerate ? await universe.capture(session.root, signal) : void 0;
20194
- return new _ProjectMapSourceReader(session, commit, universe, snapshot, signal);
20268
+ const snapshot = source.kind === "WORKTREE" && enumerate ? await new ProjectEvidenceFileUniverse().capture(session.root, signal) : void 0;
20269
+ return new _ProjectMapSourceReader(session, commit, snapshot, signal);
20195
20270
  }
20196
20271
  paths() {
20197
20272
  return this.snapshot?.files ?? this.commit?.entries.map((entry) => entry.path) ?? [];
20198
20273
  }
20199
- async read(relative, expected) {
20274
+ /** Reads a file and checks it still has the content captured. */
20275
+ async read(expected) {
20276
+ return (await this.readAll([expected]))[0];
20277
+ }
20278
+ /**
20279
+ * Reads files in their order and checks each still has the content captured: a commit's many
20280
+ * blobs to a Git process, a directory's files several at a time.
20281
+ */
20282
+ async readAll(expected) {
20200
20283
  if (this.signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
20201
- assertProjectEvidencePathNotSensitive(relative);
20202
- if (isProjectEvidenceTraversalExcluded(relative))
20203
- throw new ProjectEvidenceError("PROJECT_FILE_NOT_ALLOWED", false);
20204
- const result = this.commit ? await this.commit.read(relative) : await this.session.captureFile(relative);
20205
- if (expected && (result.entry.state !== expected.state || result.entry.contentDigest !== expected.contentDigest || result.entry.byteLength !== expected.byteLength)) {
20206
- throw new ProjectEvidenceError("PROJECT_MAP_SOURCE_CHANGED", true);
20284
+ const paths = expected.map(({ path: path14 }) => {
20285
+ assertProjectEvidencePathNotSensitive(path14);
20286
+ if (isProjectEvidenceTraversalExcluded(path14))
20287
+ throw new ProjectEvidenceError("PROJECT_FILE_NOT_ALLOWED", false);
20288
+ return path14;
20289
+ });
20290
+ const results = this.commit ? await this.commit.readAll(paths) : await concurrently(paths, (path14) => this.session.captureFile(path14));
20291
+ for (const [index, { entry }] of results.entries()) {
20292
+ const wanted = expected[index];
20293
+ if (entry.state !== wanted?.state || entry.contentDigest !== wanted.contentDigest || entry.byteLength !== wanted.byteLength)
20294
+ throw new ProjectEvidenceError("PROJECT_MAP_SOURCE_CHANGED", true);
20207
20295
  }
20208
- return result;
20296
+ return results;
20209
20297
  }
20210
- async assertStable() {
20211
- await this.session.assertStable();
20212
- if (this.snapshot)
20213
- await this.universe.assertCurrent(this.session.root, this.snapshot, this.signal);
20214
- await this.session.assertStable();
20298
+ /**
20299
+ * The files read are unchanged and the directories holding them the same. Files added or removed
20300
+ * since the reader opened do not count: what was read is a capture's files, which reads of each
20301
+ * against its captured digest confirm.
20302
+ */
20303
+ assertStable() {
20304
+ return this.session.assertStable();
20215
20305
  }
20216
20306
  };
20217
- async function readAll(items, read) {
20307
+ async function concurrently(items, read) {
20218
20308
  const results = [];
20219
20309
  let next = 0;
20220
20310
  let failed2 = false;
@@ -20258,10 +20348,10 @@ var ProjectMapReadSession = class {
20258
20348
  this.worktree ??= await ProjectMapSourceReader.open(this.source, this.signal, false);
20259
20349
  const reader = this.worktree ?? await ProjectMapSourceReader.open(this.source, this.signal, false, entry.path);
20260
20350
  for (const configuration of this.pendingConfigurations(entry)) {
20261
- await reader.read(configuration.path, configuration);
20351
+ await reader.read(configuration);
20262
20352
  this.configurations.add(configuration.path);
20263
20353
  }
20264
- const result = await reader.read(entry.path, entry);
20354
+ const result = await reader.read(entry);
20265
20355
  if (!result.content) throw new ProjectEvidenceError("PROJECT_MAP_SOURCE_CHANGED", true);
20266
20356
  this.configurations.add(entry.path);
20267
20357
  if (!this.worktree) await reader.assertStable();
@@ -20864,7 +20954,7 @@ var CodeIndexStore = class {
20864
20954
  appendMapStage(buildRef, analysis, record2 = {}) {
20865
20955
  if (analysis.requiredFiles.length)
20866
20956
  throw new ProjectEvidenceError("PROJECT_MAP_CONTEXT_INCOMPLETE", false);
20867
- this.database.exec("BEGIN IMMEDIATE");
20957
+ this.database.exec("BEGIN");
20868
20958
  try {
20869
20959
  const insert = this.database.prepare(
20870
20960
  "INSERT INTO project_map_staging (build_ref, kind, value_json) VALUES (?, ?, ?)"
@@ -21271,14 +21361,24 @@ var CodeIndexStore = class {
21271
21361
  complete: complete && indexedFiles === snapshot.readableTextFileCount
21272
21362
  };
21273
21363
  }
21274
- collectGarbage(referencedVersions) {
21275
- const retained = new Set(referencedVersions);
21364
+ /**
21365
+ * Deletes the versions not retained, with what only they list, and returns how many went. The
21366
+ * versions to retain are read in the same transaction.
21367
+ */
21368
+ collectGarbage(retained) {
21276
21369
  this.database.exec("BEGIN IMMEDIATE");
21277
21370
  try {
21371
+ const kept = new Set(retained());
21372
+ let removed = 0;
21278
21373
  for (const row of this.database.prepare("SELECT version_ref FROM project_code_versions").all()) {
21279
21374
  const version2 = String(row.version_ref);
21280
- if (retained.has(version2)) continue;
21375
+ if (kept.has(version2)) continue;
21281
21376
  this.database.prepare("DELETE FROM project_code_versions WHERE version_ref = ?").run(version2);
21377
+ removed++;
21378
+ }
21379
+ if (!removed) {
21380
+ this.database.exec("COMMIT");
21381
+ return 0;
21282
21382
  }
21283
21383
  this.database.exec(`DELETE FROM project_map_units WHERE NOT EXISTS (
21284
21384
  SELECT 1 FROM project_map_version_units version WHERE version.unit_ref = project_map_units.unit_ref)`);
@@ -21292,6 +21392,7 @@ var CodeIndexStore = class {
21292
21392
  this.database.prepare(`DELETE FROM project_map_navigation_documents
21293
21393
  WHERE document_ref IN (SELECT value FROM json_each(?))`).run(orphans);
21294
21394
  this.database.exec("COMMIT");
21395
+ return removed;
21295
21396
  } catch (error51) {
21296
21397
  this.database.exec("ROLLBACK");
21297
21398
  throw error51;
@@ -21437,13 +21538,12 @@ var ProjectMapAnalyzer = class {
21437
21538
  const state = parent.state(contextRef2);
21438
21539
  return state === void 0 ? void 0 : { state, digests: parent.entries };
21439
21540
  };
21440
- const read = async (entry) => {
21441
- if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
21442
- const value = await reader.read(entry.path, entry);
21443
- if (!value.content) throw new ProjectEvidenceError("PROJECT_MAP_SOURCE_CHANGED", true);
21541
+ const decode3 = (value) => {
21542
+ if (!value?.content) throw new ProjectEvidenceError("PROJECT_MAP_SOURCE_CHANGED", true);
21444
21543
  return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(value.content);
21445
21544
  };
21446
- const contents = await readAll(readable, read);
21545
+ const read = async (entry) => decode3(await reader.read(entry));
21546
+ const contents = (await reader.readAll(readable)).map(decode3);
21447
21547
  const unitTexts = /* @__PURE__ */ Object.create(null);
21448
21548
  for (const [index, entry] of readable.entries())
21449
21549
  unitTexts[entry.path] = contents[index];
@@ -21646,7 +21746,7 @@ ${scope}`, input.cursor, 2) : [];
21646
21746
  });
21647
21747
  const reader = await ProjectMapSourceReader.open(source, signal, false);
21648
21748
  const files = /* @__PURE__ */ Object.create(null);
21649
- const contents = await readAll(entries, (entry) => reader.read(entry.path, entry));
21749
+ const contents = await reader.readAll(entries);
21650
21750
  for (const [index, entry] of entries.entries()) {
21651
21751
  const value = contents[index];
21652
21752
  if (!value?.content) throw new ProjectEvidenceError("PROJECT_MAP_SOURCE_CHANGED", true);
@@ -21805,7 +21905,7 @@ var CodeIndex = class {
21805
21905
  (unit, record2) => this.store.appendMapStage(stage, unit, record2),
21806
21906
  parent && { ...parent, link: (paths) => linked.push(...paths) }
21807
21907
  );
21808
- await readAll(result.entries, (entry) => reader.read(entry.path, entry));
21908
+ await reader.readAll(result.entries);
21809
21909
  await reader.assertStable();
21810
21910
  if (controller.signal.aborted)
21811
21911
  throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
@@ -22650,7 +22750,7 @@ function parseMapDiff(text) {
22650
22750
  ];
22651
22751
  if (oldCount > 0) current.baseLines.push([oldStart, oldStart + oldCount - 1]);
22652
22752
  current.lines.push(
22653
- newCount > 0 ? [newStart, newStart + newCount - 1] : [Math.max(newStart, 1), newStart + 1]
22753
+ newCount > 0 ? [newStart, newStart + newCount - 1] : [newStart + 1, newStart]
22654
22754
  );
22655
22755
  }
22656
22756
  }
@@ -22675,6 +22775,12 @@ var NON_CODE = [
22675
22775
  var nonCodeKind = (path14) => NON_CODE.find(([pattern]) => pattern.test(path14))?.[1];
22676
22776
  var LIMITS = Object.freeze({ depth: 8, declarations: 800, changed: 200, chain: 3, byName: 40 });
22677
22777
  var CALLER_KINDS = /* @__PURE__ */ new Set(["CALLS", "REFERENCES"]);
22778
+ var NAMING_KINDS = /* @__PURE__ */ new Set(["CALLS", "REFERENCES", "EXTENDS", "IMPLEMENTS"]);
22779
+ var USED_BY = {
22780
+ EXTENDS: "extended",
22781
+ IMPLEMENTS: "implemented",
22782
+ OVERRIDES: "overridden"
22783
+ };
22678
22784
  var IMPORT_KINDS3 = /* @__PURE__ */ new Set(["IMPORTS", "TEST_IMPORTS"]);
22679
22785
  var ROUTE2 = /^(?:[A-Z]+(?:\|[A-Z]+)* +)?\/\S*$/u;
22680
22786
  var areaOf = (file2) => /\.(?:go|java|kt)$/u.test(file2) ? file2.slice(0, file2.lastIndexOf("/") + 1) || "./" : file2;
@@ -22771,13 +22877,38 @@ var Tracer = class {
22771
22877
  if (this.callerCount.get(reached.ref) !== 0) continue;
22772
22878
  const object2 = this.graph.object(reached.ref);
22773
22879
  if (testCode(object2.anchor.path) || this.routes.has(reached.ref)) continue;
22774
- if (reached.depth === 0)
22880
+ if (reached.depth === 0) {
22881
+ const uses = this.usesWithoutCalls(reached.ref);
22775
22882
  this.unclear.push(
22776
- `${this.where(reached.ref)} has no callers in the map: it may be wired by a framework, called dynamically, or unused`
22883
+ uses.length ? `${this.where(reached.ref)} has no callers in the map, and is used without a call: ${uses.join("; ")}` : `${this.where(reached.ref)} has no callers in the map: it may be wired by a framework, called dynamically, or unused`
22777
22884
  );
22778
- else this.entry(this.where(reached.ref), false, reached, void 0, reached.certain, true);
22885
+ } else this.entry(this.where(reached.ref), false, reached, void 0, reached.certain, true);
22779
22886
  }
22780
22887
  }
22888
+ /**
22889
+ * The uses outside tests the map sees of a declaration besides calls: a class others extend or
22890
+ * implement, a member that overrides another or that others override, and a decorator that may
22891
+ * wire it to be run (a route, a task, a registry). A decorator of the language's own library
22892
+ * (dataclass, staticmethod) only shapes the declaration. Reading a value is a reference, so a
22893
+ * caller; writing one is not a use, as a value nothing reads is unused.
22894
+ */
22895
+ usesWithoutCalls(ref) {
22896
+ const uses = [];
22897
+ for (const relation of this.graph.relationsTo([ref])) {
22898
+ const verb = USED_BY[relation.kind];
22899
+ const owner = this.graph.owner(relation.from);
22900
+ if (verb && owner !== ref && !testCode(this.graph.object(owner).anchor.path))
22901
+ uses.push(`${verb} by ${this.where(owner)}`);
22902
+ }
22903
+ for (const relation of this.graph.relationsFrom([ref]))
22904
+ if (relation.kind === "OVERRIDES")
22905
+ uses.push(
22906
+ `overrides ${relation.to === void 0 ? relation.target : this.where(this.graph.owner(relation.to))}`
22907
+ );
22908
+ else if (relation.kind === "DECORATED_BY" && relation.unresolvedReason !== "COMPILER_LIBRARY")
22909
+ uses.push(`decorated by ${relation.target}`);
22910
+ return [...new Set(uses)];
22911
+ }
22781
22912
  callers(ref) {
22782
22913
  const callers = [];
22783
22914
  for (const relation of this.graph.relationsTo([ref]))
@@ -22891,6 +23022,10 @@ function mapChangeImpact(store, working, base, changes, project) {
22891
23022
  const importers = /* @__PURE__ */ new Map();
22892
23023
  let mapped;
22893
23024
  const mappedPaths = () => mapped ??= store.database.prepare("SELECT DISTINCT path FROM project_map_objects WHERE version_ref = ?").all(working).map((row) => String(row.path));
23025
+ const topLevelChanged = (path14) => {
23026
+ const note = `top-level code of ${path14} changed (imports, constants or registrations)`;
23027
+ if (!unclear.includes(note)) unclear.push(note);
23028
+ };
22894
23029
  for (const file2 of changes.files) {
22895
23030
  if (file2.binary) continue;
22896
23031
  const kind = nonCodeKind(file2.path);
@@ -22910,7 +23045,7 @@ function mapChangeImpact(store, working, base, changes, project) {
22910
23045
  const containing = inFile.filter(
22911
23046
  (object2) => object2.anchor.startLine <= to && from <= object2.anchor.endLine
22912
23047
  );
22913
- if (!containing.length) topLevel = true;
23048
+ if (!containing.length && from <= to) topLevel = true;
22914
23049
  for (const object2 of containing)
22915
23050
  if (!containing.some(
22916
23051
  (other) => other !== object2 && object2.anchor.start <= other.anchor.start && other.anchor.end <= object2.anchor.end && other.anchor.startLine <= to && from <= other.anchor.endLine
@@ -22933,8 +23068,7 @@ function mapChangeImpact(store, working, base, changes, project) {
22933
23068
  unclear.push(
22934
23069
  `the registration of ${JSON.stringify(relation.argument)} at ${relation.anchor.path}:${relation.anchor.startLine} changed; check that the route still reaches the right handler`
22935
23070
  );
22936
- if (analyzed && topLevel && file2.status !== "ADDED")
22937
- unclear.push(`top-level code of ${file2.path} changed (imports, constants or registrations)`);
23071
+ if (analyzed && topLevel && file2.status !== "ADDED") topLevelChanged(file2.path);
22938
23072
  importerTests(graph, objects2, tracer, importers);
22939
23073
  sameDirectoryTests(mappedPaths(), file2.path, tracer);
22940
23074
  mirroredTests(mappedPaths(), file2.path, tracer);
@@ -22962,6 +23096,22 @@ function mapChangeImpact(store, working, base, changes, project) {
22962
23096
  if (names.length) rewrittenTests.push({ path: file2.path, names });
22963
23097
  }
22964
23098
  const beforeTracer = new Tracer(before, cache.memberCalls(store, base));
23099
+ const changedIn = new Map(
23100
+ changes.files.flatMap((file2) => file2.basePath ? [[file2.basePath, file2]] : [])
23101
+ );
23102
+ const same2 = (g, ref) => `${g.object(ref).kind}\0${g.qualifiedName(ref)}`;
23103
+ const stillUses = (relation, user) => {
23104
+ const file2 = changedIn.get(relation.anchor.path);
23105
+ if (file2 && (file2.status === "DELETED" || overlaps(file2.baseLines, relation.anchor.startLine, relation.anchor.endLine)))
23106
+ return false;
23107
+ const name = same2(before, user);
23108
+ const now = graph.objectsAt(file2?.path ?? relation.anchor.path).find((object2) => same2(graph, object2.id) === name);
23109
+ if (!now || relation.to === void 0) return true;
23110
+ const used = same2(before, relation.to);
23111
+ return !graph.relationsFrom(graph.scope(now.id).refs).some(
23112
+ (use) => NAMING_KINDS.has(use.kind) && use.to !== void 0 && same2(graph, use.to) === used
23113
+ );
23114
+ };
22965
23115
  const gone = [];
22966
23116
  for (const file2 of changes.files) {
22967
23117
  if (!file2.basePath || !file2.baseLines.length || file2.binary || testCode(file2.basePath))
@@ -22977,11 +23127,37 @@ function mapChangeImpact(store, working, base, changes, project) {
22977
23127
  const parent = before.parent(object2.id);
22978
23128
  if (parent && !mapIsModule(before.object(parent)) && gone.includes(parent)) continue;
22979
23129
  gone.push(object2.id);
22980
- removed.push(
22981
- `${file2.basePath}: ${before.qualifiedName(object2.id)} ${mapDeclarationLabel(object2)}`
22982
- );
23130
+ const inside = (ref) => {
23131
+ for (let at = ref; at !== void 0; at = before.parent(at))
23132
+ if (at === object2.id) return true;
23133
+ return false;
23134
+ };
23135
+ const usedBy = /* @__PURE__ */ new Set();
23136
+ for (const relation of before.relationsTo(
23137
+ before.objectsAt(file2.basePath).filter((member) => inside(member.id)).map((member) => member.id)
23138
+ )) {
23139
+ const owner = before.owner(relation.from);
23140
+ if (!NAMING_KINDS.has(relation.kind) || inside(owner) || !stillUses(relation, owner))
23141
+ continue;
23142
+ const user = before.object(owner);
23143
+ usedBy.add(
23144
+ `${user.anchor.path}: ${mapIsModule(user) ? "top-level code" : before.qualifiedName(owner)}`
23145
+ );
23146
+ }
23147
+ removed.push({
23148
+ declaration: `${file2.basePath}: ${before.qualifiedName(object2.id)} ${mapDeclarationLabel(object2)}`,
23149
+ usedBy: [...usedBy].sort()
23150
+ });
22983
23151
  }
22984
23152
  }
23153
+ for (const file2 of changes.files) {
23154
+ if (!file2.basePath || file2.status === "DELETED" || testCode(file2.basePath)) continue;
23155
+ const module = before.objectsAt(file2.basePath).find(mapIsModule);
23156
+ if (module && mapLanguageOf(file2.basePath) !== void 0 && before.relationsFrom(before.scope(module.id).refs).some(
23157
+ (relation) => relation.kind !== "CONTAINS" && overlaps(file2.baseLines, relation.anchor.startLine, relation.anchor.endLine)
23158
+ ))
23159
+ topLevelChanged(file2.path);
23160
+ }
22985
23161
  if (gone.length) {
22986
23162
  beforeTracer.trace(gone);
22987
23163
  for (const entry of beforeTracer.entries.values())
@@ -23028,7 +23204,8 @@ function mapChangeImpact(store, working, base, changes, project) {
23028
23204
  const now = declarations2(graph, path14).find(
23029
23205
  (candidate) => candidate.kind === object2.kind && graph.qualifiedName(candidate.id) === name
23030
23206
  );
23031
- if (!now || outsideTests(tracer.callers(now.id), graph).length) continue;
23207
+ if (!now || outsideTests(tracer.callers(now.id), graph).length || tracer.usesWithoutCalls(now.id).length)
23208
+ continue;
23032
23209
  if (!outsideTests(beforeTracer.callers(ref), before).length) continue;
23033
23210
  const tested = tracer.callers(now.id).length > 0;
23034
23211
  uncalled.push(
@@ -23278,12 +23455,19 @@ Nothing changed against ${changes.base}.`;
23278
23455
  };
23279
23456
  list("CHANGED", impact.changed, LIST.changed);
23280
23457
  list(
23281
- "REMOVED OR RENAMED (their callers in the base still refer to them)",
23282
- impact.removed,
23458
+ "REMOVED OR RENAMED, STILL USED (code the diff did not change still calls or uses them: update it, or keep the old name)",
23459
+ impact.removed.filter(({ usedBy }) => usedBy.length).map(
23460
+ ({ declaration, usedBy }) => `${declaration} \u2190 ${usedBy.slice(0, LIST.names).join(", ")}${usedBy.length > LIST.names ? ` (+${usedBy.length - LIST.names})` : ""}`
23461
+ ),
23462
+ LIST.changed
23463
+ );
23464
+ list(
23465
+ "REMOVED OR RENAMED (no code the diff left unchanged uses them)",
23466
+ impact.removed.filter(({ usedBy }) => !usedBy.length).map(({ declaration }) => declaration),
23283
23467
  LIST.changed
23284
23468
  );
23285
23469
  list(
23286
- "LEFT WITHOUT CALLERS (the diff removed or changed their last callers; nothing outside tests calls them now)",
23470
+ "LEFT WITHOUT CALLERS (the diff removed or changed their last callers; nothing outside tests calls or otherwise uses them now)",
23287
23471
  impact.uncalled,
23288
23472
  LIST.changed
23289
23473
  );
@@ -23429,29 +23613,58 @@ Nothing changed against ${changes.base}.`;
23429
23613
  }
23430
23614
 
23431
23615
  // src/layermap.ts
23432
- var SCHEMA_VERSION = 2;
23616
+ var SCHEMA_VERSION = 3;
23433
23617
  var KEEP_VERSIONS = 3;
23618
+ var KEEP_COMMIT_VERSIONS = 2;
23619
+ var HOLD_EXPIRY_MS = 10 * 60 * 1e3;
23434
23620
  var BUSY_TIMEOUT = "PRAGMA busy_timeout = 30000;";
23435
23621
  var JOURNAL_LIMIT = 32 * 1024 * 1024;
23622
+ var CAPTURE_ATTEMPTS = 3;
23623
+ var CAPTURE_AGAIN = /* @__PURE__ */ new Set([
23624
+ "PROJECT_FILE_CHANGED",
23625
+ "PROJECT_FILE_UNIVERSE_CHANGED",
23626
+ "PROJECT_MAP_SOURCE_CHANGED",
23627
+ "PROJECT_READ_SOURCE_CHANGED",
23628
+ "PROJECT_EVIDENCE_REVISION_NOT_FOUND"
23629
+ ]);
23630
+ var LAYERMAP_TABLES = `
23631
+ CREATE TABLE layermap_version_holds (
23632
+ version_ref TEXT NOT NULL REFERENCES project_code_versions(version_ref) ON DELETE CASCADE,
23633
+ holder TEXT NOT NULL,
23634
+ held_at INTEGER NOT NULL,
23635
+ PRIMARY KEY (version_ref, holder)
23636
+ );
23637
+ CREATE TABLE layermap_commit_versions (
23638
+ capture_key TEXT PRIMARY KEY,
23639
+ version_ref TEXT NOT NULL REFERENCES project_code_versions(version_ref) ON DELETE CASCADE,
23640
+ used_at INTEGER NOT NULL
23641
+ );
23642
+ CREATE INDEX layermap_commit_version ON layermap_commit_versions(version_ref);
23643
+ `;
23644
+ var schemaVersion = (database) => Number(database.prepare("PRAGMA user_version").get()?.user_version ?? 0);
23436
23645
  function openMapDatabase(file2) {
23437
23646
  mkdirSync(path10.dirname(file2), { recursive: true, mode: 448 });
23438
23647
  const database = new DatabaseSync(file2);
23439
23648
  try {
23440
23649
  database.exec(BUSY_TIMEOUT);
23441
- const version2 = Number(database.prepare("PRAGMA user_version").get()?.user_version ?? 0);
23650
+ const version2 = schemaVersion(database);
23442
23651
  if (version2 > SCHEMA_VERSION) throw new ProjectEvidenceError("LAYERMAP_DATABASE_NEWER", false);
23443
23652
  if (version2 === 0) database.exec("PRAGMA auto_vacuum = INCREMENTAL;");
23653
+ else if (version2 === 1) database.exec("PRAGMA auto_vacuum = INCREMENTAL; VACUUM;");
23444
23654
  database.exec("PRAGMA journal_mode = WAL;");
23445
- if (version2 === 0) {
23655
+ if (version2 < SCHEMA_VERSION) {
23446
23656
  database.exec("PRAGMA foreign_keys = OFF; BEGIN IMMEDIATE;");
23447
23657
  try {
23448
- for (const sql of [
23449
- CODE_INDEX_SCHEMA,
23450
- CODE_INDEX_UNITS_MIGRATION,
23451
- CODE_INDEX_CONTEXT_RESULTS_MIGRATION,
23452
- CODE_INDEX_SHARED_NAVIGATION_MIGRATION
23453
- ])
23454
- database.exec(sql);
23658
+ const current = schemaVersion(database);
23659
+ if (current === 0)
23660
+ for (const sql of [
23661
+ CODE_INDEX_SCHEMA,
23662
+ CODE_INDEX_UNITS_MIGRATION,
23663
+ CODE_INDEX_CONTEXT_RESULTS_MIGRATION,
23664
+ CODE_INDEX_SHARED_NAVIGATION_MIGRATION
23665
+ ])
23666
+ database.exec(sql);
23667
+ if (current < 3) database.exec(LAYERMAP_TABLES);
23455
23668
  if (database.prepare("PRAGMA foreign_key_check").get())
23456
23669
  throw new ProjectEvidenceError("PROJECT_EVIDENCE_STORE_CORRUPT", false);
23457
23670
  database.exec(`PRAGMA user_version = ${SCHEMA_VERSION}; COMMIT;`);
@@ -23459,10 +23672,6 @@ function openMapDatabase(file2) {
23459
23672
  database.exec("ROLLBACK");
23460
23673
  throw error51;
23461
23674
  }
23462
- } else if (version2 === 1) {
23463
- database.exec(
23464
- `PRAGMA auto_vacuum = INCREMENTAL; VACUUM; PRAGMA user_version = ${SCHEMA_VERSION};`
23465
- );
23466
23675
  }
23467
23676
  database.exec("PRAGMA foreign_keys = ON;");
23468
23677
  return database;
@@ -23478,11 +23687,12 @@ var mapDatabasePath = (cacheDirectory2, canonicalProject) => path10.join(
23478
23687
  "map.sqlite"
23479
23688
  );
23480
23689
  var LayerMap = class _LayerMap {
23481
- constructor(project, source, store, index, budget, journal) {
23690
+ constructor(project, source, store, index, analyzer, budget, journal) {
23482
23691
  this.project = project;
23483
23692
  this.source = source;
23484
23693
  this.store = store;
23485
23694
  this.index = index;
23695
+ this.analyzer = analyzer;
23486
23696
  this.budget = budget;
23487
23697
  this.journal = journal;
23488
23698
  }
@@ -23490,12 +23700,19 @@ var LayerMap = class _LayerMap {
23490
23700
  source;
23491
23701
  store;
23492
23702
  index;
23703
+ analyzer;
23493
23704
  budget;
23494
23705
  journal;
23495
23706
  refreshing;
23707
+ // The versions this process's operations are reading, with how many hold each, and the timer
23708
+ // that renews their holds while any does.
23709
+ held = /* @__PURE__ */ new Map();
23710
+ holder = randomUUID2();
23711
+ renewal;
23712
+ closed = false;
23496
23713
  static async open(options) {
23497
23714
  const project = await realpath2(options.project);
23498
- const stat3 = await lstat2(project, { bigint: true });
23715
+ const stat3 = await lstat3(project, { bigint: true });
23499
23716
  if (!stat3.isDirectory()) throw new ProjectEvidenceError("PROJECT_PATH_INVALID", false);
23500
23717
  const source = {
23501
23718
  kind: "WORKTREE",
@@ -23507,62 +23724,156 @@ var LayerMap = class _LayerMap {
23507
23724
  openMapDatabase(file2)
23508
23725
  );
23509
23726
  const { typescript, go, python, java } = options.analyzers;
23510
- const index = new CodeIndex(
23511
- store,
23512
- void 0,
23513
- new ProjectMapAnalyzer([
23514
- new TypeScriptMapAnalyzer(typescript),
23515
- new GoMapAnalyzer(go),
23516
- new PythonMapAnalyzer(python),
23517
- new JavaMapAnalyzer(java)
23518
- ])
23519
- );
23727
+ const analyzer = new ProjectMapAnalyzer([
23728
+ new TypeScriptMapAnalyzer(typescript),
23729
+ new GoMapAnalyzer(go),
23730
+ new PythonMapAnalyzer(python),
23731
+ new JavaMapAnalyzer(java)
23732
+ ]);
23520
23733
  return new _LayerMap(
23521
23734
  project,
23522
23735
  source,
23523
23736
  store,
23524
- index,
23737
+ new CodeIndex(store, void 0, analyzer),
23738
+ analyzer.id,
23525
23739
  { maxBytes: options.maxOutputBytes ?? 96 * 1024, envelopeBytes: 0 },
23526
23740
  `${file2}-wal`
23527
23741
  );
23528
23742
  }
23529
23743
  /** The map version of the directory as it is now, built or updated if needed. */
23530
23744
  refresh(signal) {
23745
+ return this.using((hold) => this.current(signal, hold));
23746
+ }
23747
+ current(signal, hold) {
23531
23748
  return this.serialized(async () => {
23532
- const version2 = await this.index.prepare(this.source, signal, {
23533
- initialScope: DEFAULT_INITIAL_EVIDENCE_SCOPE
23534
- });
23749
+ const version2 = await this.prepare(this.source, signal, hold);
23535
23750
  this.prune(version2);
23536
23751
  this.tidyJournal();
23537
23752
  return version2.version;
23538
23753
  });
23539
23754
  }
23540
- /** The map version of a commit of the directory; files it shares with other versions are reused. */
23541
- versionAt(commit, signal) {
23755
+ /**
23756
+ * The map version of a commit of the directory: the one it was captured as before, or a new
23757
+ * capture, whose files shared with other versions are reused.
23758
+ */
23759
+ versionAt(commit, signal, hold) {
23542
23760
  return this.serialized(async () => {
23543
- const version2 = await this.index.prepare({ ...this.source, kind: "COMMIT", commit }, signal, {
23544
- initialScope: DEFAULT_INITIAL_EVIDENCE_SCOPE
23761
+ const key = digestValue({
23762
+ projectRef: this.source.projectRef,
23763
+ commit,
23764
+ scope: DEFAULT_INITIAL_EVIDENCE_SCOPE,
23765
+ analyzer: this.analyzer,
23766
+ policy: SOURCE_POLICY
23545
23767
  });
23546
- return version2.version;
23768
+ const known = this.store.database.prepare("SELECT version_ref FROM layermap_commit_versions WHERE capture_key = ?").get(key)?.version_ref;
23769
+ const version2 = typeof known === "string" && hold(known) ? known : (await this.prepare({ ...this.source, kind: "COMMIT", commit }, signal, hold)).version;
23770
+ await this.index.ensureIndex(version2, signal);
23771
+ this.store.database.prepare("INSERT OR REPLACE INTO layermap_commit_versions VALUES (?, ?, ?)").run(key, version2, Date.now());
23772
+ return version2;
23547
23773
  });
23548
23774
  }
23775
+ // A file that changes while it is captured or analyzed makes the capture describe no state of
23776
+ // the directory; the directory is captured again.
23777
+ async prepare(source, signal, hold) {
23778
+ for (let attempt = 1; ; attempt++) {
23779
+ try {
23780
+ const version2 = await this.index.captureVersion(source, signal, {
23781
+ initialScope: DEFAULT_INITIAL_EVIDENCE_SCOPE
23782
+ });
23783
+ if (!hold(version2.version))
23784
+ throw new ProjectEvidenceError("PROJECT_EVIDENCE_REVISION_NOT_FOUND", true);
23785
+ await this.index.ensureIndex(version2.version, signal);
23786
+ return version2;
23787
+ } catch (error51) {
23788
+ if (attempt === CAPTURE_ATTEMPTS || signal.aborted || !(error51 instanceof ProjectEvidenceError && CAPTURE_AGAIN.has(error51.code)))
23789
+ throw error51;
23790
+ }
23791
+ }
23792
+ }
23549
23793
  // One capture at a time; a query waiting behind one captures again, since files may change.
23550
23794
  serialized(capture) {
23551
23795
  const next = (this.refreshing ?? Promise.resolve("")).catch(() => "").then(capture);
23552
23796
  this.refreshing = next;
23553
23797
  return next;
23554
23798
  }
23555
- /** Drops versions beyond the most recent few; their files, facts and unshared units go too. */
23799
+ // An operation holds the versions it reads until it ends, so that no process's cleanup removes
23800
+ // one while it reads it.
23801
+ async using(operation) {
23802
+ const taken = [];
23803
+ const hold = (version2) => {
23804
+ if (!this.held.has(version2) && !this.renew([version2])) return false;
23805
+ taken.push(version2);
23806
+ this.held.set(version2, (this.held.get(version2) ?? 0) + 1);
23807
+ this.renewal ??= setInterval(() => {
23808
+ try {
23809
+ this.renew([...this.held.keys()]);
23810
+ } catch {
23811
+ }
23812
+ }, HOLD_EXPIRY_MS / 5).unref();
23813
+ return true;
23814
+ };
23815
+ try {
23816
+ return await operation(hold);
23817
+ } finally {
23818
+ const released = [];
23819
+ for (const version2 of taken) {
23820
+ const count = (this.held.get(version2) ?? 1) - 1;
23821
+ if (count > 0) this.held.set(version2, count);
23822
+ else if (this.held.delete(version2)) released.push(version2);
23823
+ }
23824
+ if (this.held.size === 0) {
23825
+ clearInterval(this.renewal);
23826
+ this.renewal = void 0;
23827
+ }
23828
+ if (!this.closed)
23829
+ this.store.database.prepare(`DELETE FROM layermap_version_holds
23830
+ WHERE holder = ? AND version_ref IN (SELECT value FROM json_each(?))`).run(this.holder, JSON.stringify(released));
23831
+ }
23832
+ }
23833
+ // Holds versions as of now; false when one is gone, as another process's cleanup removed it.
23834
+ renew(versions) {
23835
+ const database = this.store.database;
23836
+ database.exec("BEGIN IMMEDIATE");
23837
+ try {
23838
+ const exists = database.prepare("SELECT 1 FROM project_code_versions WHERE version_ref = ?");
23839
+ const holds = database.prepare(`INSERT INTO layermap_version_holds VALUES (?, ?, ?)
23840
+ ON CONFLICT DO UPDATE SET held_at = excluded.held_at`);
23841
+ const now = Date.now();
23842
+ let all = true;
23843
+ for (const version2 of versions) {
23844
+ if (exists.get(version2)) holds.run(version2, this.holder, now);
23845
+ else all = false;
23846
+ }
23847
+ database.exec("COMMIT");
23848
+ return all;
23849
+ } catch (error51) {
23850
+ database.exec("ROLLBACK");
23851
+ throw error51;
23852
+ }
23853
+ }
23854
+ /**
23855
+ * Drops versions beyond the most recent few and the last bases compared with, unless a process
23856
+ * holds one; their files, facts and unshared units go too. What to keep is read in the
23857
+ * transaction that deletes, so a version another process holds is either kept or found gone by it.
23858
+ */
23556
23859
  prune(version2) {
23860
+ const database = this.store.database;
23557
23861
  const count = Number(
23558
- this.store.database.prepare("SELECT count(*) AS count FROM project_code_versions").get()?.count
23862
+ database.prepare("SELECT count(*) AS count FROM project_code_versions").get()?.count
23559
23863
  );
23560
23864
  if (count <= KEEP_VERSIONS) return;
23561
- this.store.collectGarbage([
23865
+ const refs = (rows2) => rows2.map((row) => String(row.version_ref));
23866
+ const removed = this.store.collectGarbage(() => [
23562
23867
  version2.version,
23563
- ...this.store.mapParentCandidates(version2, KEEP_VERSIONS - 1)
23868
+ ...this.store.mapParentCandidates(version2, KEEP_VERSIONS - 1),
23869
+ ...refs(
23870
+ database.prepare("SELECT version_ref FROM layermap_commit_versions ORDER BY used_at DESC LIMIT ?").all(KEEP_COMMIT_VERSIONS)
23871
+ ),
23872
+ ...refs(
23873
+ database.prepare("SELECT version_ref FROM layermap_version_holds WHERE held_at > ?").all(Date.now() - HOLD_EXPIRY_MS)
23874
+ )
23564
23875
  ]);
23565
- this.store.database.exec("PRAGMA incremental_vacuum;");
23876
+ if (removed) database.exec("PRAGMA incremental_vacuum;");
23566
23877
  }
23567
23878
  // SQLite leaves the write-ahead log at the size of the largest capture written through it, often
23568
23879
  // hundreds of megabytes after a build. Once that capture is in the database the log is emptied,
@@ -23573,33 +23884,29 @@ var LayerMap = class _LayerMap {
23573
23884
  database.exec("PRAGMA busy_timeout = 0;");
23574
23885
  try {
23575
23886
  database.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get();
23576
- } catch {
23577
23887
  } finally {
23578
23888
  database.exec(BUSY_TIMEOUT);
23579
23889
  }
23580
23890
  }
23581
- async explore(input, signal) {
23582
- const version2 = await this.refresh(signal);
23583
- return this.index.query.viewMap(
23584
- { ...input, version: version2, allowedPathPrefixes: ["."], outputBudget: this.budget },
23585
- signal
23586
- );
23587
- }
23588
- async search(input, signal) {
23589
- const version2 = await this.refresh(signal);
23590
- return this.index.query.searchMapView(
23591
- { ...input, version: version2, allowedPathPrefixes: ["."], outputBudget: this.budget },
23592
- signal
23891
+ explore(input, signal) {
23892
+ return this.using(
23893
+ async (hold) => this.index.query.viewMap(
23894
+ {
23895
+ ...input,
23896
+ version: await this.current(signal, hold),
23897
+ allowedPathPrefixes: ["."],
23898
+ outputBudget: this.budget
23899
+ },
23900
+ signal
23901
+ )
23593
23902
  );
23594
23903
  }
23595
- async references(input, signal) {
23596
- const version2 = await this.refresh(signal);
23597
- return mapReferenceNavigation(
23598
- await this.index.findReferences(
23904
+ search(input, signal) {
23905
+ return this.using(
23906
+ async (hold) => this.index.query.searchMapView(
23599
23907
  {
23600
23908
  ...input,
23601
- version: version2,
23602
- source: this.source,
23909
+ version: await this.current(signal, hold),
23603
23910
  allowedPathPrefixes: ["."],
23604
23911
  outputBudget: this.budget
23605
23912
  },
@@ -23607,33 +23914,56 @@ var LayerMap = class _LayerMap {
23607
23914
  )
23608
23915
  );
23609
23916
  }
23917
+ references(input, signal) {
23918
+ return this.using(
23919
+ async (hold) => mapReferenceNavigation(
23920
+ await this.index.findReferences(
23921
+ {
23922
+ ...input,
23923
+ version: await this.current(signal, hold),
23924
+ source: this.source,
23925
+ allowedPathPrefixes: ["."],
23926
+ outputBudget: this.budget
23927
+ },
23928
+ signal
23929
+ )
23930
+ )
23931
+ );
23932
+ }
23610
23933
  /**
23611
23934
  * What the working tree's changes against a commit (HEAD by default) affect: the changed and
23612
23935
  * removed declarations, the entry points and tests their callers reach, and what the map cannot
23613
23936
  * see. The base commit's map is built only when the diff removes or changes lines there.
23614
23937
  */
23615
- async checkChanges(input, signal) {
23616
- return checkMapChanges(
23617
- {
23618
- index: this.index,
23619
- project: this.project,
23620
- working: await this.refresh(signal),
23621
- base: input.base ?? "HEAD",
23622
- baseVersion: (commit, baseSignal) => this.versionAt(commit, baseSignal)
23623
- },
23624
- signal
23938
+ checkChanges(input, signal) {
23939
+ return this.using(
23940
+ async (hold) => checkMapChanges(
23941
+ {
23942
+ index: this.index,
23943
+ project: this.project,
23944
+ working: await this.current(signal, hold),
23945
+ base: input.base ?? "HEAD",
23946
+ baseVersion: (commit, baseSignal) => this.versionAt(commit, baseSignal, hold)
23947
+ },
23948
+ signal
23949
+ )
23625
23950
  );
23626
23951
  }
23627
23952
  /**
23628
23953
  * Builds the map of a base commit (HEAD by default) ahead of a change check, so the check after an
23629
23954
  * edit does not wait for it. A clean working tree's base shares every file with its map.
23630
23955
  */
23631
- async prepareBase(signal, base = "HEAD") {
23632
- await this.versionAt(await resolveMapBase(this.project, base, signal), signal);
23956
+ prepareBase(signal, base = "HEAD") {
23957
+ return this.using(async (hold) => {
23958
+ await this.versionAt(await resolveMapBase(this.project, base, signal), signal, hold);
23959
+ });
23633
23960
  }
23634
23961
  async close() {
23962
+ clearInterval(this.renewal);
23635
23963
  await this.index.quiesce();
23636
23964
  this.index.close();
23965
+ this.store.database.prepare("DELETE FROM layermap_version_holds WHERE holder = ?").run(this.holder);
23966
+ this.closed = true;
23637
23967
  this.store.database.close();
23638
23968
  }
23639
23969
  };
@@ -23750,7 +24080,7 @@ async function resolveAnalyzers(cache, log2, env = process.env) {
23750
24080
  return await readAnalyzers(directory);
23751
24081
  }
23752
24082
  var DAY = 24 * 60 * 60 * 1e3;
23753
- async function pruneCache(cache, project, now = Date.now(), installed = packageRoot) {
24083
+ async function pruneCache(cache, project, now = Date.now(), installed = packageRoot, env = process.env) {
23754
24084
  const used = path11.join(path11.dirname(mapDatabasePath(cache, project)), "last-used");
23755
24085
  await mkdir(path11.dirname(used), { recursive: true, mode: 448 });
23756
24086
  await writeFile(used, "");
@@ -23771,13 +24101,31 @@ async function pruneCache(cache, project, now = Date.now(), installed = packageR
23771
24101
  if (built !== void 0 && now - built > (name.includes(".") ? DAY / 24 : DAY))
23772
24102
  await rm(path11.join(builds, name), { recursive: true, force: true });
23773
24103
  }
23774
- await pruneNpxInstalls(installed, now);
24104
+ const own = path11.dirname(path11.dirname(installed));
24105
+ const versions = path11.join(cache, "versions");
24106
+ const launched = path11.dirname(own) === versions;
24107
+ if (launched) await pruneVersions(versions, own, now);
24108
+ const npx = launched ? path11.join(
24109
+ env.npm_config_cache || (process.platform === "win32" ? path11.join(env.LOCALAPPDATA || path11.join(homedir(), "AppData", "Local"), "npm-cache") : path11.join(homedir(), ".npm")),
24110
+ "_npx"
24111
+ ) : path11.dirname(own);
24112
+ if (path11.basename(path11.dirname(installed)) === "node_modules" && path11.basename(npx) === "_npx")
24113
+ await pruneNpxInstalls(npx, installed, now);
24114
+ }
24115
+ async function pruneVersions(versions, own, now) {
24116
+ const used = path11.join(own, "last-used");
24117
+ await writeFile(used, "");
24118
+ await utimes(used, now / 1e3, now / 1e3);
24119
+ for (const name of await readdir(versions).catch(() => [])) {
24120
+ const directory = path11.join(versions, name);
24121
+ const marker = path11.join(directory, "last-used");
24122
+ const last = (await stat(existsSync5(marker) ? marker : directory).catch(() => void 0))?.mtimeMs;
24123
+ if (last !== void 0 && now - last > (name.startsWith(".") ? DAY / 24 : 7 * DAY))
24124
+ await rm(directory, { recursive: true, force: true });
24125
+ }
23775
24126
  }
23776
- async function pruneNpxInstalls(installed, now) {
24127
+ async function pruneNpxInstalls(npx, installed, now) {
23777
24128
  const own = path11.dirname(path11.dirname(installed));
23778
- const npx = path11.dirname(own);
23779
- if (path11.basename(path11.dirname(installed)) !== "node_modules" || path11.basename(npx) !== "_npx")
23780
- return;
23781
24129
  const manifest = async (file2) => JSON.parse(await readFile2(file2, "utf8").catch(() => "{}"));
23782
24130
  const parts = (version2) => version2?.split(".").map(Number) ?? [];
23783
24131
  const current = parts((await manifest(path11.join(installed, "package.json"))).version);
@@ -23890,7 +24238,7 @@ var mapToolDescriptions = (host) => {
23890
24238
  return Object.freeze({
23891
24239
  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.`,
23892
24240
  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.`,
23893
- check: `${lead("check")}Compares the working tree with a commit (HEAD by default, so uncommitted and untracked changes), finds the declarations the diff changed, removed or renamed, and follows their callers up to 8 levels. It reports, conclusion first: AFFECTED ENTRY POINTS reached through resolved calls, each route with its HTTP methods and full path and the chain to the change; POSSIBLY AFFECTED ones reached only through a call on an interface or base member; REQUESTED BY, the code and templates outside the tests that request the path of a route whose handler the change reaches or a route it removed, found by text; EXISTING TESTS CHANGED, the tests that existed before the diff and whose code it changed or removed; SHARED BY, when tests reach the changed code through more than one area (package or module), so a change meant for one feature may change others; NAMES STILL USED ELSEWHERE, environment variables and configuration keys the diff removed from a file that other files still read or set, found by text; NEW MODULE DEPENDENCIES, imports between the modules of the project overview that the base did not have, and those that make two modules depend on each other, for you to judge against the project's layers; EXISTING CODE LIKE THE NEW CODE, declarations the diff adds whose code reads almost the same as code the project already has; LEFT WITHOUT CALLERS, declarations whose last callers outside the tests the diff removed or changed; CHECK BY HAND for what a static map cannot follow (changed configuration, templates, migrations or dependency files, changed route registrations, declarations with no callers, calls by name on receivers of unknown type); and RELATED TESTS, the existing test files that call the changed code, import a changed file or sit beside it. It does not run or write tests: run the related ones if the change needs verifying; a failing or rewritten test of a feature the request is not about means the change leaked, so restore the test and narrow the change; a new dependency that runs against the layers or closes a cycle means moving what both modules need down rather than importing upward; new code like existing code means using the existing code, or removing the old if the new replaces it; code left without callers means deleting it, with the tests that only test it, when the change replaced it; call it once when the edits are done; and confirm the entry points in source, since an empty list does not prove a change safe.`,
24241
+ check: `${lead("check")}Compares the working tree with a commit (HEAD by default, so uncommitted and untracked changes), finds the declarations the diff changed, removed or renamed, and follows their callers up to 8 levels. It reports, conclusion first: AFFECTED ENTRY POINTS reached through resolved calls, each route with its HTTP methods and full path and the chain to the change; POSSIBLY AFFECTED ones reached only through a call on an interface or base member; REQUESTED BY, the code and templates outside the tests that request the path of a route whose handler the change reaches or a route it removed, found by text; EXISTING TESTS CHANGED, the tests that existed before the diff and whose code it changed or removed; SHARED BY, when tests reach the changed code through more than one area (package or module), so a change meant for one feature may change others; NAMES STILL USED ELSEWHERE, environment variables and configuration keys the diff removed from a file that other files still read or set, found by text; NEW MODULE DEPENDENCIES, imports between the modules of the project overview that the base did not have, and those that make two modules depend on each other, for you to judge against the project's layers; EXISTING CODE LIKE THE NEW CODE, declarations the diff adds whose code reads almost the same as code the project already has; LEFT WITHOUT CALLERS, declarations whose last callers outside the tests the diff removed or changed, and that nothing extends, implements, overrides or wires with a decorator; CHECK BY HAND for what a static map cannot follow (changed configuration, templates, migrations or dependency files, changed route registrations, declarations with no callers, calls by name on receivers of unknown type); and RELATED TESTS, the existing test files that call the changed code, import a changed file or sit beside it. It does not run or write tests: run the related ones if the change needs verifying; a failing or rewritten test of a feature the request is not about means the change leaked, so restore the test and narrow the change; a new dependency that runs against the layers or closes a cycle means moving what both modules need down rather than importing upward; new code like existing code means using the existing code, or removing the old if the new replaces it; code left without callers means deleting it, with the tests that only test it, when the change replaced it; call it once when the edits are done; and confirm the entry points in source, since an empty list does not prove a change safe.`,
23894
24242
  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.`
23895
24243
  });
23896
24244
  };
@@ -23986,8 +24334,10 @@ var more = (nextOffset) => nextOffset === void 0 ? "" : `
23986
24334
  [More entries: call again with offset ${nextOffset} and otherwise the same arguments.]`;
23987
24335
  var HINTS = {
23988
24336
  PROJECT_MAP_OBJECT_NOT_FOUND: "No such path or declaration in the map. Explore the parent directory or the file to see what it contains.",
23989
- PROJECT_READ_SOURCE_CHANGED: "Files changed while the map was updating. Call again.",
23990
- PROJECT_MAP_SOURCE_CHANGED: "Files changed while the map was updating. Call again.",
24337
+ PROJECT_FILE_CHANGED: "Files kept changing while the map was updating. Call again.",
24338
+ PROJECT_FILE_UNIVERSE_CHANGED: "Files kept changing while the map was updating. Call again.",
24339
+ PROJECT_READ_SOURCE_CHANGED: "Files kept changing while the map was updating. Call again.",
24340
+ PROJECT_MAP_SOURCE_CHANGED: "Files kept changing while the map was updating. Call again.",
23991
24341
  PROJECT_CONTINUATION_INVALID: "The offset or cursor belongs to an earlier map or other arguments. Start again without it.",
23992
24342
  PROJECT_MAP_REFERENCE_CURSOR_INVALID: "The cursor belongs to an earlier map or other arguments. Start again without it.",
23993
24343
  PROJECT_READ_INPUT_INVALID: "The arguments do not describe a valid selection.",
@@ -24090,7 +24440,11 @@ function serveMcp(options) {
24090
24440
  }).catch((error51) => {
24091
24441
  if (!session.signal.aborted) log2(`LayerMap could not build the map: ${String(error51)}`);
24092
24442
  });
24093
- entry = { opened, built };
24443
+ const opening = { opened, built };
24444
+ opened.catch(() => {
24445
+ if (maps.get(project) === opening) maps.delete(project);
24446
+ });
24447
+ entry = opening;
24094
24448
  maps.set(project, entry);
24095
24449
  }
24096
24450
  return entry;
@@ -24229,7 +24583,7 @@ ${text}` : text
24229
24583
  // src/agent/setup.ts
24230
24584
  import { execFile as execFile2 } from "node:child_process";
24231
24585
  import { existsSync as existsSync7 } from "node:fs";
24232
- import { mkdir as mkdir2, readFile as readFile3, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
24586
+ import { mkdir as mkdir2, readFile as readFile3, rename as rename2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
24233
24587
  import { homedir as homedir2 } from "node:os";
24234
24588
  import path13 from "node:path";
24235
24589
  var SERVER = "layermap";
@@ -24237,16 +24591,13 @@ var SETUP_RULE = `mcp__${SERVER}`;
24237
24591
  var PLUGIN_RULE = `mcp__plugin_${SERVER}_${SERVER}`;
24238
24592
  var BEGIN = "<!-- layermap:begin -->";
24239
24593
  var END = "<!-- layermap:end -->";
24240
- var npxServerArgs = (version2) => [
24241
- "--prefer-offline",
24242
- "-y",
24243
- `layermap@${version2}`,
24244
- "mcp"
24245
- ];
24246
- var mcpLaunchCommand = (version2, platform = process.platform) => {
24594
+ var launcherScript = (template, version2) => `// Generated from scripts/launcher.mjs.
24595
+ ${template.replace("__VERSION__", JSON.stringify(version2))}`;
24596
+ var PUBLISHED_LAUNCHER = path13.join(packageRoot, "dist", "launcher.mjs");
24597
+ var launcherFile = (env = process.env) => path13.join(cacheDirectory(env), "server.mjs");
24598
+ var mcpLaunchCommand = (env = process.env, published = existsSync7(PUBLISHED_LAUNCHER)) => {
24599
+ if (published) return ["node", launcherFile(env)];
24247
24600
  const script = path13.resolve(process.argv[1] ?? "");
24248
- if (script.includes(`${path13.sep}_npx${path13.sep}`))
24249
- return [...platform === "win32" ? ["cmd", "/c"] : [], "npx", ...npxServerArgs(version2)];
24250
24601
  const execArgv = [];
24251
24602
  for (let index = 0; index < process.execArgv.length; index++) {
24252
24603
  const argument = process.execArgv[index];
@@ -24295,6 +24646,7 @@ async function configureCodexServer(file2) {
24295
24646
  while (end < lines.length && !lines[end]?.trim().startsWith("[")) end++;
24296
24647
  const wanted = {
24297
24648
  default_tools_approval_mode: '"approve"',
24649
+ startup_timeout_sec: "120",
24298
24650
  tool_timeout_sec: "120"
24299
24651
  };
24300
24652
  const present = new Set(
@@ -24344,13 +24696,10 @@ async function disallowInClaudeSettings(file2) {
24344
24696
  }
24345
24697
  var YAML_BEGIN = "# layermap:begin";
24346
24698
  var YAML_END = "# layermap:end";
24347
- var nodeDirectory = (env = process.env) => (env.PATH ?? "").split(path13.delimiter).find(
24348
- (directory) => path13.isAbsolute(directory) && existsSync7(path13.join(directory, "node")) && existsSync7(path13.join(directory, "npx"))
24349
- ) ?? path13.dirname(process.execPath);
24699
+ var nodeDirectory = (env = process.env) => (env.PATH ?? "").split(path13.delimiter).find((directory) => path13.isAbsolute(directory) && existsSync7(path13.join(directory, "node"))) ?? path13.dirname(process.execPath);
24350
24700
  var dshPatchBlock = (command, env) => {
24351
24701
  const node = nodeDirectory(env);
24352
- const npx = path13.join(node, "npx");
24353
- const [program = "", ...args] = command[0] === "npx" && existsSync7(npx) ? [npx, ...command.slice(1)] : command;
24702
+ const [program = "", ...args] = command[0] === "node" ? [path13.join(node, "node"), ...command.slice(1)] : command;
24354
24703
  const searchPath2 = `${JSON.stringify(`${node}${path13.delimiter}`)} + process.env.PATH`;
24355
24704
  return [
24356
24705
  `${YAML_BEGIN} (written by \`layermap setup dsh\`; \`layermap remove dsh\` deletes it)`,
@@ -24434,10 +24783,28 @@ var agentFiles = (options) => {
24434
24783
  async function setupAgent(options) {
24435
24784
  const env = options.env ?? process.env;
24436
24785
  const { log: log2 } = options;
24437
- const command = mcpLaunchCommand(options.version);
24786
+ if (options.scope === "project") {
24787
+ log2(
24788
+ "Setup registers this machine's launcher, so it does not write a project's shared settings. Have each machine run setup (--scope user or local), or install the plugin; `layermap remove claude --scope project` still removes an earlier project setup."
24789
+ );
24790
+ return false;
24791
+ }
24792
+ const published = existsSync7(PUBLISHED_LAUNCHER);
24793
+ const command = mcpLaunchCommand(env, published);
24438
24794
  const quoted = command.map((part) => /^[\w./:@=-]+$/u.test(part) ? part : JSON.stringify(part));
24439
24795
  const { settings, instructions } = agentFiles(options);
24440
24796
  const note = options.instructions !== false;
24797
+ const writeLauncher = async () => {
24798
+ if (!published) return;
24799
+ const file2 = launcherFile(env);
24800
+ await mkdir2(path13.dirname(file2), { recursive: true, mode: 448 });
24801
+ await writeFile2(
24802
+ `${file2}.${process.pid}`,
24803
+ launcherScript(await readFile3(PUBLISHED_LAUNCHER, "utf8"), options.version)
24804
+ );
24805
+ await rename2(`${file2}.${process.pid}`, file2);
24806
+ };
24807
+ if (published) log2(`write the launcher of LayerMap ${options.version} to ${launcherFile(env)}`);
24441
24808
  if (options.agent === "dsh") {
24442
24809
  if (options.scope !== "user") {
24443
24810
  log2("DeepSeek Harness is set up for all its profiles at once; --scope does not apply.");
@@ -24446,6 +24813,7 @@ async function setupAgent(options) {
24446
24813
  log2(`add the ${SERVER} MCP server to ${settings}`);
24447
24814
  if (note) log2(`add a note naming the map tools to ${instructions}`);
24448
24815
  if (options.dryRun) return true;
24816
+ await writeLauncher();
24449
24817
  await writeDshPatch(settings, dshPatchBlock(command, env));
24450
24818
  if (note) await writeInstructionNote(instructions);
24451
24819
  log2(
@@ -24459,10 +24827,13 @@ async function setupAgent(options) {
24459
24827
  log2(`allow ${SETUP_RULE} in ${settings}`);
24460
24828
  } else {
24461
24829
  log2(`codex mcp add ${SERVER} -- ${quoted.join(" ")}`);
24462
- log2(`set default_tools_approval_mode = "approve" and tool_timeout_sec = 120 in ${settings}`);
24830
+ log2(
24831
+ `set default_tools_approval_mode = "approve", startup_timeout_sec = 120 and tool_timeout_sec = 120 in ${settings}`
24832
+ );
24463
24833
  }
24464
24834
  if (note) log2(`add a note naming the map tools to ${instructions}`);
24465
24835
  if (options.dryRun) return true;
24836
+ await writeLauncher();
24466
24837
  const agentCommand = options.agent;
24467
24838
  const scope = options.agent === "claude" ? ["--scope", options.scope] : [];
24468
24839
  await run(agentCommand, ["mcp", "remove", SERVER, ...scope], env);
@@ -24523,7 +24894,7 @@ async function removeAgent(options) {
24523
24894
  var USAGE = `LayerMap \u2014 a layered map of a codebase for coding agents.
24524
24895
 
24525
24896
  Usage:
24526
- layermap setup claude|codex|dsh [--scope user|project|local] [--no-instructions] [--dry-run]
24897
+ layermap setup claude|codex|dsh [--scope user|local] [--no-instructions] [--dry-run]
24527
24898
  layermap allow claude [--scope user|project|local] [--dry-run]
24528
24899
  let the plugin's read-only tools run without a prompt
24529
24900
  layermap remove claude|codex|dsh [--scope user|project|local] [--dry-run]
@@ -24574,11 +24945,6 @@ async function main(argv) {
24574
24945
  const version2 = await packageVersion();
24575
24946
  if (values.version) {
24576
24947
  process.stdout.write(`${version2}
24577
- `);
24578
- return 0;
24579
- }
24580
- if (command === "entry") {
24581
- process.stdout.write(`${fileURLToPath3(import.meta.url)}
24582
24948
  `);
24583
24949
  return 0;
24584
24950
  }