codebase-snapshot 0.20.3 → 0.20.5

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/mcp.cjs CHANGED
@@ -1,13 +1,13 @@
1
1
  'use strict';
2
2
 
3
- var fs2 = require('fs');
4
- var path5 = require('path');
5
- var crypto2 = require('crypto');
3
+ var fs3 = require('fs');
4
+ var path6 = require('path');
5
+ var crypto5 = require('crypto');
6
6
  var module$1 = require('module');
7
7
  var url = require('url');
8
8
  var childProcess = require('child_process');
9
9
  var worker_threads = require('worker_threads');
10
- require('os');
10
+ var os = require('os');
11
11
  var ts = require('typescript');
12
12
  var http = require('http');
13
13
 
@@ -32,10 +32,11 @@ function _interopNamespace(e) {
32
32
  return Object.freeze(n);
33
33
  }
34
34
 
35
- var fs2__namespace = /*#__PURE__*/_interopNamespace(fs2);
36
- var path5__namespace = /*#__PURE__*/_interopNamespace(path5);
37
- var crypto2__namespace = /*#__PURE__*/_interopNamespace(crypto2);
35
+ var fs3__namespace = /*#__PURE__*/_interopNamespace(fs3);
36
+ var path6__namespace = /*#__PURE__*/_interopNamespace(path6);
37
+ var crypto5__namespace = /*#__PURE__*/_interopNamespace(crypto5);
38
38
  var childProcess__namespace = /*#__PURE__*/_interopNamespace(childProcess);
39
+ var os__namespace = /*#__PURE__*/_interopNamespace(os);
39
40
  var ts__default = /*#__PURE__*/_interopDefault(ts);
40
41
  var http__namespace = /*#__PURE__*/_interopNamespace(http);
41
42
 
