layermap 0.1.25 → 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.
@@ -31310,6 +31310,7 @@ async function extractProjectMap(project, input, trace) {
31310
31310
  };
31311
31311
  } else if (isPropertyAccessExpression(node) || isElementAccessExpression(node)) {
31312
31312
  const writes = isMapWrite(node);
31313
+ const readsState = isPropertyAccessExpression(node) && isIdentifier(node.expression) && state.namespaces.has(node.expression.text);
31313
31314
  if (writes) {
31314
31315
  reference = {
31315
31316
  node,
@@ -31325,9 +31326,10 @@ async function extractProjectMap(project, input, trace) {
31325
31326
  kind: "REFERENCES",
31326
31327
  target: node.name.text,
31327
31328
  holder: mapValueProperty(node),
31328
- ...route ? { argument: route } : {}
31329
+ ...route ? { argument: route } : {},
31330
+ ...readsState ? { readsState } : {}
31329
31331
  };
31330
- } else if (isPropertyAccessExpression(node) && isIdentifier(node.expression) && state.namespaces.has(node.expression.text)) {
31332
+ } else if (isPropertyAccessExpression(node) && readsState) {
31331
31333
  reference = {
31332
31334
  node,
31333
31335
  lookup: node.name,
@@ -31340,6 +31342,7 @@ async function extractProjectMap(project, input, trace) {
31340
31342
  const parent = node.parent;
31341
31343
  if (!((isCallExpression(parent) || isNewExpression(parent)) && parent.expression === node)) {
31342
31344
  const writes = isMapWrite(node);
31345
+ const readsState = state.names.has(node.text) && !(isPropertyAccessExpression(parent) && parent.name === node) && !NOT_STATE_READS.has(parent.kind) && !isImportSpecifier(parent);
31343
31346
  if (writes) reference = { node, lookup: node, kind: "WRITES", target: mapNodeLabel(node) };
31344
31347
  else if (mapValueUse(node)) {
31345
31348
  const route = registeredRoute(node, "REFERENCES");
@@ -31349,9 +31352,10 @@ async function extractProjectMap(project, input, trace) {
31349
31352
  kind: "REFERENCES",
31350
31353
  target: node.text,
31351
31354
  holder: mapValueProperty(node),
31352
- ...route ? { argument: route } : {}
31355
+ ...route ? { argument: route } : {},
31356
+ ...readsState ? { readsState } : {}
31353
31357
  };
31354
- } else if (state.names.has(node.text) && !(isPropertyAccessExpression(parent) && parent.name === node) && !NOT_STATE_READS.has(parent.kind) && !isImportSpecifier(parent))
31358
+ } else if (readsState)
31355
31359
  reference = { node, lookup: node, kind: "REFERENCES", target: node.text, state: true };
31356
31360
  }
31357
31361
  } else if (isShorthandPropertyAssignment(node)) {
@@ -31481,7 +31485,7 @@ async function extractProjectMap(project, input, trace) {
31481
31485
  for (const object2 of declared.values())
31482
31486
  if (object2.execution && object2.execution !== "MODULE") valueNames.add(object2.name);
31483
31487
  const linkable = pending.filter(
31484
- (item) => item.kind !== "REFERENCES" || item.state || valueNames.has(item.target) || isPropertyAccessExpression(item.node) && isIdentifier(item.node.expression) && namespaces.has(item.node.expression.text)
31488
+ (item) => item.kind !== "REFERENCES" || item.state || item.readsState || valueNames.has(item.target) || isPropertyAccessExpression(item.node) && isIdentifier(item.node.expression) && namespaces.has(item.node.expression.text)
31485
31489
  );
31486
31490
  for (let start = 0; start < linkable.length; start += 128) {
31487
31491
  const batch = linkable.slice(start, start + 128);
@@ -31489,7 +31493,7 @@ async function extractProjectMap(project, input, trace) {
31489
31493
  const symbols = await project.checker.getSymbolAtLocation(batch.map((item) => item.lookup));
31490
31494
  trace.phase = "RELATION_TARGETS";
31491
31495
  for (const [index, item] of batch.entries()) {
31492
- if (item.state) {
31496
+ const readState = async () => {
31493
31497
  for (const destination of await targets.resolveMapped(symbols[index], moduleVariable)) {
31494
31498
  const read = `${item.owner}\0${destination.id}`;
31495
31499
  if (stateReads.has(read)) continue;
@@ -31503,11 +31507,18 @@ async function extractProjectMap(project, input, trace) {
31503
31507
  basis: "TYPE_RESOLVED"
31504
31508
  });
31505
31509
  }
31510
+ };
31511
+ if (item.state) {
31512
+ await readState();
31506
31513
  continue;
31507
31514
  }
31508
31515
  if (item.kind === "REFERENCES") {
31509
31516
  const symbol2 = isShorthandPropertyAssignment(item.node) ? await project.checker.getShorthandAssignmentValueSymbol(item.node) : symbols[index];
31510
31517
  const callable = await targets.resolveCallable(symbol2);
31518
+ if (!callable?.objects.length && item.readsState) {
31519
+ await readState();
31520
+ continue;
31521
+ }
31511
31522
  const holder = callable && item.holder ? materialize(item.holder) : void 0;
31512
31523
  if (holder && item.holder) callableHolders.add(key(item.holder));
31513
31524
  for (const destination of callable?.objects ?? [])
package/dist/cli.mjs CHANGED
@@ -20,9 +20,9 @@ import path11 from "node:path";
20
20
  import { fileURLToPath } from "node:url";
21
21
 
22
22
  // src/layermap.ts
23
- import { createHash as createHash4 } from "node:crypto";
23
+ import { createHash as createHash4, randomUUID as randomUUID2 } from "node:crypto";
24
24
  import { mkdirSync, statSync } from "node:fs";
25
- import { lstat as lstat2, realpath as realpath2 } from "node:fs/promises";
25
+ import { lstat as lstat3, realpath as realpath2 } from "node:fs/promises";
26
26
  import path10 from "node:path";
27
27
  import { DatabaseSync } from "@photostructure/sqlite";
28
28
 
@@ -30,6 +30,7 @@ import { DatabaseSync } from "@photostructure/sqlite";
30
30
  import path3 from "node:path";
31
31
 
32
32
  // src/file-universe.ts
33
+ import { lstat } from "node:fs/promises";
33
34
  import path2 from "node:path";
34
35
 
35
36
  // src/git-runner.ts
@@ -309,7 +310,6 @@ var FILE_UNIVERSE_ARGS = Object.freeze([
309
310
  "--",
310
311
  "."
311
312
  ]);
312
- var DELETED_FILE_ARGS = Object.freeze(["ls-files", "-z", "--deleted", "--", "."]);
313
313
  var PROJECT_EVIDENCE_FILE_UNIVERSE_POLICY = Object.freeze({
314
314
  kind: "GIT_TRACKED_AND_UNIGNORED_UNTRACKED",
315
315
  deletedPaths: "EXCLUDED",
@@ -356,52 +356,14 @@ var ProjectEvidenceFileUniverse = class {
356
356
  if (signal.aborted) {
357
357
  throw new ProjectEvidenceFileUniverseError("PROJECT_READ_CANCELLED");
358
358
  }
359
- let captured;
359
+ let listed;
360
360
  try {
361
- const stop = new AbortController();
362
- const combined = AbortSignal.any([signal, stop.signal]);
363
- let failed2 = false;
364
- let firstFailure;
365
- const results = await Promise.allSettled(
366
- [
367
- this.git.run(FILE_UNIVERSE_ARGS, {
368
- cwd: root,
369
- maxOutputBytes: null,
370
- signal: combined,
371
- timeoutMs: null
372
- }),
373
- this.git.run(DELETED_FILE_ARGS, {
374
- cwd: root,
375
- maxOutputBytes: null,
376
- signal: combined,
377
- timeoutMs: null
378
- })
379
- ].map(
380
- (work) => work.catch((error51) => {
381
- if (!failed2) {
382
- failed2 = true;
383
- firstFailure = error51;
384
- }
385
- stop.abort();
386
- throw error51;
387
- })
388
- )
389
- );
390
- const unconfirmed = results.find(
391
- (result) => result.status === "rejected" && result.reason instanceof GitCommandStopUnconfirmedError
392
- );
393
- if (unconfirmed?.status === "rejected") throw unconfirmed.reason;
394
- if (failed2) throw firstFailure;
395
- const [includedResult, deletedResult] = results;
396
- if (includedResult?.status !== "fulfilled") {
397
- throw includedResult?.status === "rejected" ? includedResult.reason : new Error("Missing file universe result.");
398
- }
399
- if (deletedResult?.status !== "fulfilled") {
400
- throw deletedResult?.status === "rejected" ? deletedResult.reason : new Error("Missing deleted-file result.");
401
- }
402
- const included = includedResult.value;
403
- const deleted2 = deletedResult.value;
404
- 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;
405
367
  } catch (error51) {
406
368
  if (error51 instanceof GitCommandStopUnconfirmedError) throw error51;
407
369
  if (signal.aborted) {
@@ -409,14 +371,24 @@ var ProjectEvidenceFileUniverse = class {
409
371
  }
410
372
  throw new ProjectEvidenceFileUniverseError("PROJECT_FILE_UNIVERSE_UNAVAILABLE");
411
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
+ );
412
386
  if (signal.aborted) {
413
387
  throw new ProjectEvidenceFileUniverseError("PROJECT_READ_CANCELLED");
414
388
  }
415
- const deleted = new Set(parseFileUniverse(captured.deleted));
416
- const files = Object.freeze(
417
- parseFileUniverse(captured.included).filter((candidate) => !deleted.has(candidate))
418
- );
419
- return Object.freeze({ files });
389
+ return Object.freeze({
390
+ files: Object.freeze(candidates.filter((_, index) => present[index]))
391
+ });
420
392
  }
421
393
  };
422
394
 
@@ -15168,6 +15140,8 @@ var canonicalJson = (value) => JSON.stringify(normalize(value, /* @__PURE__ */ n
15168
15140
  var digestValue = (value) => createHash("sha256").update(canonicalJson(value)).digest("hex");
15169
15141
 
15170
15142
  // src/code-commit-reader.ts
15143
+ var BATCH_BYTES = 16 * 1024 * 1024;
15144
+ var BATCH_BLOBS = 4096;
15171
15145
  var CodeCommitReader = class _CodeCommitReader {
15172
15146
  constructor(root, entries, git2, signal) {
15173
15147
  this.root = root;
@@ -15227,21 +15201,67 @@ var CodeCommitReader = class _CodeCommitReader {
15227
15201
  throw new ProjectEvidenceError("PROJECT_MAP_SOURCE_CHANGED", true);
15228
15202
  return new _CodeCommitReader(root, entries, git2, signal);
15229
15203
  }
15230
- async read(relativePath) {
15231
- const source = this.byPath.get(relativePath);
15232
- if (!source) throw new ProjectEvidenceError("PROJECT_CODE_TREE_INVALID", false);
15233
- const base = { path: relativePath, byteLength: source.bytes };
15234
- if (!isProjectEvidenceTextPath(relativePath))
15235
- return { entry: { ...base, state: "TYPE_RESTRICTED" } };
15236
- if (source.mode === "120000") return { entry: { ...base, state: "SYMLINK" } };
15237
- if (source.mode !== "100644" && source.mode !== "100755")
15238
- return { entry: { ...base, state: "UNSUPPORTED_ENTRY" } };
15239
- 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"], {
15240
15241
  cwd: this.root,
15242
+ input: Buffer.from(objects2.map((object2) => `${object2}
15243
+ `).join("")),
15241
15244
  signal: this.signal,
15242
15245
  timeoutMs: null,
15243
15246
  maxOutputBytes: null
15244
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) {
15245
15265
  const objectHash = createHash2(source.object.length === 64 ? "sha256" : "sha1").update(`blob ${content.byteLength}\0`).update(content).digest("hex");
15246
15266
  if (content.byteLength !== source.bytes || objectHash !== source.object)
15247
15267
  throw new ProjectEvidenceError("PROJECT_CODE_BLOB_INVALID", false);
@@ -15252,13 +15272,21 @@ var CodeCommitReader = class _CodeCommitReader {
15252
15272
  } catch {
15253
15273
  text = false;
15254
15274
  }
15255
- 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
+ };
15256
15284
  }
15257
15285
  };
15258
15286
 
15259
15287
  // src/code-worktree-reader.ts
15260
15288
  import { constants as fsConstants } from "node:fs";
15261
- import { lstat, open, realpath } from "node:fs/promises";
15289
+ import { lstat as lstat2, open, realpath } from "node:fs/promises";
15262
15290
  import path5 from "node:path";
15263
15291
  var fileSystemErrorCode = (error51) => {
15264
15292
  if (typeof error51 !== "object" || error51 === null || !("code" in error51)) return void 0;
@@ -15268,7 +15296,7 @@ var isInsideRoot = (root, candidate) => {
15268
15296
  const relative = path5.relative(root, candidate);
15269
15297
  return relative === "" || !relative.startsWith(`..${path5.sep}`) && relative !== "..";
15270
15298
  };
15271
- var stablePathFingerprint = (stats) => [
15299
+ var stablePathFingerprint = (stats) => (stats.isDirectory() ? ["directory", stats.dev, stats.ino] : [
15272
15300
  stats.dev,
15273
15301
  stats.ino,
15274
15302
  stats.mode,
@@ -15281,7 +15309,7 @@ var stablePathFingerprint = (stats) => [
15281
15309
  stats.blocks,
15282
15310
  stats.mtimeNs,
15283
15311
  stats.ctimeNs
15284
- ].map(String).join(":");
15312
+ ]).map(String).join(":");
15285
15313
  var StableProjectCaptureSession = class _StableProjectCaptureSession {
15286
15314
  constructor(root, rootDevice, rootInode, signal) {
15287
15315
  this.root = root;
@@ -15419,7 +15447,7 @@ var StableProjectCaptureSession = class _StableProjectCaptureSession {
15419
15447
  async assertStable() {
15420
15448
  for (const [absolutePath, expected] of this.pathFingerprints) {
15421
15449
  this.assertNotAborted();
15422
- const current = await lstat(absolutePath, { bigint: true }).catch(() => {
15450
+ const current = await lstat2(absolutePath, { bigint: true }).catch(() => {
15423
15451
  throw new ProjectEvidenceError(this.changeCode(absolutePath), true);
15424
15452
  });
15425
15453
  if (stablePathFingerprint(current) !== expected) {
@@ -15440,7 +15468,7 @@ var StableProjectCaptureSession = class _StableProjectCaptureSession {
15440
15468
  let finalStats;
15441
15469
  for (const [index, currentPath] of paths.entries()) {
15442
15470
  this.assertNotAborted();
15443
- const stats = await lstat(currentPath, { bigint: true }).catch(() => {
15471
+ const stats = await lstat2(currentPath, { bigint: true }).catch(() => {
15444
15472
  throw new ProjectEvidenceError(this.changeCode(currentPath), true);
15445
15473
  });
15446
15474
  const isFinal = index === paths.length - 1;
@@ -15616,7 +15644,7 @@ var CodeIndexCapture = class {
15616
15644
  if (relative === void 0) break;
15617
15645
  try {
15618
15646
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
15619
- const read = commit ? await commit.read(relative) : await session.captureFile(relative);
15647
+ const read = await session.captureFile(relative);
15620
15648
  capturedBytes += read.content?.byteLength ?? 0;
15621
15649
  entries.push(read.entry);
15622
15650
  processedFiles++;
@@ -15628,12 +15656,25 @@ var CodeIndexCapture = class {
15628
15656
  }
15629
15657
  }
15630
15658
  };
15631
- await Promise.all(
15632
- Array.from(
15633
- { length: Math.min(paths.length, PROJECT_EVIDENCE_POLICY_DESCRIPTOR.captureConcurrency) },
15634
- worker
15635
- )
15636
- );
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
+ );
15637
15678
  if (failed2) throw failure;
15638
15679
  await session.assertStable();
15639
15680
  if (snapshot) {
@@ -18736,7 +18777,7 @@ var PythonMapAnalyzer = class {
18736
18777
 
18737
18778
  // src/project-map-language-typescript.ts
18738
18779
  var TYPESCRIPT_MAP_LANGUAGE = Object.freeze({
18739
- id: "typescript-7.0.2-map-v17",
18780
+ id: "typescript-7.0.2-map-v18",
18740
18781
  claims: (path14) => /\.[cm]?[jt]sx?$/u.test(path14),
18741
18782
  reads: (path14) => path14.endsWith(".json") || path14 === "pnpm-workspace.yaml",
18742
18783
  create: () => new TypeScriptMapAnalyzer()
@@ -20203,16 +20244,14 @@ var ProjectMapQuery = class {
20203
20244
 
20204
20245
  // src/project-map-source.ts
20205
20246
  var ProjectMapSourceReader = class _ProjectMapSourceReader {
20206
- constructor(session, commit, universe, snapshot, signal) {
20247
+ constructor(session, commit, snapshot, signal) {
20207
20248
  this.session = session;
20208
20249
  this.commit = commit;
20209
- this.universe = universe;
20210
20250
  this.snapshot = snapshot;
20211
20251
  this.signal = signal;
20212
20252
  }
20213
20253
  session;
20214
20254
  commit;
20215
- universe;
20216
20255
  snapshot;
20217
20256
  signal;
20218
20257
  static async open(source, signal, enumerate = true, selectedPath) {
@@ -20225,33 +20264,47 @@ var ProjectMapSourceReader = class _ProjectMapSourceReader {
20225
20264
  source.directory.inode,
20226
20265
  signal
20227
20266
  );
20228
- const universe = new ProjectEvidenceFileUniverse();
20229
20267
  const commit = source.kind === "COMMIT" ? await CodeCommitReader.open(session.root, source.commit, signal, selectedPath) : void 0;
20230
- const snapshot = source.kind === "WORKTREE" && enumerate ? await universe.capture(session.root, signal) : void 0;
20231
- 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);
20232
20270
  }
20233
20271
  paths() {
20234
20272
  return this.snapshot?.files ?? this.commit?.entries.map((entry) => entry.path) ?? [];
20235
20273
  }
20236
- 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) {
20237
20283
  if (this.signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
20238
- assertProjectEvidencePathNotSensitive(relative);
20239
- if (isProjectEvidenceTraversalExcluded(relative))
20240
- throw new ProjectEvidenceError("PROJECT_FILE_NOT_ALLOWED", false);
20241
- const result = this.commit ? await this.commit.read(relative) : await this.session.captureFile(relative);
20242
- if (expected && (result.entry.state !== expected.state || result.entry.contentDigest !== expected.contentDigest || result.entry.byteLength !== expected.byteLength)) {
20243
- 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);
20244
20295
  }
20245
- return result;
20296
+ return results;
20246
20297
  }
20247
- async assertStable() {
20248
- await this.session.assertStable();
20249
- if (this.snapshot)
20250
- await this.universe.assertCurrent(this.session.root, this.snapshot, this.signal);
20251
- 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();
20252
20305
  }
20253
20306
  };
20254
- async function readAll(items, read) {
20307
+ async function concurrently(items, read) {
20255
20308
  const results = [];
20256
20309
  let next = 0;
20257
20310
  let failed2 = false;
@@ -20295,10 +20348,10 @@ var ProjectMapReadSession = class {
20295
20348
  this.worktree ??= await ProjectMapSourceReader.open(this.source, this.signal, false);
20296
20349
  const reader = this.worktree ?? await ProjectMapSourceReader.open(this.source, this.signal, false, entry.path);
20297
20350
  for (const configuration of this.pendingConfigurations(entry)) {
20298
- await reader.read(configuration.path, configuration);
20351
+ await reader.read(configuration);
20299
20352
  this.configurations.add(configuration.path);
20300
20353
  }
20301
- const result = await reader.read(entry.path, entry);
20354
+ const result = await reader.read(entry);
20302
20355
  if (!result.content) throw new ProjectEvidenceError("PROJECT_MAP_SOURCE_CHANGED", true);
20303
20356
  this.configurations.add(entry.path);
20304
20357
  if (!this.worktree) await reader.assertStable();
@@ -20901,7 +20954,7 @@ var CodeIndexStore = class {
20901
20954
  appendMapStage(buildRef, analysis, record2 = {}) {
20902
20955
  if (analysis.requiredFiles.length)
20903
20956
  throw new ProjectEvidenceError("PROJECT_MAP_CONTEXT_INCOMPLETE", false);
20904
- this.database.exec("BEGIN IMMEDIATE");
20957
+ this.database.exec("BEGIN");
20905
20958
  try {
20906
20959
  const insert = this.database.prepare(
20907
20960
  "INSERT INTO project_map_staging (build_ref, kind, value_json) VALUES (?, ?, ?)"
@@ -21308,14 +21361,24 @@ var CodeIndexStore = class {
21308
21361
  complete: complete && indexedFiles === snapshot.readableTextFileCount
21309
21362
  };
21310
21363
  }
21311
- collectGarbage(referencedVersions) {
21312
- 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) {
21313
21369
  this.database.exec("BEGIN IMMEDIATE");
21314
21370
  try {
21371
+ const kept = new Set(retained());
21372
+ let removed = 0;
21315
21373
  for (const row of this.database.prepare("SELECT version_ref FROM project_code_versions").all()) {
21316
21374
  const version2 = String(row.version_ref);
21317
- if (retained.has(version2)) continue;
21375
+ if (kept.has(version2)) continue;
21318
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;
21319
21382
  }
21320
21383
  this.database.exec(`DELETE FROM project_map_units WHERE NOT EXISTS (
21321
21384
  SELECT 1 FROM project_map_version_units version WHERE version.unit_ref = project_map_units.unit_ref)`);
@@ -21329,6 +21392,7 @@ var CodeIndexStore = class {
21329
21392
  this.database.prepare(`DELETE FROM project_map_navigation_documents
21330
21393
  WHERE document_ref IN (SELECT value FROM json_each(?))`).run(orphans);
21331
21394
  this.database.exec("COMMIT");
21395
+ return removed;
21332
21396
  } catch (error51) {
21333
21397
  this.database.exec("ROLLBACK");
21334
21398
  throw error51;
@@ -21474,13 +21538,12 @@ var ProjectMapAnalyzer = class {
21474
21538
  const state = parent.state(contextRef2);
21475
21539
  return state === void 0 ? void 0 : { state, digests: parent.entries };
21476
21540
  };
21477
- const read = async (entry) => {
21478
- if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
21479
- const value = await reader.read(entry.path, entry);
21480
- 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);
21481
21543
  return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(value.content);
21482
21544
  };
21483
- 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);
21484
21547
  const unitTexts = /* @__PURE__ */ Object.create(null);
21485
21548
  for (const [index, entry] of readable.entries())
21486
21549
  unitTexts[entry.path] = contents[index];
@@ -21683,7 +21746,7 @@ ${scope}`, input.cursor, 2) : [];
21683
21746
  });
21684
21747
  const reader = await ProjectMapSourceReader.open(source, signal, false);
21685
21748
  const files = /* @__PURE__ */ Object.create(null);
21686
- const contents = await readAll(entries, (entry) => reader.read(entry.path, entry));
21749
+ const contents = await reader.readAll(entries);
21687
21750
  for (const [index, entry] of entries.entries()) {
21688
21751
  const value = contents[index];
21689
21752
  if (!value?.content) throw new ProjectEvidenceError("PROJECT_MAP_SOURCE_CHANGED", true);
@@ -21842,7 +21905,7 @@ var CodeIndex = class {
21842
21905
  (unit, record2) => this.store.appendMapStage(stage, unit, record2),
21843
21906
  parent && { ...parent, link: (paths) => linked.push(...paths) }
21844
21907
  );
21845
- await readAll(result.entries, (entry) => reader.read(entry.path, entry));
21908
+ await reader.readAll(result.entries);
21846
21909
  await reader.assertStable();
21847
21910
  if (controller.signal.aborted)
21848
21911
  throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
@@ -22687,7 +22750,7 @@ function parseMapDiff(text) {
22687
22750
  ];
22688
22751
  if (oldCount > 0) current.baseLines.push([oldStart, oldStart + oldCount - 1]);
22689
22752
  current.lines.push(
22690
- newCount > 0 ? [newStart, newStart + newCount - 1] : [Math.max(newStart, 1), newStart + 1]
22753
+ newCount > 0 ? [newStart, newStart + newCount - 1] : [newStart + 1, newStart]
22691
22754
  );
22692
22755
  }
22693
22756
  }
@@ -22712,6 +22775,7 @@ var NON_CODE = [
22712
22775
  var nonCodeKind = (path14) => NON_CODE.find(([pattern]) => pattern.test(path14))?.[1];
22713
22776
  var LIMITS = Object.freeze({ depth: 8, declarations: 800, changed: 200, chain: 3, byName: 40 });
22714
22777
  var CALLER_KINDS = /* @__PURE__ */ new Set(["CALLS", "REFERENCES"]);
22778
+ var NAMING_KINDS = /* @__PURE__ */ new Set(["CALLS", "REFERENCES", "EXTENDS", "IMPLEMENTS"]);
22715
22779
  var USED_BY = {
22716
22780
  EXTENDS: "extended",
22717
22781
  IMPLEMENTS: "implemented",
@@ -22958,6 +23022,10 @@ function mapChangeImpact(store, working, base, changes, project) {
22958
23022
  const importers = /* @__PURE__ */ new Map();
22959
23023
  let mapped;
22960
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
+ };
22961
23029
  for (const file2 of changes.files) {
22962
23030
  if (file2.binary) continue;
22963
23031
  const kind = nonCodeKind(file2.path);
@@ -22977,7 +23045,7 @@ function mapChangeImpact(store, working, base, changes, project) {
22977
23045
  const containing = inFile.filter(
22978
23046
  (object2) => object2.anchor.startLine <= to && from <= object2.anchor.endLine
22979
23047
  );
22980
- if (!containing.length) topLevel = true;
23048
+ if (!containing.length && from <= to) topLevel = true;
22981
23049
  for (const object2 of containing)
22982
23050
  if (!containing.some(
22983
23051
  (other) => other !== object2 && object2.anchor.start <= other.anchor.start && other.anchor.end <= object2.anchor.end && other.anchor.startLine <= to && from <= other.anchor.endLine
@@ -23000,8 +23068,7 @@ function mapChangeImpact(store, working, base, changes, project) {
23000
23068
  unclear.push(
23001
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`
23002
23070
  );
23003
- if (analyzed && topLevel && file2.status !== "ADDED")
23004
- unclear.push(`top-level code of ${file2.path} changed (imports, constants or registrations)`);
23071
+ if (analyzed && topLevel && file2.status !== "ADDED") topLevelChanged(file2.path);
23005
23072
  importerTests(graph, objects2, tracer, importers);
23006
23073
  sameDirectoryTests(mappedPaths(), file2.path, tracer);
23007
23074
  mirroredTests(mappedPaths(), file2.path, tracer);
@@ -23029,6 +23096,22 @@ function mapChangeImpact(store, working, base, changes, project) {
23029
23096
  if (names.length) rewrittenTests.push({ path: file2.path, names });
23030
23097
  }
23031
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
+ };
23032
23115
  const gone = [];
23033
23116
  for (const file2 of changes.files) {
23034
23117
  if (!file2.basePath || !file2.baseLines.length || file2.binary || testCode(file2.basePath))
@@ -23044,11 +23127,37 @@ function mapChangeImpact(store, working, base, changes, project) {
23044
23127
  const parent = before.parent(object2.id);
23045
23128
  if (parent && !mapIsModule(before.object(parent)) && gone.includes(parent)) continue;
23046
23129
  gone.push(object2.id);
23047
- removed.push(
23048
- `${file2.basePath}: ${before.qualifiedName(object2.id)} ${mapDeclarationLabel(object2)}`
23049
- );
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
+ });
23050
23151
  }
23051
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
+ }
23052
23161
  if (gone.length) {
23053
23162
  beforeTracer.trace(gone);
23054
23163
  for (const entry of beforeTracer.entries.values())
@@ -23346,8 +23455,15 @@ Nothing changed against ${changes.base}.`;
23346
23455
  };
23347
23456
  list("CHANGED", impact.changed, LIST.changed);
23348
23457
  list(
23349
- "REMOVED OR RENAMED (their callers in the base still refer to them)",
23350
- 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),
23351
23467
  LIST.changed
23352
23468
  );
23353
23469
  list(
@@ -23497,29 +23613,58 @@ Nothing changed against ${changes.base}.`;
23497
23613
  }
23498
23614
 
23499
23615
  // src/layermap.ts
23500
- var SCHEMA_VERSION = 2;
23616
+ var SCHEMA_VERSION = 3;
23501
23617
  var KEEP_VERSIONS = 3;
23618
+ var KEEP_COMMIT_VERSIONS = 2;
23619
+ var HOLD_EXPIRY_MS = 10 * 60 * 1e3;
23502
23620
  var BUSY_TIMEOUT = "PRAGMA busy_timeout = 30000;";
23503
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);
23504
23645
  function openMapDatabase(file2) {
23505
23646
  mkdirSync(path10.dirname(file2), { recursive: true, mode: 448 });
23506
23647
  const database = new DatabaseSync(file2);
23507
23648
  try {
23508
23649
  database.exec(BUSY_TIMEOUT);
23509
- const version2 = Number(database.prepare("PRAGMA user_version").get()?.user_version ?? 0);
23650
+ const version2 = schemaVersion(database);
23510
23651
  if (version2 > SCHEMA_VERSION) throw new ProjectEvidenceError("LAYERMAP_DATABASE_NEWER", false);
23511
23652
  if (version2 === 0) database.exec("PRAGMA auto_vacuum = INCREMENTAL;");
23653
+ else if (version2 === 1) database.exec("PRAGMA auto_vacuum = INCREMENTAL; VACUUM;");
23512
23654
  database.exec("PRAGMA journal_mode = WAL;");
23513
- if (version2 === 0) {
23655
+ if (version2 < SCHEMA_VERSION) {
23514
23656
  database.exec("PRAGMA foreign_keys = OFF; BEGIN IMMEDIATE;");
23515
23657
  try {
23516
- for (const sql of [
23517
- CODE_INDEX_SCHEMA,
23518
- CODE_INDEX_UNITS_MIGRATION,
23519
- CODE_INDEX_CONTEXT_RESULTS_MIGRATION,
23520
- CODE_INDEX_SHARED_NAVIGATION_MIGRATION
23521
- ])
23522
- 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);
23523
23668
  if (database.prepare("PRAGMA foreign_key_check").get())
23524
23669
  throw new ProjectEvidenceError("PROJECT_EVIDENCE_STORE_CORRUPT", false);
23525
23670
  database.exec(`PRAGMA user_version = ${SCHEMA_VERSION}; COMMIT;`);
@@ -23527,10 +23672,6 @@ function openMapDatabase(file2) {
23527
23672
  database.exec("ROLLBACK");
23528
23673
  throw error51;
23529
23674
  }
23530
- } else if (version2 === 1) {
23531
- database.exec(
23532
- `PRAGMA auto_vacuum = INCREMENTAL; VACUUM; PRAGMA user_version = ${SCHEMA_VERSION};`
23533
- );
23534
23675
  }
23535
23676
  database.exec("PRAGMA foreign_keys = ON;");
23536
23677
  return database;
@@ -23546,11 +23687,12 @@ var mapDatabasePath = (cacheDirectory2, canonicalProject) => path10.join(
23546
23687
  "map.sqlite"
23547
23688
  );
23548
23689
  var LayerMap = class _LayerMap {
23549
- constructor(project, source, store, index, budget, journal) {
23690
+ constructor(project, source, store, index, analyzer, budget, journal) {
23550
23691
  this.project = project;
23551
23692
  this.source = source;
23552
23693
  this.store = store;
23553
23694
  this.index = index;
23695
+ this.analyzer = analyzer;
23554
23696
  this.budget = budget;
23555
23697
  this.journal = journal;
23556
23698
  }
@@ -23558,12 +23700,19 @@ var LayerMap = class _LayerMap {
23558
23700
  source;
23559
23701
  store;
23560
23702
  index;
23703
+ analyzer;
23561
23704
  budget;
23562
23705
  journal;
23563
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;
23564
23713
  static async open(options) {
23565
23714
  const project = await realpath2(options.project);
23566
- const stat3 = await lstat2(project, { bigint: true });
23715
+ const stat3 = await lstat3(project, { bigint: true });
23567
23716
  if (!stat3.isDirectory()) throw new ProjectEvidenceError("PROJECT_PATH_INVALID", false);
23568
23717
  const source = {
23569
23718
  kind: "WORKTREE",
@@ -23575,62 +23724,156 @@ var LayerMap = class _LayerMap {
23575
23724
  openMapDatabase(file2)
23576
23725
  );
23577
23726
  const { typescript, go, python, java } = options.analyzers;
23578
- const index = new CodeIndex(
23579
- store,
23580
- void 0,
23581
- new ProjectMapAnalyzer([
23582
- new TypeScriptMapAnalyzer(typescript),
23583
- new GoMapAnalyzer(go),
23584
- new PythonMapAnalyzer(python),
23585
- new JavaMapAnalyzer(java)
23586
- ])
23587
- );
23727
+ const analyzer = new ProjectMapAnalyzer([
23728
+ new TypeScriptMapAnalyzer(typescript),
23729
+ new GoMapAnalyzer(go),
23730
+ new PythonMapAnalyzer(python),
23731
+ new JavaMapAnalyzer(java)
23732
+ ]);
23588
23733
  return new _LayerMap(
23589
23734
  project,
23590
23735
  source,
23591
23736
  store,
23592
- index,
23737
+ new CodeIndex(store, void 0, analyzer),
23738
+ analyzer.id,
23593
23739
  { maxBytes: options.maxOutputBytes ?? 96 * 1024, envelopeBytes: 0 },
23594
23740
  `${file2}-wal`
23595
23741
  );
23596
23742
  }
23597
23743
  /** The map version of the directory as it is now, built or updated if needed. */
23598
23744
  refresh(signal) {
23745
+ return this.using((hold) => this.current(signal, hold));
23746
+ }
23747
+ current(signal, hold) {
23599
23748
  return this.serialized(async () => {
23600
- const version2 = await this.index.prepare(this.source, signal, {
23601
- initialScope: DEFAULT_INITIAL_EVIDENCE_SCOPE
23602
- });
23749
+ const version2 = await this.prepare(this.source, signal, hold);
23603
23750
  this.prune(version2);
23604
23751
  this.tidyJournal();
23605
23752
  return version2.version;
23606
23753
  });
23607
23754
  }
23608
- /** The map version of a commit of the directory; files it shares with other versions are reused. */
23609
- 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) {
23610
23760
  return this.serialized(async () => {
23611
- const version2 = await this.index.prepare({ ...this.source, kind: "COMMIT", commit }, signal, {
23612
- 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
23613
23767
  });
23614
- 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;
23615
23773
  });
23616
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
+ }
23617
23793
  // One capture at a time; a query waiting behind one captures again, since files may change.
23618
23794
  serialized(capture) {
23619
23795
  const next = (this.refreshing ?? Promise.resolve("")).catch(() => "").then(capture);
23620
23796
  this.refreshing = next;
23621
23797
  return next;
23622
23798
  }
23623
- /** 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
+ */
23624
23859
  prune(version2) {
23860
+ const database = this.store.database;
23625
23861
  const count = Number(
23626
- 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
23627
23863
  );
23628
23864
  if (count <= KEEP_VERSIONS) return;
23629
- this.store.collectGarbage([
23865
+ const refs = (rows2) => rows2.map((row) => String(row.version_ref));
23866
+ const removed = this.store.collectGarbage(() => [
23630
23867
  version2.version,
23631
- ...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
+ )
23632
23875
  ]);
23633
- this.store.database.exec("PRAGMA incremental_vacuum;");
23876
+ if (removed) database.exec("PRAGMA incremental_vacuum;");
23634
23877
  }
23635
23878
  // SQLite leaves the write-ahead log at the size of the largest capture written through it, often
23636
23879
  // hundreds of megabytes after a build. Once that capture is in the database the log is emptied,
@@ -23641,33 +23884,29 @@ var LayerMap = class _LayerMap {
23641
23884
  database.exec("PRAGMA busy_timeout = 0;");
23642
23885
  try {
23643
23886
  database.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get();
23644
- } catch {
23645
23887
  } finally {
23646
23888
  database.exec(BUSY_TIMEOUT);
23647
23889
  }
23648
23890
  }
23649
- async explore(input, signal) {
23650
- const version2 = await this.refresh(signal);
23651
- return this.index.query.viewMap(
23652
- { ...input, version: version2, allowedPathPrefixes: ["."], outputBudget: this.budget },
23653
- signal
23654
- );
23655
- }
23656
- async search(input, signal) {
23657
- const version2 = await this.refresh(signal);
23658
- return this.index.query.searchMapView(
23659
- { ...input, version: version2, allowedPathPrefixes: ["."], outputBudget: this.budget },
23660
- 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
+ )
23661
23902
  );
23662
23903
  }
23663
- async references(input, signal) {
23664
- const version2 = await this.refresh(signal);
23665
- return mapReferenceNavigation(
23666
- await this.index.findReferences(
23904
+ search(input, signal) {
23905
+ return this.using(
23906
+ async (hold) => this.index.query.searchMapView(
23667
23907
  {
23668
23908
  ...input,
23669
- version: version2,
23670
- source: this.source,
23909
+ version: await this.current(signal, hold),
23671
23910
  allowedPathPrefixes: ["."],
23672
23911
  outputBudget: this.budget
23673
23912
  },
@@ -23675,33 +23914,56 @@ var LayerMap = class _LayerMap {
23675
23914
  )
23676
23915
  );
23677
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
+ }
23678
23933
  /**
23679
23934
  * What the working tree's changes against a commit (HEAD by default) affect: the changed and
23680
23935
  * removed declarations, the entry points and tests their callers reach, and what the map cannot
23681
23936
  * see. The base commit's map is built only when the diff removes or changes lines there.
23682
23937
  */
23683
- async checkChanges(input, signal) {
23684
- return checkMapChanges(
23685
- {
23686
- index: this.index,
23687
- project: this.project,
23688
- working: await this.refresh(signal),
23689
- base: input.base ?? "HEAD",
23690
- baseVersion: (commit, baseSignal) => this.versionAt(commit, baseSignal)
23691
- },
23692
- 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
+ )
23693
23950
  );
23694
23951
  }
23695
23952
  /**
23696
23953
  * Builds the map of a base commit (HEAD by default) ahead of a change check, so the check after an
23697
23954
  * edit does not wait for it. A clean working tree's base shares every file with its map.
23698
23955
  */
23699
- async prepareBase(signal, base = "HEAD") {
23700
- 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
+ });
23701
23960
  }
23702
23961
  async close() {
23962
+ clearInterval(this.renewal);
23703
23963
  await this.index.quiesce();
23704
23964
  this.index.close();
23965
+ this.store.database.prepare("DELETE FROM layermap_version_holds WHERE holder = ?").run(this.holder);
23966
+ this.closed = true;
23705
23967
  this.store.database.close();
23706
23968
  }
23707
23969
  };
@@ -24072,8 +24334,10 @@ var more = (nextOffset) => nextOffset === void 0 ? "" : `
24072
24334
  [More entries: call again with offset ${nextOffset} and otherwise the same arguments.]`;
24073
24335
  var HINTS = {
24074
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.",
24075
- PROJECT_READ_SOURCE_CHANGED: "Files changed while the map was updating. Call again.",
24076
- 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.",
24077
24341
  PROJECT_CONTINUATION_INVALID: "The offset or cursor belongs to an earlier map or other arguments. Start again without it.",
24078
24342
  PROJECT_MAP_REFERENCE_CURSOR_INVALID: "The cursor belongs to an earlier map or other arguments. Start again without it.",
24079
24343
  PROJECT_READ_INPUT_INVALID: "The arguments do not describe a valid selection.",
@@ -24176,7 +24440,11 @@ function serveMcp(options) {
24176
24440
  }).catch((error51) => {
24177
24441
  if (!session.signal.aborted) log2(`LayerMap could not build the map: ${String(error51)}`);
24178
24442
  });
24179
- entry = { opened, built };
24443
+ const opening = { opened, built };
24444
+ opened.catch(() => {
24445
+ if (maps.get(project) === opening) maps.delete(project);
24446
+ });
24447
+ entry = opening;
24180
24448
  maps.set(project, entry);
24181
24449
  }
24182
24450
  return entry;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "layermap",
3
- "version": "0.1.25",
3
+ "version": "0.1.26",
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
@@ -235,7 +235,7 @@ export default function layermap(pi) {
235
235
  if (server && !server.dead) return server;
236
236
  starting ??= (async () => {
237
237
  const next = new MapServer(cwd);
238
- const tools = await next.start("0.1.25");
238
+ const tools = await next.start("0.1.26");
239
239
  for (const tool of tools) {
240
240
  if (registered.has(tool.name)) continue;
241
241
  registered.add(tool.name);