@@ -363,7 +364,7 @@ function parseOwnerBrief(filePath, text) {
363
364
  return {
364
365
  brief: {
365
366
  path: filePath,
366
- digest: crypto2.createHash("sha256").update(text, "utf8").digest("hex"),
367
+ digest: crypto5.createHash("sha256").update(text, "utf8").digest("hex"),
367
368
  ...recognised["Stakes"] ? { stakes: recognised["Stakes"] } : {},
368
369
  ...recognised["The system"] ? { system: recognised["The system"] } : {},
369
370
  ...recognised["What came before"] ? { history: recognised["What came before"] } : {},
@@ -421,15 +422,15 @@ var SKIPPED_WALK_DIRS = /* @__PURE__ */ new Set([
421
422
  ]);
422
423
  function readSmallFile(fullPath) {
423
424
  try {
424
- const stats = fs2__namespace.statSync(fullPath);
425
+ const stats = fs3__namespace.statSync(fullPath);
425
426
  if (!stats.isFile() || stats.size > MANIFEST_MAX_BYTES) return null;
426
- return fs2__namespace.readFileSync(fullPath, "utf8");
427
+ return fs3__namespace.readFileSync(fullPath, "utf8");
427
428
  } catch {
428
429
  return null;
429
430
  }
430
431
  }
431
432
  function readManifest(cwd, name) {
432
- return readSmallFile(path5__namespace.join(cwd, name));
433
+ return readSmallFile(path6__namespace.join(cwd, name));
433
434
  }
434
435
  function dependenciesFromPackageJson(raw) {
435
436
  const names = /* @__PURE__ */ new Set();
@@ -489,7 +490,7 @@ function pnpmWorkspacePatterns(raw) {
489
490
  function childDirectories(cwd, parent) {
490
491
  let entries;
491
492
  try {
492
- entries = fs2__namespace.readdirSync(path5__namespace.join(cwd, parent), { withFileTypes: true });
493
+ entries = fs3__namespace.readdirSync(path6__namespace.join(cwd, parent), { withFileTypes: true });
493
494
  } catch {
494
495
  return [];
495
496
  }
@@ -524,13 +525,13 @@ function workspacePackageDirs(cwd, patterns) {
524
525
  function scanWorkspacePackages(cwd, patterns) {
525
526
  const files = /* @__PURE__ */ new Set();
526
527
  const dependencies = /* @__PURE__ */ new Set();
527
- for (const relative9 of workspacePackageDirs(cwd, patterns)) {
528
- const full = path5__namespace.join(cwd, relative9);
528
+ for (const relative10 of workspacePackageDirs(cwd, patterns)) {
529
+ const full = path6__namespace.join(cwd, relative10);
529
530
  try {
530
- for (const entry of fs2__namespace.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
531
+ for (const entry of fs3__namespace.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
531
532
  } catch {
532
533
  }
533
- const raw = readSmallFile(path5__namespace.join(full, "package.json"));
534
+ const raw = readSmallFile(path6__namespace.join(full, "package.json"));
534
535
  if (raw !== null) {
535
536
  for (const name of dependenciesFromPackageJson(raw)) dependencies.add(name);
536
537
  }
@@ -540,7 +541,7 @@ function scanWorkspacePackages(cwd, patterns) {
540
541
  var SNAPSHOT_MARKER = ".codebase-snapshot";
541
542
  function isToolOwnedDirectory(dir) {
542
543
  try {
543
- return fs2__namespace.statSync(dir).isDirectory() && fs2__namespace.existsSync(path5__namespace.join(dir, SNAPSHOT_MARKER));
544
+ return fs3__namespace.statSync(dir).isDirectory() && fs3__namespace.existsSync(path6__namespace.join(dir, SNAPSHOT_MARKER));
544
545
  } catch {
545
546
  return false;
546
547
  }
@@ -555,7 +556,7 @@ function countMarkdownFiles(cwd) {
555
556
  directoriesSeen += 1;
556
557
  let entries;
557
558
  try {
558
- entries = fs2__namespace.readdirSync(current.dir, { withFileTypes: true });
559
+ entries = fs3__namespace.readdirSync(current.dir, { withFileTypes: true });
559
560
  } catch {
560
561
  continue;
561
562
  }
@@ -566,7 +567,7 @@ function countMarkdownFiles(cwd) {
566
567
  }
567
568
  if (!entry.isDirectory() || current.depth >= 2) continue;
568
569
  if (entry.name.startsWith(".") || SKIPPED_WALK_DIRS.has(entry.name)) continue;
569
- const child = path5__namespace.join(current.dir, entry.name);
570
+ const child = path6__namespace.join(current.dir, entry.name);
570
571
  if (isToolOwnedDirectory(child)) continue;
571
572
  queue.push({ dir: child, depth: current.depth + 1 });
572
573
  }
@@ -577,7 +578,7 @@ function buildPresetContext(cwd) {
577
578
  const files = /* @__PURE__ */ new Set();
578
579
  const dirs = /* @__PURE__ */ new Set();
579
580
  try {
580
- for (const entry of fs2__namespace.readdirSync(cwd, { withFileTypes: true })) {
581
+ for (const entry of fs3__namespace.readdirSync(cwd, { withFileTypes: true })) {
581
582
  if (entry.isDirectory()) dirs.add(entry.name);
582
583
  else if (entry.isFile()) files.add(entry.name);
583
584
  }
@@ -594,7 +595,7 @@ function buildPresetContext(cwd) {
594
595
  const isWorkspace = files.has("pnpm-workspace.yaml") || files.has("nx.json") || files.has("turbo.json") || files.has("lerna.json") || packageJson !== void 0 && packageJson.includes('"workspaces"') || declaredWorkspaces.length > 0;
595
596
  let workspace = { files: /* @__PURE__ */ new Set(), dependencies: /* @__PURE__ */ new Set() };
596
597
  if (isWorkspace) {
597
- const pnpmRaw = files.has("pnpm-workspace.yaml") ? readSmallFile(path5__namespace.join(cwd, "pnpm-workspace.yaml")) : null;
598
+ const pnpmRaw = files.has("pnpm-workspace.yaml") ? readSmallFile(path6__namespace.join(cwd, "pnpm-workspace.yaml")) : null;
598
599
  const declared = pnpmRaw === null ? [] : pnpmWorkspacePatterns(pnpmRaw);
599
600
  const patterns = declared.length > 0 ? declared : declaredWorkspaces.length > 0 ? declaredWorkspaces : DEFAULT_WORKSPACE_PATTERNS;
600
601
  workspace = scanWorkspacePackages(cwd, patterns);
@@ -1739,7 +1740,7 @@ var DEFAULT_SECRET_PATTERNS = [
1739
1740
  // rendering of textual userinfo mixes cases, while the prose the earlier rules were
1740
1741
  // protecting (`Bearer authentication`) is a lowercase word.
1741
1742
  rule: "authorization-header",
1742
- pattern: /(?<=[Aa]uthorization["']?\s*[:=]\s*["']?[A-Za-z][A-Za-z0-9._~+/-]{0,31}\s{1,8})(?:[A-Za-z0-9_.+/-]{0,31}[0-9][A-Za-z0-9_.+/-]{0,1024}|[A-Za-z0-9_.+/-]{32,1024}|[A-Za-z0-9_.+/-]{8,1024}={1,2}|(?=[A-Za-z0-9_.+/-]{0,1023}[A-Z])(?=[A-Za-z0-9_.+/-]{0,1023}[a-z])[A-Za-z0-9_.+/-]{12,1024})(?![A-Za-z0-9_.+/=-])/
1743
+ pattern: /(?<=[Aa][Uu][Tt][Hh][Oo][Rr][Ii][Zz][Aa][Tt][Ii][Oo][Nn]["']?\s*[:=]\s*["']?[A-Za-z][A-Za-z0-9._~+/-]{0,31}\s{1,8})(?:[A-Za-z0-9_.+/-]{0,31}[0-9][A-Za-z0-9_.+/-]{0,1024}|[A-Za-z0-9_.+/-]{32,1024}|[A-Za-z0-9_.+/-]{8,1024}={1,2}|(?=[A-Za-z0-9_.+/-]{0,1023}[A-Z])(?=[A-Za-z0-9_.+/-]{0,1023}[a-z])[A-Za-z0-9_.+/-]{12,1024})(?![A-Za-z0-9_.+/=-])/
1743
1744
  },
1744
1745
  {
1745
1746
  // Broader names than before (`apiKey`, `clientSecret`, `privateKey` were
@@ -2317,6 +2318,7 @@ function redactStructuredValues(text, filePath, recordFinding) {
2317
2318
  if (firstValue === void 0) continue;
2318
2319
  const valueIndent = (/^[ \t]*/.exec(firstValue)?.[0] ?? "").length;
2319
2320
  if (valueIndent <= baseIndent) continue;
2321
+ if (STRUCTURED_KEY.test(firstValue) || /^[ \t]*-[ \t]/.test(firstValue)) continue;
2320
2322
  let masked = false;
2321
2323
  while (cursor < segments.length) {
2322
2324
  const body = segments[cursor] ?? "";
@@ -2553,10 +2555,43 @@ function applySpansKeepingQuotes(line, spans) {
2553
2555
  out += line.slice(cursor);
2554
2556
  return out;
2555
2557
  }
2558
+ var SIGNATURE_FILE = "signature.json";
2559
+ function verifySnapshotSignature(snapshotDir) {
2560
+ const signaturePath = path6__namespace.join(snapshotDir, SIGNATURE_FILE);
2561
+ const manifestPath = path6__namespace.join(snapshotDir, "manifest.json");
2562
+ if (!fs3__namespace.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
2563
+ let record;
2564
+ try {
2565
+ record = JSON.parse(fs3__namespace.readFileSync(signaturePath, "utf8"));
2566
+ } catch (error) {
2567
+ return { ok: false, reason: "signature.json is not JSON: " + error.message };
2568
+ }
2569
+ if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
2570
+ return { ok: false, reason: "signature.json is not an ed25519 record" };
2571
+ }
2572
+ let bytes;
2573
+ try {
2574
+ bytes = fs3__namespace.readFileSync(manifestPath);
2575
+ } catch {
2576
+ return { ok: false, reason: "the signed manifest is missing" };
2577
+ }
2578
+ const sha2562 = crypto5__namespace.createHash("sha256").update(bytes).digest("hex");
2579
+ if (sha2562 !== record.manifestSha256) {
2580
+ return { ok: false, reason: "manifest.json changed after it was signed" };
2581
+ }
2582
+ let verified = false;
2583
+ try {
2584
+ const key = crypto5__namespace.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
2585
+ verified = crypto5__namespace.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
2586
+ } catch (error) {
2587
+ return { ok: false, reason: "the signature could not be checked: " + error.message };
2588
+ }
2589
+ return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
2590
+ }
2556
2591
 
2557
2592
  // src/version.ts
2558
2593
  var GENERATOR_NAME = "codebase-snapshot";
2559
- var GENERATOR_VERSION = "0.20.3";
2594
+ var GENERATOR_VERSION = "0.20.5";
2560
2595
  var SCHEMA_VERSION = "3.0.0";
2561
2596
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2562
2597
  function isOurGeneratorName(name) {
@@ -2573,14 +2608,14 @@ var PRESET_IGNORES = new Set(
2573
2608
  );
2574
2609
  function readLinkTarget(linkPath, fallback) {
2575
2610
  try {
2576
- return fs2__namespace.readlinkSync(linkPath);
2611
+ return fs3__namespace.readlinkSync(linkPath);
2577
2612
  } catch {
2578
2613
  return fallback;
2579
2614
  }
2580
2615
  }
2581
2616
  function brokenLinkRecord(linkPath, relativePath, rootReal) {
2582
2617
  const rawTarget = readLinkTarget(linkPath, linkPath);
2583
- const resolvedFallback = path5__namespace.resolve(path5__namespace.dirname(linkPath), rawTarget);
2618
+ const resolvedFallback = path6__namespace.resolve(path6__namespace.dirname(linkPath), rawTarget);
2584
2619
  return isInside(rootReal, resolvedFallback) ? { path: relativePath, reason: "read-error", detail: "broken symlink" } : {
2585
2620
  path: relativePath,
2586
2621
  reason: "outside-root",
@@ -2588,8 +2623,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
2588
2623
  };
2589
2624
  }
2590
2625
  function isInside(root, candidate) {
2591
- const relative9 = path5__namespace.relative(root, candidate);
2592
- return relative9 === "" || !relative9.startsWith(`..${path5__namespace.sep}`) && relative9 !== ".." && !path5__namespace.isAbsolute(relative9);
2626
+ const relative10 = path6__namespace.relative(root, candidate);
2627
+ return relative10 === "" || !relative10.startsWith(`..${path6__namespace.sep}`) && relative10 !== ".." && !path6__namespace.isAbsolute(relative10);
2593
2628
  }
2594
2629
  var GIT_OUTPUT_LIMIT = 68157440;
2595
2630
  function getGitInfo(cwd, fallbackBranch = "main") {
@@ -2849,10 +2884,10 @@ function trimUnescapedTrailingSpaces(line) {
2849
2884
  return line.slice(0, end);
2850
2885
  }
2851
2886
  function readGitignoreRules(dir) {
2852
- const gitignorePath = path5__namespace.join(dir, ".gitignore");
2887
+ const gitignorePath = path6__namespace.join(dir, ".gitignore");
2853
2888
  let raw;
2854
2889
  try {
2855
- raw = fs2__namespace.readFileSync(gitignorePath, "utf8");
2890
+ raw = fs3__namespace.readFileSync(gitignorePath, "utf8");
2856
2891
  } catch {
2857
2892
  return [];
2858
2893
  }
@@ -3025,7 +3060,7 @@ function listIgnoredPaths(cwd) {
3025
3060
  }
3026
3061
  function hasSnapshotMarker(target) {
3027
3062
  try {
3028
- return fs2__namespace.statSync(target).isDirectory() && fs2__namespace.existsSync(path5__namespace.join(target, ".codebase-snapshot"));
3063
+ return fs3__namespace.statSync(target).isDirectory() && isToolOwnedDirectory2(target);
3029
3064
  } catch {
3030
3065
  return false;
3031
3066
  }
@@ -3034,7 +3069,7 @@ var IGNORABLE_DIRECTORY_ENTRIES = /* @__PURE__ */ new Set([".DS_Store"]);
3034
3069
  function isToolOwnedDirectory2(dir) {
3035
3070
  let raw;
3036
3071
  try {
3037
- raw = fs2__namespace.readFileSync(path5__namespace.join(dir, ".codebase-snapshot"), "utf8");
3072
+ raw = fs3__namespace.readFileSync(path6__namespace.join(dir, ".codebase-snapshot"), "utf8");
3038
3073
  } catch {
3039
3074
  return false;
3040
3075
  }
@@ -3061,12 +3096,14 @@ function isToolOwnedDirectory2(dir) {
3061
3096
  }
3062
3097
  let entries;
3063
3098
  try {
3064
- entries = fs2__namespace.readdirSync(dir);
3099
+ entries = fs3__namespace.readdirSync(dir);
3065
3100
  } catch {
3066
3101
  return false;
3067
3102
  }
3068
3103
  return entries.every(
3069
- (entry) => entry === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry) || accounted.has(entry)
3104
+ (entry) => entry === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry) || // A snapshot signed before signing moved into staging has a valid signature.json the old
3105
+ // marker could not record. It is our artifact when the signature verifies.
3106
+ entry === "signature.json" && verifySnapshotSignature(dir).ok || accounted.has(entry)
3070
3107
  );
3071
3108
  }
3072
3109
  function makeToolOwnedDecider(cwd, toolOwnedPaths) {
@@ -3078,7 +3115,7 @@ function makeToolOwnedDecider(cwd, toolOwnedPaths) {
3078
3115
  const prefix = parts.slice(0, depth).join("/");
3079
3116
  let hasMarker = markers.get(prefix);
3080
3117
  if (hasMarker === void 0) {
3081
- hasMarker = isToolOwnedDirectory2(path5__namespace.join(cwd, prefix));
3118
+ hasMarker = isToolOwnedDirectory2(path6__namespace.join(cwd, prefix));
3082
3119
  markers.set(prefix, hasMarker);
3083
3120
  }
3084
3121
  if (hasMarker) return true;
@@ -3093,7 +3130,7 @@ function makeLinkProbe() {
3093
3130
  let known = cache.get(absolutePath);
3094
3131
  if (known === void 0) {
3095
3132
  try {
3096
- known = fs2__namespace.lstatSync(absolutePath).isSymbolicLink();
3133
+ known = fs3__namespace.lstatSync(absolutePath).isSymbolicLink();
3097
3134
  } catch {
3098
3135
  known = false;
3099
3136
  }
@@ -3106,7 +3143,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
3106
3143
  const isLink = makeLinkProbe();
3107
3144
  let rootReal = cwd;
3108
3145
  try {
3109
- rootReal = fs2__namespace.realpathSync(cwd);
3146
+ rootReal = fs3__namespace.realpathSync(cwd);
3110
3147
  } catch {
3111
3148
  }
3112
3149
  const reported = /* @__PURE__ */ new Set();
@@ -3121,7 +3158,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
3121
3158
  let linkedPath = null;
3122
3159
  for (let depth = 1; depth <= parts.length; depth += 1) {
3123
3160
  const prefix = parts.slice(0, depth).join("/");
3124
- if (isLink(path5__namespace.join(cwd, prefix))) {
3161
+ if (isLink(path6__namespace.join(cwd, prefix))) {
3125
3162
  linkedPath = prefix;
3126
3163
  break;
3127
3164
  }
@@ -3130,11 +3167,11 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
3130
3167
  kept.push(candidate);
3131
3168
  continue;
3132
3169
  }
3133
- const absolute = path5__namespace.join(cwd, linkedPath);
3170
+ const absolute = path6__namespace.join(cwd, linkedPath);
3134
3171
  const rawTarget = readLinkTarget(absolute, absolute);
3135
3172
  let targetReal = null;
3136
3173
  try {
3137
- targetReal = fs2__namespace.realpathSync(absolute);
3174
+ targetReal = fs3__namespace.realpathSync(absolute);
3138
3175
  } catch {
3139
3176
  targetReal = null;
3140
3177
  }
@@ -3152,7 +3189,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
3152
3189
  }
3153
3190
  let stats = null;
3154
3191
  try {
3155
- stats = fs2__namespace.statSync(absolute);
3192
+ stats = fs3__namespace.statSync(absolute);
3156
3193
  } catch {
3157
3194
  stats = null;
3158
3195
  }
@@ -3176,6 +3213,15 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
3176
3213
  });
3177
3214
  continue;
3178
3215
  }
3216
+ const targetRelative = path6__namespace.relative(rootReal, targetReal).split(path6__namespace.sep).join("/");
3217
+ if (isSensitivePath(targetRelative)) {
3218
+ report2(linkedPath, {
3219
+ path: linkedPath,
3220
+ reason: "sensitive-file",
3221
+ detail: "link target is a credential-bearing file; not followed"
3222
+ });
3223
+ continue;
3224
+ }
3179
3225
  kept.push(candidate);
3180
3226
  }
3181
3227
  return kept;
@@ -3240,7 +3286,7 @@ function collectFiles(cwd, options = {}) {
3240
3286
  "Discovery mode is `git`, but git could not list this directory's files. Run inside a working repository, or pass --discovery walk (or auto) to scan the tree directly."
3241
3287
  );
3242
3288
  }
3243
- if (fs2__namespace.existsSync(path5__namespace.join(cwd, ".git"))) {
3289
+ if (fs3__namespace.existsSync(path6__namespace.join(cwd, ".git"))) {
3244
3290
  throw new Error(
3245
3291
  "This directory is a git repository, but git could not list its files. A plain walk honours .gitignore files, but git also applies .git/info/exclude and your global excludes file, includes files that are tracked although a .gitignore now matches them, and treats a submodule as a single entry. Fix the repository (git status should work), run outside git, or pass --discovery walk to accept those differences."
3246
3292
  );
@@ -3259,7 +3305,7 @@ function collectFiles(cwd, options = {}) {
3259
3305
  candidates.push(extra);
3260
3306
  }
3261
3307
  }
3262
- const files = candidates.filter((file) => {
3308
+ let files = candidates.filter((file) => {
3263
3309
  if (isToolOwned(file)) return false;
3264
3310
  const ignored = defaultIgnoreReason(file, toolDirNames);
3265
3311
  if (ignored) {
@@ -3304,11 +3350,53 @@ function collectFiles(cwd, options = {}) {
3304
3350
  }
3305
3351
  return true;
3306
3352
  }).sort();
3353
+ files = dropSymlinksToUnincludedTargets(cwd, files, skipped);
3307
3354
  return { files, skipped: maskSkipPaths(skipped, pathRules) };
3308
3355
  }
3356
+ function dropSymlinksToUnincludedTargets(cwd, files, skipped) {
3357
+ const aliases = /* @__PURE__ */ new Set();
3358
+ for (const file of files) {
3359
+ try {
3360
+ if (fs3__namespace.lstatSync(path6__namespace.join(cwd, file)).isSymbolicLink()) aliases.add(file);
3361
+ } catch {
3362
+ }
3363
+ }
3364
+ if (aliases.size === 0) return [...files];
3365
+ const includedTargets = /* @__PURE__ */ new Set();
3366
+ for (const file of files) {
3367
+ try {
3368
+ includedTargets.add(fs3__namespace.realpathSync(path6__namespace.join(cwd, file)));
3369
+ } catch {
3370
+ }
3371
+ }
3372
+ const kept = [];
3373
+ for (const file of files) {
3374
+ if (!aliases.has(file)) {
3375
+ kept.push(file);
3376
+ continue;
3377
+ }
3378
+ let target;
3379
+ try {
3380
+ target = fs3__namespace.realpathSync(path6__namespace.join(cwd, file));
3381
+ } catch {
3382
+ skipped.push({ path: file, reason: "read-error", detail: "symlink target could not be resolved" });
3383
+ continue;
3384
+ }
3385
+ if (includedTargets.has(target)) {
3386
+ kept.push(file);
3387
+ continue;
3388
+ }
3389
+ skipped.push({
3390
+ path: file,
3391
+ reason: "symlink",
3392
+ detail: "link target was excluded from the snapshot; not followed"
3393
+ });
3394
+ }
3395
+ return kept;
3396
+ }
3309
3397
  function rootRealFor(root) {
3310
3398
  try {
3311
- return fs2__namespace.realpathSync(root);
3399
+ return fs3__namespace.realpathSync(root);
3312
3400
  } catch {
3313
3401
  return root;
3314
3402
  }
@@ -3317,18 +3405,18 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
3317
3405
  const results = { files: [], skipped: [] };
3318
3406
  const stack = [];
3319
3407
  const toolDirNames = toolDirNamesFor(reservedPaths);
3320
- const relativeToBase = (target) => path5__namespace.relative(baseDir, target).replace(/\\/g, "/") || ".";
3408
+ const relativeToBase = (target) => path6__namespace.relative(baseDir, target).replace(/\\/g, "/") || ".";
3321
3409
  const enter = (current, layers) => {
3322
3410
  if (visited.has(current)) return false;
3323
3411
  visited.add(current);
3324
3412
  const localRules = readGitignoreRules(current);
3325
3413
  const gitignoreLayers = localRules.length === 0 ? layers : [
3326
3414
  ...layers,
3327
- { prefix: path5__namespace.relative(baseDir, current).replace(/\\/g, "/"), rules: localRules }
3415
+ { prefix: path6__namespace.relative(baseDir, current).replace(/\\/g, "/"), rules: localRules }
3328
3416
  ];
3329
3417
  let entries;
3330
3418
  try {
3331
- entries = fs2__namespace.readdirSync(current, { withFileTypes: true });
3419
+ entries = fs3__namespace.readdirSync(current, { withFileTypes: true });
3332
3420
  } catch {
3333
3421
  results.skipped.push({
3334
3422
  path: relativeToBase(current),
@@ -3350,8 +3438,8 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
3350
3438
  }
3351
3439
  const entry = frame.entries[frame.index];
3352
3440
  frame.index += 1;
3353
- const fullPath = path5__namespace.join(frame.dir, entry.name);
3354
- const relPath = path5__namespace.relative(baseDir, fullPath).replace(/\\/g, "/");
3441
+ const fullPath = path6__namespace.join(frame.dir, entry.name);
3442
+ const relPath = path6__namespace.relative(baseDir, fullPath).replace(/\\/g, "/");
3355
3443
  if (reservedPaths.has(relPath)) continue;
3356
3444
  if (entry.isDirectory() && DEFAULT_IGNORED_DIRS.includes(entry.name)) {
3357
3445
  results.skipped.push({
@@ -3384,14 +3472,14 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
3384
3472
  if (entry.isSymbolicLink()) {
3385
3473
  let targetReal;
3386
3474
  try {
3387
- targetReal = fs2__namespace.realpathSync(fullPath);
3475
+ targetReal = fs3__namespace.realpathSync(fullPath);
3388
3476
  } catch {
3389
3477
  results.skipped.push(brokenLinkRecord(fullPath, relPath, rootReal));
3390
3478
  continue;
3391
3479
  }
3392
3480
  let stats;
3393
3481
  try {
3394
- stats = fs2__namespace.statSync(fullPath);
3482
+ stats = fs3__namespace.statSync(fullPath);
3395
3483
  } catch {
3396
3484
  results.skipped.push({ path: relPath, reason: "read-error", detail: "unreadable symlink" });
3397
3485
  continue;
@@ -3421,7 +3509,7 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
3421
3509
  });
3422
3510
  continue;
3423
3511
  }
3424
- const targetRelative = path5__namespace.relative(rootReal, targetReal).split(path5__namespace.sep).join("/");
3512
+ const targetRelative = path6__namespace.relative(rootReal, targetReal).split(path6__namespace.sep).join("/");
3425
3513
  if (isSensitivePath(targetRelative)) {
3426
3514
  results.skipped.push({
3427
3515
  path: relPath,
@@ -3617,21 +3705,25 @@ var CONFIG_KEY_NAMES = [
3617
3705
  "kinds",
3618
3706
  "largeFileBytes",
3619
3707
  "layers",
3708
+ "logCount",
3620
3709
  "layersMode",
3621
3710
  "maxMonolithBytes",
3622
3711
  "maxPartBytes",
3623
3712
  "maxParts",
3624
3713
  "maxPartTokens",
3625
3714
  "outDir",
3715
+ "pack",
3626
3716
  "preset",
3627
3717
  "previewHeadLines",
3628
3718
  "promptTask",
3629
3719
  "staged",
3630
3720
  "previewTailLines",
3721
+ "removeEmptyLines",
3631
3722
  "secretRules",
3632
3723
  "secrets",
3633
3724
  "sarif",
3634
3725
  "skeleton",
3726
+ "stripComments",
3635
3727
  "tmpDir",
3636
3728
  "withDependents"
3637
3729
  ];
@@ -3676,10 +3768,10 @@ function readConfigExport(exported, file) {
3676
3768
  var lastModuleConfig = null;
3677
3769
  function moduleConfigKey(fullPath) {
3678
3770
  try {
3679
- return crypto2.createHash("sha256").update(fs2__namespace.readFileSync(fullPath)).digest("hex").slice(0, 24);
3771
+ return crypto5.createHash("sha256").update(fs3__namespace.readFileSync(fullPath)).digest("hex").slice(0, 24);
3680
3772
  } catch {
3681
3773
  try {
3682
- const stats = fs2__namespace.statSync(fullPath);
3774
+ const stats = fs3__namespace.statSync(fullPath);
3683
3775
  return `stat-${stats.mtimeMs}-${stats.size}`;
3684
3776
  } catch {
3685
3777
  return "unreadable";
@@ -3705,7 +3797,7 @@ async function importConfigModule(fullPath) {
3705
3797
  function attachConfigDir(config, filePath) {
3706
3798
  if (typeof config === "object" && config !== null) {
3707
3799
  Object.defineProperty(config, CONFIG_DIR_SYMBOL, {
3708
- value: path5__namespace.dirname(filePath),
3800
+ value: path6__namespace.dirname(filePath),
3709
3801
  enumerable: false,
3710
3802
  configurable: true
3711
3803
  });
@@ -3717,12 +3809,12 @@ async function loadConfigFileDetailed(cwd, options = {}) {
3717
3809
  const errors = [];
3718
3810
  const configDirectories = [];
3719
3811
  for (const filename of CONFIG_FILENAMES) {
3720
- const fullPath = path5__namespace.join(cwd, filename);
3812
+ const fullPath = path6__namespace.join(cwd, filename);
3721
3813
  let candidateStats = null;
3722
3814
  try {
3723
- candidateStats = fs2__namespace.statSync(fullPath);
3815
+ candidateStats = fs3__namespace.statSync(fullPath);
3724
3816
  } catch {
3725
- if (!fs2__namespace.existsSync(fullPath)) continue;
3817
+ if (!fs3__namespace.existsSync(fullPath)) continue;
3726
3818
  }
3727
3819
  if (candidateStats !== null && !candidateStats.isFile()) {
3728
3820
  configDirectories.push(fullPath);
@@ -3730,7 +3822,7 @@ async function loadConfigFileDetailed(cwd, options = {}) {
3730
3822
  }
3731
3823
  if (filename.endsWith(".json") || filename === ".snapshotrc") {
3732
3824
  try {
3733
- const config = parseJsonish(fs2__namespace.readFileSync(fullPath, "utf8"), fullPath);
3825
+ const config = parseJsonish(fs3__namespace.readFileSync(fullPath, "utf8"), fullPath);
3734
3826
  if (config === null || typeof config !== "object" || Array.isArray(config)) {
3735
3827
  throw new Error(
3736
3828
  `${fullPath} does not hold a configuration object (received ${describeValue2(config)}).`
@@ -3770,10 +3862,10 @@ async function loadConfigFileDetailed(cwd, options = {}) {
3770
3862
  continue;
3771
3863
  }
3772
3864
  }
3773
- const pkgJsonPath = path5__namespace.join(cwd, "package.json");
3774
- if (fs2__namespace.existsSync(pkgJsonPath)) {
3865
+ const pkgJsonPath = path6__namespace.join(cwd, "package.json");
3866
+ if (fs3__namespace.existsSync(pkgJsonPath)) {
3775
3867
  try {
3776
- const parsed = parseJsonish(fs2__namespace.readFileSync(pkgJsonPath, "utf8"), pkgJsonPath);
3868
+ const parsed = parseJsonish(fs3__namespace.readFileSync(pkgJsonPath, "utf8"), pkgJsonPath);
3777
3869
  const snapshotKey = parsed.snapshot;
3778
3870
  if (snapshotKey && typeof snapshotKey === "object" && !Array.isArray(snapshotKey)) {
3779
3871
  assertKnownConfigKeys(
@@ -3939,11 +4031,38 @@ function readConfiguredBrief(cwd, value) {
3939
4031
  "brief must be a path to a markdown file (received " + describeValue2(value) + ")."
3940
4032
  );
3941
4033
  }
3942
- const filePath = path5__namespace.resolve(cwd, value);
4034
+ const rootReal = (() => {
4035
+ try {
4036
+ return fs3__namespace.realpathSync(cwd);
4037
+ } catch {
4038
+ return path6__namespace.resolve(cwd);
4039
+ }
4040
+ })();
4041
+ const requested = path6__namespace.resolve(cwd, value);
4042
+ let filePath;
4043
+ try {
4044
+ filePath = fs3__namespace.realpathSync(requested);
4045
+ } catch {
4046
+ throw new Error(
4047
+ 'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
4048
+ );
4049
+ }
4050
+ const relative10 = path6__namespace.relative(rootReal, filePath);
4051
+ if (relative10.length === 0 || relative10 === ".." || relative10.startsWith(`..${path6__namespace.sep}`) || path6__namespace.isAbsolute(relative10)) {
4052
+ throw new Error(
4053
+ 'brief "' + value + '" resolves outside the repository. A brief must be a file inside the repository being described; an absolute or parent path is refused.'
4054
+ );
4055
+ }
4056
+ const posixRelative = relative10.split(path6__namespace.sep).join("/");
4057
+ if (isSensitivePath(posixRelative) || isSensitivePath(value)) {
4058
+ throw new Error(
4059
+ 'brief "' + value + '" is a credential-bearing file. A snapshot must not reproduce secrets, so it cannot be used as the owner brief.'
4060
+ );
4061
+ }
3943
4062
  let text;
3944
4063
  try {
3945
- if (!fs2__namespace.statSync(filePath).isFile()) throw new Error("not a file");
3946
- text = fs2__namespace.readFileSync(filePath, "utf8");
4064
+ if (!fs3__namespace.statSync(filePath).isFile()) throw new Error("not a file");
4065
+ text = fs3__namespace.readFileSync(filePath, "utf8");
3947
4066
  } catch {
3948
4067
  throw new Error(
3949
4068
  'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
@@ -4055,12 +4174,12 @@ function resolveKindRules(value) {
4055
4174
  function outputExcludePatterns(cwd, outDir, tmpDir) {
4056
4175
  const patterns = [];
4057
4176
  for (const dir of [outDir, tmpDir]) {
4058
- const absolute = path5__namespace.resolve(cwd, dir);
4059
- const relative9 = path5__namespace.relative(cwd, absolute);
4060
- if (!relative9 || relative9 === ".." || relative9.startsWith(`..${path5__namespace.sep}`) || path5__namespace.isAbsolute(relative9)) {
4177
+ const absolute = path6__namespace.resolve(cwd, dir);
4178
+ const relative10 = path6__namespace.relative(cwd, absolute);
4179
+ if (!relative10 || relative10 === ".." || relative10.startsWith(`..${path6__namespace.sep}`) || path6__namespace.isAbsolute(relative10)) {
4061
4180
  continue;
4062
4181
  }
4063
- patterns.push(`${relative9.replace(/\\/g, "/")}/**`);
4182
+ patterns.push(`${relative10.replace(/\\/g, "/")}/**`);
4064
4183
  }
4065
4184
  return patterns;
4066
4185
  }
@@ -4190,11 +4309,11 @@ function resolveCandidateCwd(userConfig, cliOptions, baseDir) {
4190
4309
  );
4191
4310
  }
4192
4311
  const candidate = cliOptions?.cwd || userConfig?.cwd || baseDir || process.cwd();
4193
- const resolved = path5__namespace.resolve(candidate);
4194
- if (!fs2__namespace.existsSync(resolved)) {
4312
+ const resolved = path6__namespace.resolve(candidate);
4313
+ if (!fs3__namespace.existsSync(resolved)) {
4195
4314
  throw new Error(`Working directory does not exist: ${resolved}`);
4196
4315
  }
4197
- if (!fs2__namespace.statSync(resolved).isDirectory()) {
4316
+ if (!fs3__namespace.statSync(resolved).isDirectory()) {
4198
4317
  throw new Error(`Working directory is not a directory: ${resolved}`);
4199
4318
  }
4200
4319
  return resolved;
@@ -4524,7 +4643,7 @@ function configDigest(config) {
4524
4643
  (rule) => `${rule.rule}:${rule.pattern.source}/${rule.pattern.flags}:${rule.valueGroup ?? ""}`
4525
4644
  ).sort()
4526
4645
  };
4527
- return crypto2.createHash("sha256").update(JSON.stringify(material)).digest("hex");
4646
+ return crypto5.createHash("sha256").update(JSON.stringify(material)).digest("hex");
4528
4647
  }
4529
4648
 
4530
4649
  // src/ast/profiles/shared.ts
@@ -4848,9 +4967,9 @@ var JAVA_METHOD = /^\s+(?:public|private|protected)\s+(?:static\s+)?(?:final\s+)
4848
4967
  var jvmProfile = {
4849
4968
  id: "jvm",
4850
4969
  extensions: [".java", ".kt", ".kts", ".scala"],
4851
- summarize(path16, content) {
4970
+ summarize(path17, content) {
4852
4971
  const summary = emptySummary();
4853
- const lower = path16.toLowerCase();
4972
+ const lower = path17.toLowerCase();
4854
4973
  const isJava = lower.endsWith(".java");
4855
4974
  const isKotlin = lower.endsWith(".kt") || lower.endsWith(".kts");
4856
4975
  eachLine(content, (line) => {
@@ -5073,9 +5192,9 @@ var rubyProfile = {
5073
5192
  eachLine(content, (line) => {
5074
5193
  const trimmed = line.trim();
5075
5194
  if (!trimmed || trimmed.startsWith("#")) return;
5076
- const relative9 = REQUIRE_RELATIVE.exec(trimmed);
5077
- if (relative9) {
5078
- summary.imports.push(`./${relative9[1]}`);
5195
+ const relative10 = REQUIRE_RELATIVE.exec(trimmed);
5196
+ if (relative10) {
5197
+ summary.imports.push(`./${relative10[1]}`);
5079
5198
  return;
5080
5199
  }
5081
5200
  const required = REQUIRE.exec(trimmed);
@@ -5458,17 +5577,17 @@ function summarizeTypeScriptSource(relativePath, content) {
5458
5577
  var SCRIPT_BLOCK = /<script([^>]*)>([\s\S]*?)<\/script>/gi;
5459
5578
  var JSX_LANG = /\blang\s*=\s*["']?[tj]sx\b/i;
5460
5579
  var ASTRO_FRONTMATTER = /^\uFEFF?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?=\r?\n|$)/;
5461
- function componentName(path16) {
5462
- const base = path16.split("/").pop() ?? path16;
5580
+ function componentName(path17) {
5581
+ const base = path17.split("/").pop() ?? path17;
5463
5582
  return base.replace(/\.[^.]+$/, "");
5464
5583
  }
5465
5584
  var sfcProfile = {
5466
5585
  id: "sfc",
5467
5586
  extensions: [".vue", ".svelte", ".astro"],
5468
- summarize(path16, content) {
5587
+ summarize(path17, content) {
5469
5588
  let script = "";
5470
- let usesJsx = path16.toLowerCase().endsWith(".astro");
5471
- if (path16.toLowerCase().endsWith(".astro")) {
5589
+ let usesJsx = path17.toLowerCase().endsWith(".astro");
5590
+ if (path17.toLowerCase().endsWith(".astro")) {
5472
5591
  const frontmatter = ASTRO_FRONTMATTER.exec(content);
5473
5592
  if (frontmatter) script += `${frontmatter[1]}
5474
5593
  `;
@@ -5478,7 +5597,7 @@ var sfcProfile = {
5478
5597
  script += `${match[2]}
5479
5598
  `;
5480
5599
  }
5481
- const name = componentName(path16);
5600
+ const name = componentName(path17);
5482
5601
  if (!script.trim()) {
5483
5602
  const summary2 = emptySummary();
5484
5603
  if (name) {
@@ -5669,15 +5788,15 @@ for (const profile of LANGUAGE_PROFILES) {
5669
5788
  BY_EXTENSION.set(extension.toLowerCase(), profile);
5670
5789
  }
5671
5790
  }
5672
- function profileForPath(path16) {
5673
- const lower = path16.toLowerCase();
5791
+ function profileForPath(path17) {
5792
+ const lower = path17.toLowerCase();
5674
5793
  const dot = lower.lastIndexOf(".");
5675
5794
  if (dot === -1) return null;
5676
5795
  return BY_EXTENSION.get(lower.slice(dot)) ?? null;
5677
5796
  }
5678
- function summarizeWithProfile(path16, content) {
5679
- const profile = profileForPath(path16);
5680
- return profile ? profile.summarize(path16, content) : null;
5797
+ function summarizeWithProfile(path17, content) {
5798
+ const profile = profileForPath(path17);
5799
+ return profile ? profile.summarize(path17, content) : null;
5681
5800
  }
5682
5801
  var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
5683
5802
  ".png",
@@ -5722,7 +5841,7 @@ var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
5722
5841
  ".so"
5723
5842
  ]);
5724
5843
  function isBinaryExtension(filePath) {
5725
- const ext = path5__namespace.extname(filePath).toLowerCase();
5844
+ const ext = path6__namespace.extname(filePath).toLowerCase();
5726
5845
  return BINARY_EXTENSIONS.has(ext);
5727
5846
  }
5728
5847
  function countControlBytes(buffer) {
@@ -5889,13 +6008,13 @@ function isBinaryFile(absolutePath) {
5889
6008
  if (isBinaryExtension(absolutePath)) return true;
5890
6009
  let fd;
5891
6010
  try {
5892
- fd = fs2__namespace.openSync(absolutePath, "r");
6011
+ fd = fs3__namespace.openSync(absolutePath, "r");
5893
6012
  const buffer = Buffer.alloc(CHUNK);
5894
6013
  let sample2;
5895
6014
  let position = 0;
5896
6015
  while (position < BINARY_SCAN_BYTES) {
5897
6016
  const wanted = Math.min(CHUNK, BINARY_SCAN_BYTES - position);
5898
- const bytesRead = fs2__namespace.readSync(fd, buffer, 0, wanted, position);
6017
+ const bytesRead = fs3__namespace.readSync(fd, buffer, 0, wanted, position);
5899
6018
  if (bytesRead === 0) return false;
5900
6019
  const chunk = buffer.subarray(0, bytesRead);
5901
6020
  if (sample2 === void 0) {
@@ -5913,7 +6032,7 @@ function isBinaryFile(absolutePath) {
5913
6032
  } finally {
5914
6033
  if (fd !== void 0) {
5915
6034
  try {
5916
- fs2__namespace.closeSync(fd);
6035
+ fs3__namespace.closeSync(fd);
5917
6036
  } catch {
5918
6037
  }
5919
6038
  }
@@ -5935,9 +6054,9 @@ function importsOfText(relativePath, text) {
5935
6054
  function importsOfFile(relativePath, absolutePath) {
5936
6055
  let buffer;
5937
6056
  try {
5938
- const stats = fs2__namespace.statSync(absolutePath);
6057
+ const stats = fs3__namespace.statSync(absolutePath);
5939
6058
  if (!stats.isFile() || stats.size > SUMMARY_MAX_SOURCE_BYTES) return [];
5940
- buffer = fs2__namespace.readFileSync(absolutePath);
6059
+ buffer = fs3__namespace.readFileSync(absolutePath);
5941
6060
  } catch {
5942
6061
  return [];
5943
6062
  }
@@ -6036,6 +6155,9 @@ function countLines(content) {
6036
6155
  const last = content.charCodeAt(content.length - 1);
6037
6156
  return last === 10 || last === 13 ? breaks : breaks + 1;
6038
6157
  }
6158
+ function countBodyLines(content) {
6159
+ return content.length === 0 ? 0 : content.split("\n").length;
6160
+ }
6039
6161
  function truncateToBytes(content, maxBytes) {
6040
6162
  const buffer = Buffer.from(content, "utf8");
6041
6163
  if (buffer.length <= maxBytes) return { content, isTruncated: false };
@@ -6093,7 +6215,7 @@ function emittedBody(content) {
6093
6215
  }
6094
6216
  function anchorForPath(filePath) {
6095
6217
  const slug = filePath.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
6096
- const digest = crypto2__namespace.createHash("sha256").update(filePath).digest("hex").slice(0, 8);
6218
+ const digest = crypto5__namespace.createHash("sha256").update(filePath).digest("hex").slice(0, 8);
6097
6219
  return `${slug || "file"}-${digest}`;
6098
6220
  }
6099
6221
 
@@ -6189,10 +6311,10 @@ function resolveImport(from, specifier, byPath) {
6189
6311
  if (segment === "..") parts.pop();
6190
6312
  else parts.push(segment);
6191
6313
  }
6192
- const path16 = parts.join("/");
6193
- const withoutExtension = path16.replace(/\.[cm]?[jt]sx?$/, "");
6314
+ const path17 = parts.join("/");
6315
+ const withoutExtension = path17.replace(/\.[cm]?[jt]sx?$/, "");
6194
6316
  const candidates = [
6195
- path16,
6317
+ path17,
6196
6318
  withoutExtension + ".ts",
6197
6319
  withoutExtension + ".tsx",
6198
6320
  withoutExtension + ".js",
@@ -6201,18 +6323,18 @@ function resolveImport(from, specifier, byPath) {
6201
6323
  withoutExtension + ".go",
6202
6324
  withoutExtension + ".rs",
6203
6325
  withoutExtension + "/index.ts",
6204
- path16 + ".ts",
6205
- path16 + ".tsx",
6206
- path16 + ".js",
6207
- path16 + ".jsx",
6208
- path16 + ".mjs",
6209
- path16 + ".cjs",
6210
- path16 + ".py",
6211
- path16 + ".go",
6212
- path16 + ".rs",
6213
- path16 + ".java",
6214
- path16 + "/index.ts",
6215
- path16 + "/index.js"
6326
+ path17 + ".ts",
6327
+ path17 + ".tsx",
6328
+ path17 + ".js",
6329
+ path17 + ".jsx",
6330
+ path17 + ".mjs",
6331
+ path17 + ".cjs",
6332
+ path17 + ".py",
6333
+ path17 + ".go",
6334
+ path17 + ".rs",
6335
+ path17 + ".java",
6336
+ path17 + "/index.ts",
6337
+ path17 + "/index.js"
6216
6338
  ];
6217
6339
  for (const candidate of candidates) {
6218
6340
  const found = byPath.get(candidate);
@@ -6241,12 +6363,12 @@ function planForQuestion(manifest, question, options = {}) {
6241
6363
  const scored = [];
6242
6364
  for (const file of manifest.files) {
6243
6365
  if (isTest(file) && !wantsTests) continue;
6244
- const path16 = file.relativePath.toLowerCase();
6245
- const words = path16.split(/[^a-z0-9_]+/).filter((word) => word.length >= 3);
6366
+ const path17 = file.relativePath.toLowerCase();
6367
+ const words = path17.split(/[^a-z0-9_]+/).filter((word) => word.length >= 3);
6246
6368
  let score = 0;
6247
6369
  const reasons = [];
6248
6370
  for (const term of terms) {
6249
- if (path16.includes(term)) {
6371
+ if (path17.includes(term)) {
6250
6372
  score += 8;
6251
6373
  reasons.push("path:" + term);
6252
6374
  continue;
@@ -6450,6 +6572,17 @@ function gitPaths(cwd, args) {
6450
6572
  }
6451
6573
  return output.split("\0").filter((entry) => entry.length > 0);
6452
6574
  }
6575
+ function readStagedBlob(cwd, relativePath) {
6576
+ try {
6577
+ return childProcess.execFileSync("git", ["cat-file", "blob", `:${relativePath}`], {
6578
+ cwd,
6579
+ stdio: ["ignore", "pipe", "pipe"],
6580
+ maxBuffer: 512 * 1024 * 1024
6581
+ });
6582
+ } catch {
6583
+ return null;
6584
+ }
6585
+ }
6453
6586
  function assertUsableRef(ref) {
6454
6587
  if (ref.startsWith("-")) {
6455
6588
  throw new Error(
@@ -6464,7 +6597,7 @@ function resolveChangedScope(cwd, request) {
6464
6597
  const descriptions = [];
6465
6598
  if (request.changedSince !== void 0) {
6466
6599
  assertUsableRef(request.changedSince);
6467
- for (const path16 of gitPaths(cwd, [
6600
+ for (const path17 of gitPaths(cwd, [
6468
6601
  "diff",
6469
6602
  "--name-only",
6470
6603
  "-z",
@@ -6472,9 +6605,9 @@ function resolveChangedScope(cwd, request) {
6472
6605
  `${request.changedSince}...HEAD`,
6473
6606
  "--"
6474
6607
  ])) {
6475
- paths.add(path16);
6608
+ paths.add(path17);
6476
6609
  }
6477
- for (const path16 of gitPaths(cwd, [
6610
+ for (const path17 of gitPaths(cwd, [
6478
6611
  "diff",
6479
6612
  "--name-only",
6480
6613
  "-z",
@@ -6482,15 +6615,15 @@ function resolveChangedScope(cwd, request) {
6482
6615
  "HEAD",
6483
6616
  "--"
6484
6617
  ])) {
6485
- paths.add(path16);
6618
+ paths.add(path17);
6486
6619
  }
6487
- for (const path16 of gitPaths(cwd, ["ls-files", "--others", "--exclude-standard", "-z", "--"])) {
6488
- paths.add(path16);
6620
+ for (const path17 of gitPaths(cwd, ["ls-files", "--others", "--exclude-standard", "-z", "--"])) {
6621
+ paths.add(path17);
6489
6622
  }
6490
6623
  descriptions.push(`changed since ${request.changedSince}`);
6491
6624
  }
6492
6625
  if (request.staged === true) {
6493
- for (const path16 of gitPaths(cwd, [
6626
+ for (const path17 of gitPaths(cwd, [
6494
6627
  "diff",
6495
6628
  "--cached",
6496
6629
  "--name-only",
@@ -6498,10 +6631,10 @@ function resolveChangedScope(cwd, request) {
6498
6631
  "--relative",
6499
6632
  "--"
6500
6633
  ])) {
6501
- paths.add(path16);
6502
- stagedPaths.add(path16);
6634
+ paths.add(path17);
6635
+ stagedPaths.add(path17);
6503
6636
  }
6504
- for (const path16 of gitPaths(cwd, [
6637
+ for (const path17 of gitPaths(cwd, [
6505
6638
  "diff",
6506
6639
  "--cached",
6507
6640
  "--name-only",
@@ -6510,7 +6643,7 @@ function resolveChangedScope(cwd, request) {
6510
6643
  "--diff-filter=D",
6511
6644
  "--"
6512
6645
  ])) {
6513
- deletedPaths.add(path16);
6646
+ deletedPaths.add(path17);
6514
6647
  }
6515
6648
  descriptions.push("staged");
6516
6649
  }
@@ -6548,10 +6681,10 @@ var PYTHON_SUFFIXES = [".py", ".pyi", "/__init__.py", "/__init__.pyi"];
6548
6681
  var CASE_INSENSITIVE_FILESYSTEM = process.platform === "win32" || process.platform === "darwin";
6549
6682
  var TSCONFIG_CACHE = /* @__PURE__ */ new Map();
6550
6683
  function tsconfigPathsFor(cwd) {
6551
- const configPath = path5__namespace.join(cwd, "tsconfig.json");
6684
+ const configPath = path6__namespace.join(cwd, "tsconfig.json");
6552
6685
  let stats;
6553
6686
  try {
6554
- stats = fs2__namespace.statSync(configPath);
6687
+ stats = fs3__namespace.statSync(configPath);
6555
6688
  } catch (err) {
6556
6689
  if (err.code === "ENOENT") return null;
6557
6690
  return null;
@@ -6585,8 +6718,8 @@ function tsconfigPathsFor(cwd) {
6585
6718
  return value;
6586
6719
  }
6587
6720
  function repositoryRelative(cwd, target) {
6588
- const relative9 = path5__namespace.relative(cwd, target).replace(/\\/g, "/");
6589
- return relative9.length === 0 || !relative9.startsWith("..") && !path5__namespace.isAbsolute(relative9) ? relative9 : null;
6721
+ const relative10 = path6__namespace.relative(cwd, target).replace(/\\/g, "/");
6722
+ return relative10.length === 0 || !relative10.startsWith("..") && !path6__namespace.isAbsolute(relative10) ? relative10 : null;
6590
6723
  }
6591
6724
  function rememberFirst(map, key, value) {
6592
6725
  if (!map.has(key)) map.set(key, value);
@@ -6601,15 +6734,15 @@ function buildImportResolver(files, options = {}) {
6601
6734
  if (CASE_INSENSITIVE_FILESYSTEM) {
6602
6735
  rememberFirst(byPathFolded, relativePath.toLowerCase(), relativePath);
6603
6736
  }
6604
- const extension = path5__namespace.posix.extname(relativePath);
6737
+ const extension = path6__namespace.posix.extname(relativePath);
6605
6738
  if (!SOURCE_EXTENSIONS.has(extension)) return;
6606
6739
  const stem = relativePath.slice(0, -extension.length);
6607
6740
  rememberFirst(byStem, stem, relativePath);
6608
6741
  if (CASE_INSENSITIVE_FILESYSTEM) {
6609
6742
  rememberFirst(byStemFolded, stem.toLowerCase(), relativePath);
6610
6743
  }
6611
- if (path5__namespace.posix.basename(stem) === "index") {
6612
- const directory = path5__namespace.posix.dirname(stem);
6744
+ if (path6__namespace.posix.basename(stem) === "index") {
6745
+ const directory = path6__namespace.posix.dirname(stem);
6613
6746
  rememberFirst(byStem, directory, relativePath);
6614
6747
  if (CASE_INSENSITIVE_FILESYSTEM) {
6615
6748
  rememberFirst(byStemFolded, directory.toLowerCase(), relativePath);
@@ -6625,7 +6758,7 @@ function buildImportResolver(files, options = {}) {
6625
6758
  return { byPath, byPathFolded, byStem, byStemFolded, tsconfig: options.tsconfig ?? null };
6626
6759
  }
6627
6760
  function resolveSpecifier(fromFile, specifier, resolver) {
6628
- const extension = path5__namespace.posix.extname(fromFile).toLowerCase();
6761
+ const extension = path6__namespace.posix.extname(fromFile).toLowerCase();
6629
6762
  const exact = (key) => resolver.byPath.get(key) ?? (CASE_INSENSITIVE_FILESYSTEM ? resolver.byPathFolded.get(key.toLowerCase()) : void 0) ?? null;
6630
6763
  const firstOf = (candidates) => {
6631
6764
  for (const candidate of candidates) {
@@ -6648,34 +6781,34 @@ function resolveSpecifier(fromFile, specifier, resolver) {
6648
6781
  if (PYTHON_EXTENSIONS.has(extension) && specifier.startsWith(".")) {
6649
6782
  const dots = /^\.+/.exec(specifier)?.[0].length ?? 0;
6650
6783
  const rest = specifier.slice(dots).replace(/\./g, "/");
6651
- let base = path5__namespace.posix.dirname(fromFile);
6652
- for (let up = 1; up < dots; up += 1) base = path5__namespace.posix.dirname(base);
6653
- const joined2 = rest ? path5__namespace.posix.normalize(path5__namespace.posix.join(base, rest)) : base;
6784
+ let base = path6__namespace.posix.dirname(fromFile);
6785
+ for (let up = 1; up < dots; up += 1) base = path6__namespace.posix.dirname(base);
6786
+ const joined2 = rest ? path6__namespace.posix.normalize(path6__namespace.posix.join(base, rest)) : base;
6654
6787
  return firstOf([joined2, ...PYTHON_SUFFIXES.map((suffix) => `${joined2}${suffix}`)]);
6655
6788
  }
6656
6789
  if (RUBY_EXTENSIONS.has(extension) && specifier.startsWith("./")) {
6657
- const joined2 = path5__namespace.posix.normalize(
6658
- path5__namespace.posix.join(path5__namespace.posix.dirname(fromFile), specifier)
6790
+ const joined2 = path6__namespace.posix.normalize(
6791
+ path6__namespace.posix.join(path6__namespace.posix.dirname(fromFile), specifier)
6659
6792
  );
6660
6793
  return firstOf([`${joined2}.rb`, joined2]);
6661
6794
  }
6662
6795
  if (C_EXTENSIONS.has(extension) && specifier.startsWith("./")) {
6663
- const joined2 = path5__namespace.posix.normalize(
6664
- path5__namespace.posix.join(path5__namespace.posix.dirname(fromFile), specifier)
6796
+ const joined2 = path6__namespace.posix.normalize(
6797
+ path6__namespace.posix.join(path6__namespace.posix.dirname(fromFile), specifier)
6665
6798
  );
6666
6799
  return exact(joined2);
6667
6800
  }
6668
6801
  if (extension === ".dart" && !specifier.includes(":")) {
6669
- const joined2 = path5__namespace.posix.normalize(
6670
- path5__namespace.posix.join(path5__namespace.posix.dirname(fromFile), specifier)
6802
+ const joined2 = path6__namespace.posix.normalize(
6803
+ path6__namespace.posix.join(path6__namespace.posix.dirname(fromFile), specifier)
6671
6804
  );
6672
6805
  return firstOf([joined2, `${joined2}.dart`]);
6673
6806
  }
6674
6807
  if (!RELATIVE_SPECIFIER.test(specifier)) {
6675
6808
  return resolveTsconfigSpecifier(specifier, resolver, lookupPath);
6676
6809
  }
6677
- const joined = path5__namespace.posix.normalize(
6678
- path5__namespace.posix.join(path5__namespace.posix.dirname(fromFile), specifier)
6810
+ const joined = path6__namespace.posix.normalize(
6811
+ path6__namespace.posix.join(path6__namespace.posix.dirname(fromFile), specifier)
6679
6812
  );
6680
6813
  return lookupPath(joined);
6681
6814
  }
@@ -6699,13 +6832,13 @@ function resolveTsconfigSpecifier(specifier, resolver, lookupPath) {
6699
6832
  if (captured === null) continue;
6700
6833
  for (const target of rule.targets) {
6701
6834
  const substituted = target.split("*").join(captured);
6702
- const base = config.baseUrl === null ? substituted : path5__namespace.posix.join(config.baseUrl, substituted);
6703
- const hit = lookupPath(path5__namespace.posix.normalize(base));
6835
+ const base = config.baseUrl === null ? substituted : path6__namespace.posix.join(config.baseUrl, substituted);
6836
+ const hit = lookupPath(path6__namespace.posix.normalize(base));
6704
6837
  if (hit) return hit;
6705
6838
  }
6706
6839
  }
6707
6840
  if (config.baseUrl !== null) {
6708
- return lookupPath(path5__namespace.posix.normalize(path5__namespace.posix.join(config.baseUrl, specifier)));
6841
+ return lookupPath(path6__namespace.posix.normalize(path6__namespace.posix.join(config.baseUrl, specifier)));
6709
6842
  }
6710
6843
  return null;
6711
6844
  }
@@ -6773,79 +6906,44 @@ var LANGUAGE_BY_BASENAME = {
6773
6906
  };
6774
6907
  function detectLanguage(filePath) {
6775
6908
  const normalized = filePath.replace(/\\/g, "/");
6776
- const base = path5__namespace.posix.basename(normalized);
6909
+ const base = path6__namespace.posix.basename(normalized);
6777
6910
  if (LANGUAGE_BY_BASENAME[base]) return LANGUAGE_BY_BASENAME[base];
6778
6911
  if (base === ".env" || base.startsWith(".env.")) return "dotenv";
6779
- const ext = path5__namespace.posix.extname(base).toLowerCase();
6912
+ const ext = path6__namespace.posix.extname(base).toLowerCase();
6780
6913
  return LANGUAGE_BY_EXTENSION[ext] ?? "text";
6781
6914
  }
6782
- var SIGNATURE_FILE = "signature.json";
6783
- function verifySnapshotSignature(snapshotDir) {
6784
- const signaturePath = path5__namespace.join(snapshotDir, SIGNATURE_FILE);
6785
- const manifestPath = path5__namespace.join(snapshotDir, "manifest.json");
6786
- if (!fs2__namespace.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
6787
- let record;
6788
- try {
6789
- record = JSON.parse(fs2__namespace.readFileSync(signaturePath, "utf8"));
6790
- } catch (error) {
6791
- return { ok: false, reason: "signature.json is not JSON: " + error.message };
6792
- }
6793
- if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
6794
- return { ok: false, reason: "signature.json is not an ed25519 record" };
6795
- }
6796
- let bytes;
6797
- try {
6798
- bytes = fs2__namespace.readFileSync(manifestPath);
6799
- } catch {
6800
- return { ok: false, reason: "the signed manifest is missing" };
6801
- }
6802
- const sha2562 = crypto2__namespace.createHash("sha256").update(bytes).digest("hex");
6803
- if (sha2562 !== record.manifestSha256) {
6804
- return { ok: false, reason: "manifest.json changed after it was signed" };
6805
- }
6806
- let verified = false;
6807
- try {
6808
- const key = crypto2__namespace.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
6809
- verified = crypto2__namespace.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
6810
- } catch (error) {
6811
- return { ok: false, reason: "the signature could not be checked: " + error.message };
6812
- }
6813
- return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
6814
- }
6815
-
6816
- // src/validator/validate.ts
6817
6915
  function maskedPath(value, secretRules) {
6818
6916
  return findSecretInPath(value, secretRules)?.masked ?? value;
6819
6917
  }
6820
6918
  function confineToDirectory(directory, filename) {
6821
6919
  if (filename.includes("\0")) return null;
6822
- if (path5__namespace.isAbsolute(filename)) return null;
6823
- const base = path5__namespace.resolve(directory);
6824
- const resolved = path5__namespace.resolve(base, filename);
6920
+ if (path6__namespace.isAbsolute(filename)) return null;
6921
+ const base = path6__namespace.resolve(directory);
6922
+ const resolved = path6__namespace.resolve(base, filename);
6825
6923
  const caseInsensitive = process.platform === "win32" || process.platform === "darwin";
6826
- const prefix = caseInsensitive ? `${base}${path5__namespace.sep}`.toLowerCase() : `${base}${path5__namespace.sep}`;
6924
+ const prefix = caseInsensitive ? `${base}${path6__namespace.sep}`.toLowerCase() : `${base}${path6__namespace.sep}`;
6827
6925
  const candidate = caseInsensitive ? resolved.toLowerCase() : resolved;
6828
6926
  return candidate.startsWith(prefix) ? resolved : null;
6829
6927
  }
6830
6928
  function findStagingDirectory(config) {
6831
- const tmpDir = path5__namespace.resolve(config.cwd, config.tmpDir);
6929
+ const tmpDir = path6__namespace.resolve(config.cwd, config.tmpDir);
6832
6930
  let entries;
6833
6931
  try {
6834
- entries = fs2__namespace.readdirSync(tmpDir);
6932
+ entries = fs3__namespace.readdirSync(tmpDir);
6835
6933
  } catch {
6836
6934
  return null;
6837
6935
  }
6838
6936
  const runs = entries.filter((name) => name.startsWith("run-")).sort();
6839
6937
  const newest = runs[runs.length - 1];
6840
- return newest ? path5__namespace.join(tmpDir, newest) : null;
6938
+ return newest ? path6__namespace.join(tmpDir, newest) : null;
6841
6939
  }
6842
6940
  function describeMissingManifest(config, manifestPath) {
6843
- const outDir = path5__namespace.resolve(config.cwd, config.outDir);
6844
- const markerPath = path5__namespace.join(outDir, ".codebase-snapshot");
6941
+ const outDir = path6__namespace.resolve(config.cwd, config.outDir);
6942
+ const markerPath = path6__namespace.join(outDir, ".codebase-snapshot");
6845
6943
  let marker = null;
6846
6944
  try {
6847
- if (fs2__namespace.existsSync(markerPath)) {
6848
- const parsed = JSON.parse(fs2__namespace.readFileSync(markerPath, "utf8"));
6945
+ if (fs3__namespace.existsSync(markerPath)) {
6946
+ const parsed = JSON.parse(fs3__namespace.readFileSync(markerPath, "utf8"));
6849
6947
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
6850
6948
  marker = parsed;
6851
6949
  }
@@ -6877,16 +6975,16 @@ function emptyDrift() {
6877
6975
  };
6878
6976
  }
6879
6977
  function sha256Hex(buffer) {
6880
- return crypto2__namespace.createHash("sha256").update(buffer).digest("hex");
6978
+ return crypto5__namespace.createHash("sha256").update(buffer).digest("hex");
6881
6979
  }
6882
6980
  function wouldNowBeIncluded(cwd, relativePath) {
6883
- const absolutePath = path5__namespace.join(cwd, relativePath);
6981
+ const absolutePath = path6__namespace.join(cwd, relativePath);
6884
6982
  try {
6885
- const stats = fs2__namespace.statSync(absolutePath);
6983
+ const stats = fs3__namespace.statSync(absolutePath);
6886
6984
  if (!stats.isFile()) return false;
6887
6985
  if (isBinaryExtension(absolutePath)) return false;
6888
6986
  if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) return false;
6889
- return !decodeText(fs2__namespace.readFileSync(absolutePath)).binary;
6987
+ return !decodeText(fs3__namespace.readFileSync(absolutePath)).binary;
6890
6988
  } catch {
6891
6989
  return false;
6892
6990
  }
@@ -6898,7 +6996,7 @@ var TRUNCATION_REASONS = /* @__PURE__ */ new Set([
6898
6996
  ]);
6899
6997
  function isConfinedRelative(value) {
6900
6998
  if (value.length === 0 || value.includes("\0") || value.includes("\\")) return false;
6901
- if (path5__namespace.isAbsolute(value)) return false;
6999
+ if (path6__namespace.isAbsolute(value)) return false;
6902
7000
  return !value.split("/").includes("..");
6903
7001
  }
6904
7002
  function describeManifestShapeProblem(value) {
@@ -7092,7 +7190,7 @@ function describeManifestShapeProblem(value) {
7092
7190
  if (typeof filename !== "string" || filename.trim() === "") {
7093
7191
  return 'a "parts" entry has no "filename"';
7094
7192
  }
7095
- if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path5__namespace.isAbsolute(filename)) {
7193
+ if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path6__namespace.isAbsolute(filename)) {
7096
7194
  return 'a "parts" entry "filename" must be a bare filename inside parts/';
7097
7195
  }
7098
7196
  if (currentSchema) {
@@ -7118,8 +7216,8 @@ function describeManifestShapeProblem(value) {
7118
7216
  function validateSnapshot(configInput) {
7119
7217
  assertUsableConfigInput(configInput);
7120
7218
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput);
7121
- const manifestPath = path5__namespace.resolve(config.cwd, config.outDir, "manifest.json");
7122
- if (!fs2__namespace.existsSync(manifestPath)) {
7219
+ const manifestPath = path6__namespace.resolve(config.cwd, config.outDir, "manifest.json");
7220
+ if (!fs3__namespace.existsSync(manifestPath)) {
7123
7221
  return {
7124
7222
  valid: false,
7125
7223
  manifestPresent: false,
@@ -7130,7 +7228,7 @@ function validateSnapshot(configInput) {
7130
7228
  }
7131
7229
  let manifest;
7132
7230
  try {
7133
- manifest = JSON.parse(fs2__namespace.readFileSync(manifestPath, "utf8"));
7231
+ manifest = JSON.parse(fs3__namespace.readFileSync(manifestPath, "utf8"));
7134
7232
  } catch (err) {
7135
7233
  return {
7136
7234
  valid: false,
@@ -7152,7 +7250,7 @@ function validateSnapshot(configInput) {
7152
7250
  }
7153
7251
  const drift = emptyDrift();
7154
7252
  const warnings = [];
7155
- const snapshotDir = path5__namespace.resolve(config.cwd, config.outDir);
7253
+ const snapshotDir = path6__namespace.resolve(config.cwd, config.outDir);
7156
7254
  const unreadableSkips = manifest.skipped.filter(
7157
7255
  (entry) => entry.reason === "missing" || entry.reason === "read-error"
7158
7256
  );
@@ -7230,17 +7328,18 @@ function validateSnapshot(configInput) {
7230
7328
  return skippedReasons.get(maskedPath(diskFile, config.secretRules)) ?? null;
7231
7329
  };
7232
7330
  let unchangedScope = null;
7331
+ let stagedScope = null;
7233
7332
  const recordedChangedSince = manifest.config?.changedSince;
7234
7333
  const recordedStaged = manifest.config?.staged === true;
7235
7334
  const recordedWithDependents = manifest.config?.withDependents === true;
7236
7335
  if (recordedChangedSince !== void 0 || recordedStaged) {
7237
7336
  try {
7238
- unchangedScope = new Set(
7239
- resolveChangedScope(config.cwd, {
7240
- ...recordedChangedSince === void 0 ? {} : { changedSince: recordedChangedSince },
7241
- ...recordedStaged ? { staged: true } : {}
7242
- }).paths
7243
- );
7337
+ const scope = resolveChangedScope(config.cwd, {
7338
+ ...recordedChangedSince === void 0 ? {} : { changedSince: recordedChangedSince },
7339
+ ...recordedStaged ? { staged: true } : {}
7340
+ });
7341
+ unchangedScope = new Set(scope.paths);
7342
+ if (recordedStaged) stagedScope = new Set(scope.stagedPaths);
7244
7343
  } catch {
7245
7344
  warnings.push(
7246
7345
  "The snapshot was generated with a changed-files scope, but that scope could not be re-resolved; files it recorded as `unchanged` were trusted rather than re-checked."
@@ -7251,11 +7350,15 @@ function validateSnapshot(configInput) {
7251
7350
  function becameDependent(diskFile) {
7252
7351
  if (!recordedWithDependents || unchangedScope === null) return false;
7253
7352
  dependentResolver ??= buildImportResolver(
7254
- collection.files.map((file) => ({ relativePath: file }))
7353
+ collection.files.map((file) => ({ relativePath: file })),
7354
+ {
7355
+ tsconfig: tsconfigPathsFor(config.cwd),
7356
+ ...unchangedScope === null ? {} : { extraPaths: unchangedScope }
7357
+ }
7255
7358
  );
7256
7359
  return importsChangedFile(
7257
7360
  diskFile,
7258
- importsOfFile(diskFile, path5__namespace.join(config.cwd, diskFile)),
7361
+ importsOfFile(diskFile, path6__namespace.join(config.cwd, diskFile)),
7259
7362
  unchangedScope,
7260
7363
  dependentResolver
7261
7364
  );
@@ -7269,12 +7372,16 @@ function validateSnapshot(configInput) {
7269
7372
  // discovery mode" meant `validate` could enumerate files one way while the snapshot
7270
7373
  // had been generated another way, and then blame the difference on drift.
7271
7374
  discovery: config.discovery,
7375
+ // `generate --staged` adds index-only paths to the candidate list. Without the same
7376
+ // extra paths, a staged file that is absent from the working tree was invisible to
7377
+ // this scan and then reported as deleted, although the snapshot matched the index.
7378
+ ...stagedScope === null ? {} : { extraPaths: [...stagedScope] },
7272
7379
  // The same exclusion `generate` applies: without it, `validate` recounted the tool's
7273
7380
  // own output directory as a set of files missing from the snapshot, so a correct
7274
7381
  // snapshot was reported as drifting.
7275
7382
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
7276
- (directory) => path5__namespace.relative(config.cwd, path5__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
7277
- ).filter((relative9) => relative9.length > 0 && !relative9.startsWith(".."))
7383
+ (directory) => path6__namespace.relative(config.cwd, path6__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
7384
+ ).filter((relative10) => relative10.length > 0 && !relative10.startsWith(".."))
7278
7385
  });
7279
7386
  for (const diskFile of collection.files) {
7280
7387
  const snapshotHash = manifestFileMap.get(diskFile);
@@ -7300,7 +7407,8 @@ function validateSnapshot(configInput) {
7300
7407
  }
7301
7408
  let diskHash;
7302
7409
  try {
7303
- diskHash = sha256Hex(fs2__namespace.readFileSync(path5__namespace.join(config.cwd, diskFile)));
7410
+ const stagedBlob = recordedStaged && stagedScope?.has(diskFile) === true ? readStagedBlob(config.cwd, diskFile) : null;
7411
+ diskHash = sha256Hex(stagedBlob ?? fs3__namespace.readFileSync(path6__namespace.join(config.cwd, diskFile)));
7304
7412
  } catch (err) {
7305
7413
  if (err.code === "ENOENT") {
7306
7414
  drift.missingOnDisk.push(diskFile);
@@ -7314,6 +7422,12 @@ function validateSnapshot(configInput) {
7314
7422
  }
7315
7423
  }
7316
7424
  for (const snapshotFile of manifestFileMap.keys()) {
7425
+ if (recordedStaged && stagedScope?.has(snapshotFile)) {
7426
+ if (readStagedBlob(config.cwd, snapshotFile) === null) {
7427
+ drift.missingOnDisk.push(snapshotFile);
7428
+ }
7429
+ continue;
7430
+ }
7317
7431
  const confined = confineToDirectory(config.cwd, snapshotFile);
7318
7432
  if (confined === null) {
7319
7433
  drift.partIssues.push({
@@ -7324,7 +7438,7 @@ function validateSnapshot(configInput) {
7324
7438
  }
7325
7439
  let statFailure = null;
7326
7440
  try {
7327
- fs2__namespace.statSync(confined);
7441
+ fs3__namespace.statSync(confined);
7328
7442
  } catch (err) {
7329
7443
  statFailure = err;
7330
7444
  }
@@ -7344,7 +7458,7 @@ function validateSnapshot(configInput) {
7344
7458
  ...Object.values(config.budgets.byLayer)
7345
7459
  );
7346
7460
  const partNames = /* @__PURE__ */ new Set();
7347
- const partsDir = path5__namespace.join(snapshotDir, "parts");
7461
+ const partsDir = path6__namespace.join(snapshotDir, "parts");
7348
7462
  for (const part of manifest.parts) {
7349
7463
  if (!part || typeof part.filename !== "string") continue;
7350
7464
  partNames.add(part.filename);
@@ -7359,7 +7473,7 @@ function validateSnapshot(configInput) {
7359
7473
  }
7360
7474
  let buffer;
7361
7475
  try {
7362
- buffer = fs2__namespace.readFileSync(partPath);
7476
+ buffer = fs3__namespace.readFileSync(partPath);
7363
7477
  } catch {
7364
7478
  drift.partIssues.push({ part: part.filename, issue: "missing from snapshot/parts" });
7365
7479
  continue;
@@ -7736,11 +7850,11 @@ function validateSnapshot(configInput) {
7736
7850
  ];
7737
7851
  for (const [key, artifact] of declaredArtifacts) {
7738
7852
  if (!artifact) continue;
7739
- const artifactPath = path5__namespace.join(snapshotDir, ...key.split("/"));
7853
+ const artifactPath = path6__namespace.join(snapshotDir, ...key.split("/"));
7740
7854
  let buffer;
7741
7855
  try {
7742
- if (!fs2__namespace.statSync(artifactPath).isFile()) throw new Error("not a regular file");
7743
- buffer = fs2__namespace.readFileSync(artifactPath);
7856
+ if (!fs3__namespace.statSync(artifactPath).isFile()) throw new Error("not a regular file");
7857
+ buffer = fs3__namespace.readFileSync(artifactPath);
7744
7858
  } catch {
7745
7859
  drift.partIssues.push({ part: key, issue: "declared artifact is missing" });
7746
7860
  continue;
@@ -7753,9 +7867,9 @@ function validateSnapshot(configInput) {
7753
7867
  for (const match of buffer.toString("utf8").matchAll(/\]\(([^)\s]+)\)/g)) {
7754
7868
  const target = match[1].split("#")[0];
7755
7869
  if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
7756
- const resolved = path5__namespace.resolve(snapshotDir, "reports", target);
7757
- const relative9 = path5__namespace.relative(snapshotDir, resolved);
7758
- if (relative9.startsWith("..") || path5__namespace.isAbsolute(relative9) || !fs2__namespace.existsSync(resolved)) {
7870
+ const resolved = path6__namespace.resolve(snapshotDir, "reports", target);
7871
+ const relative10 = path6__namespace.relative(snapshotDir, resolved);
7872
+ if (relative10.startsWith("..") || path6__namespace.isAbsolute(relative10) || !fs3__namespace.existsSync(resolved)) {
7759
7873
  drift.partIssues.push({
7760
7874
  part: key,
7761
7875
  issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
@@ -7768,7 +7882,7 @@ function validateSnapshot(configInput) {
7768
7882
  if (sarifArtifact) {
7769
7883
  const sarifKey = "reports/audit.sarif";
7770
7884
  try {
7771
- const buffer = fs2__namespace.readFileSync(path5__namespace.join(snapshotDir, "reports", "audit.sarif"));
7885
+ const buffer = fs3__namespace.readFileSync(path6__namespace.join(snapshotDir, "reports", "audit.sarif"));
7772
7886
  if (sha256Hex(buffer) !== sarifArtifact.sha256 || buffer.length !== sarifArtifact.byteSize) {
7773
7887
  drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
7774
7888
  }
@@ -7814,9 +7928,9 @@ function validateSnapshot(configInput) {
7814
7928
  `${drift.configMismatches.length} configuration mismatch(es) between the manifest and this run.`
7815
7929
  );
7816
7930
  }
7817
- const signaturePath = path5__namespace.join(path5__namespace.dirname(manifestPath), "signature.json");
7818
- if (fs2__namespace.existsSync(signaturePath)) {
7819
- const outcome = verifySnapshotSignature(path5__namespace.dirname(manifestPath));
7931
+ const signaturePath = path6__namespace.join(path6__namespace.dirname(manifestPath), "signature.json");
7932
+ if (fs3__namespace.existsSync(signaturePath)) {
7933
+ const outcome = verifySnapshotSignature(path6__namespace.dirname(manifestPath));
7820
7934
  if (!outcome.ok) errors.push("signature: " + outcome.reason + ".");
7821
7935
  }
7822
7936
  if (manifest.slice !== void 0 || manifest.budget !== void 0) {
@@ -7872,11 +7986,11 @@ var MAX_LINE_BYTES = 32 * 1024 * 1024;
7872
7986
  function createWriter(output) {
7873
7987
  return {
7874
7988
  write(value) {
7875
- return new Promise((resolve10, reject) => {
7989
+ return new Promise((resolve11, reject) => {
7876
7990
  output.write(`${JSON.stringify(value)}
7877
7991
  `, (error) => {
7878
7992
  if (error) reject(error);
7879
- else resolve10();
7993
+ else resolve11();
7880
7994
  });
7881
7995
  });
7882
7996
  }
@@ -8194,8 +8308,8 @@ function findSection(sections, relativePath) {
8194
8308
  if (exact) return exact;
8195
8309
  const foldedPath = rendered.toLowerCase();
8196
8310
  const folded = sections.filter((section) => {
8197
- const path16 = section.path.toLowerCase();
8198
- return path16 === relativePath.toLowerCase() || path16 === foldedPath;
8311
+ const path17 = section.path.toLowerCase();
8312
+ return path17 === relativePath.toLowerCase() || path17 === foldedPath;
8199
8313
  });
8200
8314
  return folded.length === 1 ? folded[0] : null;
8201
8315
  }
@@ -8218,18 +8332,18 @@ var ARTIFACT_FILES = {
8218
8332
  };
8219
8333
  var TEXT_ARTIFACT = /\.(md|json|txt|sarif)$/i;
8220
8334
  function sha256(buffer) {
8221
- return crypto2.createHash("sha256").update(buffer).digest("hex");
8335
+ return crypto5.createHash("sha256").update(buffer).digest("hex");
8222
8336
  }
8223
8337
  function readBytes(file) {
8224
8338
  try {
8225
- return fs2__namespace.readFileSync(file);
8339
+ return fs3__namespace.readFileSync(file);
8226
8340
  } catch {
8227
8341
  return null;
8228
8342
  }
8229
8343
  }
8230
8344
  function readText(file) {
8231
8345
  try {
8232
- return fs2__namespace.readFileSync(file, "utf8");
8346
+ return fs3__namespace.readFileSync(file, "utf8");
8233
8347
  } catch {
8234
8348
  return null;
8235
8349
  }
@@ -8246,15 +8360,15 @@ function readJson(file) {
8246
8360
  function walk(dir, prefix = "") {
8247
8361
  let entries;
8248
8362
  try {
8249
- entries = fs2__namespace.readdirSync(dir, { withFileTypes: true });
8363
+ entries = fs3__namespace.readdirSync(dir, { withFileTypes: true });
8250
8364
  } catch {
8251
8365
  return [];
8252
8366
  }
8253
8367
  const files = [];
8254
8368
  for (const entry of entries) {
8255
- const relative9 = prefix === "" ? entry.name : prefix + "/" + entry.name;
8256
- if (entry.isDirectory()) files.push(...walk(path5__namespace.join(dir, entry.name), relative9));
8257
- else if (entry.isFile()) files.push(relative9);
8369
+ const relative10 = prefix === "" ? entry.name : prefix + "/" + entry.name;
8370
+ if (entry.isDirectory()) files.push(...walk(path6__namespace.join(dir, entry.name), relative10));
8371
+ else if (entry.isFile()) files.push(relative10);
8258
8372
  }
8259
8373
  return files;
8260
8374
  }
@@ -8294,9 +8408,9 @@ function secretTokens(text) {
8294
8408
  }
8295
8409
  function readArtifactTexts(snapshotDir) {
8296
8410
  const texts = [];
8297
- for (const relative9 of walk(snapshotDir)) {
8298
- if (!TEXT_ARTIFACT.test(relative9)) continue;
8299
- const text = readText(path5__namespace.join(snapshotDir, relative9));
8411
+ for (const relative10 of walk(snapshotDir)) {
8412
+ if (!TEXT_ARTIFACT.test(relative10)) continue;
8413
+ const text = readText(path6__namespace.join(snapshotDir, relative10));
8300
8414
  if (text !== null) texts.push(text);
8301
8415
  }
8302
8416
  return texts;
@@ -8312,15 +8426,15 @@ function findHostPaths(snapshotDir, repoDir) {
8312
8426
  ];
8313
8427
  const repoPattern = new RegExp(escapeRegExp(repoDir), "g");
8314
8428
  const hits = /* @__PURE__ */ new Set();
8315
- for (const relative9 of walk(snapshotDir)) {
8316
- if (!TEXT_ARTIFACT.test(relative9)) continue;
8317
- const text = readText(path5__namespace.join(snapshotDir, relative9));
8429
+ for (const relative10 of walk(snapshotDir)) {
8430
+ if (!TEXT_ARTIFACT.test(relative10)) continue;
8431
+ const text = readText(path6__namespace.join(snapshotDir, relative10));
8318
8432
  if (text === null) continue;
8319
8433
  for (const pattern of patterns) {
8320
- for (const match of text.match(pattern) ?? []) hits.add(relative9 + ": " + match);
8434
+ for (const match of text.match(pattern) ?? []) hits.add(relative10 + ": " + match);
8321
8435
  }
8322
8436
  repoPattern.lastIndex = 0;
8323
- if (repoPattern.test(text)) hits.add(relative9 + ": the repository absolute path");
8437
+ if (repoPattern.test(text)) hits.add(relative10 + ": the repository absolute path");
8324
8438
  }
8325
8439
  return [...hits];
8326
8440
  }
@@ -8470,10 +8584,10 @@ function markdownPackBodies(text) {
8470
8584
  return bodies.size === 0 ? null : bodies;
8471
8585
  }
8472
8586
  function auditSnapshot(options) {
8473
- const snapshotDir = path5__namespace.resolve(options.snapshotDir);
8474
- const repoDir = path5__namespace.resolve(options.repoDir);
8587
+ const snapshotDir = path6__namespace.resolve(options.snapshotDir);
8588
+ const repoDir = path6__namespace.resolve(options.repoDir);
8475
8589
  const checks = [];
8476
- const manifestFile = path5__namespace.join(snapshotDir, "manifest.json");
8590
+ const manifestFile = path6__namespace.join(snapshotDir, "manifest.json");
8477
8591
  const raw = readJson(manifestFile);
8478
8592
  const problem = raw === null ? "the file is missing or is not valid JSON" : describeManifestShapeProblem(raw);
8479
8593
  if (raw === null || problem !== null) {
@@ -8502,7 +8616,7 @@ function auditSnapshot(options) {
8502
8616
  const missingParts = [];
8503
8617
  const mismatched = [];
8504
8618
  for (const part of manifest.parts) {
8505
- const bytes = readBytes(path5__namespace.join(snapshotDir, "parts", part.filename));
8619
+ const bytes = readBytes(path6__namespace.join(snapshotDir, "parts", part.filename));
8506
8620
  if (bytes === null) {
8507
8621
  missingParts.push(part.filename);
8508
8622
  continue;
@@ -8567,13 +8681,13 @@ function auditSnapshot(options) {
8567
8681
  let artifactCount = 0;
8568
8682
  for (const [key, value] of Object.entries(artifacts)) {
8569
8683
  if (value === null || value === void 0) continue;
8570
- const relative9 = ARTIFACT_FILES[key];
8571
- if (relative9 === void 0) continue;
8684
+ const relative10 = ARTIFACT_FILES[key];
8685
+ if (relative10 === void 0) continue;
8572
8686
  artifactCount += 1;
8573
- const bytes = readBytes(path5__namespace.join(snapshotDir, relative9));
8574
- if (bytes === null) artifactProblems.push(relative9 + " is missing");
8687
+ const bytes = readBytes(path6__namespace.join(snapshotDir, relative10));
8688
+ if (bytes === null) artifactProblems.push(relative10 + " is missing");
8575
8689
  else if (typeof value.sha256 === "string" && sha256(bytes) !== value.sha256) {
8576
- artifactProblems.push(relative9 + " changed");
8690
+ artifactProblems.push(relative10 + " changed");
8577
8691
  }
8578
8692
  }
8579
8693
  checks.push(
@@ -8617,8 +8731,8 @@ function auditSnapshot(options) {
8617
8731
  unexpected.length + " unexpected path(s): " + sample(unexpected)
8618
8732
  )
8619
8733
  );
8620
- const signaturePath = path5__namespace.join(snapshotDir, "signature.json");
8621
- if (fs2__namespace.existsSync(signaturePath)) {
8734
+ const signaturePath = path6__namespace.join(snapshotDir, "signature.json");
8735
+ if (fs3__namespace.existsSync(signaturePath)) {
8622
8736
  const outcome = verifySnapshotSignature(snapshotDir);
8623
8737
  checks.push(
8624
8738
  outcome.ok ? check(
@@ -8683,7 +8797,7 @@ function auditSnapshot(options) {
8683
8797
  manifest.files.map((file) => [anchorForPath(file.relativePath), file.relativePath])
8684
8798
  );
8685
8799
  for (const part of manifest.parts) {
8686
- const partText = readText(path5__namespace.join(snapshotDir, "parts", part.filename));
8800
+ const partText = readText(path6__namespace.join(snapshotDir, "parts", part.filename));
8687
8801
  if (partText === null) continue;
8688
8802
  const sections = parsePartSections(partText);
8689
8803
  partTexts.set(part.filename, partText);
@@ -8750,7 +8864,7 @@ function auditSnapshot(options) {
8750
8864
  }
8751
8865
  };
8752
8866
  if (manifest.artifacts?.readme != null) {
8753
- const text = readText(path5__namespace.join(snapshotDir, "README.md"));
8867
+ const text = readText(path6__namespace.join(snapshotDir, "README.md"));
8754
8868
  if (text === null) {
8755
8869
  reportProblems.push("README.md is recorded but unreadable");
8756
8870
  } else {
@@ -8790,7 +8904,7 @@ function auditSnapshot(options) {
8790
8904
  }
8791
8905
  }
8792
8906
  if (manifest.artifacts?.prompt != null) {
8793
- const text = readText(path5__namespace.join(snapshotDir, "PROMPT.md"));
8907
+ const text = readText(path6__namespace.join(snapshotDir, "PROMPT.md"));
8794
8908
  if (text === null) {
8795
8909
  reportProblems.push("PROMPT.md is recorded but unreadable");
8796
8910
  } else {
@@ -8979,7 +9093,7 @@ function auditSnapshot(options) {
8979
9093
  ];
8980
9094
  for (const reader of packReaders) {
8981
9095
  if (manifest.artifacts?.[reader.key] == null) continue;
8982
- const packText = readText(path5__namespace.join(snapshotDir, reader.file));
9096
+ const packText = readText(path6__namespace.join(snapshotDir, reader.file));
8983
9097
  const problems = [];
8984
9098
  if (packText === null) {
8985
9099
  problems.push(reader.file + " is recorded but unreadable");
@@ -8992,8 +9106,8 @@ function auditSnapshot(options) {
8992
9106
  for (const file of manifest.files) {
8993
9107
  if (!packed.has(file.relativePath)) problems.push(file.relativePath + " is in the manifest but not the pack");
8994
9108
  }
8995
- for (const path16 of packed) {
8996
- if (!known2.has(path16)) problems.push(path16 + " is in the pack but not the manifest");
9109
+ for (const path17 of packed) {
9110
+ if (!known2.has(path17)) problems.push(path17 + " is in the pack but not the manifest");
8997
9111
  }
8998
9112
  }
8999
9113
  }
@@ -9029,7 +9143,7 @@ function auditSnapshot(options) {
9029
9143
  bodyByPath.set(file.relativePath, section.body);
9030
9144
  bodiesChecked += 1;
9031
9145
  const bytes = Buffer.byteLength(section.body, "utf8");
9032
- const bodyLines = section.body === "" ? 0 : section.body.split("\n").length - (section.body.endsWith("\n") ? 1 : 0);
9146
+ const bodyLines = countBodyLines(section.body);
9033
9147
  if (bytes !== file.includedBytes) {
9034
9148
  bodyProblems.push(file.relativePath + ": manifest says " + file.includedBytes + " B, part holds " + bytes + " B");
9035
9149
  } else if (bodyLines !== file.includedLines) {
@@ -9142,7 +9256,7 @@ function auditSnapshot(options) {
9142
9256
  let packBodies = 0;
9143
9257
  let packSkipped = 0;
9144
9258
  for (const pack of packsWanted) {
9145
- const text = readText(path5__namespace.join(snapshotDir, pack.file));
9259
+ const text = readText(path6__namespace.join(snapshotDir, pack.file));
9146
9260
  if (text === null) continue;
9147
9261
  const bodies = pack.read(text);
9148
9262
  if (bodies === null) {
@@ -9206,7 +9320,7 @@ function auditSnapshot(options) {
9206
9320
  unreplayable += 1;
9207
9321
  continue;
9208
9322
  }
9209
- const bytes = readBytes(path5__namespace.join(repoDir, file.relativePath));
9323
+ const bytes = readBytes(path6__namespace.join(repoDir, file.relativePath));
9210
9324
  if (bytes === null || sha256(bytes) !== file.hashSha256) {
9211
9325
  unreplayable += 1;
9212
9326
  continue;
@@ -9244,9 +9358,9 @@ function auditSnapshot(options) {
9244
9358
  )
9245
9359
  );
9246
9360
  }
9247
- const indexParent = path5__namespace.dirname(snapshotDir);
9248
- const indexPath = path5__namespace.join(indexParent, "WORKSPACE.json");
9249
- if (fs2__namespace.existsSync(indexPath)) {
9361
+ const indexParent = path6__namespace.dirname(snapshotDir);
9362
+ const indexPath = path6__namespace.join(indexParent, "WORKSPACE.json");
9363
+ if (fs3__namespace.existsSync(indexPath)) {
9250
9364
  const indexText = readText(indexPath);
9251
9365
  let members = [];
9252
9366
  let problem2 = null;
@@ -9257,7 +9371,7 @@ function auditSnapshot(options) {
9257
9371
  } catch (error) {
9258
9372
  problem2 = error.message;
9259
9373
  }
9260
- const memberName = path5__namespace.basename(snapshotDir);
9374
+ const memberName = path6__namespace.basename(snapshotDir);
9261
9375
  const member = members.find((entry) => entry.name === memberName);
9262
9376
  if (problem2 !== null) {
9263
9377
  checks.push(check(
@@ -9281,7 +9395,7 @@ function auditSnapshot(options) {
9281
9395
  if (typeof member.files === "number" && member.files !== manifest.counts.totalFiles) {
9282
9396
  disagreements.push("file count");
9283
9397
  }
9284
- const sourceGone = typeof member.path === "string" && !fs2__namespace.existsSync(member.path) ? "Member " + memberName + " source directory is gone (" + member.path + "); the snapshot still describes it. Regenerate the workspace." : null;
9398
+ const sourceGone = typeof member.path === "string" && !fs3__namespace.existsSync(member.path) ? "Member " + memberName + " source directory is gone (" + member.path + "); the snapshot still describes it. Regenerate the workspace." : null;
9285
9399
  checks.push(
9286
9400
  sourceGone !== null ? check("workspace.index", "The workspace index agrees with this member", "warning", "warn", sourceGone) : disagreements.length === 0 ? check(
9287
9401
  "workspace.index",
@@ -9303,29 +9417,29 @@ function auditSnapshot(options) {
9303
9417
  const scanBudget = options.maxScanBytes ?? 32 * 1024 * 1024;
9304
9418
  const leakHits = [];
9305
9419
  let scannedBytes = 0;
9306
- for (const relative9 of walk(snapshotDir)) {
9307
- if (!TEXT_ARTIFACT.test(relative9) || scannedBytes > scanBudget) continue;
9308
- if (relative9 === SIGNATURE_FILE) continue;
9309
- const text = readText(path5__namespace.join(snapshotDir, relative9));
9420
+ for (const relative10 of walk(snapshotDir)) {
9421
+ if (!TEXT_ARTIFACT.test(relative10) || scannedBytes > scanBudget) continue;
9422
+ if (relative10 === SIGNATURE_FILE) continue;
9423
+ const text = readText(path6__namespace.join(snapshotDir, relative10));
9310
9424
  if (text === null) continue;
9311
9425
  scannedBytes += Buffer.byteLength(text, "utf8");
9312
9426
  let findingCount = 0;
9313
- if (/^parts[\\/].*\.md$/i.test(relative9)) {
9427
+ if (/^parts[\\/].*\.md$/i.test(relative10)) {
9314
9428
  let headerText = text;
9315
9429
  for (const section of parsePartSections(text)) {
9316
9430
  findingCount += scanAndRedactSecrets(section.body, rules, section.path).findings.length;
9317
9431
  headerText = headerText.replace(section.body, "");
9318
9432
  }
9319
- findingCount += scanAndRedactSecrets(headerText, rules, relative9).findings.length;
9433
+ findingCount += scanAndRedactSecrets(headerText, rules, relative10).findings.length;
9320
9434
  } else {
9321
- findingCount = scanAndRedactSecrets(text, rules, relative9).findings.length;
9435
+ findingCount = scanAndRedactSecrets(text, rules, relative10).findings.length;
9322
9436
  }
9323
9437
  if (findingCount > 0) {
9324
- leakHits.push(relative9 + " (" + findingCount + " line(s))");
9438
+ leakHits.push(relative10 + " (" + findingCount + " line(s))");
9325
9439
  }
9326
9440
  }
9327
- const signatureRecordPath = path5__namespace.join(snapshotDir, SIGNATURE_FILE);
9328
- if (fs2__namespace.existsSync(signatureRecordPath)) {
9441
+ const signatureRecordPath = path6__namespace.join(snapshotDir, SIGNATURE_FILE);
9442
+ if (fs3__namespace.existsSync(signatureRecordPath)) {
9329
9443
  const recordText = readText(signatureRecordPath);
9330
9444
  if (recordText !== null) {
9331
9445
  scannedBytes += Buffer.byteLength(recordText, "utf8");
@@ -9370,7 +9484,7 @@ function auditSnapshot(options) {
9370
9484
  const artifactContains = (token) => artifactTexts.some((text) => text.includes(token));
9371
9485
  for (const record of skippedSensitive.slice(0, 40)) {
9372
9486
  if (record.path.includes("[REDACTED") || compared > 400) continue;
9373
- const text = readText(path5__namespace.join(repoDir, record.path));
9487
+ const text = readText(path6__namespace.join(repoDir, record.path));
9374
9488
  if (text === null) continue;
9375
9489
  for (const token of secretTokens(text)) {
9376
9490
  compared += 1;
@@ -9522,42 +9636,42 @@ function describeMatcher(matcher) {
9522
9636
  return String(matcher);
9523
9637
  }
9524
9638
  function normalizeTarget(cwd, target) {
9525
- const resolvedCwd = path5__namespace.resolve(cwd);
9526
- const absolute = path5__namespace.resolve(resolvedCwd, target);
9527
- const relative9 = path5__namespace.relative(resolvedCwd, absolute);
9528
- if (relative9 === "" || relative9 === ".." || relative9.startsWith(`..${path5__namespace.sep}`) || path5__namespace.isAbsolute(relative9)) {
9639
+ const resolvedCwd = path6__namespace.resolve(cwd);
9640
+ const absolute = path6__namespace.resolve(resolvedCwd, target);
9641
+ const relative10 = path6__namespace.relative(resolvedCwd, absolute);
9642
+ if (relative10 === "" || relative10 === ".." || relative10.startsWith(`..${path6__namespace.sep}`) || path6__namespace.isAbsolute(relative10)) {
9529
9643
  return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
9530
9644
  }
9531
- return { relative: relative9.split(path5__namespace.sep).join("/"), outsideRoot: false };
9645
+ return { relative: relative10.split(path6__namespace.sep).join("/"), outsideRoot: false };
9532
9646
  }
9533
9647
  function findRuleMatch(rules, relativePath) {
9534
9648
  return rules.find(
9535
9649
  (rule) => matchRule(relativePath, rule.match)
9536
9650
  );
9537
9651
  }
9538
- function findRecordedAncestor(skipped, relative9, maskedPath2) {
9652
+ function findRecordedAncestor(skipped, relative10, maskedPath2) {
9539
9653
  let nearest;
9540
9654
  for (const record of skipped) {
9541
9655
  const ancestorPath = record.path;
9542
9656
  if (ancestorPath.length === 0) continue;
9543
- const isAncestor = relative9.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
9657
+ const isAncestor = relative10.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
9544
9658
  if (!isAncestor) continue;
9545
9659
  if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
9546
9660
  }
9547
9661
  return nearest;
9548
9662
  }
9549
9663
  function readManifest2(config) {
9550
- const manifestPath = path5__namespace.resolve(config.cwd, config.outDir, "manifest.json");
9664
+ const manifestPath = path6__namespace.resolve(config.cwd, config.outDir, "manifest.json");
9551
9665
  try {
9552
- return JSON.parse(fs2__namespace.readFileSync(manifestPath, "utf8"));
9666
+ return JSON.parse(fs3__namespace.readFileSync(manifestPath, "utf8"));
9553
9667
  } catch {
9554
9668
  return null;
9555
9669
  }
9556
9670
  }
9557
9671
  function explainPath(config, target) {
9558
9672
  const normalized = normalizeTarget(config.cwd, target);
9559
- const relative9 = normalized.relative;
9560
- const maskedPath2 = findSecretInPath(relative9, config.secretRules)?.masked ?? relative9;
9673
+ const relative10 = normalized.relative;
9674
+ const maskedPath2 = findSecretInPath(relative10, config.secretRules)?.masked ?? relative10;
9561
9675
  if (normalized.outsideRoot) {
9562
9676
  return {
9563
9677
  path: maskedPath2,
@@ -9567,10 +9681,10 @@ function explainPath(config, target) {
9567
9681
  detail: "path resolves outside the configured repository root and was not inspected"
9568
9682
  };
9569
9683
  }
9570
- const absolute = path5__namespace.join(config.cwd, relative9);
9684
+ const absolute = path6__namespace.join(config.cwd, relative10);
9571
9685
  const result = {
9572
9686
  path: maskedPath2,
9573
- exists: fs2__namespace.existsSync(absolute),
9687
+ exists: fs3__namespace.existsSync(absolute),
9574
9688
  included: false
9575
9689
  };
9576
9690
  const collection = collectFiles(config.cwd, {
@@ -9584,12 +9698,12 @@ function explainPath(config, target) {
9584
9698
  // Same exclusion `generate` applies, so `explain` never says "not-discovered" about a file
9585
9699
  // that is only missing because the walker dropped the tool's own output directory.
9586
9700
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
9587
- (directory) => path5__namespace.relative(config.cwd, path5__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
9588
- ).filter((relative10) => relative10.length > 0 && !relative10.startsWith(".."))
9701
+ (directory) => path6__namespace.relative(config.cwd, path6__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
9702
+ ).filter((relative11) => relative11.length > 0 && !relative11.startsWith(".."))
9589
9703
  });
9590
- if (!collection.files.includes(relative9)) {
9704
+ if (!collection.files.includes(relative10)) {
9591
9705
  const record = collection.skipped.find(
9592
- (entry2) => entry2.path === relative9 || entry2.path === maskedPath2
9706
+ (entry2) => entry2.path === relative10 || entry2.path === maskedPath2
9593
9707
  );
9594
9708
  if (record) {
9595
9709
  result.reason = record.reason;
@@ -9598,7 +9712,7 @@ function explainPath(config, target) {
9598
9712
  result.reason = "missing";
9599
9713
  result.detail = "no such file or directory, relative to the configured cwd";
9600
9714
  } else {
9601
- const ancestor = findRecordedAncestor(collection.skipped, relative9, maskedPath2);
9715
+ const ancestor = findRecordedAncestor(collection.skipped, relative10, maskedPath2);
9602
9716
  if (ancestor) {
9603
9717
  result.reason = ancestor.reason;
9604
9718
  result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
@@ -9618,13 +9732,15 @@ function explainPath(config, target) {
9618
9732
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
9619
9733
  ...config.staged === true ? { staged: true } : {}
9620
9734
  });
9621
- inScope = scope.paths.has(relative9);
9735
+ inScope = scope.paths.has(relative10);
9622
9736
  if (!inScope && config.withDependents === true) {
9623
9737
  inScope = importsChangedFile(
9624
- relative9,
9625
- importsOfFile(relative9, absolute),
9738
+ relative10,
9739
+ importsOfFile(relative10, absolute),
9626
9740
  scope.paths,
9627
- buildImportResolver(collection.files.map((file) => ({ relativePath: file })))
9741
+ buildImportResolver(collection.files.map((file) => ({ relativePath: file })), {
9742
+ tsconfig: tsconfigPathsFor(config.cwd)
9743
+ })
9628
9744
  );
9629
9745
  }
9630
9746
  scopeDetail = scope.detail;
@@ -9649,7 +9765,7 @@ function explainPath(config, target) {
9649
9765
  }
9650
9766
  let sizeOnDisk = null;
9651
9767
  try {
9652
- sizeOnDisk = fs2__namespace.statSync(absolute).size;
9768
+ sizeOnDisk = fs3__namespace.statSync(absolute).size;
9653
9769
  } catch {
9654
9770
  sizeOnDisk = null;
9655
9771
  }
@@ -9659,10 +9775,10 @@ function explainPath(config, target) {
9659
9775
  result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
9660
9776
  return result;
9661
9777
  }
9662
- if (fs2__namespace.existsSync(absolute) && fs2__namespace.statSync(absolute).isFile()) {
9778
+ if (fs3__namespace.existsSync(absolute) && fs3__namespace.statSync(absolute).isFile()) {
9663
9779
  let buffer;
9664
9780
  try {
9665
- buffer = fs2__namespace.readFileSync(absolute);
9781
+ buffer = fs3__namespace.readFileSync(absolute);
9666
9782
  } catch (err) {
9667
9783
  result.included = false;
9668
9784
  result.reason = "read-error";
@@ -9680,15 +9796,15 @@ function explainPath(config, target) {
9680
9796
  result.bytes = buffer.length;
9681
9797
  result.lines = countLines(text);
9682
9798
  if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
9683
- const { findings } = scanAndRedactSecrets(text, config.secretRules, relative9);
9799
+ const { findings } = scanAndRedactSecrets(text, config.secretRules, relative10);
9684
9800
  result.secretCount = findings.length;
9685
9801
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
9686
9802
  let inclusionMode = "full";
9687
- if (config.skeleton === true && isSkeletonizable(relative9)) {
9688
- const skeleton = skeletonizeTypeScript(text, relative9);
9803
+ if (config.skeleton === true && isSkeletonizable(relative10)) {
9804
+ const skeleton = skeletonizeTypeScript(text, relative10);
9689
9805
  if (skeleton.collapsed > 0) inclusionMode = "signatures";
9690
9806
  }
9691
- if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative9) && stripComments2(text, relative9).removed > 0) {
9807
+ if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative10) && stripComments2(text, relative10).removed > 0) {
9692
9808
  inclusionMode = "comments-stripped";
9693
9809
  }
9694
9810
  if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
@@ -9697,18 +9813,18 @@ function explainPath(config, target) {
9697
9813
  }
9698
9814
  result.inclusionMode = inclusionMode;
9699
9815
  }
9700
- result.layer = classifyLayer(relative9, config.layers);
9701
- result.kind = classifyKind(relative9, config.kinds);
9702
- result.language = detectLanguage(relative9);
9703
- const layerRule = findRuleMatch(config.layers, relative9);
9816
+ result.layer = classifyLayer(relative10, config.layers);
9817
+ result.kind = classifyKind(relative10, config.kinds);
9818
+ result.language = detectLanguage(relative10);
9819
+ const layerRule = findRuleMatch(config.layers, relative10);
9704
9820
  if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
9705
- const kindRule = findRuleMatch(config.kinds, relative9);
9821
+ const kindRule = findRuleMatch(config.kinds, relative10);
9706
9822
  if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
9707
9823
  const manifest = readManifest2(config);
9708
- const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative9) : void 0;
9824
+ const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative10) : void 0;
9709
9825
  result.part = entry?.part ?? null;
9710
9826
  if (entry === void 0) {
9711
- const record = manifest?.skipped?.find((skip) => skip.path === relative9);
9827
+ const record = manifest?.skipped?.find((skip) => skip.path === relative10);
9712
9828
  if (record !== void 0 && (record.reason === "not-selected" || record.reason === "unchanged")) {
9713
9829
  result.included = false;
9714
9830
  result.reason = record.reason;
@@ -9752,7 +9868,7 @@ function renderExplainText(result) {
9752
9868
  return lines.join("\n");
9753
9869
  }
9754
9870
  function workerEntry(directory, isCjs) {
9755
- const entry = path5__namespace.join(directory, isCjs ? "index.cjs" : "index.js");
9871
+ const entry = path6__namespace.join(directory, isCjs ? "index.cjs" : "index.js");
9756
9872
  return { path: entry, url: url.pathToFileURL(entry).href };
9757
9873
  }
9758
9874
  var WORKER_SOURCE = `
@@ -9773,6 +9889,7 @@ const { parentPort, workerData } = require("node:worker_threads");
9773
9889
  const manifest = mod.generateSnapshot(config, {
9774
9890
  dryRun: workerData.dryRun === true,
9775
9891
  ...(workerData.narrow ?? {}),
9892
+ ...(workerData.runId === undefined ? {} : { runId: workerData.runId }),
9776
9893
  });
9777
9894
  const skipCounts = new Map();
9778
9895
  for (const record of manifest.skipped) {
@@ -9812,17 +9929,22 @@ const { parentPort, workerData } = require("node:worker_threads");
9812
9929
  })();
9813
9930
  `;
9814
9931
  function generateInWorker(cwd, cliOptions, options = {}) {
9815
- return new Promise((resolve10) => {
9932
+ return new Promise((resolve11) => {
9816
9933
  let settled = false;
9817
9934
  let worker = null;
9818
9935
  const finish = (result) => {
9819
9936
  if (settled) return;
9820
9937
  settled = true;
9821
- if (worker !== null) void worker.terminate();
9822
- resolve10(result);
9938
+ const terminated = worker === null ? Promise.resolve(void 0) : worker.terminate();
9939
+ void terminated.catch(() => void 0).then(() => {
9940
+ if (!result.ok && options.runId !== void 0 && options.lockRoots !== void 0) {
9941
+ releaseAbandonedRun(options.lockRoots, options.runId);
9942
+ }
9943
+ resolve11(result);
9944
+ });
9823
9945
  };
9824
9946
  const isCjs = typeof __dirname !== "undefined";
9825
- const directory = isCjs ? __dirname : path5__namespace.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('mcp.cjs', document.baseURI).href))));
9947
+ const directory = isCjs ? __dirname : path6__namespace.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('mcp.cjs', document.baseURI).href))));
9826
9948
  try {
9827
9949
  worker = new worker_threads.Worker(WORKER_SOURCE, {
9828
9950
  eval: true,
@@ -9831,7 +9953,8 @@ function generateInWorker(cwd, cliOptions, options = {}) {
9831
9953
  cwd,
9832
9954
  cliOptions,
9833
9955
  dryRun: options.dryRun === true,
9834
- narrow: options.narrow ?? {}
9956
+ narrow: options.narrow ?? {},
9957
+ ...options.runId === void 0 ? {} : { runId: options.runId }
9835
9958
  }
9836
9959
  });
9837
9960
  } catch (error) {
@@ -9883,43 +10006,99 @@ function windowText(body, fromLine, lineCount) {
9883
10006
  pastEnd
9884
10007
  };
9885
10008
  }
10009
+ function isInside2(parent, child) {
10010
+ const relative10 = path6__namespace.relative(parent, child);
10011
+ return relative10 === "" || !relative10.startsWith("..") && !path6__namespace.isAbsolute(relative10);
10012
+ }
10013
+ function readConfinedText(baseDir, relativePath) {
10014
+ if (relativePath.length === 0 || relativePath.includes("\0")) {
10015
+ return { ok: false, reason: "not-file", message: "the file name is empty or contains a NUL byte" };
10016
+ }
10017
+ if (path6__namespace.isAbsolute(relativePath)) {
10018
+ return { ok: false, reason: "outside", message: "an absolute path is not a snapshot-relative file" };
10019
+ }
10020
+ let baseReal;
10021
+ try {
10022
+ baseReal = fs3__namespace.realpathSync(path6__namespace.resolve(baseDir));
10023
+ } catch {
10024
+ return { ok: false, reason: "missing", message: "the snapshot directory does not exist" };
10025
+ }
10026
+ const candidate = path6__namespace.resolve(baseReal, relativePath);
10027
+ if (!isInside2(baseReal, candidate)) {
10028
+ return { ok: false, reason: "outside", message: "the path resolves outside the snapshot directory" };
10029
+ }
10030
+ let stats;
10031
+ try {
10032
+ stats = fs3__namespace.lstatSync(candidate);
10033
+ } catch (error) {
10034
+ const code = error.code;
10035
+ return {
10036
+ ok: false,
10037
+ reason: code === "ENOENT" || code === "ENOTDIR" ? "missing" : "unreadable",
10038
+ message: code === "ENOENT" || code === "ENOTDIR" ? "the file does not exist" : "the file could not be inspected"
10039
+ };
10040
+ }
10041
+ if (stats.isSymbolicLink()) {
10042
+ return { ok: false, reason: "not-file", message: "the file is a symbolic link" };
10043
+ }
10044
+ if (!stats.isFile()) {
10045
+ return { ok: false, reason: "not-file", message: "the path is not a regular file" };
10046
+ }
10047
+ let real;
10048
+ try {
10049
+ real = fs3__namespace.realpathSync(candidate);
10050
+ } catch {
10051
+ return { ok: false, reason: "unreadable", message: "the file could not be resolved" };
10052
+ }
10053
+ if (!isInside2(baseReal, real)) {
10054
+ return { ok: false, reason: "outside", message: "the file resolves outside the snapshot directory" };
10055
+ }
10056
+ try {
10057
+ const text = fs3__namespace.readFileSync(real, "utf8");
10058
+ return { ok: true, text, path: real, stats: fs3__namespace.statSync(real) };
10059
+ } catch {
10060
+ return { ok: false, reason: "unreadable", message: "the file could not be read" };
10061
+ }
10062
+ }
10063
+
10064
+ // src/mcp/workspace.ts
9886
10065
  function foldForComparison(value) {
9887
10066
  return process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
9888
10067
  }
9889
10068
  function canonicalPath(value) {
9890
- const absolute = path5__namespace.resolve(value);
10069
+ const absolute = path6__namespace.resolve(value);
9891
10070
  try {
9892
- return fs2__namespace.realpathSync(absolute);
10071
+ return fs3__namespace.realpathSync(absolute);
9893
10072
  } catch {
9894
10073
  return absolute;
9895
10074
  }
9896
10075
  }
9897
- function isInside2(parent, child) {
10076
+ function isInside3(parent, child) {
9898
10077
  const foldedParent = foldForComparison(parent);
9899
10078
  const foldedChild = foldForComparison(child);
9900
- return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path5__namespace.sep}`);
10079
+ return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path6__namespace.sep}`);
9901
10080
  }
9902
10081
  function resolveThroughExistingAncestor(target) {
9903
10082
  let existing = target;
9904
10083
  const missing = [];
9905
- while (!fs2__namespace.existsSync(existing)) {
9906
- missing.unshift(path5__namespace.basename(existing));
9907
- const parent = path5__namespace.dirname(existing);
10084
+ while (!fs3__namespace.existsSync(existing)) {
10085
+ missing.unshift(path6__namespace.basename(existing));
10086
+ const parent = path6__namespace.dirname(existing);
9908
10087
  if (parent === existing) break;
9909
10088
  existing = parent;
9910
10089
  }
9911
10090
  const resolved = canonicalPath(existing);
9912
- return missing.length === 0 ? resolved : path5__namespace.join(resolved, ...missing);
10091
+ return missing.length === 0 ? resolved : path6__namespace.join(resolved, ...missing);
9913
10092
  }
9914
10093
  function resolveRoot(requested, context) {
9915
10094
  if (requested !== void 0 && (typeof requested !== "string" || requested.trim().length === 0)) {
9916
10095
  return { ok: false, message: '"root" must be a non-empty string when provided.' };
9917
10096
  }
9918
10097
  const wanted = typeof requested === "string" ? requested.trim() : context.cwd;
9919
- const absolute = path5__namespace.resolve(context.cwd, wanted);
10098
+ const absolute = path6__namespace.resolve(context.cwd, wanted);
9920
10099
  let stats;
9921
10100
  try {
9922
- stats = fs2__namespace.statSync(absolute);
10101
+ stats = fs3__namespace.statSync(absolute);
9923
10102
  } catch {
9924
10103
  return { ok: false, message: `"${wanted}" does not exist, so it cannot be a repository root.` };
9925
10104
  }
@@ -9928,7 +10107,7 @@ function resolveRoot(requested, context) {
9928
10107
  }
9929
10108
  const resolved = canonicalPath(absolute);
9930
10109
  for (const allowed of context.roots) {
9931
- if (isInside2(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
10110
+ if (isInside3(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
9932
10111
  }
9933
10112
  const shown = context.roots.join(", ");
9934
10113
  return {
@@ -9971,8 +10150,8 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
9971
10150
  }
9972
10151
  const requested = overrides.outDir.trim();
9973
10152
  const permitted = allowedRoots !== void 0 && allowedRoots.length > 0 ? allowedRoots : [root];
9974
- const resolved = resolveThroughExistingAncestor(path5__namespace.resolve(root, requested));
9975
- if (!permitted.some((allowed) => isInside2(canonicalPath(allowed), resolved))) {
10153
+ const resolved = resolveThroughExistingAncestor(path6__namespace.resolve(root, requested));
10154
+ if (!permitted.some((allowed) => isInside3(canonicalPath(allowed), resolved))) {
9976
10155
  const shown = permitted.map((allowed) => canonicalPath(allowed)).join(", ");
9977
10156
  return {
9978
10157
  ok: false,
@@ -9994,9 +10173,26 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
9994
10173
  if (overrides.sarif === true) cliOptions.sarif = true;
9995
10174
  if (overrides.staged === true) cliOptions.staged = true;
9996
10175
  if (overrides.withDependents === true) cliOptions.withDependents = true;
10176
+ for (const key of ["only", "ignore"]) {
10177
+ const value = overrides[key];
10178
+ if (value === void 0) continue;
10179
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
10180
+ return { ok: false, message: `"${key}" must be an array of glob strings.` };
10181
+ }
10182
+ cliOptions[key] = value;
10183
+ }
9997
10184
  try {
9998
10185
  const config = resolveConfig(loaded.config, cliOptions, root);
9999
- return { ok: true, workspace: { root, config, configFile: loaded.file, cliOptions } };
10186
+ return {
10187
+ ok: true,
10188
+ workspace: {
10189
+ root,
10190
+ config,
10191
+ configFile: loaded.file,
10192
+ sourceConfig: loaded.config ?? null,
10193
+ cliOptions
10194
+ }
10195
+ };
10000
10196
  } catch (error) {
10001
10197
  return { ok: false, message: error instanceof Error ? error.message : String(error) };
10002
10198
  }
@@ -10004,25 +10200,25 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
10004
10200
  var MANIFEST_CACHE_LIMIT = 8;
10005
10201
  var manifestCache = /* @__PURE__ */ new Map();
10006
10202
  function manifestPathFor(workspace) {
10007
- return path5__namespace.resolve(workspace.root, workspace.config.outDir, "manifest.json");
10203
+ return path6__namespace.resolve(workspace.root, workspace.config.outDir, "manifest.json");
10008
10204
  }
10009
10205
  function partPathFor(workspace, filename) {
10010
10206
  if (filename.length === 0 || filename.includes("\0")) return null;
10011
- const partsDir = path5__namespace.resolve(workspace.root, workspace.config.outDir, "parts");
10012
- const resolved = path5__namespace.resolve(partsDir, filename);
10013
- const relative9 = path5__namespace.relative(partsDir, resolved);
10014
- if (relative9.length === 0 || relative9.includes(path5__namespace.sep) || relative9.includes("/") || relative9.includes("\\") || path5__namespace.isAbsolute(relative9)) {
10207
+ const partsDir = path6__namespace.resolve(workspace.root, workspace.config.outDir, "parts");
10208
+ const resolved = path6__namespace.resolve(partsDir, filename);
10209
+ const relative10 = path6__namespace.relative(partsDir, resolved);
10210
+ if (relative10.length === 0 || relative10.includes(path6__namespace.sep) || relative10.includes("/") || relative10.includes("\\") || path6__namespace.isAbsolute(relative10)) {
10015
10211
  return null;
10016
10212
  }
10017
10213
  let stats;
10018
10214
  try {
10019
- stats = fs2__namespace.lstatSync(resolved);
10215
+ stats = fs3__namespace.lstatSync(resolved);
10020
10216
  } catch {
10021
10217
  return null;
10022
10218
  }
10023
10219
  if (!stats.isFile()) return null;
10024
10220
  try {
10025
- if (path5__namespace.dirname(fs2__namespace.realpathSync(resolved)) !== fs2__namespace.realpathSync(partsDir)) return null;
10221
+ if (path6__namespace.dirname(fs3__namespace.realpathSync(resolved)) !== fs3__namespace.realpathSync(partsDir)) return null;
10026
10222
  } catch {
10027
10223
  return null;
10028
10224
  }
@@ -10030,31 +10226,28 @@ function partPathFor(workspace, filename) {
10030
10226
  }
10031
10227
  function readManifest3(workspace) {
10032
10228
  const file = manifestPathFor(workspace);
10033
- const shown = path5__namespace.relative(workspace.root, file).split(path5__namespace.sep).join("/") || file;
10034
- let stats;
10035
- try {
10036
- stats = fs2__namespace.statSync(file);
10037
- } catch {
10229
+ const shown = path6__namespace.relative(workspace.root, file).split(path6__namespace.sep).join("/") || file;
10230
+ const confined = readConfinedText(path6__namespace.dirname(file), path6__namespace.basename(file));
10231
+ if (!confined.ok) {
10232
+ if (confined.reason === "missing") {
10233
+ return {
10234
+ ok: false,
10235
+ missing: true,
10236
+ message: `There is no snapshot manifest at ${shown}. Call snapshot_plan to preview what would be included, or snapshot_generate to write it.`
10237
+ };
10238
+ }
10038
10239
  return {
10039
10240
  ok: false,
10040
- missing: true,
10041
- message: `There is no snapshot manifest at ${shown}. Call snapshot_plan to preview what would be included, or snapshot_generate to write it.`
10241
+ missing: false,
10242
+ message: `${shown} could not be read as a snapshot manifest: ${confined.message}.`
10042
10243
  };
10043
10244
  }
10245
+ const stats = confined.stats;
10246
+ const raw = confined.text;
10044
10247
  const cached = manifestCache.get(file);
10045
10248
  if (cached && cached.mtimeMs === stats.mtimeMs && cached.ctimeMs === stats.ctimeMs && cached.size === stats.size) {
10046
10249
  return { ok: true, manifest: cached.manifest, file };
10047
10250
  }
10048
- let raw;
10049
- try {
10050
- raw = fs2__namespace.readFileSync(file, "utf8");
10051
- } catch (error) {
10052
- return {
10053
- ok: false,
10054
- missing: false,
10055
- message: `${shown} exists but could not be read: ${error instanceof Error ? error.message : String(error)}`
10056
- };
10057
- }
10058
10251
  let parsed;
10059
10252
  try {
10060
10253
  parsed = JSON.parse(raw);
@@ -10084,6 +10277,96 @@ function forgetManifest(file) {
10084
10277
  manifestCache.delete(file);
10085
10278
  }
10086
10279
 
10280
+ // src/security/regex.ts
10281
+ var MAX_PATTERN_LENGTH = 256;
10282
+ var MAX_QUANTIFIER_REPEAT = 1e4;
10283
+ function unsafeRegExpReason(source) {
10284
+ if (source.length === 0) return null;
10285
+ if (source.length > MAX_PATTERN_LENGTH) {
10286
+ return `the pattern is longer than ${MAX_PATTERN_LENGTH} characters`;
10287
+ }
10288
+ let inClass = false;
10289
+ let unbounded = 0;
10290
+ const groups = [];
10291
+ for (let index = 0; index < source.length; index += 1) {
10292
+ const char = source[index];
10293
+ if (char === "\\") {
10294
+ index += 1;
10295
+ continue;
10296
+ }
10297
+ if (inClass) {
10298
+ if (char === "]") inClass = false;
10299
+ continue;
10300
+ }
10301
+ if (char === "[") {
10302
+ inClass = true;
10303
+ continue;
10304
+ }
10305
+ if (char === "(") {
10306
+ groups.push({ quantified: false, alternation: false });
10307
+ continue;
10308
+ }
10309
+ if (char === ")") {
10310
+ const group = groups.pop();
10311
+ if (group === void 0) continue;
10312
+ const next = source[index + 1];
10313
+ if (next === "*" || next === "+" || next === "{" && isUnboundedBrace(source, index + 1)) {
10314
+ if (group.quantified || group.alternation) {
10315
+ return "a quantified group contains another quantifier or an alternation";
10316
+ }
10317
+ }
10318
+ continue;
10319
+ }
10320
+ if (char === "|") {
10321
+ const group = groups[groups.length - 1];
10322
+ if (group !== void 0) group.alternation = true;
10323
+ continue;
10324
+ }
10325
+ if (char === "?") {
10326
+ const previous = source[index - 1];
10327
+ if (previous !== "(" && previous !== "?" && previous !== "*" && previous !== "+" && previous !== "}") {
10328
+ const group = groups[groups.length - 1];
10329
+ if (group !== void 0) group.quantified = true;
10330
+ }
10331
+ continue;
10332
+ }
10333
+ if (char === "*" || char === "+") {
10334
+ unbounded += 1;
10335
+ const group = groups[groups.length - 1];
10336
+ if (group !== void 0) group.quantified = true;
10337
+ continue;
10338
+ }
10339
+ if (char === "{") {
10340
+ const close = source.indexOf("}", index + 1);
10341
+ if (close === -1) continue;
10342
+ const body = source.slice(index + 1, close);
10343
+ const match = /^(\d+)(?:,(\d*))?$/.exec(body);
10344
+ if (match === null) {
10345
+ index = close;
10346
+ continue;
10347
+ }
10348
+ const max = match[2] === void 0 ? Number(match[1]) : match[2] === "" ? Infinity : Number(match[2]);
10349
+ if (max > MAX_QUANTIFIER_REPEAT) {
10350
+ return "a repetition bound is larger than the search budget can evaluate safely";
10351
+ }
10352
+ if (max === Infinity) unbounded += 1;
10353
+ const group = groups[groups.length - 1];
10354
+ if (group !== void 0) group.quantified = true;
10355
+ index = close;
10356
+ }
10357
+ }
10358
+ if (unbounded > 1) {
10359
+ return "the pattern has more than one unbounded repetition";
10360
+ }
10361
+ return null;
10362
+ }
10363
+ function isUnboundedBrace(source, start) {
10364
+ const close = source.indexOf("}", start + 1);
10365
+ if (close === -1) return false;
10366
+ const body = source.slice(start + 1, close);
10367
+ return /^\d+,$/.test(body);
10368
+ }
10369
+
10087
10370
  // src/mcp/tools.ts
10088
10371
  var MAX_SEARCH_BYTES = 4 * 1024 * 1024;
10089
10372
  var READ_ONLY = {
@@ -10115,6 +10398,16 @@ var OUT_DIR_PROPERTY = {
10115
10398
  };
10116
10399
  var outDirOverride = (args) => ({ outDir: args.outDir });
10117
10400
  var SCOPE_PROPERTIES = {
10401
+ only: {
10402
+ type: "array",
10403
+ items: { type: "string" },
10404
+ description: "Globs to include: replaces the config allow-list for this run."
10405
+ },
10406
+ ignore: {
10407
+ type: "array",
10408
+ items: { type: "string" },
10409
+ description: "Globs to exclude, added to the config deny-list for this run."
10410
+ },
10118
10411
  maxPartTokens: {
10119
10412
  type: "string",
10120
10413
  description: 'Token ceiling per part, for example 32000 or "32k". Narrower than maxPartBytes; it converts at four bytes per token.'
@@ -10149,7 +10442,9 @@ function workspaceOverrides(args) {
10149
10442
  sarif: args.sarif,
10150
10443
  changedSince: args.changedSince,
10151
10444
  staged: args.staged,
10152
- withDependents: args.withDependents
10445
+ withDependents: args.withDependents,
10446
+ only: args.only,
10447
+ ignore: args.ignore
10153
10448
  };
10154
10449
  }
10155
10450
  function failure(message) {
@@ -10164,7 +10459,7 @@ function formatBytes2(bytes) {
10164
10459
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
10165
10460
  }
10166
10461
  function relativeFor(workspace, absolute) {
10167
- return path5__namespace.relative(workspace.root, absolute).split(path5__namespace.sep).join("/");
10462
+ return path6__namespace.relative(workspace.root, absolute).split(path6__namespace.sep).join("/");
10168
10463
  }
10169
10464
  function capped(values, limit = 20) {
10170
10465
  return { count: values.length, sample: values.slice(0, limit) };
@@ -10183,13 +10478,13 @@ function summarizeDrift(drift) {
10183
10478
  function toRelativePath(root, value) {
10184
10479
  const cleaned = value.trim();
10185
10480
  if (cleaned.length === 0 || cleaned.includes("\0")) return null;
10186
- const resolvedRoot = path5__namespace.resolve(root);
10187
- const absolute = path5__namespace.resolve(resolvedRoot, cleaned);
10188
- const relative9 = path5__namespace.relative(resolvedRoot, absolute);
10189
- if (relative9 === "" || relative9 === ".." || relative9.startsWith(`..${path5__namespace.sep}`) || path5__namespace.isAbsolute(relative9)) {
10481
+ const resolvedRoot = path6__namespace.resolve(root);
10482
+ const absolute = path6__namespace.resolve(resolvedRoot, cleaned);
10483
+ const relative10 = path6__namespace.relative(resolvedRoot, absolute);
10484
+ if (relative10 === "" || relative10 === ".." || relative10.startsWith(`..${path6__namespace.sep}`) || path6__namespace.isAbsolute(relative10)) {
10190
10485
  return null;
10191
10486
  }
10192
- return relative9.split(path5__namespace.sep).join("/");
10487
+ return relative10.split(path6__namespace.sep).join("/");
10193
10488
  }
10194
10489
  function symbolsOf(entry) {
10195
10490
  const summary = entry.summary;
@@ -10282,20 +10577,19 @@ var historyTool = {
10282
10577
  async handler(args, context) {
10283
10578
  const prepared = await prepare(args, context, outDirOverride(args));
10284
10579
  if (!prepared.ok) return prepared.outcome;
10285
- const reportPath = path5__namespace.resolve(prepared.workspace.root, prepared.workspace.config.outDir, "reports", "log.md");
10286
- let text;
10287
- try {
10288
- text = fs2__namespace.readFileSync(reportPath, "utf8");
10289
- } catch {
10580
+ const snapshotDir = path6__namespace.resolve(prepared.workspace.root, prepared.workspace.config.outDir);
10581
+ const reportRead = readConfinedText(snapshotDir, path6__namespace.posix.join("reports", "log.md"));
10582
+ if (!reportRead.ok) {
10290
10583
  return {
10291
- text: "This snapshot has no reports/log.md. Generate it with `snapshot_generate { includeLogs: 20 }`, or `generate --include-logs 20` on the command line; the report is opt-in because the commit subjects are repository content.",
10584
+ text: "This snapshot has no readable reports/log.md. Generate it with `snapshot_generate { includeLogs: 20 }`, or `generate --include-logs 20` on the command line; the report is opt-in because the commit subjects are repository content, and it must be a regular file inside the snapshot.",
10292
10585
  isError: true
10293
10586
  };
10294
10587
  }
10588
+ const text = reportRead.text;
10295
10589
  const manifestRead = readManifest3(prepared.workspace);
10296
10590
  const recordedLog = manifestRead.ok ? manifestRead.manifest.artifacts?.log : void 0;
10297
10591
  if (recordedLog !== void 0 && recordedLog !== null) {
10298
- const digest = crypto2.createHash("sha256").update(text, "utf8").digest("hex");
10592
+ const digest = crypto5.createHash("sha256").update(text, "utf8").digest("hex");
10299
10593
  if (digest !== recordedLog.sha256) {
10300
10594
  return {
10301
10595
  text: "reports/log.md changed after the snapshot was generated (its digest no longer matches the manifest). Regenerate the snapshot rather than trusting this history.",
@@ -10352,7 +10646,7 @@ var budgetTool = {
10352
10646
  ...args.includeTests === true ? { includeTests: true } : {}
10353
10647
  });
10354
10648
  const paths = new Set(plan.files.map((file) => file.path));
10355
- const gained = [...paths].filter((path16) => !previous.has(path16)).sort();
10649
+ const gained = [...paths].filter((path17) => !previous.has(path17)).sort();
10356
10650
  previous = paths;
10357
10651
  rows.push({
10358
10652
  budget,
@@ -10403,7 +10697,9 @@ var testsTool = {
10403
10697
  const cap = Math.max(1, typeof args.maxFiles === "number" ? args.maxFiles : 50);
10404
10698
  const isTest2 = (filePath) => /(^|\/)(tests?|__tests__|spec)\//.test(filePath) || /\.(test|spec)\.[a-z0-9]+$/i.test(filePath);
10405
10699
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath, file]));
10406
- const resolver = buildImportResolver(read.manifest.files, {});
10700
+ const resolver = buildImportResolver(read.manifest.files, {
10701
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
10702
+ });
10407
10703
  const testFiles = read.manifest.files.filter((file) => isTest2(file.relativePath));
10408
10704
  const importsOf = (filePath) => {
10409
10705
  const entry = read.manifest.indexes.imports.byFile.find((candidate) => candidate.path === filePath);
@@ -10451,18 +10747,18 @@ var workspaceTool = {
10451
10747
  },
10452
10748
  annotations: READ_ONLY,
10453
10749
  async handler(args, context) {
10454
- const root = path5__namespace.resolve(context.cwd, typeof args.root === "string" ? args.root : ".");
10455
- const outDir = typeof args.outDir === "string" ? args.outDir : "snapshot";
10456
- const index = path5__namespace.resolve(root, outDir, "WORKSPACE.json");
10457
- let text;
10458
- try {
10459
- text = fs2__namespace.readFileSync(index, "utf8");
10460
- } catch {
10750
+ const prepared = await prepare(args, context, outDirOverride(args));
10751
+ if (!prepared.ok) return prepared.outcome;
10752
+ const snapshotDir = path6__namespace.resolve(prepared.workspace.root, prepared.workspace.config.outDir);
10753
+ const index = path6__namespace.join(snapshotDir, "WORKSPACE.json");
10754
+ const read = readConfinedText(snapshotDir, "WORKSPACE.json");
10755
+ if (!read.ok) {
10461
10756
  return {
10462
- text: "No workspace index at " + index + ". Generate one with `generate --workspace member-a,member-b`; a single snapshot has no members to list.",
10757
+ text: "No workspace index at " + index + " (the file is absent, or it is not a regular file inside the snapshot). Generate one with `generate --workspace member-a,member-b`; a single snapshot has no members to list.",
10463
10758
  isError: true
10464
10759
  };
10465
10760
  }
10761
+ const text = read.text;
10466
10762
  const document = JSON.parse(text);
10467
10763
  const members = document.members ?? [];
10468
10764
  const links = document.links ?? [];
@@ -10510,7 +10806,9 @@ var neighborsTool = {
10510
10806
  const file = read.manifest.files.find((candidate) => candidate.relativePath === wanted) ?? read.manifest.files.find((candidate) => candidate.relativePath.toLowerCase() === wanted.toLowerCase());
10511
10807
  if (file === void 0) return { text: wanted + " is not in the snapshot; snapshot_explain says why.", isError: true };
10512
10808
  const byPath = new Map(read.manifest.files.map((candidate) => [candidate.relativePath, candidate]));
10513
- const resolver = buildImportResolver(read.manifest.files, {});
10809
+ const resolver = buildImportResolver(read.manifest.files, {
10810
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
10811
+ });
10514
10812
  const entry = read.manifest.indexes.imports.byFile.find((candidate) => candidate.path === file.relativePath);
10515
10813
  const imports = [];
10516
10814
  for (const specifier of entry?.imports ?? []) {
@@ -10601,6 +10899,10 @@ var routesTool = {
10601
10899
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
10602
10900
  let filter = null;
10603
10901
  if (typeof args.pattern === "string") {
10902
+ const unsafe = unsafeRegExpReason(args.pattern);
10903
+ if (unsafe !== null) {
10904
+ return { text: "pattern is refused: " + unsafe + ".", isError: true };
10905
+ }
10604
10906
  try {
10605
10907
  filter = new RegExp(args.pattern, "i");
10606
10908
  } catch (error) {
@@ -10652,9 +10954,11 @@ var cyclesTool = {
10652
10954
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
10653
10955
  const cap = Math.max(1, typeof args.maxComponents === "number" ? args.maxComponents : 20);
10654
10956
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath, file]));
10655
- const resolver = buildImportResolver(read.manifest.files, {});
10957
+ const resolver = buildImportResolver(read.manifest.files, {
10958
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
10959
+ });
10656
10960
  const edges = /* @__PURE__ */ new Map();
10657
- for (const path16 of byPath.keys()) edges.set(path16, []);
10961
+ for (const path17 of byPath.keys()) edges.set(path17, []);
10658
10962
  for (const entry of read.manifest.indexes.imports.byFile) {
10659
10963
  const targets = edges.get(entry.path);
10660
10964
  if (targets === void 0) continue;
@@ -10742,6 +11046,12 @@ var searchTool = {
10742
11046
  const cap = Math.max(1, Math.min(500, typeof args.maxMatches === "number" ? args.maxMatches : 50));
10743
11047
  const contextLines = Math.max(0, Math.min(10, typeof args.contextLines === "number" ? args.contextLines : 0));
10744
11048
  let pattern;
11049
+ if (args.regex === true) {
11050
+ const unsafe = unsafeRegExpReason(query);
11051
+ if (unsafe !== null) {
11052
+ return { text: "regex is refused: " + unsafe + ".", isError: true };
11053
+ }
11054
+ }
10745
11055
  try {
10746
11056
  pattern = args.regex === true ? new RegExp(query, "i") : new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i");
10747
11057
  } catch (error) {
@@ -10760,7 +11070,7 @@ var searchTool = {
10760
11070
  if (partPath === null) continue;
10761
11071
  let text;
10762
11072
  try {
10763
- text = fs2__namespace.readFileSync(partPath, "utf8");
11073
+ text = fs3__namespace.readFileSync(partPath, "utf8");
10764
11074
  } catch {
10765
11075
  continue;
10766
11076
  }
@@ -10891,7 +11201,7 @@ var reviewTool = {
10891
11201
  return { text: error.message, isError: true };
10892
11202
  }
10893
11203
  const report2 = auditSnapshot({
10894
- snapshotDir: path5__namespace.resolve(workspace.root, workspace.config.outDir),
11204
+ snapshotDir: path6__namespace.resolve(workspace.root, workspace.config.outDir),
10895
11205
  repoDir: workspace.root
10896
11206
  });
10897
11207
  const failed = report2.checks.filter((check2) => check2.status === "fail").map((check2) => check2.id + ": " + check2.detail);
@@ -10913,7 +11223,7 @@ var reviewTool = {
10913
11223
  }
10914
11224
  let section = null;
10915
11225
  try {
10916
- section = findSection(parsePartSections(fs2__namespace.readFileSync(partPath, "utf8")), file.relativePath);
11226
+ section = findSection(parsePartSections(fs3__namespace.readFileSync(partPath, "utf8")), file.relativePath);
10917
11227
  } catch {
10918
11228
  section = null;
10919
11229
  }
@@ -11003,31 +11313,31 @@ var diffContextTool = {
11003
11313
  const changed = [];
11004
11314
  const text = [];
11005
11315
  let used = 0;
11006
- for (const path16 of wanted) {
11007
- const file = byPath.get(path16.toLowerCase());
11316
+ for (const path17 of wanted) {
11317
+ const file = byPath.get(path17.toLowerCase());
11008
11318
  if (file === void 0) {
11009
- missing.push(path16);
11319
+ missing.push(path17);
11010
11320
  continue;
11011
11321
  }
11012
11322
  const partPath = partPathFor(workspace, file.part);
11013
11323
  if (partPath === null) {
11014
- missing.push(path16 + " (part missing)");
11324
+ missing.push(path17 + " (part missing)");
11015
11325
  continue;
11016
11326
  }
11017
11327
  let section;
11018
11328
  try {
11019
- section = findSection(parsePartSections(fs2__namespace.readFileSync(partPath, "utf8")), file.relativePath);
11329
+ section = findSection(parsePartSections(fs3__namespace.readFileSync(partPath, "utf8")), file.relativePath);
11020
11330
  } catch {
11021
11331
  section = null;
11022
11332
  }
11023
11333
  if (section === null) {
11024
- missing.push(path16 + " (section not found)");
11334
+ missing.push(path17 + " (section not found)");
11025
11335
  continue;
11026
11336
  }
11027
11337
  const window = windowText(section.body, 1, linesPerFile);
11028
11338
  const tokens = Math.max(1, Math.ceil(Buffer.byteLength(window.text, "utf8") / 4));
11029
11339
  if (used + tokens > budget) {
11030
- missing.push(path16 + " (budget)");
11340
+ missing.push(path17 + " (budget)");
11031
11341
  continue;
11032
11342
  }
11033
11343
  used += tokens;
@@ -11102,7 +11412,7 @@ var symbolTool = {
11102
11412
  if (partPath === null) continue;
11103
11413
  let partText;
11104
11414
  try {
11105
- partText = fs2__namespace.readFileSync(partPath, "utf8");
11415
+ partText = fs3__namespace.readFileSync(partPath, "utf8");
11106
11416
  } catch {
11107
11417
  continue;
11108
11418
  }
@@ -11134,28 +11444,39 @@ var symbolTool = {
11134
11444
  };
11135
11445
  }
11136
11446
  const callSites = [];
11447
+ let referencesTruncated = false;
11137
11448
  if (args.references !== false) {
11138
11449
  const limit = Math.max(1, typeof args.maxReferences === "number" ? args.maxReferences : 20);
11139
11450
  const definitionKeys = new Set(matches.map((match) => match.path + ":" + match.line));
11140
11451
  const word = new RegExp("\\b" + name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\b");
11141
- const parts = /* @__PURE__ */ new Map();
11452
+ const sectionsByPart = /* @__PURE__ */ new Map();
11142
11453
  let scanned = 0;
11143
11454
  for (const file of read.manifest.files) {
11144
11455
  if (callSites.length >= limit) break;
11145
11456
  const partPath = partPathFor(workspace, file.part);
11146
11457
  if (partPath === null) continue;
11147
- let partText = parts.get(partPath);
11148
- if (partText === void 0) {
11458
+ let sections = sectionsByPart.get(partPath);
11459
+ if (sections === void 0) {
11460
+ if (scanned >= MAX_SEARCH_BYTES) {
11461
+ referencesTruncated = true;
11462
+ break;
11463
+ }
11464
+ let partText;
11149
11465
  try {
11150
- partText = fs2__namespace.readFileSync(partPath, "utf8");
11466
+ partText = fs3__namespace.readFileSync(partPath, "utf8");
11151
11467
  } catch {
11152
11468
  continue;
11153
11469
  }
11154
- parts.set(partPath, partText);
11470
+ const bytes = Buffer.byteLength(partText, "utf8");
11471
+ if (scanned + bytes > MAX_SEARCH_BYTES) {
11472
+ referencesTruncated = true;
11473
+ break;
11474
+ }
11475
+ scanned += bytes;
11476
+ sections = parsePartSections(partText);
11477
+ sectionsByPart.set(partPath, sections);
11155
11478
  }
11156
- if (scanned > MAX_SEARCH_BYTES) break;
11157
- scanned += Buffer.byteLength(partText, "utf8");
11158
- const section = findSection(parsePartSections(partText), file.relativePath);
11479
+ const section = findSection(sections, file.relativePath);
11159
11480
  if (section === null) continue;
11160
11481
  const bodyLines = section.body.split("\n");
11161
11482
  for (let index = 0; index < bodyLines.length && callSites.length < limit; index += 1) {
@@ -11169,8 +11490,11 @@ var symbolTool = {
11169
11490
  }
11170
11491
  }
11171
11492
  }
11172
- const text = matches.map((match) => "### " + match.path + " (" + match.part + ", line " + match.line + ")\n" + match.text).join("\n\n") + (args.references === false ? "" : "\n\n" + (callSites.length === 0 ? "No call site was found in the snapshot." : "Call sites (" + callSites.length + "):\n" + callSites.map((site) => " " + site.path + ":" + site.line + " " + site.text).join("\n")));
11173
- return { text, structured: { found: matches.length, matches, references: callSites } };
11493
+ const text = matches.map((match) => "### " + match.path + " (" + match.part + ", line " + match.line + ")\n" + match.text).join("\n\n") + (args.references === false ? "" : "\n\n" + (callSites.length === 0 ? "No call site was found in the snapshot." : "Call sites (" + callSites.length + "):\n" + callSites.map((site) => " " + site.path + ":" + site.line + " " + site.text).join("\n"))) + (referencesTruncated ? "\n\nSearch stopped at the 4 MB part budget; call sites in later parts were not read. Narrow the name or inspect the remaining parts directly." : "");
11494
+ return {
11495
+ text,
11496
+ structured: { found: matches.length, matches, references: callSites, truncated: referencesTruncated }
11497
+ };
11174
11498
  }
11175
11499
  };
11176
11500
  var contextTool = {
@@ -11243,7 +11567,7 @@ var contextTool = {
11243
11567
  }
11244
11568
  if (!sectionsByPart.has(file.part)) {
11245
11569
  try {
11246
- sectionsByPart.set(file.part, parsePartSections(fs2__namespace.readFileSync(partPath, "utf8")));
11570
+ sectionsByPart.set(file.part, parsePartSections(fs3__namespace.readFileSync(partPath, "utf8")));
11247
11571
  } catch {
11248
11572
  sectionsByPart.set(file.part, null);
11249
11573
  }
@@ -11328,6 +11652,10 @@ var queryTool = {
11328
11652
  const maxFiles = typeof args.maxFiles === "number" ? Math.min(200, Math.max(1, args.maxFiles)) : 40;
11329
11653
  let pattern = null;
11330
11654
  if (typeof args.pathPattern === "string") {
11655
+ const unsafe = unsafeRegExpReason(args.pathPattern);
11656
+ if (unsafe !== null) {
11657
+ return { text: "pathPattern is refused: " + unsafe + ".", isError: true };
11658
+ }
11331
11659
  try {
11332
11660
  pattern = new RegExp(args.pathPattern, "i");
11333
11661
  } catch (error) {
@@ -11477,7 +11805,7 @@ var answerTool = {
11477
11805
  let partText = parts.get(partPath);
11478
11806
  if (partText === void 0) {
11479
11807
  try {
11480
- partText = fs2__namespace.readFileSync(partPath, "utf8");
11808
+ partText = fs3__namespace.readFileSync(partPath, "utf8");
11481
11809
  } catch {
11482
11810
  omitted.push({ path: planned.path, reason: "its part could not be read" });
11483
11811
  continue;
@@ -11574,7 +11902,7 @@ var healthTool = {
11574
11902
  if (!prepared.ok) return prepared.outcome;
11575
11903
  const workspace = prepared.workspace;
11576
11904
  const report2 = auditSnapshot({
11577
- snapshotDir: path5__namespace.resolve(workspace.root, workspace.config.outDir),
11905
+ snapshotDir: path6__namespace.resolve(workspace.root, workspace.config.outDir),
11578
11906
  repoDir: workspace.root,
11579
11907
  ...typeof args.maxScanBytes === "number" ? { maxScanBytes: args.maxScanBytes } : {},
11580
11908
  ...args.deep === true ? { deep: true } : {}
@@ -11803,16 +12131,6 @@ var generateTool = {
11803
12131
  minimum: 500,
11804
12132
  description: "Fit the snapshot into this token budget, highest value first."
11805
12133
  },
11806
- only: {
11807
- type: "array",
11808
- items: { type: "string" },
11809
- description: "Globs to include: replaces the config allow-list for this run."
11810
- },
11811
- ignore: {
11812
- type: "array",
11813
- items: { type: "string" },
11814
- description: "Globs to exclude, added to the config deny-list for this run."
11815
- },
11816
12134
  ...SCOPE_PROPERTIES
11817
12135
  },
11818
12136
  additionalProperties: false
@@ -11852,16 +12170,23 @@ var generateTool = {
11852
12170
  ...typeof args.slice === "string" ? { slice: { question: args.slice, ...typeof args.sliceTokens === "number" ? { maxTokens: args.sliceTokens } : {} } } : {},
11853
12171
  ...typeof args.budgetTokens === "number" ? { budgetTokens: args.budgetTokens } : {}
11854
12172
  };
12173
+ let lockRoots;
12174
+ try {
12175
+ const safe = resolveSafeOutputDirs(workspace.config);
12176
+ lockRoots = [safe.outDir, safe.tmpDir];
12177
+ } catch (error) {
12178
+ return failure(error instanceof Error ? error.message : String(error));
12179
+ }
11855
12180
  const result = await generateInWorker(
11856
12181
  workspace.root,
11857
12182
  { ...workspace.cliOptions, ...reportOptions },
11858
- { signal: controller.signal, narrow }
12183
+ { signal: controller.signal, narrow, runId: crypto5.randomUUID(), lockRoots }
11859
12184
  );
11860
12185
  if (!result.ok) return failure(result.message);
11861
12186
  context.notify?.({ message: "writing the snapshot", progress: 2, total: 2 });
11862
12187
  const summary = result.summary;
11863
12188
  forgetManifest(manifestPathFor(workspace));
11864
- const written = relativeFor(workspace, path5__namespace.resolve(workspace.root, workspace.config.outDir));
12189
+ const written = relativeFor(workspace, path6__namespace.resolve(workspace.root, workspace.config.outDir));
11865
12190
  const lines = [
11866
12191
  `Wrote ${written}/`,
11867
12192
  `Files: ${summary.totalFiles} included, ${summary.skippedCount} skipped, ${plural(summary.partsCount, "part")}`,
@@ -11889,16 +12214,42 @@ var generateTool = {
11889
12214
  };
11890
12215
  function configAsGenerated(workspace, manifest) {
11891
12216
  const recorded = manifest.config;
12217
+ const cli = workspace.cliOptions;
12218
+ const source = workspace.sourceConfig;
12219
+ const configured = (key) => source !== null && Object.prototype.hasOwnProperty.call(source, key);
12220
+ const sourceArtifacts = source !== null && source.artifacts !== null && typeof source.artifacts === "object" ? source.artifacts : null;
12221
+ const artifacts = { ...workspace.config.artifacts };
12222
+ if (recorded?.artifacts !== void 0) {
12223
+ for (const [key, value] of Object.entries(recorded.artifacts)) {
12224
+ if (sourceArtifacts === null || !Object.prototype.hasOwnProperty.call(sourceArtifacts, key)) {
12225
+ artifacts[key] = value;
12226
+ }
12227
+ }
12228
+ }
12229
+ let artifactOverride = recorded?.artifacts !== void 0;
12230
+ if (cli.includeDiffs === true) {
12231
+ artifacts.diff = true;
12232
+ artifactOverride = true;
12233
+ }
12234
+ if (cli.includeLogs !== void 0) {
12235
+ artifacts.log = true;
12236
+ artifactOverride = true;
12237
+ }
12238
+ if (cli.tokenTree === true) {
12239
+ artifacts.tokenTree = true;
12240
+ artifactOverride = true;
12241
+ }
12242
+ const choose = (key, recordedValue, current, cliValue) => cliValue !== void 0 ? cliValue : configured(key) ? current : recordedValue ?? current;
11892
12243
  return {
11893
12244
  ...workspace.config,
11894
- ...recorded?.artifacts === void 0 ? {} : { artifacts: recorded.artifacts },
11895
- ...recorded?.stripComments === void 0 ? {} : { stripComments: recorded.stripComments },
11896
- ...recorded?.removeEmptyLines === void 0 ? {} : { removeEmptyLines: recorded.removeEmptyLines },
11897
- ...recorded?.pack === void 0 ? {} : { pack: recorded.pack },
11898
- ...recorded?.logCount === void 0 ? {} : { logCount: recorded.logCount },
11899
- ...recorded?.skeleton === void 0 ? {} : { skeleton: recorded.skeleton },
11900
- ...recorded?.sarif === void 0 ? {} : { sarif: recorded.sarif },
11901
- ...recorded?.maxParts === void 0 ? {} : { maxParts: recorded.maxParts }
12245
+ ...artifactOverride ? { artifacts } : {},
12246
+ ...cli.stripComments === true || configured("stripComments") || recorded?.stripComments !== void 0 ? { stripComments: choose("stripComments", recorded?.stripComments, workspace.config.stripComments, cli.stripComments === true ? true : void 0) } : {},
12247
+ ...cli.removeEmptyLines === true || configured("removeEmptyLines") || recorded?.removeEmptyLines !== void 0 ? { removeEmptyLines: choose("removeEmptyLines", recorded?.removeEmptyLines, workspace.config.removeEmptyLines, cli.removeEmptyLines === true ? true : void 0) } : {},
12248
+ ...cli.pack !== void 0 || configured("pack") || recorded?.pack !== void 0 ? { pack: choose("pack", recorded?.pack ?? void 0, workspace.config.pack, cli.pack) } : {},
12249
+ ...cli.includeLogs !== void 0 || configured("logCount") || recorded?.logCount !== void 0 ? { logCount: choose("logCount", recorded?.logCount, workspace.config.logCount, cli.includeLogs) } : {},
12250
+ ...cli.skeleton === true || configured("skeleton") || recorded?.skeleton !== void 0 ? { skeleton: choose("skeleton", recorded?.skeleton, workspace.config.skeleton, cli.skeleton === true ? true : void 0) } : {},
12251
+ ...cli.sarif === true || configured("sarif") || recorded?.sarif !== void 0 ? { sarif: choose("sarif", recorded?.sarif, workspace.config.sarif, cli.sarif === true ? true : void 0) } : {},
12252
+ ...configured("maxParts") || recorded?.maxParts !== void 0 ? { maxParts: choose("maxParts", recorded?.maxParts, workspace.config.maxParts) } : {}
11902
12253
  };
11903
12254
  }
11904
12255
  var validateTool = {
@@ -12135,7 +12486,9 @@ var dependentsTool = {
12135
12486
  }
12136
12487
  const direction = args.direction === "imports" || args.direction === "imported-by" ? String(args.direction) : "both";
12137
12488
  const limit = typeof args.limit === "number" && args.limit > 0 ? Math.floor(args.limit) : 50;
12138
- const resolver = buildImportResolver(manifest.files);
12489
+ const resolver = buildImportResolver(manifest.files, {
12490
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
12491
+ });
12139
12492
  const imports = [];
12140
12493
  const unresolved = [];
12141
12494
  if (direction !== "imported-by") {
@@ -12278,7 +12631,7 @@ var readTool = {
12278
12631
  }
12279
12632
  let partText;
12280
12633
  try {
12281
- partText = fs2__namespace.readFileSync(partPath, "utf8");
12634
+ partText = fs3__namespace.readFileSync(partPath, "utf8");
12282
12635
  } catch {
12283
12636
  return failure(
12284
12637
  `${entry.part} could not be read, so the snapshot is damaged. Run snapshot_generate to rebuild it.`
@@ -12531,12 +12884,12 @@ async function runStdioServer(options) {
12531
12884
  });
12532
12885
  return writeChain;
12533
12886
  };
12534
- const MAX_IN_FLIGHT = 4;
12887
+ const MAX_IN_FLIGHT2 = 4;
12535
12888
  let inFlight = 0;
12536
12889
  let inputEnded = false;
12537
12890
  let resolveDone = () => void 0;
12538
- const finished = new Promise((resolve10) => {
12539
- resolveDone = resolve10;
12891
+ const finished = new Promise((resolve11) => {
12892
+ resolveDone = resolve11;
12540
12893
  });
12541
12894
  const finishIfIdle = () => {
12542
12895
  if (inputEnded && inFlight === 0) resolveDone(0);
@@ -12566,14 +12919,14 @@ async function runStdioServer(options) {
12566
12919
  errorResponse(
12567
12920
  id,
12568
12921
  ERROR_CODES.overloaded,
12569
- `The server is already handling ${MAX_IN_FLIGHT} requests; retry this one when it is free.`
12922
+ `The server is already handling ${MAX_IN_FLIGHT2} requests; retry this one when it is free.`
12570
12923
  )
12571
12924
  );
12572
12925
  };
12573
12926
  const stopReading = createLineReader(process.stdin, {
12574
12927
  onOverflow: (bytes) => log(`mcp: discarded an oversized message (${bytes} bytes)`),
12575
12928
  onLine: (line) => {
12576
- if (inFlight >= MAX_IN_FLIGHT) {
12929
+ if (inFlight >= MAX_IN_FLIGHT2) {
12577
12930
  rejectOverloaded(line);
12578
12931
  return;
12579
12932
  }
@@ -12598,6 +12951,171 @@ async function runStdioServer(options) {
12598
12951
  await writeChain;
12599
12952
  return code;
12600
12953
  }
12954
+ function sha256Hex2(input) {
12955
+ return crypto5__namespace.createHash("sha256").update(input).digest("hex");
12956
+ }
12957
+ function resolveSafeOutputDirs(config) {
12958
+ const cwd = path6__namespace.resolve(config.cwd);
12959
+ const outDir = path6__namespace.resolve(cwd, config.outDir);
12960
+ const tmpDir = path6__namespace.resolve(cwd, config.tmpDir);
12961
+ const root = path6__namespace.parse(cwd).root;
12962
+ const contains = (parent, child) => child === parent || child.startsWith(`${parent}${path6__namespace.sep}`);
12963
+ const reject = (reason) => {
12964
+ throw new Error(
12965
+ `Refusing to generate: ${reason}. outDir=${outDir} tmpDir=${tmpDir} cwd=${cwd}`
12966
+ );
12967
+ };
12968
+ if (outDir === root) reject("outDir resolves to the filesystem root");
12969
+ if (outDir === cwd || contains(outDir, cwd)) {
12970
+ reject("outDir is the working directory or one of its ancestors");
12971
+ }
12972
+ if (tmpDir === root) reject("tmpDir resolves to the filesystem root");
12973
+ if (tmpDir === cwd || contains(tmpDir, cwd)) {
12974
+ reject("tmpDir is the working directory or one of its ancestors");
12975
+ }
12976
+ if (tmpDir === outDir) reject("outDir and tmpDir are the same directory");
12977
+ if (contains(outDir, tmpDir)) reject("tmpDir is inside outDir");
12978
+ if (contains(tmpDir, outDir)) reject("outDir is inside tmpDir");
12979
+ return { outDir, tmpDir };
12980
+ }
12981
+ var RUN_DIR_PREFIX = "run-";
12982
+ var OWNERSHIP_MARKER = ".codebase-snapshot";
12983
+ var SUPPORTED_MARKER_SCHEMAS = /* @__PURE__ */ new Set([SCHEMA_VERSION]);
12984
+ var SNAPSHOT_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
12985
+ var SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/;
12986
+ function readOwnershipMarker(dir) {
12987
+ const markerPath = path6__namespace.join(dir, OWNERSHIP_MARKER);
12988
+ if (!fs3__namespace.existsSync(markerPath)) {
12989
+ return { marker: null, problem: "it holds no .codebase-snapshot marker" };
12990
+ }
12991
+ let raw;
12992
+ try {
12993
+ raw = fs3__namespace.readFileSync(markerPath, "utf8");
12994
+ } catch {
12995
+ return { marker: null, problem: "its .codebase-snapshot marker could not be read" };
12996
+ }
12997
+ if (raw.trim().length === 0) {
12998
+ return { marker: null, problem: "its .codebase-snapshot marker is empty" };
12999
+ }
13000
+ let parsed;
13001
+ try {
13002
+ parsed = JSON.parse(raw);
13003
+ } catch {
13004
+ return { marker: null, problem: "its .codebase-snapshot marker is not valid JSON" };
13005
+ }
13006
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
13007
+ return { marker: null, problem: "its .codebase-snapshot marker is not a JSON object" };
13008
+ }
13009
+ const candidate = parsed;
13010
+ if (!isOurGeneratorName(candidate.generator)) {
13011
+ return { marker: null, problem: "its .codebase-snapshot marker names a different generator" };
13012
+ }
13013
+ if (typeof candidate.schemaVersion !== "string" || !SUPPORTED_MARKER_SCHEMAS.has(candidate.schemaVersion)) {
13014
+ return {
13015
+ marker: null,
13016
+ problem: `its .codebase-snapshot marker has a schema version this build does not understand (${String(candidate.schemaVersion)})`
13017
+ };
13018
+ }
13019
+ if (typeof candidate.id !== "string" || !SNAPSHOT_ID_PATTERN.test(candidate.id)) {
13020
+ return { marker: null, problem: "its .codebase-snapshot marker carries no snapshot id" };
13021
+ }
13022
+ if (candidate.state !== "staging" && candidate.state !== "complete") {
13023
+ return { marker: null, problem: "its .codebase-snapshot marker records no run state" };
13024
+ }
13025
+ const rawFiles = candidate.files;
13026
+ let files;
13027
+ if (rawFiles !== void 0) {
13028
+ if (!Array.isArray(rawFiles)) {
13029
+ return {
13030
+ marker: null,
13031
+ problem: "its .codebase-snapshot marker's file inventory is not an array"
13032
+ };
13033
+ }
13034
+ files = [];
13035
+ for (const item of rawFiles) {
13036
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
13037
+ return {
13038
+ marker: null,
13039
+ problem: "its .codebase-snapshot marker's file inventory holds an entry that is not an object"
13040
+ };
13041
+ }
13042
+ const record = item;
13043
+ if (typeof record.path !== "string" || typeof record.bytes !== "number" || !Number.isInteger(record.bytes) || record.bytes < 0 || typeof record.sha256 !== "string" || !SHA256_HEX_PATTERN.test(record.sha256)) {
13044
+ return {
13045
+ marker: null,
13046
+ problem: "its .codebase-snapshot marker's file inventory holds an entry this build cannot read"
13047
+ };
13048
+ }
13049
+ files.push({ path: record.path, bytes: record.bytes, sha256: record.sha256 });
13050
+ }
13051
+ }
13052
+ return {
13053
+ marker: {
13054
+ generator: GENERATOR_NAME,
13055
+ version: typeof candidate.version === "string" ? candidate.version : "unknown",
13056
+ schemaVersion: candidate.schemaVersion,
13057
+ createdAt: typeof candidate.createdAt === "string" ? candidate.createdAt : "unknown",
13058
+ state: candidate.state,
13059
+ id: candidate.id,
13060
+ runId: typeof candidate.runId === "string" ? candidate.runId : void 0,
13061
+ pid: typeof candidate.pid === "number" ? candidate.pid : void 0,
13062
+ manifestSha256: typeof candidate.manifestSha256 === "string" ? candidate.manifestSha256 : void 0,
13063
+ entries: Array.isArray(candidate.entries) && candidate.entries.every((entry) => typeof entry === "string") ? candidate.entries : void 0,
13064
+ files
13065
+ },
13066
+ problem: null
13067
+ };
13068
+ }
13069
+ function lockKeyFor(stagingRoot) {
13070
+ let key = canonicalLockTarget(stagingRoot);
13071
+ if (process.platform === "win32" || process.platform === "darwin") key = key.toLowerCase();
13072
+ return sha256Hex2(key).slice(0, 16);
13073
+ }
13074
+ function canonicalLockTarget(targetPath) {
13075
+ const resolved = path6__namespace.resolve(targetPath);
13076
+ let existing = resolved;
13077
+ const tail = [];
13078
+ for (; ; ) {
13079
+ try {
13080
+ return path6__namespace.join(fs3__namespace.realpathSync(existing), ...tail);
13081
+ } catch {
13082
+ const parent = path6__namespace.dirname(existing);
13083
+ if (parent === existing) return resolved;
13084
+ tail.unshift(path6__namespace.basename(existing));
13085
+ existing = parent;
13086
+ }
13087
+ }
13088
+ }
13089
+ function lockPathFor(stagingRoot) {
13090
+ return path6__namespace.join(os__namespace.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
13091
+ }
13092
+ function releaseAbandonedRun(stagingRoots, runId) {
13093
+ if (runId.length === 0) return;
13094
+ for (const root of new Set(stagingRoots)) {
13095
+ const lockPath = lockPathFor(root);
13096
+ try {
13097
+ const payload = JSON.parse(fs3__namespace.readFileSync(lockPath, "utf8"));
13098
+ if (payload.runId === runId) fs3__namespace.rmSync(lockPath, { force: true });
13099
+ } catch {
13100
+ }
13101
+ let entries;
13102
+ try {
13103
+ entries = fs3__namespace.readdirSync(root);
13104
+ } catch {
13105
+ continue;
13106
+ }
13107
+ for (const name of entries) {
13108
+ if (!name.startsWith(RUN_DIR_PREFIX)) continue;
13109
+ const directory = path6__namespace.join(root, name);
13110
+ const { marker } = readOwnershipMarker(directory);
13111
+ if (marker?.runId !== runId) continue;
13112
+ try {
13113
+ fs3__namespace.rmSync(directory, { recursive: true, force: true });
13114
+ } catch {
13115
+ }
13116
+ }
13117
+ }
13118
+ }
12601
13119
 
12602
13120
  // src/mcp/uris.ts
12603
13121
  var STATIC_RESOURCE_URIS = [
@@ -13513,6 +14031,10 @@ function buildAgentContract() {
13513
14031
  { key: "maxPartBytes", type: "number | string", default: 307200, summary: "Per-part byte budget." },
13514
14032
  { key: "maxPartTokens", type: "number | string | null", default: null, summary: "Per-part token ceiling; narrows maxPartBytes. Minimum 1024." },
13515
14033
  { key: "skeleton", type: "boolean", default: false, summary: "Collapse function bodies to `{ /* ... */ }` in TS, JS, TSX and JSX files." },
14034
+ { key: "stripComments", type: "boolean", default: false, summary: "Remove comment text from JS/TS bodies." },
14035
+ { key: "removeEmptyLines", type: "boolean", default: false, summary: "Drop blank lines from emitted bodies; the part's line numbers move, and files[] records emptyLinesRemoved." },
14036
+ { key: "pack", type: '"single" | "xml" | "json" | null', default: null, summary: "Write one single-file pack in this format." },
14037
+ { key: "logCount", type: "number", default: 20, summary: "Commit lines in reports/log.md (also set by --include-logs <n>)." },
13516
14038
  { key: "sarif", type: "boolean", default: false, summary: "Also write reports/audit.sarif." },
13517
14039
  { key: "changedSince", type: "string | null", default: null, summary: "Snapshot only files that differ from this git ref." },
13518
14040
  { key: "staged", type: "boolean", default: false, summary: "Snapshot only files staged in the index." },
@@ -13852,7 +14374,7 @@ async function workspaceFor(context) {
13852
14374
  }
13853
14375
  function readFileIfPresent(file) {
13854
14376
  try {
13855
- return fs2__namespace.readFileSync(file, "utf8");
14377
+ return fs3__namespace.readFileSync(file, "utf8");
13856
14378
  } catch {
13857
14379
  return null;
13858
14380
  }
@@ -13891,9 +14413,9 @@ function buildResourceProvider() {
13891
14413
  }
13892
14414
  ];
13893
14415
  const workspace = await workspaceFor(context);
13894
- const reportsDir = "error" in workspace ? null : path5__namespace.resolve(workspace.root, workspace.config.outDir, "reports");
14416
+ const reportsDir = "error" in workspace ? null : path6__namespace.resolve(workspace.root, workspace.config.outDir, "reports");
13895
14417
  for (const [uri, report2] of REPORT_URIS) {
13896
- const present = reportsDir !== null && fs2__namespace.existsSync(path5__namespace.join(reportsDir, report2.file));
14418
+ const present = reportsDir !== null && fs3__namespace.existsSync(path6__namespace.join(reportsDir, report2.file));
13897
14419
  if (!present) continue;
13898
14420
  resources.push({
13899
14421
  uri,
@@ -13955,36 +14477,46 @@ function buildResourceProvider() {
13955
14477
  }
13956
14478
  const workspace = await workspaceFor(context);
13957
14479
  if ("error" in workspace) return null;
14480
+ const snapshotDir = path6__namespace.resolve(workspace.root, workspace.config.outDir);
13958
14481
  if (uri === PROMPT_URI) {
13959
- const text = readFileIfPresent(
13960
- path5__namespace.resolve(workspace.root, workspace.config.outDir, "PROMPT.md")
13961
- );
13962
- if (text === null) {
14482
+ const read = readConfinedText(snapshotDir, "PROMPT.md");
14483
+ if (!read.ok) {
13963
14484
  throw new ResourceNotFoundError(
13964
14485
  uri,
13965
- "This snapshot contains no PROMPT.md: the prompt artifact was disabled (artifacts.prompt = false or --skip-artifacts prompt), or nothing has been generated yet. Run snapshot_generate first."
14486
+ "This snapshot contains no readable PROMPT.md: the prompt artifact was disabled (artifacts.prompt = false or --skip-artifacts prompt), nothing has been generated yet, or the file is not a regular file inside the snapshot. Run snapshot_generate first."
13966
14487
  );
13967
14488
  }
13968
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text, PROMPT_ADVICE) };
14489
+ return {
14490
+ uri,
14491
+ mimeType: "text/markdown",
14492
+ text: ensureSingleRead(uri, read.text, PROMPT_ADVICE)
14493
+ };
13969
14494
  }
13970
14495
  const report2 = REPORT_URIS.get(uri);
13971
14496
  if (report2) {
13972
- const text = readFileIfPresent(
13973
- path5__namespace.resolve(workspace.root, workspace.config.outDir, "reports", report2.file)
13974
- );
13975
- if (text === null) {
14497
+ const read = readConfinedText(snapshotDir, path6__namespace.posix.join("reports", report2.file));
14498
+ if (!read.ok) {
13976
14499
  throw new ResourceNotFoundError(
13977
14500
  uri,
13978
- "This snapshot contains no " + report2.file + ": that report was disabled, or nothing has been generated yet. Run snapshot_generate first."
14501
+ "This snapshot contains no readable " + report2.file + ": that report was disabled, nothing has been generated yet, or the file is not a regular file inside the snapshot. Run snapshot_generate first."
13979
14502
  );
13980
14503
  }
13981
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text, REPORT_ADVICE) };
14504
+ return {
14505
+ uri,
14506
+ mimeType: "text/markdown",
14507
+ text: ensureSingleRead(uri, read.text, REPORT_ADVICE)
14508
+ };
13982
14509
  }
13983
14510
  if (uri === "snapshot://manifest") {
13984
14511
  const read = readManifest3(workspace);
13985
14512
  if (!read.ok) return null;
13986
- const text = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
13987
- return { uri, mimeType: "application/json", text: ensureSingleRead(uri, text, MANIFEST_ADVICE) };
14513
+ const confined = readConfinedText(path6__namespace.dirname(read.file), path6__namespace.basename(read.file));
14514
+ if (!confined.ok) return null;
14515
+ return {
14516
+ uri,
14517
+ mimeType: "application/json",
14518
+ text: ensureSingleRead(uri, confined.text, MANIFEST_ADVICE)
14519
+ };
13988
14520
  }
13989
14521
  const partMatch = PART_URI.exec(uri);
13990
14522
  if (partMatch) {
@@ -13997,7 +14529,7 @@ function buildResourceProvider() {
13997
14529
  if (partPath === null) return null;
13998
14530
  let partBytes;
13999
14531
  try {
14000
- partBytes = fs2__namespace.statSync(partPath).size;
14532
+ partBytes = fs3__namespace.statSync(partPath).size;
14001
14533
  } catch {
14002
14534
  return null;
14003
14535
  }
@@ -14033,52 +14565,52 @@ function validateArguments(schema, value) {
14033
14565
  }
14034
14566
  return problems;
14035
14567
  }
14036
- function checkValue(path16, schema, value) {
14568
+ function checkValue(path17, schema, value) {
14037
14569
  if (schema.enum && !schema.enum.includes(value)) {
14038
- return [`"${path16}" must be one of: ${schema.enum.join(", ")}`];
14570
+ return [`"${path17}" must be one of: ${schema.enum.join(", ")}`];
14039
14571
  }
14040
14572
  switch (schema.type) {
14041
14573
  case "string": {
14042
- if (typeof value !== "string") return [`"${path16}" must be a string`];
14574
+ if (typeof value !== "string") return [`"${path17}" must be a string`];
14043
14575
  const problems = [];
14044
14576
  if (schema.minLength !== void 0 && value.length < schema.minLength) {
14045
- problems.push(`"${path16}" must be at least ${schema.minLength} character(s)`);
14577
+ problems.push(`"${path17}" must be at least ${schema.minLength} character(s)`);
14046
14578
  }
14047
14579
  if (schema.maxLength !== void 0 && value.length > schema.maxLength) {
14048
- problems.push(`"${path16}" must be at most ${schema.maxLength} character(s)`);
14580
+ problems.push(`"${path17}" must be at most ${schema.maxLength} character(s)`);
14049
14581
  }
14050
14582
  return problems;
14051
14583
  }
14052
14584
  case "number":
14053
14585
  case "integer": {
14054
14586
  if (typeof value !== "number" || Number.isNaN(value)) {
14055
- return [`"${path16}" must be a number`];
14587
+ return [`"${path17}" must be a number`];
14056
14588
  }
14057
14589
  if (schema.type === "integer" && !Number.isInteger(value)) {
14058
- return [`"${path16}" must be an integer`];
14590
+ return [`"${path17}" must be an integer`];
14059
14591
  }
14060
14592
  const problems = [];
14061
14593
  if (schema.minimum !== void 0 && value < schema.minimum) {
14062
- problems.push(`"${path16}" must be >= ${schema.minimum}`);
14594
+ problems.push(`"${path17}" must be >= ${schema.minimum}`);
14063
14595
  }
14064
14596
  if (schema.maximum !== void 0 && value > schema.maximum) {
14065
- problems.push(`"${path16}" must be <= ${schema.maximum}`);
14597
+ problems.push(`"${path17}" must be <= ${schema.maximum}`);
14066
14598
  }
14067
14599
  return problems;
14068
14600
  }
14069
14601
  case "boolean":
14070
- return typeof value === "boolean" ? [] : [`"${path16}" must be a boolean`];
14602
+ return typeof value === "boolean" ? [] : [`"${path17}" must be a boolean`];
14071
14603
  case "array": {
14072
- if (!Array.isArray(value)) return [`"${path16}" must be an array`];
14604
+ if (!Array.isArray(value)) return [`"${path17}" must be an array`];
14073
14605
  if (!schema.items) return [];
14074
14606
  const problems = [];
14075
14607
  value.forEach((item, index) => {
14076
- problems.push(...checkValue(`${path16}[${index}]`, schema.items, item));
14608
+ problems.push(...checkValue(`${path17}[${index}]`, schema.items, item));
14077
14609
  });
14078
14610
  return problems;
14079
14611
  }
14080
14612
  case "object":
14081
- return isJsonObject(value) ? [] : [`"${path16}" must be an object`];
14613
+ return isJsonObject(value) ? [] : [`"${path17}" must be an object`];
14082
14614
  default:
14083
14615
  return [];
14084
14616
  }
@@ -14442,8 +14974,11 @@ var DEFAULT_PORT = 4789;
14442
14974
  var DEFAULT_MAX_BODY = 2 * 1024 * 1024;
14443
14975
  var RATE_LIMIT = 60;
14444
14976
  var RATE_WINDOW_MS = 1e4;
14977
+ var MAX_IN_FLIGHT = 4;
14978
+ var MAX_SESSION_ENTRIES = 64;
14979
+ var MAX_RATE_WINDOWS = 1024;
14445
14980
  function generateToken() {
14446
- return crypto2__namespace.randomBytes(24).toString("base64url");
14981
+ return crypto5__namespace.randomBytes(24).toString("base64url");
14447
14982
  }
14448
14983
  function isLoopbackOrigin(origin) {
14449
14984
  try {
@@ -14459,7 +14994,7 @@ function timingSafeEqual2(left, right) {
14459
14994
  const a = Buffer.from(left, "utf8");
14460
14995
  const b = Buffer.from(right, "utf8");
14461
14996
  if (a.length !== b.length) return false;
14462
- return crypto2__namespace.timingSafeEqual(a, b);
14997
+ return crypto5__namespace.timingSafeEqual(a, b);
14463
14998
  }
14464
14999
  async function startHttpTransport(options) {
14465
15000
  const host = options.host ?? "127.0.0.1";
@@ -14473,8 +15008,46 @@ async function startHttpTransport(options) {
14473
15008
  "Refusing to serve " + host + " without a token: a repository reachable from the network must require Authorization. Drop --no-auth, or bind the loopback address."
14474
15009
  );
14475
15010
  }
14476
- const server = createServer({ cwd: options.cwd, log });
15011
+ const createMcp = () => createServer({ cwd: options.cwd, log });
14477
15012
  const toolCount = buildTools().length;
15013
+ const mcpSessions = /* @__PURE__ */ new Map();
15014
+ const socketServers = /* @__PURE__ */ new WeakMap();
15015
+ const rememberSession = (id, server) => {
15016
+ if (!mcpSessions.has(id) && mcpSessions.size >= MAX_SESSION_ENTRIES) {
15017
+ const oldest = mcpSessions.keys().next().value;
15018
+ if (oldest !== void 0) mcpSessions.delete(oldest);
15019
+ }
15020
+ mcpSessions.set(id, server);
15021
+ };
15022
+ const anonymousServers = /* @__PURE__ */ new Map();
15023
+ const serverFor = (request) => {
15024
+ const header = request.headers["mcp-session-id"];
15025
+ const supplied = typeof header === "string" ? header.trim() : "";
15026
+ if (supplied !== "") {
15027
+ let existing = mcpSessions.get(supplied);
15028
+ if (existing === void 0) {
15029
+ existing = createMcp();
15030
+ rememberSession(supplied, existing);
15031
+ }
15032
+ return existing;
15033
+ }
15034
+ const onSocket = socketServers.get(request.socket);
15035
+ if (onSocket !== void 0) return onSocket;
15036
+ const userAgent = typeof request.headers["user-agent"] === "string" ? request.headers["user-agent"] : "";
15037
+ const fallbackKey = (request.socket.remoteAddress ?? "unknown") + "\0" + userAgent;
15038
+ let fallback = anonymousServers.get(fallbackKey);
15039
+ if (fallback === void 0) {
15040
+ fallback = createMcp();
15041
+ if (anonymousServers.size >= 64) {
15042
+ const oldest = anonymousServers.keys().next().value;
15043
+ if (oldest !== void 0) anonymousServers.delete(oldest);
15044
+ }
15045
+ anonymousServers.set(fallbackKey, fallback);
15046
+ }
15047
+ socketServers.set(request.socket, fallback);
15048
+ return fallback;
15049
+ };
15050
+ const newSessionId = () => crypto5__namespace.randomBytes(12).toString("hex");
14478
15051
  const sseSessions = /* @__PURE__ */ new Map();
14479
15052
  const tokenAccepted = (request, url) => {
14480
15053
  if (token === null) return true;
@@ -14485,6 +15058,35 @@ async function startHttpTransport(options) {
14485
15058
  return fromQuery !== null && timingSafeEqual2(fromQuery, token);
14486
15059
  };
14487
15060
  const sessions = /* @__PURE__ */ new Map();
15061
+ let inFlight = 0;
15062
+ const acquireToolSlot = () => {
15063
+ if (inFlight >= MAX_IN_FLIGHT) return false;
15064
+ inFlight += 1;
15065
+ return true;
15066
+ };
15067
+ const releaseToolSlot = () => {
15068
+ if (inFlight > 0) inFlight -= 1;
15069
+ };
15070
+ const busyResponse = (id) => ({
15071
+ jsonrpc: "2.0",
15072
+ id: typeof id === "string" || typeof id === "number" || id === null ? id : null,
15073
+ error: {
15074
+ code: -32001,
15075
+ message: "server busy: too many tool calls are already in flight"
15076
+ }
15077
+ });
15078
+ const isToolCall = (message) => message !== null && typeof message === "object" && message.method === "tools/call";
15079
+ const rememberRateWindow = (remote, now) => {
15080
+ if (!sessions.has(remote) && sessions.size >= MAX_RATE_WINDOWS) {
15081
+ for (const [key, value] of sessions) if (value.resetAt <= now) sessions.delete(key);
15082
+ while (sessions.size >= MAX_RATE_WINDOWS) {
15083
+ const oldest = sessions.keys().next().value;
15084
+ if (oldest === void 0) break;
15085
+ sessions.delete(oldest);
15086
+ }
15087
+ }
15088
+ sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
15089
+ };
14488
15090
  const metrics = {
14489
15091
  requests: 0,
14490
15092
  byMethod: /* @__PURE__ */ new Map(),
@@ -14495,6 +15097,18 @@ async function startHttpTransport(options) {
14495
15097
  const method = request.method ?? "UNKNOWN";
14496
15098
  metrics.byMethod.set(method, (metrics.byMethod.get(method) ?? 0) + 1);
14497
15099
  };
15100
+ const rateLimited = (request) => {
15101
+ const remote = request.socket.remoteAddress ?? "unknown";
15102
+ const now = Date.now();
15103
+ const window = sessions.get(remote);
15104
+ if (window === void 0 || window.resetAt <= now) {
15105
+ rememberRateWindow(remote, now);
15106
+ return false;
15107
+ }
15108
+ if (window.count >= RATE_LIMIT) return true;
15109
+ window.count += 1;
15110
+ return false;
15111
+ };
14498
15112
  const allowedOrigin = (origin) => {
14499
15113
  if (origin === void 0) return null;
14500
15114
  if (isLoopbackOrigin(origin)) return origin;
@@ -14502,7 +15116,10 @@ async function startHttpTransport(options) {
14502
15116
  };
14503
15117
  const httpServer = http__namespace.createServer((request, response) => {
14504
15118
  noteRequest(request);
15119
+ let responseSent = false;
14505
15120
  const send = (status, body, extra = {}) => {
15121
+ if (responseSent) return;
15122
+ responseSent = true;
14506
15123
  const text = typeof body === "string" ? body : JSON.stringify(body);
14507
15124
  if (status >= 400 && status < 500 && status !== 429) metrics.refused += 1;
14508
15125
  response.writeHead(status, {
@@ -14578,7 +15195,12 @@ async function startHttpTransport(options) {
14578
15195
  send(401, { error: "unauthorized" }, { ...cors, "www-authenticate": 'Bearer realm="codebase-snapshot"' });
14579
15196
  return;
14580
15197
  }
14581
- const id = crypto2__namespace.randomBytes(12).toString("hex");
15198
+ if (rateLimited(request)) {
15199
+ metrics.rateLimited += 1;
15200
+ send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
15201
+ return;
15202
+ }
15203
+ const id = crypto5__namespace.randomBytes(12).toString("hex");
14582
15204
  response.writeHead(200, {
14583
15205
  ...cors,
14584
15206
  "content-type": "text/event-stream",
@@ -14589,7 +15211,7 @@ async function startHttpTransport(options) {
14589
15211
  const write = (payload) => {
14590
15212
  response.write(payload);
14591
15213
  };
14592
- sseSessions.set(id, { write, end: () => response.end() });
15214
+ sseSessions.set(id, { write, end: () => response.end(), server: createMcp() });
14593
15215
  const heartbeat = setInterval(() => write(": ping\n\n"), 15e3);
14594
15216
  const cleanup = () => {
14595
15217
  clearInterval(heartbeat);
@@ -14605,6 +15227,11 @@ async function startHttpTransport(options) {
14605
15227
  send(401, { error: "unauthorized" }, { ...cors, "www-authenticate": 'Bearer realm="codebase-snapshot"' });
14606
15228
  return;
14607
15229
  }
15230
+ if (rateLimited(request)) {
15231
+ metrics.rateLimited += 1;
15232
+ send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
15233
+ return;
15234
+ }
14608
15235
  const id = url.searchParams.get("sessionId") ?? "";
14609
15236
  const stream = sseSessions.get(id);
14610
15237
  if (stream === void 0) {
@@ -14613,9 +15240,12 @@ async function startHttpTransport(options) {
14613
15240
  }
14614
15241
  const chunks2 = [];
14615
15242
  let received2 = 0;
15243
+ let tooLarge2 = false;
14616
15244
  request.on("data", (chunk) => {
15245
+ if (tooLarge2) return;
14617
15246
  received2 += chunk.length;
14618
15247
  if (received2 > maxBody) {
15248
+ tooLarge2 = true;
14619
15249
  request.destroy();
14620
15250
  send(413, { error: "request body too large", limit: maxBody });
14621
15251
  return;
@@ -14623,6 +15253,7 @@ async function startHttpTransport(options) {
14623
15253
  chunks2.push(chunk);
14624
15254
  });
14625
15255
  request.on("end", () => {
15256
+ if (tooLarge2) return;
14626
15257
  void (async () => {
14627
15258
  let message;
14628
15259
  try {
@@ -14631,8 +15262,19 @@ async function startHttpTransport(options) {
14631
15262
  send(400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: String(error) } });
14632
15263
  return;
14633
15264
  }
14634
- const answer = await server.handle(message);
14635
- if (answer !== null) stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
15265
+ const gated = isToolCall(message);
15266
+ if (gated && !acquireToolSlot()) {
15267
+ const answer = busyResponse(message.id);
15268
+ stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
15269
+ send(202, "", cors);
15270
+ return;
15271
+ }
15272
+ try {
15273
+ const answer = await stream.server.handle(message);
15274
+ if (answer !== null) stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
15275
+ } finally {
15276
+ if (gated) releaseToolSlot();
15277
+ }
14636
15278
  send(202, "", cors);
14637
15279
  })();
14638
15280
  });
@@ -14658,20 +15300,22 @@ async function startHttpTransport(options) {
14658
15300
  return;
14659
15301
  }
14660
15302
  }
14661
- const remote = request.socket.remoteAddress ?? "unknown";
14662
- const now = Date.now();
14663
- const window = sessions.get(remote);
14664
- if (window === void 0 || window.resetAt <= now) sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
14665
- else if (window.count >= RATE_LIMIT) {
15303
+ if (rateLimited(request)) {
14666
15304
  metrics.rateLimited += 1;
14667
15305
  send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
14668
15306
  return;
14669
- } else window.count += 1;
15307
+ }
15308
+ const activeServer = serverFor(request);
15309
+ const sessionHeader = request.headers["mcp-session-id"];
15310
+ let sessionId = typeof sessionHeader === "string" ? sessionHeader.trim() : "";
14670
15311
  let received = 0;
15312
+ let tooLarge = false;
14671
15313
  const chunks = [];
14672
15314
  request.on("data", (chunk) => {
15315
+ if (tooLarge) return;
14673
15316
  received += chunk.length;
14674
15317
  if (received > maxBody) {
15318
+ tooLarge = true;
14675
15319
  request.destroy();
14676
15320
  send(413, { error: "request body too large", limit: maxBody }, cors);
14677
15321
  return;
@@ -14679,6 +15323,7 @@ async function startHttpTransport(options) {
14679
15323
  chunks.push(chunk);
14680
15324
  });
14681
15325
  request.on("end", () => {
15326
+ if (tooLarge) return;
14682
15327
  void (async () => {
14683
15328
  let message;
14684
15329
  try {
@@ -14687,17 +15332,35 @@ async function startHttpTransport(options) {
14687
15332
  send(400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error: " + error.message } }, cors);
14688
15333
  return;
14689
15334
  }
14690
- const answers = [];
14691
15335
  const batch = Array.isArray(message) ? message : [message];
15336
+ if (batch.length > 100) {
15337
+ send(400, { error: "JSON-RPC batch is limited to 100 messages" }, cors);
15338
+ return;
15339
+ }
15340
+ if (sessionId === "" && !Array.isArray(message) && message.method === "initialize") {
15341
+ sessionId = newSessionId();
15342
+ rememberSession(sessionId, activeServer);
15343
+ }
15344
+ const sessionHeaders = sessionId === "" ? cors : { ...cors, "mcp-session-id": sessionId };
15345
+ const answers = [];
14692
15346
  for (const item of batch) {
14693
- const answer = await server.handle(item);
14694
- if (answer !== null) answers.push(answer);
15347
+ const gated = isToolCall(item);
15348
+ if (gated && !acquireToolSlot()) {
15349
+ answers.push(busyResponse(item.id));
15350
+ continue;
15351
+ }
15352
+ try {
15353
+ const answer = await activeServer.handle(item);
15354
+ if (answer !== null) answers.push(answer);
15355
+ } finally {
15356
+ if (gated) releaseToolSlot();
15357
+ }
14695
15358
  }
14696
15359
  if (answers.length === 0) {
14697
- send(202, "", cors);
15360
+ send(202, "", sessionHeaders);
14698
15361
  return;
14699
15362
  }
14700
- send(200, Array.isArray(message) ? answers : answers[0], cors);
15363
+ send(200, Array.isArray(message) ? answers : answers[0], sessionHeaders);
14701
15364
  })().catch((error) => {
14702
15365
  log("mcp/http: " + error.message);
14703
15366
  send(500, { jsonrpc: "2.0", id: null, error: { code: -32603, message: "Internal error" } }, cors);
@@ -14710,11 +15373,11 @@ async function startHttpTransport(options) {
14710
15373
  }
14711
15374
  });
14712
15375
  });
14713
- await new Promise((resolve10, reject) => {
15376
+ await new Promise((resolve11, reject) => {
14714
15377
  httpServer.once("error", reject);
14715
15378
  httpServer.listen(port, host, () => {
14716
15379
  httpServer.removeListener("error", reject);
14717
- resolve10();
15380
+ resolve11();
14718
15381
  });
14719
15382
  });
14720
15383
  const address = httpServer.address();
@@ -14725,7 +15388,7 @@ async function startHttpTransport(options) {
14725
15388
  port: actualPort,
14726
15389
  host,
14727
15390
  token,
14728
- close: () => new Promise((resolve10) => {
15391
+ close: () => new Promise((resolve11) => {
14729
15392
  for (const [, session] of sseSessions) {
14730
15393
  try {
14731
15394
  session.end();
@@ -14733,7 +15396,7 @@ async function startHttpTransport(options) {
14733
15396
  }
14734
15397
  }
14735
15398
  sseSessions.clear();
14736
- httpServer.close(() => resolve10());
15399
+ httpServer.close(() => resolve11());
14737
15400
  httpServer.closeAllConnections();
14738
15401
  })
14739
15402
  };