codebase-snapshot 0.20.4 → 0.20.6

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,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var fs8 = require('fs');
3
+ var fs3 = require('fs');
4
4
  var path6 = require('path');
5
5
  var crypto5 = require('crypto');
6
6
  var module$1 = require('module');
@@ -32,7 +32,7 @@ function _interopNamespace(e) {
32
32
  return Object.freeze(n);
33
33
  }
34
34
 
35
- var fs8__namespace = /*#__PURE__*/_interopNamespace(fs8);
35
+ var fs3__namespace = /*#__PURE__*/_interopNamespace(fs3);
36
36
  var path6__namespace = /*#__PURE__*/_interopNamespace(path6);
37
37
  var crypto5__namespace = /*#__PURE__*/_interopNamespace(crypto5);
38
38
  var childProcess__namespace = /*#__PURE__*/_interopNamespace(childProcess);
@@ -422,9 +422,9 @@ var SKIPPED_WALK_DIRS = /* @__PURE__ */ new Set([
422
422
  ]);
423
423
  function readSmallFile(fullPath) {
424
424
  try {
425
- const stats = fs8__namespace.statSync(fullPath);
425
+ const stats = fs3__namespace.statSync(fullPath);
426
426
  if (!stats.isFile() || stats.size > MANIFEST_MAX_BYTES) return null;
427
- return fs8__namespace.readFileSync(fullPath, "utf8");
427
+ return fs3__namespace.readFileSync(fullPath, "utf8");
428
428
  } catch {
429
429
  return null;
430
430
  }
@@ -435,7 +435,7 @@ function readManifest(cwd, name) {
435
435
  function dependenciesFromPackageJson(raw) {
436
436
  const names = /* @__PURE__ */ new Set();
437
437
  try {
438
- const parsed = JSON.parse(raw);
438
+ const parsed = JSON.parse(stripJsonComments(raw.replace(/^\uFEFF/, "")));
439
439
  for (const section of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
440
440
  const block = parsed[section];
441
441
  if (block && typeof block === "object") {
@@ -490,7 +490,7 @@ function pnpmWorkspacePatterns(raw) {
490
490
  function childDirectories(cwd, parent) {
491
491
  let entries;
492
492
  try {
493
- entries = fs8__namespace.readdirSync(path6__namespace.join(cwd, parent), { withFileTypes: true });
493
+ entries = fs3__namespace.readdirSync(path6__namespace.join(cwd, parent), { withFileTypes: true });
494
494
  } catch {
495
495
  return [];
496
496
  }
@@ -525,10 +525,10 @@ function workspacePackageDirs(cwd, patterns) {
525
525
  function scanWorkspacePackages(cwd, patterns) {
526
526
  const files = /* @__PURE__ */ new Set();
527
527
  const dependencies = /* @__PURE__ */ new Set();
528
- for (const relative9 of workspacePackageDirs(cwd, patterns)) {
529
- const full = path6__namespace.join(cwd, relative9);
528
+ for (const relative10 of workspacePackageDirs(cwd, patterns)) {
529
+ const full = path6__namespace.join(cwd, relative10);
530
530
  try {
531
- for (const entry of fs8__namespace.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
531
+ for (const entry of fs3__namespace.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
532
532
  } catch {
533
533
  }
534
534
  const raw = readSmallFile(path6__namespace.join(full, "package.json"));
@@ -541,7 +541,7 @@ function scanWorkspacePackages(cwd, patterns) {
541
541
  var SNAPSHOT_MARKER = ".codebase-snapshot";
542
542
  function isToolOwnedDirectory(dir) {
543
543
  try {
544
- return fs8__namespace.statSync(dir).isDirectory() && fs8__namespace.existsSync(path6__namespace.join(dir, SNAPSHOT_MARKER));
544
+ return fs3__namespace.statSync(dir).isDirectory() && fs3__namespace.existsSync(path6__namespace.join(dir, SNAPSHOT_MARKER));
545
545
  } catch {
546
546
  return false;
547
547
  }
@@ -556,7 +556,7 @@ function countMarkdownFiles(cwd) {
556
556
  directoriesSeen += 1;
557
557
  let entries;
558
558
  try {
559
- entries = fs8__namespace.readdirSync(current.dir, { withFileTypes: true });
559
+ entries = fs3__namespace.readdirSync(current.dir, { withFileTypes: true });
560
560
  } catch {
561
561
  continue;
562
562
  }
@@ -578,7 +578,7 @@ function buildPresetContext(cwd) {
578
578
  const files = /* @__PURE__ */ new Set();
579
579
  const dirs = /* @__PURE__ */ new Set();
580
580
  try {
581
- for (const entry of fs8__namespace.readdirSync(cwd, { withFileTypes: true })) {
581
+ for (const entry of fs3__namespace.readdirSync(cwd, { withFileTypes: true })) {
582
582
  if (entry.isDirectory()) dirs.add(entry.name);
583
583
  else if (entry.isFile()) files.add(entry.name);
584
584
  }
@@ -1740,7 +1740,7 @@ var DEFAULT_SECRET_PATTERNS = [
1740
1740
  // rendering of textual userinfo mixes cases, while the prose the earlier rules were
1741
1741
  // protecting (`Bearer authentication`) is a lowercase word.
1742
1742
  rule: "authorization-header",
1743
- 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_.+/=-])/
1744
1744
  },
1745
1745
  {
1746
1746
  // Broader names than before (`apiKey`, `clientSecret`, `privateKey` were
@@ -2318,6 +2318,7 @@ function redactStructuredValues(text, filePath, recordFinding) {
2318
2318
  if (firstValue === void 0) continue;
2319
2319
  const valueIndent = (/^[ \t]*/.exec(firstValue)?.[0] ?? "").length;
2320
2320
  if (valueIndent <= baseIndent) continue;
2321
+ if (STRUCTURED_KEY.test(firstValue) || /^[ \t]*-[ \t]/.test(firstValue)) continue;
2321
2322
  let masked = false;
2322
2323
  while (cursor < segments.length) {
2323
2324
  const body = segments[cursor] ?? "";
@@ -2333,7 +2334,7 @@ function redactStructuredValues(text, filePath, recordFinding) {
2333
2334
  }
2334
2335
  return segments.join("");
2335
2336
  }
2336
- var DOCKERFILE_ENV = /^([ \t]*ENV[ \t]+)([A-Za-z_][A-Za-z0-9_]*)([ \t]+)(\S.*)$/;
2337
+ var DOCKERFILE_ENV = /^([ \t]*)(ENV|ARG)([ \t]+)([A-Za-z_][A-Za-z0-9_]*)([ \t]*=[ \t]*|[ \t]+)(\S.*)$/i;
2337
2338
  function redactDockerfileEnv(text, filePath, recordFinding) {
2338
2339
  if (!isDockerfile(filePath)) return text;
2339
2340
  const segments = text.split(LINE_BREAK);
@@ -2342,10 +2343,9 @@ function redactDockerfileEnv(text, filePath, recordFinding) {
2342
2343
  if (line === void 0) continue;
2343
2344
  const match = DOCKERFILE_ENV.exec(line);
2344
2345
  if (match === null) continue;
2345
- if (!CREDENTIAL_KEY_TAIL.test(match[2] ?? "")) continue;
2346
- const value = match[4] ?? "";
2347
- if (value.startsWith("=")) continue;
2348
- segments[index] = `${match[1]}${match[2]}${match[3]}${REDACTION_MARKER}`;
2346
+ if (!CREDENTIAL_KEY_TAIL.test(match[4] ?? "")) continue;
2347
+ const separator = match[5] ?? "";
2348
+ segments[index] = `${match[1]}${match[2]}${match[3]}${match[4]}${separator}${REDACTION_MARKER}`;
2349
2349
  recordFinding(index / 2 + 1, ["dockerfile-env-secret"]);
2350
2350
  }
2351
2351
  return segments.join("");
@@ -2430,6 +2430,7 @@ function isSourceCodeFile(filePath) {
2430
2430
  var PLACEHOLDER_PATTERNS = [
2431
2431
  /^<[^>]*>?$/,
2432
2432
  /^\.{3,}$/,
2433
+ /^(?:[A-Za-z0-9_-]{1,8}-)?\.{3,}$/,
2433
2434
  /^(?:x{4,}|X{4,}|\*{3,})$/,
2434
2435
  /^(?:replace|change)[-_ ]?me(?:[-_ ].*)?$/i,
2435
2436
  /^your[-_ ].*$/i,
@@ -2443,7 +2444,7 @@ function isPlaceholderValue(value) {
2443
2444
  if (trimmed.length === 0) return false;
2444
2445
  if (PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(trimmed))) return true;
2445
2446
  if (trimmed.includes(REDACTION_MARKER) || trimmed.includes(PEM_REDACTION_MARKER)) return true;
2446
- return trimmed.includes("...") || /^<[^>]*$/.test(trimmed);
2447
+ return false;
2447
2448
  }
2448
2449
  function quotesAreBalanced(text) {
2449
2450
  let single = 0;
@@ -2495,6 +2496,7 @@ var ASSIGNMENT_FILE = /\.(?:sh|bash|zsh|ksh|fish|env|ya?ml|toml|ini|conf|cfg|pro
2495
2496
  var ASSIGNMENT_BASENAME = /^(?:\.env(?:\.[^/]*)?|\.envrc|\.profile|\.bashrc|\.zshrc|\.bash_profile)$/i;
2496
2497
  function isAssignmentFile(filePath) {
2497
2498
  if (filePath === void 0) return false;
2499
+ if (isDockerfile(filePath)) return true;
2498
2500
  const normalised = filePath.replace(/\\/g, "/");
2499
2501
  if (ASSIGNMENT_FILE.test(normalised)) return true;
2500
2502
  const base = normalised.slice(normalised.lastIndexOf("/") + 1);
@@ -2558,10 +2560,10 @@ var SIGNATURE_FILE = "signature.json";
2558
2560
  function verifySnapshotSignature(snapshotDir) {
2559
2561
  const signaturePath = path6__namespace.join(snapshotDir, SIGNATURE_FILE);
2560
2562
  const manifestPath = path6__namespace.join(snapshotDir, "manifest.json");
2561
- if (!fs8__namespace.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
2563
+ if (!fs3__namespace.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
2562
2564
  let record;
2563
2565
  try {
2564
- record = JSON.parse(fs8__namespace.readFileSync(signaturePath, "utf8"));
2566
+ record = JSON.parse(fs3__namespace.readFileSync(signaturePath, "utf8"));
2565
2567
  } catch (error) {
2566
2568
  return { ok: false, reason: "signature.json is not JSON: " + error.message };
2567
2569
  }
@@ -2570,7 +2572,7 @@ function verifySnapshotSignature(snapshotDir) {
2570
2572
  }
2571
2573
  let bytes;
2572
2574
  try {
2573
- bytes = fs8__namespace.readFileSync(manifestPath);
2575
+ bytes = fs3__namespace.readFileSync(manifestPath);
2574
2576
  } catch {
2575
2577
  return { ok: false, reason: "the signed manifest is missing" };
2576
2578
  }
@@ -2578,6 +2580,15 @@ function verifySnapshotSignature(snapshotDir) {
2578
2580
  if (sha2562 !== record.manifestSha256) {
2579
2581
  return { ok: false, reason: "manifest.json changed after it was signed" };
2580
2582
  }
2583
+ let signedFingerprint;
2584
+ try {
2585
+ signedFingerprint = JSON.parse(bytes.toString("utf8")).fingerprint;
2586
+ } catch {
2587
+ return { ok: false, reason: "the signed manifest is not JSON" };
2588
+ }
2589
+ if (typeof record.fingerprint !== "string" || record.fingerprint !== signedFingerprint) {
2590
+ return { ok: false, reason: "signature.json names a different fingerprint than the manifest" };
2591
+ }
2581
2592
  let verified = false;
2582
2593
  try {
2583
2594
  const key = crypto5__namespace.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
@@ -2590,7 +2601,7 @@ function verifySnapshotSignature(snapshotDir) {
2590
2601
 
2591
2602
  // src/version.ts
2592
2603
  var GENERATOR_NAME = "codebase-snapshot";
2593
- var GENERATOR_VERSION = "0.20.4";
2604
+ var GENERATOR_VERSION = "0.20.6";
2594
2605
  var SCHEMA_VERSION = "3.0.0";
2595
2606
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2596
2607
  function isOurGeneratorName(name) {
@@ -2607,7 +2618,7 @@ var PRESET_IGNORES = new Set(
2607
2618
  );
2608
2619
  function readLinkTarget(linkPath, fallback) {
2609
2620
  try {
2610
- return fs8__namespace.readlinkSync(linkPath);
2621
+ return fs3__namespace.readlinkSync(linkPath);
2611
2622
  } catch {
2612
2623
  return fallback;
2613
2624
  }
@@ -2622,8 +2633,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
2622
2633
  };
2623
2634
  }
2624
2635
  function isInside(root, candidate) {
2625
- const relative9 = path6__namespace.relative(root, candidate);
2626
- return relative9 === "" || !relative9.startsWith(`..${path6__namespace.sep}`) && relative9 !== ".." && !path6__namespace.isAbsolute(relative9);
2636
+ const relative10 = path6__namespace.relative(root, candidate);
2637
+ return relative10 === "" || !relative10.startsWith(`..${path6__namespace.sep}`) && relative10 !== ".." && !path6__namespace.isAbsolute(relative10);
2627
2638
  }
2628
2639
  var GIT_OUTPUT_LIMIT = 68157440;
2629
2640
  function getGitInfo(cwd, fallbackBranch = "main") {
@@ -2689,7 +2700,7 @@ var DEFAULT_IGNORED_FILES = [
2689
2700
  var SENSITIVE_BASENAME = /^(?:\.env(?:[._-][A-Za-z0-9_-]*)*|\.env(?:backup|bak|old|orig|copy|save)|\.envrc|\.npmrc(?:\.[A-Za-z0-9_-]+)?|\.yarnrc(?:\.yml)?|\.netrc(?:\.[A-Za-z0-9_-]+)?|\.git-credentials|\.htpasswd|\.pgpass|\.pypirc|\.vault-token|vault[-_]agent[-_]token|\.composer-auth\.json|auth\.json|application_default_credentials\.json|id_[a-z0-9_]+(?:\.[A-Za-z0-9_-]+)?|credentials(?:\.(?:json|ya?ml|toml))?|service[-_]?account(?:\.[a-z0-9_-]+)*\.json|secrets?\.(?:json|ya?ml|toml)|env|[A-Za-z0-9_-]{1,64}\.env)$/i;
2690
2701
  var SENSITIVE_PATH = /(?:^|\/)\.(?:aws|ssh|gnupg)\/|(?:^|\/)\.docker\/config\.json$|(?:^|\/)\.kube\/config$|(?:^|\/)\.config\/gcloud\/|(?:^|\/)\.composer\/|(?:^|\/)\.terraform\/credentials\.tfrc\.json$/i;
2691
2702
  var SENSITIVE_EXT = /\.(?:pem|key|p12|pfx|jks|keystore|ppk|asc|kdbx|tfstate|tfvars)$/i;
2692
- var TEMPLATE_SUFFIX = /^(.*)\.(?:example|sample|template|dist)(\.[A-Za-z0-9_-]+)?$/i;
2703
+ var TEMPLATE_SUFFIX = /^(.*)\.(?:example|sample|template|dist)(\.(?:json|ya?ml|toml|ini|txt|md|properties|conf|cfg))?$/i;
2693
2704
  var BACKUP_SUFFIX = /(?:~|\.(?:bak|backup|old|orig|save|copy|swp|swo|tmp|part))$/i;
2694
2705
  function normaliseName(name) {
2695
2706
  let normalised = name.trim().replace(/[. ]+$/, "");
@@ -2886,7 +2897,7 @@ function readGitignoreRules(dir) {
2886
2897
  const gitignorePath = path6__namespace.join(dir, ".gitignore");
2887
2898
  let raw;
2888
2899
  try {
2889
- raw = fs8__namespace.readFileSync(gitignorePath, "utf8");
2900
+ raw = fs3__namespace.readFileSync(gitignorePath, "utf8");
2890
2901
  } catch {
2891
2902
  return [];
2892
2903
  }
@@ -3059,7 +3070,7 @@ function listIgnoredPaths(cwd) {
3059
3070
  }
3060
3071
  function hasSnapshotMarker(target) {
3061
3072
  try {
3062
- return fs8__namespace.statSync(target).isDirectory() && isToolOwnedDirectory2(target);
3073
+ return fs3__namespace.statSync(target).isDirectory() && isToolOwnedDirectory2(target);
3063
3074
  } catch {
3064
3075
  return false;
3065
3076
  }
@@ -3068,7 +3079,7 @@ var IGNORABLE_DIRECTORY_ENTRIES = /* @__PURE__ */ new Set([".DS_Store"]);
3068
3079
  function isToolOwnedDirectory2(dir) {
3069
3080
  let raw;
3070
3081
  try {
3071
- raw = fs8__namespace.readFileSync(path6__namespace.join(dir, ".codebase-snapshot"), "utf8");
3082
+ raw = fs3__namespace.readFileSync(path6__namespace.join(dir, ".codebase-snapshot"), "utf8");
3072
3083
  } catch {
3073
3084
  return false;
3074
3085
  }
@@ -3080,30 +3091,67 @@ function isToolOwnedDirectory2(dir) {
3080
3091
  }
3081
3092
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
3082
3093
  const marker = parsed;
3083
- if (marker.generator !== GENERATOR_NAME || marker.state !== "complete" || typeof marker.id !== "string" || !Array.isArray(marker.files)) {
3094
+ if (marker.generator !== GENERATOR_NAME || marker.state !== "complete" || marker.schemaVersion !== SCHEMA_VERSION || typeof marker.id !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(marker.id) || typeof marker.manifestSha256 !== "string" || !Array.isArray(marker.files)) {
3095
+ return false;
3096
+ }
3097
+ let manifestBytes;
3098
+ try {
3099
+ manifestBytes = fs3__namespace.readFileSync(path6__namespace.join(dir, "manifest.json"));
3100
+ } catch {
3101
+ return false;
3102
+ }
3103
+ if (crypto5.createHash("sha256").update(manifestBytes).digest("hex") !== marker.manifestSha256) {
3084
3104
  return false;
3085
3105
  }
3086
- const accounted = /* @__PURE__ */ new Set();
3106
+ const recordedFiles = /* @__PURE__ */ new Set();
3087
3107
  for (const item of marker.files) {
3088
3108
  if (!item || typeof item !== "object" || Array.isArray(item)) return false;
3089
- const entry = item.path;
3090
- if (typeof entry !== "string" || entry.length === 0) return false;
3091
- const parts = entry.split("/");
3092
- for (let depth = 1; depth <= parts.length; depth += 1) {
3093
- accounted.add(parts.slice(0, depth).join("/"));
3109
+ const record = item;
3110
+ const entry = record.path;
3111
+ if (typeof entry !== "string" || entry.length === 0 || entry.includes(String.fromCharCode(92)) || entry.includes("\0") || path6__namespace.isAbsolute(entry) || entry.split("/").includes("..") || typeof record.bytes !== "number" || !Number.isSafeInteger(record.bytes) || record.bytes < 0 || typeof record.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(record.sha256)) {
3112
+ return false;
3113
+ }
3114
+ const full = path6__namespace.join(dir, ...entry.split("/"));
3115
+ let stats;
3116
+ try {
3117
+ stats = fs3__namespace.lstatSync(full);
3118
+ } catch {
3119
+ return false;
3120
+ }
3121
+ if (!stats.isFile() || stats.size !== record.bytes) return false;
3122
+ let digest;
3123
+ try {
3124
+ digest = crypto5.createHash("sha256").update(fs3__namespace.readFileSync(full)).digest("hex");
3125
+ } catch {
3126
+ return false;
3094
3127
  }
3128
+ if (digest !== record.sha256) return false;
3129
+ recordedFiles.add(entry);
3095
3130
  }
3096
- let entries;
3097
- try {
3098
- entries = fs8__namespace.readdirSync(dir);
3099
- } catch {
3100
- return false;
3131
+ const stack = [""];
3132
+ while (stack.length > 0) {
3133
+ const current = stack.pop();
3134
+ let entries;
3135
+ try {
3136
+ entries = fs3__namespace.readdirSync(path6__namespace.join(dir, current), { withFileTypes: true });
3137
+ } catch {
3138
+ return false;
3139
+ }
3140
+ for (const entry of entries) {
3141
+ const relative10 = current === "" ? entry.name : current + "/" + entry.name;
3142
+ if (relative10 === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry.name)) continue;
3143
+ if (entry.isDirectory()) {
3144
+ stack.push(relative10);
3145
+ continue;
3146
+ }
3147
+ if (!entry.isFile()) return false;
3148
+ if (relative10 === "signature.json" && !recordedFiles.has(relative10) && verifySnapshotSignature(dir).ok) {
3149
+ continue;
3150
+ }
3151
+ if (!recordedFiles.has(relative10)) return false;
3152
+ }
3101
3153
  }
3102
- return entries.every(
3103
- (entry) => entry === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry) || // A snapshot signed before signing moved into staging has a valid signature.json the old
3104
- // marker could not record. It is our artifact when the signature verifies.
3105
- entry === "signature.json" && verifySnapshotSignature(dir).ok || accounted.has(entry)
3106
- );
3154
+ return true;
3107
3155
  }
3108
3156
  function makeToolOwnedDecider(cwd, toolOwnedPaths) {
3109
3157
  const markers = /* @__PURE__ */ new Map();
@@ -3129,7 +3177,7 @@ function makeLinkProbe() {
3129
3177
  let known = cache.get(absolutePath);
3130
3178
  if (known === void 0) {
3131
3179
  try {
3132
- known = fs8__namespace.lstatSync(absolutePath).isSymbolicLink();
3180
+ known = fs3__namespace.lstatSync(absolutePath).isSymbolicLink();
3133
3181
  } catch {
3134
3182
  known = false;
3135
3183
  }
@@ -3142,7 +3190,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
3142
3190
  const isLink = makeLinkProbe();
3143
3191
  let rootReal = cwd;
3144
3192
  try {
3145
- rootReal = fs8__namespace.realpathSync(cwd);
3193
+ rootReal = fs3__namespace.realpathSync(cwd);
3146
3194
  } catch {
3147
3195
  }
3148
3196
  const reported = /* @__PURE__ */ new Set();
@@ -3170,7 +3218,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
3170
3218
  const rawTarget = readLinkTarget(absolute, absolute);
3171
3219
  let targetReal = null;
3172
3220
  try {
3173
- targetReal = fs8__namespace.realpathSync(absolute);
3221
+ targetReal = fs3__namespace.realpathSync(absolute);
3174
3222
  } catch {
3175
3223
  targetReal = null;
3176
3224
  }
@@ -3188,7 +3236,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
3188
3236
  }
3189
3237
  let stats = null;
3190
3238
  try {
3191
- stats = fs8__namespace.statSync(absolute);
3239
+ stats = fs3__namespace.statSync(absolute);
3192
3240
  } catch {
3193
3241
  stats = null;
3194
3242
  }
@@ -3285,7 +3333,7 @@ function collectFiles(cwd, options = {}) {
3285
3333
  "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."
3286
3334
  );
3287
3335
  }
3288
- if (fs8__namespace.existsSync(path6__namespace.join(cwd, ".git"))) {
3336
+ if (fs3__namespace.existsSync(path6__namespace.join(cwd, ".git"))) {
3289
3337
  throw new Error(
3290
3338
  "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."
3291
3339
  );
@@ -3304,7 +3352,7 @@ function collectFiles(cwd, options = {}) {
3304
3352
  candidates.push(extra);
3305
3353
  }
3306
3354
  }
3307
- const files = candidates.filter((file) => {
3355
+ let files = candidates.filter((file) => {
3308
3356
  if (isToolOwned(file)) return false;
3309
3357
  const ignored = defaultIgnoreReason(file, toolDirNames);
3310
3358
  if (ignored) {
@@ -3349,11 +3397,54 @@ function collectFiles(cwd, options = {}) {
3349
3397
  }
3350
3398
  return true;
3351
3399
  }).sort();
3400
+ files = dropSymlinksToUnincludedTargets(cwd, files, skipped);
3352
3401
  return { files, skipped: maskSkipPaths(skipped, pathRules) };
3353
3402
  }
3403
+ function dropSymlinksToUnincludedTargets(cwd, files, skipped) {
3404
+ const aliases = /* @__PURE__ */ new Set();
3405
+ for (const file of files) {
3406
+ try {
3407
+ if (fs3__namespace.lstatSync(path6__namespace.join(cwd, file)).isSymbolicLink()) aliases.add(file);
3408
+ } catch {
3409
+ }
3410
+ }
3411
+ if (aliases.size === 0) return [...files];
3412
+ const includedTargets = /* @__PURE__ */ new Set();
3413
+ for (const file of files) {
3414
+ if (aliases.has(file)) continue;
3415
+ try {
3416
+ includedTargets.add(fs3__namespace.realpathSync(path6__namespace.join(cwd, file)));
3417
+ } catch {
3418
+ }
3419
+ }
3420
+ const kept = [];
3421
+ for (const file of files) {
3422
+ if (!aliases.has(file)) {
3423
+ kept.push(file);
3424
+ continue;
3425
+ }
3426
+ let target;
3427
+ try {
3428
+ target = fs3__namespace.realpathSync(path6__namespace.join(cwd, file));
3429
+ } catch {
3430
+ skipped.push({ path: file, reason: "read-error", detail: "symlink target could not be resolved" });
3431
+ continue;
3432
+ }
3433
+ if (includedTargets.has(target)) {
3434
+ kept.push(file);
3435
+ continue;
3436
+ }
3437
+ skipped.push({
3438
+ path: file,
3439
+ reason: "symlink",
3440
+ detail: "link target was excluded from the snapshot; not followed"
3441
+ });
3442
+ }
3443
+ return kept;
3444
+ }
3354
3445
  function rootRealFor(root) {
3355
3446
  try {
3356
- return fs8__namespace.realpathSync(root);
3447
+ return fs3__namespace.realpathSync(root);
3357
3448
  } catch {
3358
3449
  return root;
3359
3450
  }
@@ -3373,7 +3464,7 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
3373
3464
  ];
3374
3465
  let entries;
3375
3466
  try {
3376
- entries = fs8__namespace.readdirSync(current, { withFileTypes: true });
3467
+ entries = fs3__namespace.readdirSync(current, { withFileTypes: true });
3377
3468
  } catch {
3378
3469
  results.skipped.push({
3379
3470
  path: relativeToBase(current),
@@ -3429,14 +3520,14 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
3429
3520
  if (entry.isSymbolicLink()) {
3430
3521
  let targetReal;
3431
3522
  try {
3432
- targetReal = fs8__namespace.realpathSync(fullPath);
3523
+ targetReal = fs3__namespace.realpathSync(fullPath);
3433
3524
  } catch {
3434
3525
  results.skipped.push(brokenLinkRecord(fullPath, relPath, rootReal));
3435
3526
  continue;
3436
3527
  }
3437
3528
  let stats;
3438
3529
  try {
3439
- stats = fs8__namespace.statSync(fullPath);
3530
+ stats = fs3__namespace.statSync(fullPath);
3440
3531
  } catch {
3441
3532
  results.skipped.push({ path: relPath, reason: "read-error", detail: "unreadable symlink" });
3442
3533
  continue;
@@ -3569,8 +3660,25 @@ function normalizeResolvedConfig(config) {
3569
3660
  monolithWanted,
3570
3661
  monolithWanted
3571
3662
  );
3663
+ if (!Number.isSafeInteger(config.maxPartBytes) || config.maxPartBytes < MIN_MAX_PART_BYTES) {
3664
+ throw new Error(
3665
+ `maxPartBytes must be at least ${MIN_MAX_PART_BYTES} bytes (received ${String(config.maxPartBytes)}).`
3666
+ );
3667
+ }
3668
+ if (!Number.isSafeInteger(config.largeFileBytes) || config.largeFileBytes < 0) {
3669
+ throw new Error(
3670
+ `largeFileBytes must be a non-negative integer; received ${String(config.largeFileBytes)}.`
3671
+ );
3672
+ }
3673
+ const maxPartTokens = config.maxPartTokens ?? Math.floor(config.maxPartBytes / 4);
3674
+ if (!Number.isSafeInteger(maxPartTokens) || maxPartTokens < MIN_MAX_PART_TOKENS) {
3675
+ throw new Error(
3676
+ `maxPartTokens must be at least ${MIN_MAX_PART_TOKENS} tokens; received ${String(maxPartTokens)}.`
3677
+ );
3678
+ }
3572
3679
  return markResolvedConfig({
3573
3680
  ...config,
3681
+ maxPartTokens,
3574
3682
  discovery,
3575
3683
  // A spread copy built before the field existed carries no value; the default applies, and it
3576
3684
  // is re-validated because the number reaches a rendered artifact.
@@ -3725,10 +3833,10 @@ function readConfigExport(exported, file) {
3725
3833
  var lastModuleConfig = null;
3726
3834
  function moduleConfigKey(fullPath) {
3727
3835
  try {
3728
- return crypto5.createHash("sha256").update(fs8__namespace.readFileSync(fullPath)).digest("hex").slice(0, 24);
3836
+ return crypto5.createHash("sha256").update(fs3__namespace.readFileSync(fullPath)).digest("hex").slice(0, 24);
3729
3837
  } catch {
3730
3838
  try {
3731
- const stats = fs8__namespace.statSync(fullPath);
3839
+ const stats = fs3__namespace.statSync(fullPath);
3732
3840
  return `stat-${stats.mtimeMs}-${stats.size}`;
3733
3841
  } catch {
3734
3842
  return "unreadable";
@@ -3769,9 +3877,9 @@ async function loadConfigFileDetailed(cwd, options = {}) {
3769
3877
  const fullPath = path6__namespace.join(cwd, filename);
3770
3878
  let candidateStats = null;
3771
3879
  try {
3772
- candidateStats = fs8__namespace.statSync(fullPath);
3880
+ candidateStats = fs3__namespace.statSync(fullPath);
3773
3881
  } catch {
3774
- if (!fs8__namespace.existsSync(fullPath)) continue;
3882
+ if (!fs3__namespace.existsSync(fullPath)) continue;
3775
3883
  }
3776
3884
  if (candidateStats !== null && !candidateStats.isFile()) {
3777
3885
  configDirectories.push(fullPath);
@@ -3779,7 +3887,7 @@ async function loadConfigFileDetailed(cwd, options = {}) {
3779
3887
  }
3780
3888
  if (filename.endsWith(".json") || filename === ".snapshotrc") {
3781
3889
  try {
3782
- const config = parseJsonish(fs8__namespace.readFileSync(fullPath, "utf8"), fullPath);
3890
+ const config = parseJsonish(fs3__namespace.readFileSync(fullPath, "utf8"), fullPath);
3783
3891
  if (config === null || typeof config !== "object" || Array.isArray(config)) {
3784
3892
  throw new Error(
3785
3893
  `${fullPath} does not hold a configuration object (received ${describeValue2(config)}).`
@@ -3820,9 +3928,9 @@ async function loadConfigFileDetailed(cwd, options = {}) {
3820
3928
  }
3821
3929
  }
3822
3930
  const pkgJsonPath = path6__namespace.join(cwd, "package.json");
3823
- if (fs8__namespace.existsSync(pkgJsonPath)) {
3931
+ if (fs3__namespace.existsSync(pkgJsonPath)) {
3824
3932
  try {
3825
- const parsed = parseJsonish(fs8__namespace.readFileSync(pkgJsonPath, "utf8"), pkgJsonPath);
3933
+ const parsed = parseJsonish(fs3__namespace.readFileSync(pkgJsonPath, "utf8"), pkgJsonPath);
3826
3934
  const snapshotKey = parsed.snapshot;
3827
3935
  if (snapshotKey && typeof snapshotKey === "object" && !Array.isArray(snapshotKey)) {
3828
3936
  assertKnownConfigKeys(
@@ -3990,7 +4098,7 @@ function readConfiguredBrief(cwd, value) {
3990
4098
  }
3991
4099
  const rootReal = (() => {
3992
4100
  try {
3993
- return fs8__namespace.realpathSync(cwd);
4101
+ return fs3__namespace.realpathSync(cwd);
3994
4102
  } catch {
3995
4103
  return path6__namespace.resolve(cwd);
3996
4104
  }
@@ -3998,19 +4106,19 @@ function readConfiguredBrief(cwd, value) {
3998
4106
  const requested = path6__namespace.resolve(cwd, value);
3999
4107
  let filePath;
4000
4108
  try {
4001
- filePath = fs8__namespace.realpathSync(requested);
4109
+ filePath = fs3__namespace.realpathSync(requested);
4002
4110
  } catch {
4003
4111
  throw new Error(
4004
4112
  'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
4005
4113
  );
4006
4114
  }
4007
- const relative9 = path6__namespace.relative(rootReal, filePath);
4008
- if (relative9.length === 0 || relative9 === ".." || relative9.startsWith(`..${path6__namespace.sep}`) || path6__namespace.isAbsolute(relative9)) {
4115
+ const relative10 = path6__namespace.relative(rootReal, filePath);
4116
+ if (relative10.length === 0 || relative10 === ".." || relative10.startsWith(`..${path6__namespace.sep}`) || path6__namespace.isAbsolute(relative10)) {
4009
4117
  throw new Error(
4010
4118
  'brief "' + value + '" resolves outside the repository. A brief must be a file inside the repository being described; an absolute or parent path is refused.'
4011
4119
  );
4012
4120
  }
4013
- const posixRelative = relative9.split(path6__namespace.sep).join("/");
4121
+ const posixRelative = relative10.split(path6__namespace.sep).join("/");
4014
4122
  if (isSensitivePath(posixRelative) || isSensitivePath(value)) {
4015
4123
  throw new Error(
4016
4124
  'brief "' + value + '" is a credential-bearing file. A snapshot must not reproduce secrets, so it cannot be used as the owner brief.'
@@ -4018,9 +4126,16 @@ function readConfiguredBrief(cwd, value) {
4018
4126
  }
4019
4127
  let text;
4020
4128
  try {
4021
- if (!fs8__namespace.statSync(filePath).isFile()) throw new Error("not a file");
4022
- text = fs8__namespace.readFileSync(filePath, "utf8");
4023
- } catch {
4129
+ const stats = fs3__namespace.statSync(filePath);
4130
+ if (!stats.isFile()) throw new Error("not a file");
4131
+ if (stats.size > MAX_BRIEF_BYTES) {
4132
+ throw new Error(
4133
+ 'brief "' + value + '" is ' + stats.size + " bytes; the limit is " + MAX_BRIEF_BYTES + ". Keep it to what a reader can act on, or move the detail into a document the snapshot carries."
4134
+ );
4135
+ }
4136
+ text = fs3__namespace.readFileSync(filePath, "utf8");
4137
+ } catch (error) {
4138
+ if (error instanceof Error && error.message.startsWith('brief "')) throw error;
4024
4139
  throw new Error(
4025
4140
  'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
4026
4141
  );
@@ -4132,11 +4247,11 @@ function outputExcludePatterns(cwd, outDir, tmpDir) {
4132
4247
  const patterns = [];
4133
4248
  for (const dir of [outDir, tmpDir]) {
4134
4249
  const absolute = path6__namespace.resolve(cwd, dir);
4135
- const relative9 = path6__namespace.relative(cwd, absolute);
4136
- if (!relative9 || relative9 === ".." || relative9.startsWith(`..${path6__namespace.sep}`) || path6__namespace.isAbsolute(relative9)) {
4250
+ const relative10 = path6__namespace.relative(cwd, absolute);
4251
+ if (!relative10 || relative10 === ".." || relative10.startsWith(`..${path6__namespace.sep}`) || path6__namespace.isAbsolute(relative10)) {
4137
4252
  continue;
4138
4253
  }
4139
- patterns.push(`${relative9.replace(/\\/g, "/")}/**`);
4254
+ patterns.push(`${relative10.replace(/\\/g, "/")}/**`);
4140
4255
  }
4141
4256
  return patterns;
4142
4257
  }
@@ -4267,10 +4382,10 @@ function resolveCandidateCwd(userConfig, cliOptions, baseDir) {
4267
4382
  }
4268
4383
  const candidate = cliOptions?.cwd || userConfig?.cwd || baseDir || process.cwd();
4269
4384
  const resolved = path6__namespace.resolve(candidate);
4270
- if (!fs8__namespace.existsSync(resolved)) {
4385
+ if (!fs3__namespace.existsSync(resolved)) {
4271
4386
  throw new Error(`Working directory does not exist: ${resolved}`);
4272
4387
  }
4273
- if (!fs8__namespace.statSync(resolved).isDirectory()) {
4388
+ if (!fs3__namespace.statSync(resolved).isDirectory()) {
4274
4389
  throw new Error(`Working directory is not a directory: ${resolved}`);
4275
4390
  }
4276
4391
  return resolved;
@@ -4423,7 +4538,10 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
4423
4538
  outDir,
4424
4539
  tmpDir,
4425
4540
  maxPartBytes: resolvedMaxPartBytes,
4426
- ...maxPartTokens === void 0 ? {} : { maxPartTokens },
4541
+ // Record the effective value even when the user did not set it. normalizeResolvedConfig
4542
+ // derives it for the manifest; leaving validate's fresh resolution unset made a clean
4543
+ // snapshot report a configuration mismatch.
4544
+ maxPartTokens: maxPartTokens ?? Math.floor(resolvedMaxPartBytes / 4),
4427
4545
  largeFileBytes: largeFileBytesFor(resolvedMaxPartBytes, cliOptions, userConfig),
4428
4546
  previewHeadLines: strictPositiveInteger(userConfig?.previewHeadLines, 80, "`previewHeadLines`"),
4429
4547
  previewTailLines: strictPositiveInteger(userConfig?.previewTailLines, 40, "`previewTailLines`"),
@@ -4644,7 +4762,7 @@ function finalizeSummary(summary) {
4644
4762
  }
4645
4763
  function eachLine(content, visit) {
4646
4764
  const text = content.length > MAX_SUMMARY_CHARS ? content.slice(0, MAX_SUMMARY_CHARS) : content;
4647
- for (const line of text.split(/\r?\n/)) visit(line);
4765
+ for (const line of text.split(/\r\n|\n|\r/)) visit(line);
4648
4766
  }
4649
4767
  function isTopLevel(line) {
4650
4768
  return !/^[\s]/.test(line);
@@ -4924,9 +5042,9 @@ var JAVA_METHOD = /^\s+(?:public|private|protected)\s+(?:static\s+)?(?:final\s+)
4924
5042
  var jvmProfile = {
4925
5043
  id: "jvm",
4926
5044
  extensions: [".java", ".kt", ".kts", ".scala"],
4927
- summarize(path16, content) {
5045
+ summarize(path17, content) {
4928
5046
  const summary = emptySummary();
4929
- const lower = path16.toLowerCase();
5047
+ const lower = path17.toLowerCase();
4930
5048
  const isJava = lower.endsWith(".java");
4931
5049
  const isKotlin = lower.endsWith(".kt") || lower.endsWith(".kts");
4932
5050
  eachLine(content, (line) => {
@@ -5149,9 +5267,9 @@ var rubyProfile = {
5149
5267
  eachLine(content, (line) => {
5150
5268
  const trimmed = line.trim();
5151
5269
  if (!trimmed || trimmed.startsWith("#")) return;
5152
- const relative9 = REQUIRE_RELATIVE.exec(trimmed);
5153
- if (relative9) {
5154
- summary.imports.push(`./${relative9[1]}`);
5270
+ const relative10 = REQUIRE_RELATIVE.exec(trimmed);
5271
+ if (relative10) {
5272
+ summary.imports.push(`./${relative10[1]}`);
5155
5273
  return;
5156
5274
  }
5157
5275
  const required = REQUIRE.exec(trimmed);
@@ -5335,7 +5453,7 @@ function summarizeTypeScriptSource(relativePath, content) {
5335
5453
  routeHandlers: []
5336
5454
  };
5337
5455
  const lowerPath = relativePath.toLowerCase();
5338
- const scriptKind2 = /.tsx$/.test(lowerPath) ? ts__default.default.ScriptKind.TSX : /.jsx$/.test(lowerPath) ? ts__default.default.ScriptKind.JSX : /.(?:js|mjs|cjs)$/.test(lowerPath) ? ts__default.default.ScriptKind.JS : ts__default.default.ScriptKind.TS;
5456
+ const scriptKind2 = /\.tsx$/.test(lowerPath) ? ts__default.default.ScriptKind.TSX : /\.jsx$/.test(lowerPath) ? ts__default.default.ScriptKind.JSX : /.(?:js|mjs|cjs)$/.test(lowerPath) ? ts__default.default.ScriptKind.JS : ts__default.default.ScriptKind.TS;
5339
5457
  const sourceFile = ts__default.default.createSourceFile(
5340
5458
  relativePath,
5341
5459
  content,
@@ -5534,17 +5652,17 @@ function summarizeTypeScriptSource(relativePath, content) {
5534
5652
  var SCRIPT_BLOCK = /<script([^>]*)>([\s\S]*?)<\/script>/gi;
5535
5653
  var JSX_LANG = /\blang\s*=\s*["']?[tj]sx\b/i;
5536
5654
  var ASTRO_FRONTMATTER = /^\uFEFF?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?=\r?\n|$)/;
5537
- function componentName(path16) {
5538
- const base = path16.split("/").pop() ?? path16;
5655
+ function componentName(path17) {
5656
+ const base = path17.split("/").pop() ?? path17;
5539
5657
  return base.replace(/\.[^.]+$/, "");
5540
5658
  }
5541
5659
  var sfcProfile = {
5542
5660
  id: "sfc",
5543
5661
  extensions: [".vue", ".svelte", ".astro"],
5544
- summarize(path16, content) {
5662
+ summarize(path17, content) {
5545
5663
  let script = "";
5546
- let usesJsx = path16.toLowerCase().endsWith(".astro");
5547
- if (path16.toLowerCase().endsWith(".astro")) {
5664
+ let usesJsx = path17.toLowerCase().endsWith(".astro");
5665
+ if (path17.toLowerCase().endsWith(".astro")) {
5548
5666
  const frontmatter = ASTRO_FRONTMATTER.exec(content);
5549
5667
  if (frontmatter) script += `${frontmatter[1]}
5550
5668
  `;
@@ -5554,7 +5672,7 @@ var sfcProfile = {
5554
5672
  script += `${match[2]}
5555
5673
  `;
5556
5674
  }
5557
- const name = componentName(path16);
5675
+ const name = componentName(path17);
5558
5676
  if (!script.trim()) {
5559
5677
  const summary2 = emptySummary();
5560
5678
  if (name) {
@@ -5745,15 +5863,15 @@ for (const profile of LANGUAGE_PROFILES) {
5745
5863
  BY_EXTENSION.set(extension.toLowerCase(), profile);
5746
5864
  }
5747
5865
  }
5748
- function profileForPath(path16) {
5749
- const lower = path16.toLowerCase();
5866
+ function profileForPath(path17) {
5867
+ const lower = path17.toLowerCase();
5750
5868
  const dot = lower.lastIndexOf(".");
5751
5869
  if (dot === -1) return null;
5752
5870
  return BY_EXTENSION.get(lower.slice(dot)) ?? null;
5753
5871
  }
5754
- function summarizeWithProfile(path16, content) {
5755
- const profile = profileForPath(path16);
5756
- return profile ? profile.summarize(path16, content) : null;
5872
+ function summarizeWithProfile(path17, content) {
5873
+ const profile = profileForPath(path17);
5874
+ return profile ? profile.summarize(path17, content) : null;
5757
5875
  }
5758
5876
  var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
5759
5877
  ".png",
@@ -5924,17 +6042,17 @@ function decodeText(buffer) {
5924
6042
  };
5925
6043
  }
5926
6044
  const invalidBytes = countInvalidUtf8Bytes(buffer);
6045
+ const controlBytes = countControlBytes(buffer);
6046
+ if (controlBytes > CONTROL_BYTES_FLOOR && controlBytes * 100 > buffer.length) {
6047
+ return {
6048
+ text: "",
6049
+ encoding: "utf-8",
6050
+ invalidBytes,
6051
+ binary: true,
6052
+ binaryReason: `${controlBytes} control byte(s) in ${buffer.length} B; not text`
6053
+ };
6054
+ }
5927
6055
  if (invalidBytes === 0) {
5928
- const controlBytes = countControlBytes(buffer);
5929
- if (controlBytes > CONTROL_BYTES_FLOOR && controlBytes * 100 > buffer.length) {
5930
- return {
5931
- text: "",
5932
- encoding: "utf-8",
5933
- invalidBytes: 0,
5934
- binary: true,
5935
- binaryReason: `${controlBytes} control byte(s) in ${buffer.length} B; valid UTF-8 but not text`
5936
- };
5937
- }
5938
6056
  return {
5939
6057
  text: new TextDecoder("utf-8").decode(buffer),
5940
6058
  encoding: "utf-8",
@@ -5965,13 +6083,13 @@ function isBinaryFile(absolutePath) {
5965
6083
  if (isBinaryExtension(absolutePath)) return true;
5966
6084
  let fd;
5967
6085
  try {
5968
- fd = fs8__namespace.openSync(absolutePath, "r");
6086
+ fd = fs3__namespace.openSync(absolutePath, "r");
5969
6087
  const buffer = Buffer.alloc(CHUNK);
5970
6088
  let sample2;
5971
6089
  let position = 0;
5972
6090
  while (position < BINARY_SCAN_BYTES) {
5973
6091
  const wanted = Math.min(CHUNK, BINARY_SCAN_BYTES - position);
5974
- const bytesRead = fs8__namespace.readSync(fd, buffer, 0, wanted, position);
6092
+ const bytesRead = fs3__namespace.readSync(fd, buffer, 0, wanted, position);
5975
6093
  if (bytesRead === 0) return false;
5976
6094
  const chunk = buffer.subarray(0, bytesRead);
5977
6095
  if (sample2 === void 0) {
@@ -5989,7 +6107,7 @@ function isBinaryFile(absolutePath) {
5989
6107
  } finally {
5990
6108
  if (fd !== void 0) {
5991
6109
  try {
5992
- fs8__namespace.closeSync(fd);
6110
+ fs3__namespace.closeSync(fd);
5993
6111
  } catch {
5994
6112
  }
5995
6113
  }
@@ -6011,9 +6129,9 @@ function importsOfText(relativePath, text) {
6011
6129
  function importsOfFile(relativePath, absolutePath) {
6012
6130
  let buffer;
6013
6131
  try {
6014
- const stats = fs8__namespace.statSync(absolutePath);
6132
+ const stats = fs3__namespace.statSync(absolutePath);
6015
6133
  if (!stats.isFile() || stats.size > SUMMARY_MAX_SOURCE_BYTES) return [];
6016
- buffer = fs8__namespace.readFileSync(absolutePath);
6134
+ buffer = fs3__namespace.readFileSync(absolutePath);
6017
6135
  } catch {
6018
6136
  return [];
6019
6137
  }
@@ -6057,9 +6175,15 @@ function skeletonizeTypeScript(source, fileName = "file.ts") {
6057
6175
  if (end > start) spans.push({ start, end });
6058
6176
  }
6059
6177
  }
6060
- ts__default.default.forEachChild(node, visit);
6061
6178
  };
6062
- visit(sourceFile);
6179
+ const stack = [sourceFile];
6180
+ while (stack.length > 0) {
6181
+ const node = stack.pop();
6182
+ visit(node);
6183
+ ts__default.default.forEachChild(node, (child) => {
6184
+ stack.push(child);
6185
+ });
6186
+ }
6063
6187
  if (spans.length === 0) return { text: source, collapsed: 0 };
6064
6188
  const outermost = [];
6065
6189
  for (const span of spans.sort((a, b) => a.start - b.start || b.end - a.end)) {
@@ -6112,6 +6236,9 @@ function countLines(content) {
6112
6236
  const last = content.charCodeAt(content.length - 1);
6113
6237
  return last === 10 || last === 13 ? breaks : breaks + 1;
6114
6238
  }
6239
+ function countBodyLines(content) {
6240
+ return content.length === 0 ? 0 : content.split("\n").length;
6241
+ }
6115
6242
  function truncateToBytes(content, maxBytes) {
6116
6243
  const buffer = Buffer.from(content, "utf8");
6117
6244
  if (buffer.length <= maxBytes) return { content, isTruncated: false };
@@ -6265,10 +6392,10 @@ function resolveImport(from, specifier, byPath) {
6265
6392
  if (segment === "..") parts.pop();
6266
6393
  else parts.push(segment);
6267
6394
  }
6268
- const path16 = parts.join("/");
6269
- const withoutExtension = path16.replace(/\.[cm]?[jt]sx?$/, "");
6395
+ const path17 = parts.join("/");
6396
+ const withoutExtension = path17.replace(/\.[cm]?[jt]sx?$/, "");
6270
6397
  const candidates = [
6271
- path16,
6398
+ path17,
6272
6399
  withoutExtension + ".ts",
6273
6400
  withoutExtension + ".tsx",
6274
6401
  withoutExtension + ".js",
@@ -6277,18 +6404,18 @@ function resolveImport(from, specifier, byPath) {
6277
6404
  withoutExtension + ".go",
6278
6405
  withoutExtension + ".rs",
6279
6406
  withoutExtension + "/index.ts",
6280
- path16 + ".ts",
6281
- path16 + ".tsx",
6282
- path16 + ".js",
6283
- path16 + ".jsx",
6284
- path16 + ".mjs",
6285
- path16 + ".cjs",
6286
- path16 + ".py",
6287
- path16 + ".go",
6288
- path16 + ".rs",
6289
- path16 + ".java",
6290
- path16 + "/index.ts",
6291
- path16 + "/index.js"
6407
+ path17 + ".ts",
6408
+ path17 + ".tsx",
6409
+ path17 + ".js",
6410
+ path17 + ".jsx",
6411
+ path17 + ".mjs",
6412
+ path17 + ".cjs",
6413
+ path17 + ".py",
6414
+ path17 + ".go",
6415
+ path17 + ".rs",
6416
+ path17 + ".java",
6417
+ path17 + "/index.ts",
6418
+ path17 + "/index.js"
6292
6419
  ];
6293
6420
  for (const candidate of candidates) {
6294
6421
  const found = byPath.get(candidate);
@@ -6317,12 +6444,12 @@ function planForQuestion(manifest, question, options = {}) {
6317
6444
  const scored = [];
6318
6445
  for (const file of manifest.files) {
6319
6446
  if (isTest(file) && !wantsTests) continue;
6320
- const path16 = file.relativePath.toLowerCase();
6321
- const words = path16.split(/[^a-z0-9_]+/).filter((word) => word.length >= 3);
6447
+ const path17 = file.relativePath.toLowerCase();
6448
+ const words = path17.split(/[^a-z0-9_]+/).filter((word) => word.length >= 3);
6322
6449
  let score = 0;
6323
6450
  const reasons = [];
6324
6451
  for (const term of terms) {
6325
- if (path16.includes(term)) {
6452
+ if (path17.includes(term)) {
6326
6453
  score += 8;
6327
6454
  reasons.push("path:" + term);
6328
6455
  continue;
@@ -6373,7 +6500,9 @@ function planForQuestion(manifest, question, options = {}) {
6373
6500
  notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
6374
6501
  }
6375
6502
  }
6376
- scored.sort((left, right) => right.score - left.score || left.file.relativePath.localeCompare(right.file.relativePath));
6503
+ scored.sort(
6504
+ (left, right) => right.score - left.score || (left.file.relativePath < right.file.relativePath ? -1 : left.file.relativePath > right.file.relativePath ? 1 : 0)
6505
+ );
6377
6506
  const chosen = /* @__PURE__ */ new Map();
6378
6507
  const skipped = [];
6379
6508
  let used = 0;
@@ -6481,12 +6610,15 @@ function stripComments2(text, relativePath) {
6481
6610
  if (ranges_ === void 0) return;
6482
6611
  for (const range of ranges_) ranges.push([range.pos, range.end]);
6483
6612
  };
6484
- const visit = (node) => {
6613
+ const stack = [source];
6614
+ while (stack.length > 0) {
6615
+ const node = stack.pop();
6485
6616
  collect(ts__default.default.getLeadingCommentRanges(text, node.getFullStart()));
6486
6617
  collect(ts__default.default.getTrailingCommentRanges(text, node.getEnd()));
6487
- ts__default.default.forEachChild(node, visit);
6488
- };
6489
- visit(source);
6618
+ ts__default.default.forEachChild(node, (child) => {
6619
+ stack.push(child);
6620
+ });
6621
+ }
6490
6622
  collect(ts__default.default.getLeadingCommentRanges(text, source.endOfFileToken.getFullStart()));
6491
6623
  if (ranges.length === 0) return { text, removed: 0 };
6492
6624
  ranges.sort((left, right) => left[0] - right[0]);
@@ -6551,7 +6683,7 @@ function resolveChangedScope(cwd, request) {
6551
6683
  const descriptions = [];
6552
6684
  if (request.changedSince !== void 0) {
6553
6685
  assertUsableRef(request.changedSince);
6554
- for (const path16 of gitPaths(cwd, [
6686
+ for (const path17 of gitPaths(cwd, [
6555
6687
  "diff",
6556
6688
  "--name-only",
6557
6689
  "-z",
@@ -6559,9 +6691,9 @@ function resolveChangedScope(cwd, request) {
6559
6691
  `${request.changedSince}...HEAD`,
6560
6692
  "--"
6561
6693
  ])) {
6562
- paths.add(path16);
6694
+ paths.add(path17);
6563
6695
  }
6564
- for (const path16 of gitPaths(cwd, [
6696
+ for (const path17 of gitPaths(cwd, [
6565
6697
  "diff",
6566
6698
  "--name-only",
6567
6699
  "-z",
@@ -6569,15 +6701,15 @@ function resolveChangedScope(cwd, request) {
6569
6701
  "HEAD",
6570
6702
  "--"
6571
6703
  ])) {
6572
- paths.add(path16);
6704
+ paths.add(path17);
6573
6705
  }
6574
- for (const path16 of gitPaths(cwd, ["ls-files", "--others", "--exclude-standard", "-z", "--"])) {
6575
- paths.add(path16);
6706
+ for (const path17 of gitPaths(cwd, ["ls-files", "--others", "--exclude-standard", "-z", "--"])) {
6707
+ paths.add(path17);
6576
6708
  }
6577
6709
  descriptions.push(`changed since ${request.changedSince}`);
6578
6710
  }
6579
6711
  if (request.staged === true) {
6580
- for (const path16 of gitPaths(cwd, [
6712
+ for (const path17 of gitPaths(cwd, [
6581
6713
  "diff",
6582
6714
  "--cached",
6583
6715
  "--name-only",
@@ -6585,10 +6717,10 @@ function resolveChangedScope(cwd, request) {
6585
6717
  "--relative",
6586
6718
  "--"
6587
6719
  ])) {
6588
- paths.add(path16);
6589
- stagedPaths.add(path16);
6720
+ paths.add(path17);
6721
+ stagedPaths.add(path17);
6590
6722
  }
6591
- for (const path16 of gitPaths(cwd, [
6723
+ for (const path17 of gitPaths(cwd, [
6592
6724
  "diff",
6593
6725
  "--cached",
6594
6726
  "--name-only",
@@ -6597,7 +6729,7 @@ function resolveChangedScope(cwd, request) {
6597
6729
  "--diff-filter=D",
6598
6730
  "--"
6599
6731
  ])) {
6600
- deletedPaths.add(path16);
6732
+ deletedPaths.add(path17);
6601
6733
  }
6602
6734
  descriptions.push("staged");
6603
6735
  }
@@ -6638,12 +6770,16 @@ function tsconfigPathsFor(cwd) {
6638
6770
  const configPath = path6__namespace.join(cwd, "tsconfig.json");
6639
6771
  let stats;
6640
6772
  try {
6641
- stats = fs8__namespace.statSync(configPath);
6773
+ stats = fs3__namespace.statSync(configPath);
6642
6774
  } catch (err) {
6643
6775
  if (err.code === "ENOENT") return null;
6644
6776
  return null;
6645
6777
  }
6646
6778
  const key = `${stats.mtimeMs}:${stats.size}`;
6779
+ if (!TSCONFIG_CACHE.has(configPath) && TSCONFIG_CACHE.size >= 64) {
6780
+ const oldest = TSCONFIG_CACHE.keys().next().value;
6781
+ if (oldest !== void 0) TSCONFIG_CACHE.delete(oldest);
6782
+ }
6647
6783
  const cached = TSCONFIG_CACHE.get(configPath);
6648
6784
  if (cached !== void 0 && cached.key === key) return cached.value;
6649
6785
  let value = null;
@@ -6672,8 +6808,8 @@ function tsconfigPathsFor(cwd) {
6672
6808
  return value;
6673
6809
  }
6674
6810
  function repositoryRelative(cwd, target) {
6675
- const relative9 = path6__namespace.relative(cwd, target).replace(/\\/g, "/");
6676
- return relative9.length === 0 || !relative9.startsWith("..") && !path6__namespace.isAbsolute(relative9) ? relative9 : null;
6811
+ const relative10 = path6__namespace.relative(cwd, target).replace(/\\/g, "/");
6812
+ return relative10.length === 0 || !relative10.startsWith("..") && !path6__namespace.isAbsolute(relative10) ? relative10 : null;
6677
6813
  }
6678
6814
  function rememberFirst(map, key, value) {
6679
6815
  if (!map.has(key)) map.set(key, value);
@@ -6803,6 +6939,75 @@ function importsChangedFile(importerPath, imports, changedPaths, resolver) {
6803
6939
  }
6804
6940
  return false;
6805
6941
  }
6942
+ function isInside2(parent, child) {
6943
+ const relative10 = path6__namespace.relative(parent, child);
6944
+ return relative10 === "" || !relative10.startsWith("..") && !path6__namespace.isAbsolute(relative10);
6945
+ }
6946
+ function resolveConfined(baseDir, relativePath) {
6947
+ if (relativePath.length === 0 || relativePath.includes("\0")) {
6948
+ return { ok: false, reason: "not-file", message: "the file name is empty or contains a NUL byte" };
6949
+ }
6950
+ if (path6__namespace.isAbsolute(relativePath)) {
6951
+ return { ok: false, reason: "outside", message: "an absolute path is not a snapshot-relative file" };
6952
+ }
6953
+ let baseReal;
6954
+ try {
6955
+ baseReal = fs3__namespace.realpathSync(path6__namespace.resolve(baseDir));
6956
+ } catch {
6957
+ return { ok: false, reason: "missing", message: "the snapshot directory does not exist" };
6958
+ }
6959
+ const candidate = path6__namespace.resolve(baseReal, relativePath);
6960
+ if (!isInside2(baseReal, candidate)) {
6961
+ return { ok: false, reason: "outside", message: "the path resolves outside the snapshot directory" };
6962
+ }
6963
+ let stats;
6964
+ try {
6965
+ stats = fs3__namespace.lstatSync(candidate);
6966
+ } catch (error) {
6967
+ const code = error.code;
6968
+ return {
6969
+ ok: false,
6970
+ reason: code === "ENOENT" || code === "ENOTDIR" ? "missing" : "unreadable",
6971
+ message: code === "ENOENT" || code === "ENOTDIR" ? "the file does not exist" : "the file could not be inspected"
6972
+ };
6973
+ }
6974
+ if (stats.isSymbolicLink()) {
6975
+ return { ok: false, reason: "not-file", message: "the file is a symbolic link" };
6976
+ }
6977
+ if (!stats.isFile()) {
6978
+ return { ok: false, reason: "not-file", message: "the path is not a regular file" };
6979
+ }
6980
+ let real;
6981
+ try {
6982
+ real = fs3__namespace.realpathSync(candidate);
6983
+ } catch {
6984
+ return { ok: false, reason: "unreadable", message: "the file could not be resolved" };
6985
+ }
6986
+ if (!isInside2(baseReal, real)) {
6987
+ return { ok: false, reason: "outside", message: "the file resolves outside the snapshot directory" };
6988
+ }
6989
+ return { ok: true, path: real, stats };
6990
+ }
6991
+ function readConfinedBytes(baseDir, relativePath) {
6992
+ const resolved = resolveConfined(baseDir, relativePath);
6993
+ if (!resolved.ok) return resolved;
6994
+ try {
6995
+ const bytes = fs3__namespace.readFileSync(resolved.path);
6996
+ return { ok: true, bytes, path: resolved.path, stats: fs3__namespace.statSync(resolved.path) };
6997
+ } catch {
6998
+ return { ok: false, reason: "unreadable", message: "the file could not be read" };
6999
+ }
7000
+ }
7001
+ function readConfinedText(baseDir, relativePath) {
7002
+ const resolved = resolveConfined(baseDir, relativePath);
7003
+ if (!resolved.ok) return resolved;
7004
+ try {
7005
+ const text = fs3__namespace.readFileSync(resolved.path, "utf8");
7006
+ return { ok: true, text, path: resolved.path, stats: fs3__namespace.statSync(resolved.path) };
7007
+ } catch {
7008
+ return { ok: false, reason: "unreadable", message: "the file could not be read" };
7009
+ }
7010
+ }
6806
7011
  var LANGUAGE_BY_EXTENSION = {
6807
7012
  ".ts": "typescript",
6808
7013
  ".mts": "typescript",
@@ -6883,7 +7088,7 @@ function findStagingDirectory(config) {
6883
7088
  const tmpDir = path6__namespace.resolve(config.cwd, config.tmpDir);
6884
7089
  let entries;
6885
7090
  try {
6886
- entries = fs8__namespace.readdirSync(tmpDir);
7091
+ entries = fs3__namespace.readdirSync(tmpDir);
6887
7092
  } catch {
6888
7093
  return null;
6889
7094
  }
@@ -6896,8 +7101,8 @@ function describeMissingManifest(config, manifestPath) {
6896
7101
  const markerPath = path6__namespace.join(outDir, ".codebase-snapshot");
6897
7102
  let marker = null;
6898
7103
  try {
6899
- if (fs8__namespace.existsSync(markerPath)) {
6900
- const parsed = JSON.parse(fs8__namespace.readFileSync(markerPath, "utf8"));
7104
+ if (fs3__namespace.existsSync(markerPath)) {
7105
+ const parsed = JSON.parse(fs3__namespace.readFileSync(markerPath, "utf8"));
6901
7106
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
6902
7107
  marker = parsed;
6903
7108
  }
@@ -6934,11 +7139,11 @@ function sha256Hex(buffer) {
6934
7139
  function wouldNowBeIncluded(cwd, relativePath) {
6935
7140
  const absolutePath = path6__namespace.join(cwd, relativePath);
6936
7141
  try {
6937
- const stats = fs8__namespace.statSync(absolutePath);
7142
+ const stats = fs3__namespace.statSync(absolutePath);
6938
7143
  if (!stats.isFile()) return false;
6939
7144
  if (isBinaryExtension(absolutePath)) return false;
6940
7145
  if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) return false;
6941
- return !decodeText(fs8__namespace.readFileSync(absolutePath)).binary;
7146
+ return !decodeText(fs3__namespace.readFileSync(absolutePath)).binary;
6942
7147
  } catch {
6943
7148
  return false;
6944
7149
  }
@@ -7116,6 +7321,9 @@ function describeManifestShapeProblem(value) {
7116
7321
  if (typeof fields.relativePath !== "string") {
7117
7322
  return 'a "files" entry has no "relativePath"';
7118
7323
  }
7324
+ if (!isConfinedRelative(fields.relativePath)) {
7325
+ return 'a "files" entry "relativePath" resolves outside the repository and was not inspected';
7326
+ }
7119
7327
  if (!currentSchema) continue;
7120
7328
  if (typeof fields.part !== "string" || fields.part.length === 0) {
7121
7329
  return 'a "files" entry records no "part"';
@@ -7134,6 +7342,18 @@ function describeManifestShapeProblem(value) {
7134
7342
  }
7135
7343
  }
7136
7344
  if (!Array.isArray(candidate.skipped)) return 'missing "skipped" array';
7345
+ for (const entry of candidate.skipped) {
7346
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
7347
+ return 'a "skipped" entry is not an object';
7348
+ }
7349
+ const fields = entry;
7350
+ if (typeof fields.path !== "string" || !isConfinedRelative(fields.path)) {
7351
+ return 'a "skipped" entry "path" resolves outside the repository and was not inspected';
7352
+ }
7353
+ if (typeof fields.reason !== "string" || fields.reason.length === 0) {
7354
+ return 'a "skipped" entry has no "reason"';
7355
+ }
7356
+ }
7137
7357
  if (!Array.isArray(candidate.parts)) return 'missing "parts" array';
7138
7358
  for (const entry of candidate.parts) {
7139
7359
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
@@ -7171,7 +7391,7 @@ function validateSnapshot(configInput) {
7171
7391
  assertUsableConfigInput(configInput);
7172
7392
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput);
7173
7393
  const manifestPath = path6__namespace.resolve(config.cwd, config.outDir, "manifest.json");
7174
- if (!fs8__namespace.existsSync(manifestPath)) {
7394
+ if (!fs3__namespace.existsSync(manifestPath)) {
7175
7395
  return {
7176
7396
  valid: false,
7177
7397
  manifestPresent: false,
@@ -7182,7 +7402,7 @@ function validateSnapshot(configInput) {
7182
7402
  }
7183
7403
  let manifest;
7184
7404
  try {
7185
- manifest = JSON.parse(fs8__namespace.readFileSync(manifestPath, "utf8"));
7405
+ manifest = JSON.parse(fs3__namespace.readFileSync(manifestPath, "utf8"));
7186
7406
  } catch (err) {
7187
7407
  return {
7188
7408
  valid: false,
@@ -7194,10 +7414,12 @@ function validateSnapshot(configInput) {
7194
7414
  }
7195
7415
  const shapeProblem = describeManifestShapeProblem(manifest);
7196
7416
  if (shapeProblem) {
7417
+ const drift2 = emptyDrift();
7418
+ drift2.partIssues.push({ part: "manifest.json", issue: shapeProblem });
7197
7419
  return {
7198
7420
  valid: false,
7199
7421
  manifestPresent: true,
7200
- drift: emptyDrift(),
7422
+ drift: drift2,
7201
7423
  errors: [`${manifestPath} is not a snapshot manifest: ${shapeProblem}`],
7202
7424
  warnings: []
7203
7425
  };
@@ -7326,12 +7548,16 @@ function validateSnapshot(configInput) {
7326
7548
  // discovery mode" meant `validate` could enumerate files one way while the snapshot
7327
7549
  // had been generated another way, and then blame the difference on drift.
7328
7550
  discovery: config.discovery,
7551
+ // `generate --staged` adds index-only paths to the candidate list. Without the same
7552
+ // extra paths, a staged file that is absent from the working tree was invisible to
7553
+ // this scan and then reported as deleted, although the snapshot matched the index.
7554
+ ...stagedScope === null ? {} : { extraPaths: [...stagedScope] },
7329
7555
  // The same exclusion `generate` applies: without it, `validate` recounted the tool's
7330
7556
  // own output directory as a set of files missing from the snapshot, so a correct
7331
7557
  // snapshot was reported as drifting.
7332
7558
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
7333
7559
  (directory) => path6__namespace.relative(config.cwd, path6__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
7334
- ).filter((relative9) => relative9.length > 0 && !relative9.startsWith(".."))
7560
+ ).filter((relative10) => relative10.length > 0 && !relative10.startsWith(".."))
7335
7561
  });
7336
7562
  for (const diskFile of collection.files) {
7337
7563
  const snapshotHash = manifestFileMap.get(diskFile);
@@ -7358,7 +7584,7 @@ function validateSnapshot(configInput) {
7358
7584
  let diskHash;
7359
7585
  try {
7360
7586
  const stagedBlob = recordedStaged && stagedScope?.has(diskFile) === true ? readStagedBlob(config.cwd, diskFile) : null;
7361
- diskHash = sha256Hex(stagedBlob ?? fs8__namespace.readFileSync(path6__namespace.join(config.cwd, diskFile)));
7587
+ diskHash = sha256Hex(stagedBlob ?? fs3__namespace.readFileSync(path6__namespace.join(config.cwd, diskFile)));
7362
7588
  } catch (err) {
7363
7589
  if (err.code === "ENOENT") {
7364
7590
  drift.missingOnDisk.push(diskFile);
@@ -7372,6 +7598,12 @@ function validateSnapshot(configInput) {
7372
7598
  }
7373
7599
  }
7374
7600
  for (const snapshotFile of manifestFileMap.keys()) {
7601
+ if (recordedStaged && stagedScope?.has(snapshotFile)) {
7602
+ if (readStagedBlob(config.cwd, snapshotFile) === null) {
7603
+ drift.missingOnDisk.push(snapshotFile);
7604
+ }
7605
+ continue;
7606
+ }
7375
7607
  const confined = confineToDirectory(config.cwd, snapshotFile);
7376
7608
  if (confined === null) {
7377
7609
  drift.partIssues.push({
@@ -7382,7 +7614,7 @@ function validateSnapshot(configInput) {
7382
7614
  }
7383
7615
  let statFailure = null;
7384
7616
  try {
7385
- fs8__namespace.statSync(confined);
7617
+ fs3__namespace.statSync(confined);
7386
7618
  } catch (err) {
7387
7619
  statFailure = err;
7388
7620
  }
@@ -7415,13 +7647,15 @@ function validateSnapshot(configInput) {
7415
7647
  });
7416
7648
  continue;
7417
7649
  }
7418
- let buffer;
7419
- try {
7420
- buffer = fs8__namespace.readFileSync(partPath);
7421
- } catch {
7422
- drift.partIssues.push({ part: part.filename, issue: "missing from snapshot/parts" });
7650
+ const partRead = readConfinedBytes(partsDir, part.filename);
7651
+ if (!partRead.ok) {
7652
+ drift.partIssues.push({
7653
+ part: part.filename,
7654
+ issue: `missing or not a regular file in snapshot/parts (${partRead.reason})`
7655
+ });
7423
7656
  continue;
7424
7657
  }
7658
+ const buffer = partRead.bytes;
7425
7659
  if (buffer.length !== part.byteSize) {
7426
7660
  drift.partIssues.push({
7427
7661
  part: part.filename,
@@ -7794,15 +8028,15 @@ function validateSnapshot(configInput) {
7794
8028
  ];
7795
8029
  for (const [key, artifact] of declaredArtifacts) {
7796
8030
  if (!artifact) continue;
7797
- const artifactPath = path6__namespace.join(snapshotDir, ...key.split("/"));
7798
- let buffer;
7799
- try {
7800
- if (!fs8__namespace.statSync(artifactPath).isFile()) throw new Error("not a regular file");
7801
- buffer = fs8__namespace.readFileSync(artifactPath);
7802
- } catch {
7803
- drift.partIssues.push({ part: key, issue: "declared artifact is missing" });
8031
+ const artifactRead = readConfinedBytes(snapshotDir, key);
8032
+ if (!artifactRead.ok) {
8033
+ drift.partIssues.push({
8034
+ part: key,
8035
+ issue: `declared artifact is missing or not a regular file (${artifactRead.reason})`
8036
+ });
7804
8037
  continue;
7805
8038
  }
8039
+ const buffer = artifactRead.bytes;
7806
8040
  if (sha256Hex(buffer) !== artifact.sha256 || buffer.length !== artifact.byteSize) {
7807
8041
  drift.partIssues.push({ part: key, issue: "artifact does not match its recorded digest" });
7808
8042
  continue;
@@ -7812,8 +8046,8 @@ function validateSnapshot(configInput) {
7812
8046
  const target = match[1].split("#")[0];
7813
8047
  if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
7814
8048
  const resolved = path6__namespace.resolve(snapshotDir, "reports", target);
7815
- const relative9 = path6__namespace.relative(snapshotDir, resolved);
7816
- if (relative9.startsWith("..") || path6__namespace.isAbsolute(relative9) || !fs8__namespace.existsSync(resolved)) {
8049
+ const relative10 = path6__namespace.relative(snapshotDir, resolved);
8050
+ if (relative10.startsWith("..") || path6__namespace.isAbsolute(relative10) || !fs3__namespace.existsSync(resolved)) {
7817
8051
  drift.partIssues.push({
7818
8052
  part: key,
7819
8053
  issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
@@ -7825,13 +8059,11 @@ function validateSnapshot(configInput) {
7825
8059
  const sarifArtifact = manifest.artifacts?.sarif;
7826
8060
  if (sarifArtifact) {
7827
8061
  const sarifKey = "reports/audit.sarif";
7828
- try {
7829
- const buffer = fs8__namespace.readFileSync(path6__namespace.join(snapshotDir, "reports", "audit.sarif"));
7830
- if (sha256Hex(buffer) !== sarifArtifact.sha256 || buffer.length !== sarifArtifact.byteSize) {
7831
- drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
7832
- }
7833
- } catch {
7834
- drift.partIssues.push({ part: sarifKey, issue: "declared artifact is missing" });
8062
+ const sarifRead = readConfinedBytes(snapshotDir, "reports/audit.sarif");
8063
+ if (!sarifRead.ok) {
8064
+ drift.partIssues.push({ part: sarifKey, issue: "declared artifact is missing or not a regular file" });
8065
+ } else if (sha256Hex(sarifRead.bytes) !== sarifArtifact.sha256 || sarifRead.bytes.length !== sarifArtifact.byteSize) {
8066
+ drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
7835
8067
  }
7836
8068
  }
7837
8069
  if (manifest.git && manifest.git.branch && manifest.git.branch !== config.branch) {
@@ -7873,7 +8105,7 @@ function validateSnapshot(configInput) {
7873
8105
  );
7874
8106
  }
7875
8107
  const signaturePath = path6__namespace.join(path6__namespace.dirname(manifestPath), "signature.json");
7876
- if (fs8__namespace.existsSync(signaturePath)) {
8108
+ if (fs3__namespace.existsSync(signaturePath)) {
7877
8109
  const outcome = verifySnapshotSignature(path6__namespace.dirname(manifestPath));
7878
8110
  if (!outcome.ok) errors.push("signature: " + outcome.reason + ".");
7879
8111
  }
@@ -7930,11 +8162,11 @@ var MAX_LINE_BYTES = 32 * 1024 * 1024;
7930
8162
  function createWriter(output) {
7931
8163
  return {
7932
8164
  write(value) {
7933
- return new Promise((resolve10, reject) => {
8165
+ return new Promise((resolve11, reject) => {
7934
8166
  output.write(`${JSON.stringify(value)}
7935
8167
  `, (error) => {
7936
8168
  if (error) reject(error);
7937
- else resolve10();
8169
+ else resolve11();
7938
8170
  });
7939
8171
  });
7940
8172
  }
@@ -8179,7 +8411,7 @@ var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
8179
8411
  var META_PREFIX = "- Meta: ";
8180
8412
  var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
8181
8413
  var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
8182
- var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
8414
+ var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures", "comments-stripped"]);
8183
8415
  var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
8184
8416
  function readIncludedLines(fields) {
8185
8417
  const last = fields[fields.length - 1];
@@ -8252,8 +8484,8 @@ function findSection(sections, relativePath) {
8252
8484
  if (exact) return exact;
8253
8485
  const foldedPath = rendered.toLowerCase();
8254
8486
  const folded = sections.filter((section) => {
8255
- const path16 = section.path.toLowerCase();
8256
- return path16 === relativePath.toLowerCase() || path16 === foldedPath;
8487
+ const path17 = section.path.toLowerCase();
8488
+ return path17 === relativePath.toLowerCase() || path17 === foldedPath;
8257
8489
  });
8258
8490
  return folded.length === 1 ? folded[0] : null;
8259
8491
  }
@@ -8274,26 +8506,28 @@ var ARTIFACT_FILES = {
8274
8506
  fullXml: "full-codebase.xml",
8275
8507
  sarif: "reports/audit.sarif"
8276
8508
  };
8277
- var TEXT_ARTIFACT = /\.(md|json|txt|sarif)$/i;
8509
+ var TEXT_ARTIFACT = /\.(md|json|txt|sarif|xml)$/i;
8278
8510
  function sha256(buffer) {
8279
8511
  return crypto5.createHash("sha256").update(buffer).digest("hex");
8280
8512
  }
8281
- function readBytes(file) {
8282
- try {
8283
- return fs8__namespace.readFileSync(file);
8284
- } catch {
8285
- return null;
8286
- }
8287
- }
8288
8513
  function readText(file) {
8289
8514
  try {
8290
- return fs8__namespace.readFileSync(file, "utf8");
8515
+ return fs3__namespace.readFileSync(file, "utf8");
8291
8516
  } catch {
8292
8517
  return null;
8293
8518
  }
8294
8519
  }
8520
+ function snapshotText(snapshotDir, relative10) {
8521
+ const read = readConfinedText(snapshotDir, relative10);
8522
+ return read.ok ? read.text : null;
8523
+ }
8524
+ function snapshotBytes(snapshotDir, relative10) {
8525
+ const read = readConfinedBytes(snapshotDir, relative10);
8526
+ return read.ok ? read.bytes : null;
8527
+ }
8295
8528
  function readJson(file) {
8296
- const text = readText(file);
8529
+ const confined = readConfinedText(path6__namespace.dirname(file), path6__namespace.basename(file));
8530
+ const text = confined.ok ? confined.text : null;
8297
8531
  if (text === null) return null;
8298
8532
  try {
8299
8533
  return JSON.parse(text);
@@ -8304,15 +8538,15 @@ function readJson(file) {
8304
8538
  function walk(dir, prefix = "") {
8305
8539
  let entries;
8306
8540
  try {
8307
- entries = fs8__namespace.readdirSync(dir, { withFileTypes: true });
8541
+ entries = fs3__namespace.readdirSync(dir, { withFileTypes: true });
8308
8542
  } catch {
8309
8543
  return [];
8310
8544
  }
8311
8545
  const files = [];
8312
8546
  for (const entry of entries) {
8313
- const relative9 = prefix === "" ? entry.name : prefix + "/" + entry.name;
8314
- if (entry.isDirectory()) files.push(...walk(path6__namespace.join(dir, entry.name), relative9));
8315
- else if (entry.isFile()) files.push(relative9);
8547
+ const relative10 = prefix === "" ? entry.name : prefix + "/" + entry.name;
8548
+ if (entry.isDirectory()) files.push(...walk(path6__namespace.join(dir, entry.name), relative10));
8549
+ else if (entry.isFile()) files.push(relative10);
8316
8550
  }
8317
8551
  return files;
8318
8552
  }
@@ -8350,16 +8584,28 @@ function secretTokens(text) {
8350
8584
  }
8351
8585
  return [...tokens];
8352
8586
  }
8353
- function readArtifactTexts(snapshotDir) {
8587
+ function readArtifactTexts(snapshotDir, maxBytes = 32 * 1024 * 1024) {
8354
8588
  const texts = [];
8355
- for (const relative9 of walk(snapshotDir)) {
8356
- if (!TEXT_ARTIFACT.test(relative9)) continue;
8357
- const text = readText(path6__namespace.join(snapshotDir, relative9));
8358
- if (text !== null) texts.push(text);
8589
+ let bytes = 0;
8590
+ for (const relative10 of walk(snapshotDir)) {
8591
+ if (!TEXT_ARTIFACT.test(relative10)) continue;
8592
+ const full = path6__namespace.join(snapshotDir, relative10);
8593
+ let size;
8594
+ try {
8595
+ size = fs3__namespace.statSync(full).size;
8596
+ } catch {
8597
+ continue;
8598
+ }
8599
+ if (bytes + size > maxBytes) break;
8600
+ const text = snapshotText(snapshotDir, relative10);
8601
+ if (text !== null) {
8602
+ texts.push(text);
8603
+ bytes += Buffer.byteLength(text, "utf8");
8604
+ }
8359
8605
  }
8360
8606
  return texts;
8361
8607
  }
8362
- function findHostPaths(snapshotDir, repoDir) {
8608
+ function findHostPaths(snapshotDir, repoDir, maxBytes = 32 * 1024 * 1024) {
8363
8609
  const patterns = [
8364
8610
  /\/home\/[A-Za-z0-9._-]+/g,
8365
8611
  /\/Users\/[A-Za-z0-9._-]+/g,
@@ -8370,15 +8616,24 @@ function findHostPaths(snapshotDir, repoDir) {
8370
8616
  ];
8371
8617
  const repoPattern = new RegExp(escapeRegExp(repoDir), "g");
8372
8618
  const hits = /* @__PURE__ */ new Set();
8373
- for (const relative9 of walk(snapshotDir)) {
8374
- if (!TEXT_ARTIFACT.test(relative9)) continue;
8375
- const text = readText(path6__namespace.join(snapshotDir, relative9));
8619
+ let scanned = 0;
8620
+ for (const relative10 of walk(snapshotDir)) {
8621
+ if (!TEXT_ARTIFACT.test(relative10)) continue;
8622
+ let size;
8623
+ try {
8624
+ size = fs3__namespace.statSync(path6__namespace.join(snapshotDir, relative10)).size;
8625
+ } catch {
8626
+ continue;
8627
+ }
8628
+ if (scanned + size > maxBytes) break;
8629
+ const text = snapshotText(snapshotDir, relative10);
8376
8630
  if (text === null) continue;
8631
+ scanned += Buffer.byteLength(text, "utf8");
8377
8632
  for (const pattern of patterns) {
8378
- for (const match of text.match(pattern) ?? []) hits.add(relative9 + ": " + match);
8633
+ for (const match of text.match(pattern) ?? []) hits.add(relative10 + ": " + match);
8379
8634
  }
8380
8635
  repoPattern.lastIndex = 0;
8381
- if (repoPattern.test(text)) hits.add(relative9 + ": the repository absolute path");
8636
+ if (repoPattern.test(text)) hits.add(relative10 + ": the repository absolute path");
8382
8637
  }
8383
8638
  return [...hits];
8384
8639
  }
@@ -8560,7 +8815,7 @@ function auditSnapshot(options) {
8560
8815
  const missingParts = [];
8561
8816
  const mismatched = [];
8562
8817
  for (const part of manifest.parts) {
8563
- const bytes = readBytes(path6__namespace.join(snapshotDir, "parts", part.filename));
8818
+ const bytes = snapshotBytes(snapshotDir, "parts/" + part.filename);
8564
8819
  if (bytes === null) {
8565
8820
  missingParts.push(part.filename);
8566
8821
  continue;
@@ -8625,13 +8880,13 @@ function auditSnapshot(options) {
8625
8880
  let artifactCount = 0;
8626
8881
  for (const [key, value] of Object.entries(artifacts)) {
8627
8882
  if (value === null || value === void 0) continue;
8628
- const relative9 = ARTIFACT_FILES[key];
8629
- if (relative9 === void 0) continue;
8883
+ const relative10 = ARTIFACT_FILES[key];
8884
+ if (relative10 === void 0) continue;
8630
8885
  artifactCount += 1;
8631
- const bytes = readBytes(path6__namespace.join(snapshotDir, relative9));
8632
- if (bytes === null) artifactProblems.push(relative9 + " is missing");
8886
+ const bytes = snapshotBytes(snapshotDir, relative10);
8887
+ if (bytes === null) artifactProblems.push(relative10 + " is missing");
8633
8888
  else if (typeof value.sha256 === "string" && sha256(bytes) !== value.sha256) {
8634
- artifactProblems.push(relative9 + " changed");
8889
+ artifactProblems.push(relative10 + " changed");
8635
8890
  }
8636
8891
  }
8637
8892
  checks.push(
@@ -8676,7 +8931,7 @@ function auditSnapshot(options) {
8676
8931
  )
8677
8932
  );
8678
8933
  const signaturePath = path6__namespace.join(snapshotDir, "signature.json");
8679
- if (fs8__namespace.existsSync(signaturePath)) {
8934
+ if (fs3__namespace.existsSync(signaturePath)) {
8680
8935
  const outcome = verifySnapshotSignature(snapshotDir);
8681
8936
  checks.push(
8682
8937
  outcome.ok ? check(
@@ -8741,7 +8996,7 @@ function auditSnapshot(options) {
8741
8996
  manifest.files.map((file) => [anchorForPath(file.relativePath), file.relativePath])
8742
8997
  );
8743
8998
  for (const part of manifest.parts) {
8744
- const partText = readText(path6__namespace.join(snapshotDir, "parts", part.filename));
8999
+ const partText = snapshotText(snapshotDir, "parts/" + part.filename);
8745
9000
  if (partText === null) continue;
8746
9001
  const sections = parsePartSections(partText);
8747
9002
  partTexts.set(part.filename, partText);
@@ -8808,7 +9063,7 @@ function auditSnapshot(options) {
8808
9063
  }
8809
9064
  };
8810
9065
  if (manifest.artifacts?.readme != null) {
8811
- const text = readText(path6__namespace.join(snapshotDir, "README.md"));
9066
+ const text = snapshotText(snapshotDir, "README.md");
8812
9067
  if (text === null) {
8813
9068
  reportProblems.push("README.md is recorded but unreadable");
8814
9069
  } else {
@@ -8848,7 +9103,7 @@ function auditSnapshot(options) {
8848
9103
  }
8849
9104
  }
8850
9105
  if (manifest.artifacts?.prompt != null) {
8851
- const text = readText(path6__namespace.join(snapshotDir, "PROMPT.md"));
9106
+ const text = snapshotText(snapshotDir, "PROMPT.md");
8852
9107
  if (text === null) {
8853
9108
  reportProblems.push("PROMPT.md is recorded but unreadable");
8854
9109
  } else {
@@ -9037,7 +9292,7 @@ function auditSnapshot(options) {
9037
9292
  ];
9038
9293
  for (const reader of packReaders) {
9039
9294
  if (manifest.artifacts?.[reader.key] == null) continue;
9040
- const packText = readText(path6__namespace.join(snapshotDir, reader.file));
9295
+ const packText = snapshotText(snapshotDir, reader.file);
9041
9296
  const problems = [];
9042
9297
  if (packText === null) {
9043
9298
  problems.push(reader.file + " is recorded but unreadable");
@@ -9050,8 +9305,8 @@ function auditSnapshot(options) {
9050
9305
  for (const file of manifest.files) {
9051
9306
  if (!packed.has(file.relativePath)) problems.push(file.relativePath + " is in the manifest but not the pack");
9052
9307
  }
9053
- for (const path16 of packed) {
9054
- if (!known2.has(path16)) problems.push(path16 + " is in the pack but not the manifest");
9308
+ for (const path17 of packed) {
9309
+ if (!known2.has(path17)) problems.push(path17 + " is in the pack but not the manifest");
9055
9310
  }
9056
9311
  }
9057
9312
  }
@@ -9087,7 +9342,7 @@ function auditSnapshot(options) {
9087
9342
  bodyByPath.set(file.relativePath, section.body);
9088
9343
  bodiesChecked += 1;
9089
9344
  const bytes = Buffer.byteLength(section.body, "utf8");
9090
- const bodyLines = section.body === "" ? 0 : section.body.split("\n").length - (section.body.endsWith("\n") ? 1 : 0);
9345
+ const bodyLines = countBodyLines(section.body);
9091
9346
  if (bytes !== file.includedBytes) {
9092
9347
  bodyProblems.push(file.relativePath + ": manifest says " + file.includedBytes + " B, part holds " + bytes + " B");
9093
9348
  } else if (bodyLines !== file.includedLines) {
@@ -9200,7 +9455,7 @@ function auditSnapshot(options) {
9200
9455
  let packBodies = 0;
9201
9456
  let packSkipped = 0;
9202
9457
  for (const pack of packsWanted) {
9203
- const text = readText(path6__namespace.join(snapshotDir, pack.file));
9458
+ const text = snapshotText(snapshotDir, pack.file);
9204
9459
  if (text === null) continue;
9205
9460
  const bodies = pack.read(text);
9206
9461
  if (bodies === null) {
@@ -9264,7 +9519,8 @@ function auditSnapshot(options) {
9264
9519
  unreplayable += 1;
9265
9520
  continue;
9266
9521
  }
9267
- const bytes = readBytes(path6__namespace.join(repoDir, file.relativePath));
9522
+ const repoBytes = readConfinedBytes(repoDir, file.relativePath);
9523
+ const bytes = repoBytes.ok ? repoBytes.bytes : null;
9268
9524
  if (bytes === null || sha256(bytes) !== file.hashSha256) {
9269
9525
  unreplayable += 1;
9270
9526
  continue;
@@ -9304,7 +9560,7 @@ function auditSnapshot(options) {
9304
9560
  }
9305
9561
  const indexParent = path6__namespace.dirname(snapshotDir);
9306
9562
  const indexPath = path6__namespace.join(indexParent, "WORKSPACE.json");
9307
- if (fs8__namespace.existsSync(indexPath)) {
9563
+ if (fs3__namespace.existsSync(indexPath)) {
9308
9564
  const indexText = readText(indexPath);
9309
9565
  let members = [];
9310
9566
  let problem2 = null;
@@ -9339,7 +9595,7 @@ function auditSnapshot(options) {
9339
9595
  if (typeof member.files === "number" && member.files !== manifest.counts.totalFiles) {
9340
9596
  disagreements.push("file count");
9341
9597
  }
9342
- const sourceGone = typeof member.path === "string" && !fs8__namespace.existsSync(member.path) ? "Member " + memberName + " source directory is gone (" + member.path + "); the snapshot still describes it. Regenerate the workspace." : null;
9598
+ 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;
9343
9599
  checks.push(
9344
9600
  sourceGone !== null ? check("workspace.index", "The workspace index agrees with this member", "warning", "warn", sourceGone) : disagreements.length === 0 ? check(
9345
9601
  "workspace.index",
@@ -9361,30 +9617,37 @@ function auditSnapshot(options) {
9361
9617
  const scanBudget = options.maxScanBytes ?? 32 * 1024 * 1024;
9362
9618
  const leakHits = [];
9363
9619
  let scannedBytes = 0;
9364
- for (const relative9 of walk(snapshotDir)) {
9365
- if (!TEXT_ARTIFACT.test(relative9) || scannedBytes > scanBudget) continue;
9366
- if (relative9 === SIGNATURE_FILE) continue;
9367
- const text = readText(path6__namespace.join(snapshotDir, relative9));
9620
+ for (const relative10 of walk(snapshotDir)) {
9621
+ if (!TEXT_ARTIFACT.test(relative10) || scannedBytes > scanBudget) continue;
9622
+ if (relative10 === SIGNATURE_FILE) continue;
9623
+ let size;
9624
+ try {
9625
+ size = fs3__namespace.statSync(path6__namespace.join(snapshotDir, relative10)).size;
9626
+ } catch {
9627
+ continue;
9628
+ }
9629
+ if (scannedBytes + size > scanBudget) break;
9630
+ const text = snapshotText(snapshotDir, relative10);
9368
9631
  if (text === null) continue;
9369
9632
  scannedBytes += Buffer.byteLength(text, "utf8");
9370
9633
  let findingCount = 0;
9371
- if (/^parts[\\/].*\.md$/i.test(relative9)) {
9634
+ if (/^parts[\\/].*\.md$/i.test(relative10)) {
9372
9635
  let headerText = text;
9373
9636
  for (const section of parsePartSections(text)) {
9374
9637
  findingCount += scanAndRedactSecrets(section.body, rules, section.path).findings.length;
9375
9638
  headerText = headerText.replace(section.body, "");
9376
9639
  }
9377
- findingCount += scanAndRedactSecrets(headerText, rules, relative9).findings.length;
9640
+ findingCount += scanAndRedactSecrets(headerText, rules, relative10).findings.length;
9378
9641
  } else {
9379
- findingCount = scanAndRedactSecrets(text, rules, relative9).findings.length;
9642
+ findingCount = scanAndRedactSecrets(text, rules, relative10).findings.length;
9380
9643
  }
9381
9644
  if (findingCount > 0) {
9382
- leakHits.push(relative9 + " (" + findingCount + " line(s))");
9645
+ leakHits.push(relative10 + " (" + findingCount + " line(s))");
9383
9646
  }
9384
9647
  }
9385
9648
  const signatureRecordPath = path6__namespace.join(snapshotDir, SIGNATURE_FILE);
9386
- if (fs8__namespace.existsSync(signatureRecordPath)) {
9387
- const recordText = readText(signatureRecordPath);
9649
+ if (fs3__namespace.existsSync(signatureRecordPath)) {
9650
+ const recordText = snapshotText(snapshotDir, SIGNATURE_FILE);
9388
9651
  if (recordText !== null) {
9389
9652
  scannedBytes += Buffer.byteLength(recordText, "utf8");
9390
9653
  let scanText = recordText;
@@ -9424,11 +9687,17 @@ function auditSnapshot(options) {
9424
9687
  );
9425
9688
  const leakedFrom = [];
9426
9689
  let compared = 0;
9427
- const artifactTexts = readArtifactTexts(snapshotDir);
9690
+ const artifactTexts = readArtifactTexts(snapshotDir, scanBudget);
9428
9691
  const artifactContains = (token) => artifactTexts.some((text) => text.includes(token));
9429
9692
  for (const record of skippedSensitive.slice(0, 40)) {
9430
9693
  if (record.path.includes("[REDACTED") || compared > 400) continue;
9431
- const text = readText(path6__namespace.join(repoDir, record.path));
9694
+ try {
9695
+ if (fs3__namespace.statSync(path6__namespace.join(repoDir, record.path)).size > scanBudget) continue;
9696
+ } catch {
9697
+ continue;
9698
+ }
9699
+ const repoRead = readConfinedText(repoDir, record.path);
9700
+ const text = repoRead.ok ? repoRead.text : null;
9432
9701
  if (text === null) continue;
9433
9702
  for (const token of secretTokens(text)) {
9434
9703
  compared += 1;
@@ -9450,7 +9719,7 @@ function auditSnapshot(options) {
9450
9719
  "A value from " + sample([...new Set(leakedFrom)]) + " appears in the snapshot."
9451
9720
  )
9452
9721
  );
9453
- const pii = findHostPaths(snapshotDir, repoDir);
9722
+ const pii = findHostPaths(snapshotDir, repoDir, scanBudget);
9454
9723
  checks.push(
9455
9724
  pii.length === 0 ? check(
9456
9725
  "pii.paths",
@@ -9571,6 +9840,17 @@ function report(snapshotDir, repoDir, checks) {
9571
9840
  counts
9572
9841
  };
9573
9842
  }
9843
+ function safeRegularFile(cwd, absolute) {
9844
+ try {
9845
+ if (!fs3__namespace.lstatSync(absolute).isFile()) return false;
9846
+ const root = fs3__namespace.realpathSync(cwd);
9847
+ const real = fs3__namespace.realpathSync(absolute);
9848
+ const relative10 = path6__namespace.relative(root, real);
9849
+ return relative10 !== ".." && !relative10.startsWith(".." + path6__namespace.sep) && !path6__namespace.isAbsolute(relative10);
9850
+ } catch {
9851
+ return false;
9852
+ }
9853
+ }
9574
9854
  function describeMatcher(matcher) {
9575
9855
  if (typeof matcher === "string") return matcher;
9576
9856
  if (matcher instanceof RegExp) return String(matcher);
@@ -9582,23 +9862,23 @@ function describeMatcher(matcher) {
9582
9862
  function normalizeTarget(cwd, target) {
9583
9863
  const resolvedCwd = path6__namespace.resolve(cwd);
9584
9864
  const absolute = path6__namespace.resolve(resolvedCwd, target);
9585
- const relative9 = path6__namespace.relative(resolvedCwd, absolute);
9586
- if (relative9 === "" || relative9 === ".." || relative9.startsWith(`..${path6__namespace.sep}`) || path6__namespace.isAbsolute(relative9)) {
9865
+ const relative10 = path6__namespace.relative(resolvedCwd, absolute);
9866
+ if (relative10 === "" || relative10 === ".." || relative10.startsWith(`..${path6__namespace.sep}`) || path6__namespace.isAbsolute(relative10)) {
9587
9867
  return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
9588
9868
  }
9589
- return { relative: relative9.split(path6__namespace.sep).join("/"), outsideRoot: false };
9869
+ return { relative: relative10.split(path6__namespace.sep).join("/"), outsideRoot: false };
9590
9870
  }
9591
9871
  function findRuleMatch(rules, relativePath) {
9592
9872
  return rules.find(
9593
9873
  (rule) => matchRule(relativePath, rule.match)
9594
9874
  );
9595
9875
  }
9596
- function findRecordedAncestor(skipped, relative9, maskedPath2) {
9876
+ function findRecordedAncestor(skipped, relative10, maskedPath2) {
9597
9877
  let nearest;
9598
9878
  for (const record of skipped) {
9599
9879
  const ancestorPath = record.path;
9600
9880
  if (ancestorPath.length === 0) continue;
9601
- const isAncestor = relative9.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
9881
+ const isAncestor = relative10.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
9602
9882
  if (!isAncestor) continue;
9603
9883
  if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
9604
9884
  }
@@ -9607,15 +9887,15 @@ function findRecordedAncestor(skipped, relative9, maskedPath2) {
9607
9887
  function readManifest2(config) {
9608
9888
  const manifestPath = path6__namespace.resolve(config.cwd, config.outDir, "manifest.json");
9609
9889
  try {
9610
- return JSON.parse(fs8__namespace.readFileSync(manifestPath, "utf8"));
9890
+ return JSON.parse(fs3__namespace.readFileSync(manifestPath, "utf8"));
9611
9891
  } catch {
9612
9892
  return null;
9613
9893
  }
9614
9894
  }
9615
9895
  function explainPath(config, target) {
9616
9896
  const normalized = normalizeTarget(config.cwd, target);
9617
- const relative9 = normalized.relative;
9618
- const maskedPath2 = findSecretInPath(relative9, config.secretRules)?.masked ?? relative9;
9897
+ const relative10 = normalized.relative;
9898
+ const maskedPath2 = findSecretInPath(relative10, config.secretRules)?.masked ?? relative10;
9619
9899
  if (normalized.outsideRoot) {
9620
9900
  return {
9621
9901
  path: maskedPath2,
@@ -9625,10 +9905,14 @@ function explainPath(config, target) {
9625
9905
  detail: "path resolves outside the configured repository root and was not inspected"
9626
9906
  };
9627
9907
  }
9628
- const absolute = path6__namespace.join(config.cwd, relative9);
9908
+ const absolute = path6__namespace.join(config.cwd, relative10);
9909
+ const stagedBlob = config.staged === true ? readStagedBlob(config.cwd, relative10) : null;
9629
9910
  const result = {
9630
9911
  path: maskedPath2,
9631
- exists: fs8__namespace.existsSync(absolute),
9912
+ // `existsSync` follows a symlink, so an in-repo link to /etc/passwd answered "exists" for a
9913
+ // file the scanner refuses. `lstat` plus a canonical containment check keeps the answer about
9914
+ // a regular file the repository actually contains; a staged blob is the index's answer.
9915
+ exists: stagedBlob !== null || safeRegularFile(config.cwd, absolute),
9632
9916
  included: false
9633
9917
  };
9634
9918
  const collection = collectFiles(config.cwd, {
@@ -9643,11 +9927,11 @@ function explainPath(config, target) {
9643
9927
  // that is only missing because the walker dropped the tool's own output directory.
9644
9928
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
9645
9929
  (directory) => path6__namespace.relative(config.cwd, path6__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
9646
- ).filter((relative10) => relative10.length > 0 && !relative10.startsWith(".."))
9930
+ ).filter((relative11) => relative11.length > 0 && !relative11.startsWith(".."))
9647
9931
  });
9648
- if (!collection.files.includes(relative9)) {
9932
+ if (!collection.files.includes(relative10)) {
9649
9933
  const record = collection.skipped.find(
9650
- (entry2) => entry2.path === relative9 || entry2.path === maskedPath2
9934
+ (entry2) => entry2.path === relative10 || entry2.path === maskedPath2
9651
9935
  );
9652
9936
  if (record) {
9653
9937
  result.reason = record.reason;
@@ -9656,7 +9940,7 @@ function explainPath(config, target) {
9656
9940
  result.reason = "missing";
9657
9941
  result.detail = "no such file or directory, relative to the configured cwd";
9658
9942
  } else {
9659
- const ancestor = findRecordedAncestor(collection.skipped, relative9, maskedPath2);
9943
+ const ancestor = findRecordedAncestor(collection.skipped, relative10, maskedPath2);
9660
9944
  if (ancestor) {
9661
9945
  result.reason = ancestor.reason;
9662
9946
  result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
@@ -9676,11 +9960,11 @@ function explainPath(config, target) {
9676
9960
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
9677
9961
  ...config.staged === true ? { staged: true } : {}
9678
9962
  });
9679
- inScope = scope.paths.has(relative9);
9963
+ inScope = scope.paths.has(relative10);
9680
9964
  if (!inScope && config.withDependents === true) {
9681
9965
  inScope = importsChangedFile(
9682
- relative9,
9683
- importsOfFile(relative9, absolute),
9966
+ relative10,
9967
+ importsOfFile(relative10, absolute),
9684
9968
  scope.paths,
9685
9969
  buildImportResolver(collection.files.map((file) => ({ relativePath: file })), {
9686
9970
  tsconfig: tsconfigPathsFor(config.cwd)
@@ -9707,11 +9991,13 @@ function explainPath(config, target) {
9707
9991
  result.detail = "binary extension; generate skips it without reading and records `binary` in manifest.skipped[]";
9708
9992
  return result;
9709
9993
  }
9710
- let sizeOnDisk = null;
9711
- try {
9712
- sizeOnDisk = fs8__namespace.statSync(absolute).size;
9713
- } catch {
9714
- sizeOnDisk = null;
9994
+ let sizeOnDisk = stagedBlob?.length ?? null;
9995
+ if (sizeOnDisk === null) {
9996
+ try {
9997
+ sizeOnDisk = fs3__namespace.statSync(absolute).size;
9998
+ } catch {
9999
+ sizeOnDisk = null;
10000
+ }
9715
10001
  }
9716
10002
  if (sizeOnDisk !== null && sizeOnDisk > BINARY_SCAN_BYTES && isBinaryFile(absolute)) {
9717
10003
  result.included = false;
@@ -9719,10 +10005,10 @@ function explainPath(config, target) {
9719
10005
  result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
9720
10006
  return result;
9721
10007
  }
9722
- if (fs8__namespace.existsSync(absolute) && fs8__namespace.statSync(absolute).isFile()) {
10008
+ if (stagedBlob !== null || safeRegularFile(config.cwd, absolute)) {
9723
10009
  let buffer;
9724
10010
  try {
9725
- buffer = fs8__namespace.readFileSync(absolute);
10011
+ buffer = stagedBlob ?? fs3__namespace.readFileSync(absolute);
9726
10012
  } catch (err) {
9727
10013
  result.included = false;
9728
10014
  result.reason = "read-error";
@@ -9740,15 +10026,15 @@ function explainPath(config, target) {
9740
10026
  result.bytes = buffer.length;
9741
10027
  result.lines = countLines(text);
9742
10028
  if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
9743
- const { findings } = scanAndRedactSecrets(text, config.secretRules, relative9);
10029
+ const { findings } = scanAndRedactSecrets(text, config.secretRules, relative10);
9744
10030
  result.secretCount = findings.length;
9745
10031
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
9746
10032
  let inclusionMode = "full";
9747
- if (config.skeleton === true && isSkeletonizable(relative9)) {
9748
- const skeleton = skeletonizeTypeScript(text, relative9);
10033
+ if (config.skeleton === true && isSkeletonizable(relative10)) {
10034
+ const skeleton = skeletonizeTypeScript(text, relative10);
9749
10035
  if (skeleton.collapsed > 0) inclusionMode = "signatures";
9750
10036
  }
9751
- if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative9) && stripComments2(text, relative9).removed > 0) {
10037
+ if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative10) && stripComments2(text, relative10).removed > 0) {
9752
10038
  inclusionMode = "comments-stripped";
9753
10039
  }
9754
10040
  if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
@@ -9757,20 +10043,36 @@ function explainPath(config, target) {
9757
10043
  }
9758
10044
  result.inclusionMode = inclusionMode;
9759
10045
  }
9760
- result.layer = classifyLayer(relative9, config.layers);
9761
- result.kind = classifyKind(relative9, config.kinds);
9762
- result.language = detectLanguage(relative9);
9763
- const layerRule = findRuleMatch(config.layers, relative9);
10046
+ result.layer = classifyLayer(relative10, config.layers);
10047
+ result.kind = classifyKind(relative10, config.kinds);
10048
+ result.language = detectLanguage(relative10);
10049
+ const layerRule = findRuleMatch(config.layers, relative10);
9764
10050
  if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
9765
- const kindRule = findRuleMatch(config.kinds, relative9);
10051
+ const kindRule = findRuleMatch(config.kinds, relative10);
9766
10052
  if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
9767
10053
  const manifest = readManifest2(config);
9768
- const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative9) : void 0;
10054
+ const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative10) : void 0;
9769
10055
  result.part = entry?.part ?? null;
9770
10056
  if (entry === void 0) {
9771
- const record = manifest?.skipped?.find((skip) => skip.path === relative9);
10057
+ const record = manifest?.skipped?.find((skip) => skip.path === relative10);
9772
10058
  if (record !== void 0 && (record.reason === "not-selected" || record.reason === "unchanged")) {
9773
10059
  result.included = false;
10060
+ for (const key of [
10061
+ "layer",
10062
+ "layerMatch",
10063
+ "kind",
10064
+ "kindMatch",
10065
+ "language",
10066
+ "inclusionMode",
10067
+ "lines",
10068
+ "bytes",
10069
+ "encoding",
10070
+ "secretCount",
10071
+ "secrets"
10072
+ ]) {
10073
+ delete result[key];
10074
+ }
10075
+ result.part = null;
9774
10076
  result.reason = record.reason;
9775
10077
  result.detail = record.detail ?? (record.reason === "not-selected" ? "the snapshot was generated for a selection (--slice or --budget-tokens) that did not include this path" : "the snapshot was generated with a changed-files scope that did not include this path");
9776
10078
  }
@@ -9821,7 +10123,10 @@ const { parentPort, workerData } = require("node:worker_threads");
9821
10123
  (async () => {
9822
10124
  try {
9823
10125
  const mod = await import(workerData.entryUrl);
9824
- const loaded = await mod.loadConfigFileDetailed(workerData.cwd);
10126
+ const loaded =
10127
+ workerData.config === null || workerData.config === undefined
10128
+ ? await mod.loadConfigFileDetailed(workerData.cwd, { allowExecutableConfig: false })
10129
+ : { config: workerData.config, errors: [] };
9825
10130
  if (loaded.errors.length > 0) {
9826
10131
  parentPort.postMessage({ ok: false, message: loaded.errors.join("; ") });
9827
10132
  return;
@@ -9833,6 +10138,7 @@ const { parentPort, workerData } = require("node:worker_threads");
9833
10138
  const manifest = mod.generateSnapshot(config, {
9834
10139
  dryRun: workerData.dryRun === true,
9835
10140
  ...(workerData.narrow ?? {}),
10141
+ ...(workerData.source === undefined ? {} : { source: workerData.source }),
9836
10142
  ...(workerData.runId === undefined ? {} : { runId: workerData.runId }),
9837
10143
  });
9838
10144
  const skipCounts = new Map();
@@ -9873,7 +10179,7 @@ const { parentPort, workerData } = require("node:worker_threads");
9873
10179
  })();
9874
10180
  `;
9875
10181
  function generateInWorker(cwd, cliOptions, options = {}) {
9876
- return new Promise((resolve10) => {
10182
+ return new Promise((resolve11) => {
9877
10183
  let settled = false;
9878
10184
  let worker = null;
9879
10185
  const finish = (result) => {
@@ -9884,7 +10190,7 @@ function generateInWorker(cwd, cliOptions, options = {}) {
9884
10190
  if (!result.ok && options.runId !== void 0 && options.lockRoots !== void 0) {
9885
10191
  releaseAbandonedRun(options.lockRoots, options.runId);
9886
10192
  }
9887
- resolve10(result);
10193
+ resolve11(result);
9888
10194
  });
9889
10195
  };
9890
10196
  const isCjs = typeof __dirname !== "undefined";
@@ -9898,6 +10204,8 @@ function generateInWorker(cwd, cliOptions, options = {}) {
9898
10204
  cliOptions,
9899
10205
  dryRun: options.dryRun === true,
9900
10206
  narrow: options.narrow ?? {},
10207
+ ...options.config === void 0 ? {} : { config: options.config },
10208
+ ...options.source === void 0 ? {} : { source: options.source },
9901
10209
  ...options.runId === void 0 ? {} : { runId: options.runId }
9902
10210
  }
9903
10211
  });
@@ -9956,12 +10264,12 @@ function foldForComparison(value) {
9956
10264
  function canonicalPath(value) {
9957
10265
  const absolute = path6__namespace.resolve(value);
9958
10266
  try {
9959
- return fs8__namespace.realpathSync(absolute);
10267
+ return fs3__namespace.realpathSync(absolute);
9960
10268
  } catch {
9961
10269
  return absolute;
9962
10270
  }
9963
10271
  }
9964
- function isInside2(parent, child) {
10272
+ function isInside3(parent, child) {
9965
10273
  const foldedParent = foldForComparison(parent);
9966
10274
  const foldedChild = foldForComparison(child);
9967
10275
  return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path6__namespace.sep}`);
@@ -9969,7 +10277,7 @@ function isInside2(parent, child) {
9969
10277
  function resolveThroughExistingAncestor(target) {
9970
10278
  let existing = target;
9971
10279
  const missing = [];
9972
- while (!fs8__namespace.existsSync(existing)) {
10280
+ while (!fs3__namespace.existsSync(existing)) {
9973
10281
  missing.unshift(path6__namespace.basename(existing));
9974
10282
  const parent = path6__namespace.dirname(existing);
9975
10283
  if (parent === existing) break;
@@ -9986,7 +10294,7 @@ function resolveRoot(requested, context) {
9986
10294
  const absolute = path6__namespace.resolve(context.cwd, wanted);
9987
10295
  let stats;
9988
10296
  try {
9989
- stats = fs8__namespace.statSync(absolute);
10297
+ stats = fs3__namespace.statSync(absolute);
9990
10298
  } catch {
9991
10299
  return { ok: false, message: `"${wanted}" does not exist, so it cannot be a repository root.` };
9992
10300
  }
@@ -9995,7 +10303,7 @@ function resolveRoot(requested, context) {
9995
10303
  }
9996
10304
  const resolved = canonicalPath(absolute);
9997
10305
  for (const allowed of context.roots) {
9998
- if (isInside2(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
10306
+ if (isInside3(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
9999
10307
  }
10000
10308
  const shown = context.roots.join(", ");
10001
10309
  return {
@@ -10039,7 +10347,7 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
10039
10347
  const requested = overrides.outDir.trim();
10040
10348
  const permitted = allowedRoots !== void 0 && allowedRoots.length > 0 ? allowedRoots : [root];
10041
10349
  const resolved = resolveThroughExistingAncestor(path6__namespace.resolve(root, requested));
10042
- if (!permitted.some((allowed) => isInside2(canonicalPath(allowed), resolved))) {
10350
+ if (!permitted.some((allowed) => isInside3(canonicalPath(allowed), resolved))) {
10043
10351
  const shown = permitted.map((allowed) => canonicalPath(allowed)).join(", ");
10044
10352
  return {
10045
10353
  ok: false,
@@ -10061,6 +10369,14 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
10061
10369
  if (overrides.sarif === true) cliOptions.sarif = true;
10062
10370
  if (overrides.staged === true) cliOptions.staged = true;
10063
10371
  if (overrides.withDependents === true) cliOptions.withDependents = true;
10372
+ for (const key of ["only", "ignore"]) {
10373
+ const value = overrides[key];
10374
+ if (value === void 0) continue;
10375
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
10376
+ return { ok: false, message: `"${key}" must be an array of glob strings.` };
10377
+ }
10378
+ cliOptions[key] = value;
10379
+ }
10064
10380
  try {
10065
10381
  const config = resolveConfig(loaded.config, cliOptions, root);
10066
10382
  return {
@@ -10086,19 +10402,19 @@ function partPathFor(workspace, filename) {
10086
10402
  if (filename.length === 0 || filename.includes("\0")) return null;
10087
10403
  const partsDir = path6__namespace.resolve(workspace.root, workspace.config.outDir, "parts");
10088
10404
  const resolved = path6__namespace.resolve(partsDir, filename);
10089
- const relative9 = path6__namespace.relative(partsDir, resolved);
10090
- if (relative9.length === 0 || relative9.includes(path6__namespace.sep) || relative9.includes("/") || relative9.includes("\\") || path6__namespace.isAbsolute(relative9)) {
10405
+ const relative10 = path6__namespace.relative(partsDir, resolved);
10406
+ if (relative10.length === 0 || relative10.includes(path6__namespace.sep) || relative10.includes("/") || relative10.includes("\\") || path6__namespace.isAbsolute(relative10)) {
10091
10407
  return null;
10092
10408
  }
10093
10409
  let stats;
10094
10410
  try {
10095
- stats = fs8__namespace.lstatSync(resolved);
10411
+ stats = fs3__namespace.lstatSync(resolved);
10096
10412
  } catch {
10097
10413
  return null;
10098
10414
  }
10099
10415
  if (!stats.isFile()) return null;
10100
10416
  try {
10101
- if (path6__namespace.dirname(fs8__namespace.realpathSync(resolved)) !== fs8__namespace.realpathSync(partsDir)) return null;
10417
+ if (path6__namespace.dirname(fs3__namespace.realpathSync(resolved)) !== fs3__namespace.realpathSync(partsDir)) return null;
10102
10418
  } catch {
10103
10419
  return null;
10104
10420
  }
@@ -10107,30 +10423,27 @@ function partPathFor(workspace, filename) {
10107
10423
  function readManifest3(workspace) {
10108
10424
  const file = manifestPathFor(workspace);
10109
10425
  const shown = path6__namespace.relative(workspace.root, file).split(path6__namespace.sep).join("/") || file;
10110
- let stats;
10111
- try {
10112
- stats = fs8__namespace.statSync(file);
10113
- } catch {
10426
+ const confined = readConfinedText(path6__namespace.dirname(file), path6__namespace.basename(file));
10427
+ if (!confined.ok) {
10428
+ if (confined.reason === "missing") {
10429
+ return {
10430
+ ok: false,
10431
+ missing: true,
10432
+ message: `There is no snapshot manifest at ${shown}. Call snapshot_plan to preview what would be included, or snapshot_generate to write it.`
10433
+ };
10434
+ }
10114
10435
  return {
10115
10436
  ok: false,
10116
- missing: true,
10117
- message: `There is no snapshot manifest at ${shown}. Call snapshot_plan to preview what would be included, or snapshot_generate to write it.`
10437
+ missing: false,
10438
+ message: `${shown} could not be read as a snapshot manifest: ${confined.message}.`
10118
10439
  };
10119
10440
  }
10441
+ const stats = confined.stats;
10442
+ const raw = confined.text;
10120
10443
  const cached = manifestCache.get(file);
10121
10444
  if (cached && cached.mtimeMs === stats.mtimeMs && cached.ctimeMs === stats.ctimeMs && cached.size === stats.size) {
10122
10445
  return { ok: true, manifest: cached.manifest, file };
10123
10446
  }
10124
- let raw;
10125
- try {
10126
- raw = fs8__namespace.readFileSync(file, "utf8");
10127
- } catch (error) {
10128
- return {
10129
- ok: false,
10130
- missing: false,
10131
- message: `${shown} exists but could not be read: ${error instanceof Error ? error.message : String(error)}`
10132
- };
10133
- }
10134
10447
  let parsed;
10135
10448
  try {
10136
10449
  parsed = JSON.parse(raw);
@@ -10160,6 +10473,123 @@ function forgetManifest(file) {
10160
10473
  manifestCache.delete(file);
10161
10474
  }
10162
10475
 
10476
+ // src/security/regex.ts
10477
+ var MAX_PATTERN_LENGTH = 256;
10478
+ var MAX_QUANTIFIER_REPEAT = 1e4;
10479
+ function unsafeRegExpReason(source) {
10480
+ if (source.length === 0) return null;
10481
+ if (source.length > MAX_PATTERN_LENGTH) {
10482
+ return `the pattern is longer than ${MAX_PATTERN_LENGTH} characters`;
10483
+ }
10484
+ let inClass = false;
10485
+ let unbounded = 0;
10486
+ const groups = [];
10487
+ for (let index = 0; index < source.length; index += 1) {
10488
+ const char = source[index];
10489
+ if (char === "\\") {
10490
+ index += 1;
10491
+ continue;
10492
+ }
10493
+ if (inClass) {
10494
+ if (char === "]") inClass = false;
10495
+ continue;
10496
+ }
10497
+ if (char === "[") {
10498
+ inClass = true;
10499
+ continue;
10500
+ }
10501
+ if (char === "(") {
10502
+ groups.push({ quantified: false, alternation: false });
10503
+ continue;
10504
+ }
10505
+ if (char === ")") {
10506
+ const group = groups.pop();
10507
+ if (group === void 0) continue;
10508
+ if (isQuantifiedAt(source, index + 1)) {
10509
+ if (group.quantified || group.alternation) {
10510
+ return "a quantified group contains another quantifier or an alternation";
10511
+ }
10512
+ group.quantified = true;
10513
+ } else if (isOptionalQuantifierAt(source, index + 1)) {
10514
+ group.quantified = true;
10515
+ }
10516
+ const parent = groups[groups.length - 1];
10517
+ if (parent !== void 0) {
10518
+ parent.quantified = parent.quantified || group.quantified;
10519
+ parent.alternation = parent.alternation || group.alternation;
10520
+ }
10521
+ continue;
10522
+ }
10523
+ if (char === "|") {
10524
+ const group = groups[groups.length - 1];
10525
+ if (group !== void 0) group.alternation = true;
10526
+ continue;
10527
+ }
10528
+ if (char === "?") {
10529
+ const previous = source[index - 1];
10530
+ if (previous !== "(" && previous !== "?" && previous !== "*" && previous !== "+" && previous !== "}") {
10531
+ const group = groups[groups.length - 1];
10532
+ if (group !== void 0) group.quantified = true;
10533
+ }
10534
+ continue;
10535
+ }
10536
+ if (char === "*" || char === "+") {
10537
+ unbounded += 1;
10538
+ const group = groups[groups.length - 1];
10539
+ if (group !== void 0) group.quantified = true;
10540
+ continue;
10541
+ }
10542
+ if (char === "{") {
10543
+ const close = source.indexOf("}", index + 1);
10544
+ if (close === -1) continue;
10545
+ const body = source.slice(index + 1, close);
10546
+ const match = /^(\d+)(?:,(\d*))?$/.exec(body);
10547
+ if (match === null) {
10548
+ index = close;
10549
+ continue;
10550
+ }
10551
+ const max = match[2] === void 0 ? Number(match[1]) : match[2] === "" ? Infinity : Number(match[2]);
10552
+ if (max > MAX_QUANTIFIER_REPEAT) {
10553
+ return "a repetition bound is larger than the search budget can evaluate safely";
10554
+ }
10555
+ if (max === Infinity) unbounded += 1;
10556
+ const group = groups[groups.length - 1];
10557
+ if (group !== void 0) group.quantified = true;
10558
+ index = close;
10559
+ }
10560
+ }
10561
+ if (unbounded > 1) {
10562
+ return "the pattern has more than one unbounded repetition";
10563
+ }
10564
+ return null;
10565
+ }
10566
+ function isOptionalQuantifierAt(source, start) {
10567
+ if (source[start] === "?") return true;
10568
+ if (source[start] !== "{") return false;
10569
+ const close = source.indexOf("}", start + 1);
10570
+ if (close === -1) return false;
10571
+ const body = source.slice(start + 1, close);
10572
+ const match = /^(\d+)(?:,(\d*))?$/.exec(body);
10573
+ if (match === null) return false;
10574
+ const minimum = Number(match[1]);
10575
+ if (match[2] === void 0) return minimum <= 1;
10576
+ const maximum = match[2] === "" ? Infinity : Number(match[2]);
10577
+ return maximum <= 1;
10578
+ }
10579
+ function isQuantifiedAt(source, start) {
10580
+ const char = source[start];
10581
+ if (char === "*" || char === "+") return true;
10582
+ if (char !== "{") return false;
10583
+ const close = source.indexOf("}", start + 1);
10584
+ if (close === -1) return false;
10585
+ const body = source.slice(start + 1, close);
10586
+ const match = /^(\d+)(?:,(\d*))?$/.exec(body);
10587
+ if (match === null) return false;
10588
+ if (match[2] === void 0) return Number(match[1]) > 1;
10589
+ if (match[2] === "") return true;
10590
+ return Number(match[2]) > 1;
10591
+ }
10592
+
10163
10593
  // src/mcp/tools.ts
10164
10594
  var MAX_SEARCH_BYTES = 4 * 1024 * 1024;
10165
10595
  var READ_ONLY = {
@@ -10191,6 +10621,16 @@ var OUT_DIR_PROPERTY = {
10191
10621
  };
10192
10622
  var outDirOverride = (args) => ({ outDir: args.outDir });
10193
10623
  var SCOPE_PROPERTIES = {
10624
+ only: {
10625
+ type: "array",
10626
+ items: { type: "string" },
10627
+ description: "Globs to include: replaces the config allow-list for this run."
10628
+ },
10629
+ ignore: {
10630
+ type: "array",
10631
+ items: { type: "string" },
10632
+ description: "Globs to exclude, added to the config deny-list for this run."
10633
+ },
10194
10634
  maxPartTokens: {
10195
10635
  type: "string",
10196
10636
  description: 'Token ceiling per part, for example 32000 or "32k". Narrower than maxPartBytes; it converts at four bytes per token.'
@@ -10225,7 +10665,9 @@ function workspaceOverrides(args) {
10225
10665
  sarif: args.sarif,
10226
10666
  changedSince: args.changedSince,
10227
10667
  staged: args.staged,
10228
- withDependents: args.withDependents
10668
+ withDependents: args.withDependents,
10669
+ only: args.only,
10670
+ ignore: args.ignore
10229
10671
  };
10230
10672
  }
10231
10673
  function failure(message) {
@@ -10261,11 +10703,11 @@ function toRelativePath(root, value) {
10261
10703
  if (cleaned.length === 0 || cleaned.includes("\0")) return null;
10262
10704
  const resolvedRoot = path6__namespace.resolve(root);
10263
10705
  const absolute = path6__namespace.resolve(resolvedRoot, cleaned);
10264
- const relative9 = path6__namespace.relative(resolvedRoot, absolute);
10265
- if (relative9 === "" || relative9 === ".." || relative9.startsWith(`..${path6__namespace.sep}`) || path6__namespace.isAbsolute(relative9)) {
10706
+ const relative10 = path6__namespace.relative(resolvedRoot, absolute);
10707
+ if (relative10 === "" || relative10 === ".." || relative10.startsWith(`..${path6__namespace.sep}`) || path6__namespace.isAbsolute(relative10)) {
10266
10708
  return null;
10267
10709
  }
10268
- return relative9.split(path6__namespace.sep).join("/");
10710
+ return relative10.split(path6__namespace.sep).join("/");
10269
10711
  }
10270
10712
  function symbolsOf(entry) {
10271
10713
  const summary = entry.summary;
@@ -10358,16 +10800,15 @@ var historyTool = {
10358
10800
  async handler(args, context) {
10359
10801
  const prepared = await prepare(args, context, outDirOverride(args));
10360
10802
  if (!prepared.ok) return prepared.outcome;
10361
- const reportPath = path6__namespace.resolve(prepared.workspace.root, prepared.workspace.config.outDir, "reports", "log.md");
10362
- let text;
10363
- try {
10364
- text = fs8__namespace.readFileSync(reportPath, "utf8");
10365
- } catch {
10803
+ const snapshotDir = path6__namespace.resolve(prepared.workspace.root, prepared.workspace.config.outDir);
10804
+ const reportRead = readConfinedText(snapshotDir, path6__namespace.posix.join("reports", "log.md"));
10805
+ if (!reportRead.ok) {
10366
10806
  return {
10367
- 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.",
10807
+ 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.",
10368
10808
  isError: true
10369
10809
  };
10370
10810
  }
10811
+ const text = reportRead.text;
10371
10812
  const manifestRead = readManifest3(prepared.workspace);
10372
10813
  const recordedLog = manifestRead.ok ? manifestRead.manifest.artifacts?.log : void 0;
10373
10814
  if (recordedLog !== void 0 && recordedLog !== null) {
@@ -10428,7 +10869,7 @@ var budgetTool = {
10428
10869
  ...args.includeTests === true ? { includeTests: true } : {}
10429
10870
  });
10430
10871
  const paths = new Set(plan.files.map((file) => file.path));
10431
- const gained = [...paths].filter((path16) => !previous.has(path16)).sort();
10872
+ const gained = [...paths].filter((path17) => !previous.has(path17)).sort();
10432
10873
  previous = paths;
10433
10874
  rows.push({
10434
10875
  budget,
@@ -10531,21 +10972,22 @@ var workspaceTool = {
10531
10972
  async handler(args, context) {
10532
10973
  const prepared = await prepare(args, context, outDirOverride(args));
10533
10974
  if (!prepared.ok) return prepared.outcome;
10534
- const index = path6__namespace.resolve(
10535
- prepared.workspace.root,
10536
- prepared.workspace.config.outDir,
10537
- "WORKSPACE.json"
10538
- );
10539
- let text;
10540
- try {
10541
- text = fs8__namespace.readFileSync(index, "utf8");
10542
- } catch {
10975
+ const snapshotDir = path6__namespace.resolve(prepared.workspace.root, prepared.workspace.config.outDir);
10976
+ const index = path6__namespace.join(snapshotDir, "WORKSPACE.json");
10977
+ const read = readConfinedText(snapshotDir, "WORKSPACE.json");
10978
+ if (!read.ok) {
10543
10979
  return {
10544
- text: "No workspace index at " + index + ". Generate one with `generate --workspace member-a,member-b`; a single snapshot has no members to list.",
10980
+ 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.",
10545
10981
  isError: true
10546
10982
  };
10547
10983
  }
10548
- const document = JSON.parse(text);
10984
+ const text = read.text;
10985
+ let document;
10986
+ try {
10987
+ document = JSON.parse(text);
10988
+ } catch (error) {
10989
+ return { text: "WORKSPACE.json is not valid JSON: " + error.message, isError: true };
10990
+ }
10549
10991
  const members = document.members ?? [];
10550
10992
  const links = document.links ?? [];
10551
10993
  const lines = [
@@ -10685,6 +11127,10 @@ var routesTool = {
10685
11127
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
10686
11128
  let filter = null;
10687
11129
  if (typeof args.pattern === "string") {
11130
+ const unsafe = unsafeRegExpReason(args.pattern);
11131
+ if (unsafe !== null) {
11132
+ return { text: "pattern is refused: " + unsafe + ".", isError: true };
11133
+ }
10688
11134
  try {
10689
11135
  filter = new RegExp(args.pattern, "i");
10690
11136
  } catch (error) {
@@ -10740,7 +11186,7 @@ var cyclesTool = {
10740
11186
  tsconfig: tsconfigPathsFor(prepared.workspace.root)
10741
11187
  });
10742
11188
  const edges = /* @__PURE__ */ new Map();
10743
- for (const path16 of byPath.keys()) edges.set(path16, []);
11189
+ for (const path17 of byPath.keys()) edges.set(path17, []);
10744
11190
  for (const entry of read.manifest.indexes.imports.byFile) {
10745
11191
  const targets = edges.get(entry.path);
10746
11192
  if (targets === void 0) continue;
@@ -10828,6 +11274,12 @@ var searchTool = {
10828
11274
  const cap = Math.max(1, Math.min(500, typeof args.maxMatches === "number" ? args.maxMatches : 50));
10829
11275
  const contextLines = Math.max(0, Math.min(10, typeof args.contextLines === "number" ? args.contextLines : 0));
10830
11276
  let pattern;
11277
+ if (args.regex === true) {
11278
+ const unsafe = unsafeRegExpReason(query);
11279
+ if (unsafe !== null) {
11280
+ return { text: "regex is refused: " + unsafe + ".", isError: true };
11281
+ }
11282
+ }
10831
11283
  try {
10832
11284
  pattern = args.regex === true ? new RegExp(query, "i") : new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i");
10833
11285
  } catch (error) {
@@ -10846,15 +11298,21 @@ var searchTool = {
10846
11298
  if (partPath === null) continue;
10847
11299
  let text;
10848
11300
  try {
10849
- text = fs8__namespace.readFileSync(partPath, "utf8");
11301
+ text = fs3__namespace.readFileSync(partPath, "utf8");
10850
11302
  } catch {
10851
11303
  continue;
10852
11304
  }
10853
- if (Buffer.byteLength(text, "utf8") > MAX_SEARCH_BYTES) {
11305
+ const partBytes = Buffer.byteLength(text, "utf8");
11306
+ if (partBytes > MAX_SEARCH_BYTES) {
10854
11307
  skippedOversize.push(part.filename);
11308
+ truncated = true;
10855
11309
  continue;
10856
11310
  }
10857
- scanned += text.length;
11311
+ if (scanned + partBytes > MAX_SEARCH_BYTES) {
11312
+ truncated = true;
11313
+ break;
11314
+ }
11315
+ scanned += partBytes;
10858
11316
  for (const section of parsePartSections(text)) {
10859
11317
  if (matches.length >= cap) {
10860
11318
  truncated = true;
@@ -10999,7 +11457,7 @@ var reviewTool = {
10999
11457
  }
11000
11458
  let section = null;
11001
11459
  try {
11002
- section = findSection(parsePartSections(fs8__namespace.readFileSync(partPath, "utf8")), file.relativePath);
11460
+ section = findSection(parsePartSections(fs3__namespace.readFileSync(partPath, "utf8")), file.relativePath);
11003
11461
  } catch {
11004
11462
  section = null;
11005
11463
  }
@@ -11089,31 +11547,31 @@ var diffContextTool = {
11089
11547
  const changed = [];
11090
11548
  const text = [];
11091
11549
  let used = 0;
11092
- for (const path16 of wanted) {
11093
- const file = byPath.get(path16.toLowerCase());
11550
+ for (const path17 of wanted) {
11551
+ const file = byPath.get(path17.toLowerCase());
11094
11552
  if (file === void 0) {
11095
- missing.push(path16);
11553
+ missing.push(path17);
11096
11554
  continue;
11097
11555
  }
11098
11556
  const partPath = partPathFor(workspace, file.part);
11099
11557
  if (partPath === null) {
11100
- missing.push(path16 + " (part missing)");
11558
+ missing.push(path17 + " (part missing)");
11101
11559
  continue;
11102
11560
  }
11103
11561
  let section;
11104
11562
  try {
11105
- section = findSection(parsePartSections(fs8__namespace.readFileSync(partPath, "utf8")), file.relativePath);
11563
+ section = findSection(parsePartSections(fs3__namespace.readFileSync(partPath, "utf8")), file.relativePath);
11106
11564
  } catch {
11107
11565
  section = null;
11108
11566
  }
11109
11567
  if (section === null) {
11110
- missing.push(path16 + " (section not found)");
11568
+ missing.push(path17 + " (section not found)");
11111
11569
  continue;
11112
11570
  }
11113
11571
  const window = windowText(section.body, 1, linesPerFile);
11114
11572
  const tokens = Math.max(1, Math.ceil(Buffer.byteLength(window.text, "utf8") / 4));
11115
11573
  if (used + tokens > budget) {
11116
- missing.push(path16 + " (budget)");
11574
+ missing.push(path17 + " (budget)");
11117
11575
  continue;
11118
11576
  }
11119
11577
  used += tokens;
@@ -11188,7 +11646,7 @@ var symbolTool = {
11188
11646
  if (partPath === null) continue;
11189
11647
  let partText;
11190
11648
  try {
11191
- partText = fs8__namespace.readFileSync(partPath, "utf8");
11649
+ partText = fs3__namespace.readFileSync(partPath, "utf8");
11192
11650
  } catch {
11193
11651
  continue;
11194
11652
  }
@@ -11220,28 +11678,39 @@ var symbolTool = {
11220
11678
  };
11221
11679
  }
11222
11680
  const callSites = [];
11681
+ let referencesTruncated = false;
11223
11682
  if (args.references !== false) {
11224
11683
  const limit = Math.max(1, typeof args.maxReferences === "number" ? args.maxReferences : 20);
11225
11684
  const definitionKeys = new Set(matches.map((match) => match.path + ":" + match.line));
11226
11685
  const word = new RegExp("\\b" + name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\b");
11227
- const parts = /* @__PURE__ */ new Map();
11686
+ const sectionsByPart = /* @__PURE__ */ new Map();
11228
11687
  let scanned = 0;
11229
11688
  for (const file of read.manifest.files) {
11230
11689
  if (callSites.length >= limit) break;
11231
11690
  const partPath = partPathFor(workspace, file.part);
11232
11691
  if (partPath === null) continue;
11233
- let partText = parts.get(partPath);
11234
- if (partText === void 0) {
11692
+ let sections = sectionsByPart.get(partPath);
11693
+ if (sections === void 0) {
11694
+ if (scanned >= MAX_SEARCH_BYTES) {
11695
+ referencesTruncated = true;
11696
+ break;
11697
+ }
11698
+ let partText;
11235
11699
  try {
11236
- partText = fs8__namespace.readFileSync(partPath, "utf8");
11700
+ partText = fs3__namespace.readFileSync(partPath, "utf8");
11237
11701
  } catch {
11238
11702
  continue;
11239
11703
  }
11240
- parts.set(partPath, partText);
11704
+ const bytes = Buffer.byteLength(partText, "utf8");
11705
+ if (scanned + bytes > MAX_SEARCH_BYTES) {
11706
+ referencesTruncated = true;
11707
+ break;
11708
+ }
11709
+ scanned += bytes;
11710
+ sections = parsePartSections(partText);
11711
+ sectionsByPart.set(partPath, sections);
11241
11712
  }
11242
- if (scanned > MAX_SEARCH_BYTES) break;
11243
- scanned += Buffer.byteLength(partText, "utf8");
11244
- const section = findSection(parsePartSections(partText), file.relativePath);
11713
+ const section = findSection(sections, file.relativePath);
11245
11714
  if (section === null) continue;
11246
11715
  const bodyLines = section.body.split("\n");
11247
11716
  for (let index = 0; index < bodyLines.length && callSites.length < limit; index += 1) {
@@ -11255,8 +11724,11 @@ var symbolTool = {
11255
11724
  }
11256
11725
  }
11257
11726
  }
11258
- 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")));
11259
- return { text, structured: { found: matches.length, matches, references: callSites } };
11727
+ 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." : "");
11728
+ return {
11729
+ text,
11730
+ structured: { found: matches.length, matches, references: callSites, truncated: referencesTruncated }
11731
+ };
11260
11732
  }
11261
11733
  };
11262
11734
  var contextTool = {
@@ -11329,7 +11801,7 @@ var contextTool = {
11329
11801
  }
11330
11802
  if (!sectionsByPart.has(file.part)) {
11331
11803
  try {
11332
- sectionsByPart.set(file.part, parsePartSections(fs8__namespace.readFileSync(partPath, "utf8")));
11804
+ sectionsByPart.set(file.part, parsePartSections(fs3__namespace.readFileSync(partPath, "utf8")));
11333
11805
  } catch {
11334
11806
  sectionsByPart.set(file.part, null);
11335
11807
  }
@@ -11414,6 +11886,10 @@ var queryTool = {
11414
11886
  const maxFiles = typeof args.maxFiles === "number" ? Math.min(200, Math.max(1, args.maxFiles)) : 40;
11415
11887
  let pattern = null;
11416
11888
  if (typeof args.pathPattern === "string") {
11889
+ const unsafe = unsafeRegExpReason(args.pathPattern);
11890
+ if (unsafe !== null) {
11891
+ return { text: "pathPattern is refused: " + unsafe + ".", isError: true };
11892
+ }
11417
11893
  try {
11418
11894
  pattern = new RegExp(args.pathPattern, "i");
11419
11895
  } catch (error) {
@@ -11563,7 +12039,7 @@ var answerTool = {
11563
12039
  let partText = parts.get(partPath);
11564
12040
  if (partText === void 0) {
11565
12041
  try {
11566
- partText = fs8__namespace.readFileSync(partPath, "utf8");
12042
+ partText = fs3__namespace.readFileSync(partPath, "utf8");
11567
12043
  } catch {
11568
12044
  omitted.push({ path: planned.path, reason: "its part could not be read" });
11569
12045
  continue;
@@ -11799,7 +12275,12 @@ var planTool = {
11799
12275
  const prepared = await prepare(args, context, workspaceOverrides(args));
11800
12276
  if (!prepared.ok) return prepared.outcome;
11801
12277
  const workspace = prepared.workspace;
11802
- const result = await generateInWorker(workspace.root, workspace.cliOptions, { dryRun: true });
12278
+ const controller = new AbortController();
12279
+ context.onCancel?.(() => controller.abort());
12280
+ const result = await generateInWorker(workspace.root, workspace.cliOptions, {
12281
+ dryRun: true,
12282
+ signal: controller.signal
12283
+ });
11803
12284
  if (!result.ok) return failure(result.message);
11804
12285
  const summary = result.summary;
11805
12286
  const topReasons = summary.skipReasons;
@@ -11889,16 +12370,6 @@ var generateTool = {
11889
12370
  minimum: 500,
11890
12371
  description: "Fit the snapshot into this token budget, highest value first."
11891
12372
  },
11892
- only: {
11893
- type: "array",
11894
- items: { type: "string" },
11895
- description: "Globs to include: replaces the config allow-list for this run."
11896
- },
11897
- ignore: {
11898
- type: "array",
11899
- items: { type: "string" },
11900
- description: "Globs to exclude, added to the config deny-list for this run."
11901
- },
11902
12373
  ...SCOPE_PROPERTIES
11903
12374
  },
11904
12375
  additionalProperties: false
@@ -12017,7 +12488,12 @@ function configAsGenerated(workspace, manifest) {
12017
12488
  ...cli.includeLogs !== void 0 || configured("logCount") || recorded?.logCount !== void 0 ? { logCount: choose("logCount", recorded?.logCount, workspace.config.logCount, cli.includeLogs) } : {},
12018
12489
  ...cli.skeleton === true || configured("skeleton") || recorded?.skeleton !== void 0 ? { skeleton: choose("skeleton", recorded?.skeleton, workspace.config.skeleton, cli.skeleton === true ? true : void 0) } : {},
12019
12490
  ...cli.sarif === true || configured("sarif") || recorded?.sarif !== void 0 ? { sarif: choose("sarif", recorded?.sarif, workspace.config.sarif, cli.sarif === true ? true : void 0) } : {},
12020
- ...configured("maxParts") || recorded?.maxParts !== void 0 ? { maxParts: choose("maxParts", recorded?.maxParts, workspace.config.maxParts) } : {}
12491
+ ...configured("maxParts") || recorded?.maxParts !== void 0 ? { maxParts: choose("maxParts", recorded?.maxParts, workspace.config.maxParts) } : {},
12492
+ ...cli.maxPartTokens !== void 0 || configured("maxPartTokens") || recorded?.maxPartTokens !== void 0 ? { maxPartTokens: choose("maxPartTokens", recorded?.maxPartTokens, workspace.config.maxPartTokens, cli.maxPartTokens) } : {},
12493
+ ...cli.changedSince !== void 0 || configured("changedSince") || recorded?.changedSince !== void 0 ? { changedSince: choose("changedSince", recorded?.changedSince, workspace.config.changedSince, cli.changedSince) } : {},
12494
+ ...cli.staged === true || configured("staged") || recorded?.staged !== void 0 ? { staged: choose("staged", recorded?.staged, workspace.config.staged, cli.staged === true ? true : void 0) } : {},
12495
+ ...cli.withDependents === true || configured("withDependents") || recorded?.withDependents !== void 0 ? { withDependents: choose("withDependents", recorded?.withDependents, workspace.config.withDependents, cli.withDependents === true ? true : void 0) } : {},
12496
+ ...configured("promptTask") || recorded?.promptTask !== void 0 ? { promptTask: choose("promptTask", recorded?.promptTask, workspace.config.promptTask) } : {}
12021
12497
  };
12022
12498
  }
12023
12499
  var validateTool = {
@@ -12399,7 +12875,7 @@ var readTool = {
12399
12875
  }
12400
12876
  let partText;
12401
12877
  try {
12402
- partText = fs8__namespace.readFileSync(partPath, "utf8");
12878
+ partText = fs3__namespace.readFileSync(partPath, "utf8");
12403
12879
  } catch {
12404
12880
  return failure(
12405
12881
  `${entry.part} could not be read, so the snapshot is damaged. Run snapshot_generate to rebuild it.`
@@ -12652,12 +13128,12 @@ async function runStdioServer(options) {
12652
13128
  });
12653
13129
  return writeChain;
12654
13130
  };
12655
- const MAX_IN_FLIGHT = 4;
13131
+ const MAX_IN_FLIGHT2 = 4;
12656
13132
  let inFlight = 0;
12657
13133
  let inputEnded = false;
12658
13134
  let resolveDone = () => void 0;
12659
- const finished = new Promise((resolve10) => {
12660
- resolveDone = resolve10;
13135
+ const finished = new Promise((resolve11) => {
13136
+ resolveDone = resolve11;
12661
13137
  });
12662
13138
  const finishIfIdle = () => {
12663
13139
  if (inputEnded && inFlight === 0) resolveDone(0);
@@ -12687,14 +13163,26 @@ async function runStdioServer(options) {
12687
13163
  errorResponse(
12688
13164
  id,
12689
13165
  ERROR_CODES.overloaded,
12690
- `The server is already handling ${MAX_IN_FLIGHT} requests; retry this one when it is free.`
13166
+ `The server is already handling ${MAX_IN_FLIGHT2} requests; retry this one when it is free.`
12691
13167
  )
12692
13168
  );
12693
13169
  };
13170
+ const isCancellation = (line) => {
13171
+ try {
13172
+ const parsed = JSON.parse(line);
13173
+ return parsed !== null && typeof parsed === "object" && parsed.method === "notifications/cancelled";
13174
+ } catch {
13175
+ return false;
13176
+ }
13177
+ };
12694
13178
  const stopReading = createLineReader(process.stdin, {
12695
13179
  onOverflow: (bytes) => log(`mcp: discarded an oversized message (${bytes} bytes)`),
12696
13180
  onLine: (line) => {
12697
- if (inFlight >= MAX_IN_FLIGHT) {
13181
+ if (inFlight >= MAX_IN_FLIGHT2) {
13182
+ if (isCancellation(line)) {
13183
+ void handleLine(line);
13184
+ return;
13185
+ }
12698
13186
  rejectOverloaded(line);
12699
13187
  return;
12700
13188
  }
@@ -12727,7 +13215,12 @@ function resolveSafeOutputDirs(config) {
12727
13215
  const outDir = path6__namespace.resolve(cwd, config.outDir);
12728
13216
  const tmpDir = path6__namespace.resolve(cwd, config.tmpDir);
12729
13217
  const root = path6__namespace.parse(cwd).root;
12730
- const contains = (parent, child) => child === parent || child.startsWith(`${parent}${path6__namespace.sep}`);
13218
+ const fold = (value) => process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
13219
+ const contains = (parent, child) => {
13220
+ const foldedParent = fold(parent);
13221
+ const foldedChild = fold(child);
13222
+ return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path6__namespace.sep}`);
13223
+ };
12731
13224
  const reject = (reason) => {
12732
13225
  throw new Error(
12733
13226
  `Refusing to generate: ${reason}. outDir=${outDir} tmpDir=${tmpDir} cwd=${cwd}`
@@ -12753,12 +13246,12 @@ var SNAPSHOT_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9
12753
13246
  var SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/;
12754
13247
  function readOwnershipMarker(dir) {
12755
13248
  const markerPath = path6__namespace.join(dir, OWNERSHIP_MARKER);
12756
- if (!fs8__namespace.existsSync(markerPath)) {
13249
+ if (!fs3__namespace.existsSync(markerPath)) {
12757
13250
  return { marker: null, problem: "it holds no .codebase-snapshot marker" };
12758
13251
  }
12759
13252
  let raw;
12760
13253
  try {
12761
- raw = fs8__namespace.readFileSync(markerPath, "utf8");
13254
+ raw = fs3__namespace.readFileSync(markerPath, "utf8");
12762
13255
  } catch {
12763
13256
  return { marker: null, problem: "its .codebase-snapshot marker could not be read" };
12764
13257
  }
@@ -12845,7 +13338,7 @@ function canonicalLockTarget(targetPath) {
12845
13338
  const tail = [];
12846
13339
  for (; ; ) {
12847
13340
  try {
12848
- return path6__namespace.join(fs8__namespace.realpathSync(existing), ...tail);
13341
+ return path6__namespace.join(fs3__namespace.realpathSync(existing), ...tail);
12849
13342
  } catch {
12850
13343
  const parent = path6__namespace.dirname(existing);
12851
13344
  if (parent === existing) return resolved;
@@ -12862,13 +13355,13 @@ function releaseAbandonedRun(stagingRoots, runId) {
12862
13355
  for (const root of new Set(stagingRoots)) {
12863
13356
  const lockPath = lockPathFor(root);
12864
13357
  try {
12865
- const payload = JSON.parse(fs8__namespace.readFileSync(lockPath, "utf8"));
12866
- if (payload.runId === runId) fs8__namespace.rmSync(lockPath, { force: true });
13358
+ const payload = JSON.parse(fs3__namespace.readFileSync(lockPath, "utf8"));
13359
+ if (payload.runId === runId) fs3__namespace.rmSync(lockPath, { force: true });
12867
13360
  } catch {
12868
13361
  }
12869
13362
  let entries;
12870
13363
  try {
12871
- entries = fs8__namespace.readdirSync(root);
13364
+ entries = fs3__namespace.readdirSync(root);
12872
13365
  } catch {
12873
13366
  continue;
12874
13367
  }
@@ -12878,7 +13371,7 @@ function releaseAbandonedRun(stagingRoots, runId) {
12878
13371
  const { marker } = readOwnershipMarker(directory);
12879
13372
  if (marker?.runId !== runId) continue;
12880
13373
  try {
12881
- fs8__namespace.rmSync(directory, { recursive: true, force: true });
13374
+ fs3__namespace.rmSync(directory, { recursive: true, force: true });
12882
13375
  } catch {
12883
13376
  }
12884
13377
  }
@@ -13042,7 +13535,7 @@ var COMMAND_OPTION_SCOPE = {
13042
13535
  "version"
13043
13536
  ],
13044
13537
  diff: ["format", "mode", "no-config", "no-update-check", "help", "version"],
13045
- describe: ["format", "mode", "help", "version"],
13538
+ describe: ["format", "mode", "no-update-check", "help", "version"],
13046
13539
  init: [
13047
13540
  "install-hook",
13048
13541
  "cwd",
@@ -13063,7 +13556,7 @@ var COMMAND_OPTION_SCOPE = {
13063
13556
  "help",
13064
13557
  "version"
13065
13558
  ],
13066
- skill: ["cwd", "format", "mode", "install", "target", "help", "version"],
13559
+ skill: ["cwd", "format", "mode", "install", "target", "no-update-check", "help", "version"],
13067
13560
  // `mcp` reads the repository, so it takes --cwd. It has no --format: stdout carries JSON-RPC
13068
13561
  // messages, and there is no second shape to choose, so offering the flag would be a lie.
13069
13562
  serve: ["port", "host", "token", "no-auth", "allow-private", "cwd", "no-update-check", "help"],
@@ -13122,6 +13615,7 @@ var COMMAND_ORDER = [
13122
13615
  "health",
13123
13616
  "report",
13124
13617
  "explain",
13618
+ "update",
13125
13619
  "init",
13126
13620
  "setup",
13127
13621
  "diff",
@@ -13514,24 +14008,28 @@ function buildAgentContract() {
13514
14008
  {
13515
14009
  flag: "--only",
13516
14010
  type: "string",
14011
+ default: "unset",
13517
14012
  summary: "Comma-separated globs to include: overrides the config include list for this run.",
13518
14013
  appliesTo: optionAppliesTo("only")
13519
14014
  },
13520
14015
  {
13521
14016
  flag: "--ignore",
13522
14017
  type: "string",
14018
+ default: "unset",
13523
14019
  summary: "Comma-separated globs to exclude, added to the config exclude list for this run.",
13524
14020
  appliesTo: optionAppliesTo("ignore")
13525
14021
  },
13526
14022
  {
13527
14023
  flag: "--remove-empty-lines",
13528
14024
  type: "boolean",
14025
+ default: false,
13529
14026
  summary: "Drop blank and whitespace-only lines from emitted bodies; line numbers no longer match the source.",
13530
14027
  appliesTo: optionAppliesTo("remove-empty-lines")
13531
14028
  },
13532
14029
  {
13533
14030
  flag: "--all-members",
13534
14031
  type: "boolean",
14032
+ default: false,
13535
14033
  summary: "Audit every snapshot a --workspace run wrote, not only the one at outDir.",
13536
14034
  appliesTo: optionAppliesTo("all-members")
13537
14035
  },
@@ -14142,7 +14640,7 @@ async function workspaceFor(context) {
14142
14640
  }
14143
14641
  function readFileIfPresent(file) {
14144
14642
  try {
14145
- return fs8__namespace.readFileSync(file, "utf8");
14643
+ return fs3__namespace.readFileSync(file, "utf8");
14146
14644
  } catch {
14147
14645
  return null;
14148
14646
  }
@@ -14183,7 +14681,7 @@ function buildResourceProvider() {
14183
14681
  const workspace = await workspaceFor(context);
14184
14682
  const reportsDir = "error" in workspace ? null : path6__namespace.resolve(workspace.root, workspace.config.outDir, "reports");
14185
14683
  for (const [uri, report2] of REPORT_URIS) {
14186
- const present = reportsDir !== null && fs8__namespace.existsSync(path6__namespace.join(reportsDir, report2.file));
14684
+ const present = reportsDir !== null && fs3__namespace.existsSync(path6__namespace.join(reportsDir, report2.file));
14187
14685
  if (!present) continue;
14188
14686
  resources.push({
14189
14687
  uri,
@@ -14245,36 +14743,46 @@ function buildResourceProvider() {
14245
14743
  }
14246
14744
  const workspace = await workspaceFor(context);
14247
14745
  if ("error" in workspace) return null;
14746
+ const snapshotDir = path6__namespace.resolve(workspace.root, workspace.config.outDir);
14248
14747
  if (uri === PROMPT_URI) {
14249
- const text = readFileIfPresent(
14250
- path6__namespace.resolve(workspace.root, workspace.config.outDir, "PROMPT.md")
14251
- );
14252
- if (text === null) {
14748
+ const read = readConfinedText(snapshotDir, "PROMPT.md");
14749
+ if (!read.ok) {
14253
14750
  throw new ResourceNotFoundError(
14254
14751
  uri,
14255
- "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."
14752
+ "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."
14256
14753
  );
14257
14754
  }
14258
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text, PROMPT_ADVICE) };
14755
+ return {
14756
+ uri,
14757
+ mimeType: "text/markdown",
14758
+ text: ensureSingleRead(uri, read.text, PROMPT_ADVICE)
14759
+ };
14259
14760
  }
14260
14761
  const report2 = REPORT_URIS.get(uri);
14261
14762
  if (report2) {
14262
- const text = readFileIfPresent(
14263
- path6__namespace.resolve(workspace.root, workspace.config.outDir, "reports", report2.file)
14264
- );
14265
- if (text === null) {
14763
+ const read = readConfinedText(snapshotDir, path6__namespace.posix.join("reports", report2.file));
14764
+ if (!read.ok) {
14266
14765
  throw new ResourceNotFoundError(
14267
14766
  uri,
14268
- "This snapshot contains no " + report2.file + ": that report was disabled, or nothing has been generated yet. Run snapshot_generate first."
14767
+ "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."
14269
14768
  );
14270
14769
  }
14271
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text, REPORT_ADVICE) };
14770
+ return {
14771
+ uri,
14772
+ mimeType: "text/markdown",
14773
+ text: ensureSingleRead(uri, read.text, REPORT_ADVICE)
14774
+ };
14272
14775
  }
14273
14776
  if (uri === "snapshot://manifest") {
14274
14777
  const read = readManifest3(workspace);
14275
14778
  if (!read.ok) return null;
14276
- const text = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
14277
- return { uri, mimeType: "application/json", text: ensureSingleRead(uri, text, MANIFEST_ADVICE) };
14779
+ const confined = readConfinedText(path6__namespace.dirname(read.file), path6__namespace.basename(read.file));
14780
+ if (!confined.ok) return null;
14781
+ return {
14782
+ uri,
14783
+ mimeType: "application/json",
14784
+ text: ensureSingleRead(uri, confined.text, MANIFEST_ADVICE)
14785
+ };
14278
14786
  }
14279
14787
  const partMatch = PART_URI.exec(uri);
14280
14788
  if (partMatch) {
@@ -14287,7 +14795,7 @@ function buildResourceProvider() {
14287
14795
  if (partPath === null) return null;
14288
14796
  let partBytes;
14289
14797
  try {
14290
- partBytes = fs8__namespace.statSync(partPath).size;
14798
+ partBytes = fs3__namespace.statSync(partPath).size;
14291
14799
  } catch {
14292
14800
  return null;
14293
14801
  }
@@ -14323,52 +14831,52 @@ function validateArguments(schema, value) {
14323
14831
  }
14324
14832
  return problems;
14325
14833
  }
14326
- function checkValue(path16, schema, value) {
14834
+ function checkValue(path17, schema, value) {
14327
14835
  if (schema.enum && !schema.enum.includes(value)) {
14328
- return [`"${path16}" must be one of: ${schema.enum.join(", ")}`];
14836
+ return [`"${path17}" must be one of: ${schema.enum.join(", ")}`];
14329
14837
  }
14330
14838
  switch (schema.type) {
14331
14839
  case "string": {
14332
- if (typeof value !== "string") return [`"${path16}" must be a string`];
14840
+ if (typeof value !== "string") return [`"${path17}" must be a string`];
14333
14841
  const problems = [];
14334
14842
  if (schema.minLength !== void 0 && value.length < schema.minLength) {
14335
- problems.push(`"${path16}" must be at least ${schema.minLength} character(s)`);
14843
+ problems.push(`"${path17}" must be at least ${schema.minLength} character(s)`);
14336
14844
  }
14337
14845
  if (schema.maxLength !== void 0 && value.length > schema.maxLength) {
14338
- problems.push(`"${path16}" must be at most ${schema.maxLength} character(s)`);
14846
+ problems.push(`"${path17}" must be at most ${schema.maxLength} character(s)`);
14339
14847
  }
14340
14848
  return problems;
14341
14849
  }
14342
14850
  case "number":
14343
14851
  case "integer": {
14344
14852
  if (typeof value !== "number" || Number.isNaN(value)) {
14345
- return [`"${path16}" must be a number`];
14853
+ return [`"${path17}" must be a number`];
14346
14854
  }
14347
14855
  if (schema.type === "integer" && !Number.isInteger(value)) {
14348
- return [`"${path16}" must be an integer`];
14856
+ return [`"${path17}" must be an integer`];
14349
14857
  }
14350
14858
  const problems = [];
14351
14859
  if (schema.minimum !== void 0 && value < schema.minimum) {
14352
- problems.push(`"${path16}" must be >= ${schema.minimum}`);
14860
+ problems.push(`"${path17}" must be >= ${schema.minimum}`);
14353
14861
  }
14354
14862
  if (schema.maximum !== void 0 && value > schema.maximum) {
14355
- problems.push(`"${path16}" must be <= ${schema.maximum}`);
14863
+ problems.push(`"${path17}" must be <= ${schema.maximum}`);
14356
14864
  }
14357
14865
  return problems;
14358
14866
  }
14359
14867
  case "boolean":
14360
- return typeof value === "boolean" ? [] : [`"${path16}" must be a boolean`];
14868
+ return typeof value === "boolean" ? [] : [`"${path17}" must be a boolean`];
14361
14869
  case "array": {
14362
- if (!Array.isArray(value)) return [`"${path16}" must be an array`];
14870
+ if (!Array.isArray(value)) return [`"${path17}" must be an array`];
14363
14871
  if (!schema.items) return [];
14364
14872
  const problems = [];
14365
14873
  value.forEach((item, index) => {
14366
- problems.push(...checkValue(`${path16}[${index}]`, schema.items, item));
14874
+ problems.push(...checkValue(`${path17}[${index}]`, schema.items, item));
14367
14875
  });
14368
14876
  return problems;
14369
14877
  }
14370
14878
  case "object":
14371
- return isJsonObject(value) ? [] : [`"${path16}" must be an object`];
14879
+ return isJsonObject(value) ? [] : [`"${path17}" must be an object`];
14372
14880
  default:
14373
14881
  return [];
14374
14882
  }
@@ -14732,6 +15240,10 @@ var DEFAULT_PORT = 4789;
14732
15240
  var DEFAULT_MAX_BODY = 2 * 1024 * 1024;
14733
15241
  var RATE_LIMIT = 60;
14734
15242
  var RATE_WINDOW_MS = 1e4;
15243
+ var MAX_IN_FLIGHT = 4;
15244
+ var MAX_SESSION_ENTRIES = 64;
15245
+ var MAX_SSE_SESSIONS = 64;
15246
+ var MAX_RATE_WINDOWS = 1024;
14735
15247
  function generateToken() {
14736
15248
  return crypto5__namespace.randomBytes(24).toString("base64url");
14737
15249
  }
@@ -14767,6 +15279,10 @@ async function startHttpTransport(options) {
14767
15279
  const toolCount = buildTools().length;
14768
15280
  const mcpSessions = /* @__PURE__ */ new Map();
14769
15281
  const socketServers = /* @__PURE__ */ new WeakMap();
15282
+ const rememberSession = (id, server) => {
15283
+ if (!mcpSessions.has(id) && mcpSessions.size >= MAX_SESSION_ENTRIES) return;
15284
+ mcpSessions.set(id, server);
15285
+ };
14770
15286
  const anonymousServers = /* @__PURE__ */ new Map();
14771
15287
  const serverFor = (request) => {
14772
15288
  const header = request.headers["mcp-session-id"];
@@ -14775,11 +15291,7 @@ async function startHttpTransport(options) {
14775
15291
  let existing = mcpSessions.get(supplied);
14776
15292
  if (existing === void 0) {
14777
15293
  existing = createMcp();
14778
- if (mcpSessions.size >= 64) {
14779
- const oldest = mcpSessions.keys().next().value;
14780
- if (oldest !== void 0) mcpSessions.delete(oldest);
14781
- }
14782
- mcpSessions.set(supplied, existing);
15294
+ rememberSession(supplied, existing);
14783
15295
  }
14784
15296
  return existing;
14785
15297
  }
@@ -14810,6 +15322,35 @@ async function startHttpTransport(options) {
14810
15322
  return fromQuery !== null && timingSafeEqual2(fromQuery, token);
14811
15323
  };
14812
15324
  const sessions = /* @__PURE__ */ new Map();
15325
+ let inFlight = 0;
15326
+ const acquireToolSlot = () => {
15327
+ if (inFlight >= MAX_IN_FLIGHT) return false;
15328
+ inFlight += 1;
15329
+ return true;
15330
+ };
15331
+ const releaseToolSlot = () => {
15332
+ if (inFlight > 0) inFlight -= 1;
15333
+ };
15334
+ const busyResponse = (id) => ({
15335
+ jsonrpc: "2.0",
15336
+ id: typeof id === "string" || typeof id === "number" || id === null ? id : null,
15337
+ error: {
15338
+ code: -32001,
15339
+ message: "server busy: too many tool calls are already in flight"
15340
+ }
15341
+ });
15342
+ const isToolCall = (message) => message !== null && typeof message === "object" && message.method === "tools/call";
15343
+ const rememberRateWindow = (remote, now) => {
15344
+ if (!sessions.has(remote) && sessions.size >= MAX_RATE_WINDOWS) {
15345
+ for (const [key, value] of sessions) if (value.resetAt <= now) sessions.delete(key);
15346
+ while (sessions.size >= MAX_RATE_WINDOWS) {
15347
+ const oldest = sessions.keys().next().value;
15348
+ if (oldest === void 0) break;
15349
+ sessions.delete(oldest);
15350
+ }
15351
+ }
15352
+ sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
15353
+ };
14813
15354
  const metrics = {
14814
15355
  requests: 0,
14815
15356
  byMethod: /* @__PURE__ */ new Map(),
@@ -14825,7 +15366,7 @@ async function startHttpTransport(options) {
14825
15366
  const now = Date.now();
14826
15367
  const window = sessions.get(remote);
14827
15368
  if (window === void 0 || window.resetAt <= now) {
14828
- sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
15369
+ rememberRateWindow(remote, now);
14829
15370
  return false;
14830
15371
  }
14831
15372
  if (window.count >= RATE_LIMIT) return true;
@@ -14886,6 +15427,10 @@ async function startHttpTransport(options) {
14886
15427
  return;
14887
15428
  }
14888
15429
  if (request.method === "GET" && request.url === "/metrics") {
15430
+ if (token !== null && host !== "127.0.0.1" && host !== "localhost" && host !== "::1" && !tokenAccepted(request, new URL(request.url, "http://localhost"))) {
15431
+ send(401, { error: "unauthorized" }, { "www-authenticate": 'Bearer realm="codebase-snapshot"' });
15432
+ return;
15433
+ }
14889
15434
  const lines = [
14890
15435
  "# HELP snapshot_uptime_seconds Seconds since the process started.",
14891
15436
  "# TYPE snapshot_uptime_seconds gauge",
@@ -14923,6 +15468,10 @@ async function startHttpTransport(options) {
14923
15468
  send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
14924
15469
  return;
14925
15470
  }
15471
+ if (sseSessions.size >= MAX_SSE_SESSIONS) {
15472
+ send(503, { error: "too many open SSE sessions" }, { ...cors, "retry-after": "10" });
15473
+ return;
15474
+ }
14926
15475
  const id = crypto5__namespace.randomBytes(12).toString("hex");
14927
15476
  response.writeHead(200, {
14928
15477
  ...cors,
@@ -14932,9 +15481,21 @@ async function startHttpTransport(options) {
14932
15481
  "x-accel-buffering": "no"
14933
15482
  });
14934
15483
  const write = (payload) => {
14935
- response.write(payload);
15484
+ try {
15485
+ response.write(payload);
15486
+ } catch {
15487
+ }
14936
15488
  };
14937
- sseSessions.set(id, { write, end: () => response.end(), server: createMcp() });
15489
+ sseSessions.set(id, {
15490
+ write,
15491
+ end: () => {
15492
+ try {
15493
+ response.end();
15494
+ } catch {
15495
+ }
15496
+ },
15497
+ server: createMcp()
15498
+ });
14938
15499
  const heartbeat = setInterval(() => write(": ping\n\n"), 15e3);
14939
15500
  const cleanup = () => {
14940
15501
  clearInterval(heartbeat);
@@ -14985,10 +15546,27 @@ async function startHttpTransport(options) {
14985
15546
  send(400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: String(error) } });
14986
15547
  return;
14987
15548
  }
14988
- const answer = await stream.server.handle(message);
14989
- if (answer !== null) stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
15549
+ const gated = isToolCall(message);
15550
+ if (gated && !acquireToolSlot()) {
15551
+ const answer = busyResponse(message.id);
15552
+ stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
15553
+ send(202, "", cors);
15554
+ return;
15555
+ }
15556
+ try {
15557
+ const answer = await stream.server.handle(message);
15558
+ if (answer !== null) stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
15559
+ } finally {
15560
+ if (gated) releaseToolSlot();
15561
+ }
14990
15562
  send(202, "", cors);
14991
- })();
15563
+ })().catch((error) => {
15564
+ log("mcp/http: " + error.message);
15565
+ try {
15566
+ send(500, { jsonrpc: "2.0", id: null, error: { code: -32603, message: "Internal error" } }, cors);
15567
+ } catch {
15568
+ }
15569
+ });
14992
15570
  });
14993
15571
  return;
14994
15572
  }
@@ -15051,13 +15629,22 @@ async function startHttpTransport(options) {
15051
15629
  }
15052
15630
  if (sessionId === "" && !Array.isArray(message) && message.method === "initialize") {
15053
15631
  sessionId = newSessionId();
15054
- mcpSessions.set(sessionId, activeServer);
15632
+ rememberSession(sessionId, activeServer);
15055
15633
  }
15056
15634
  const sessionHeaders = sessionId === "" ? cors : { ...cors, "mcp-session-id": sessionId };
15057
15635
  const answers = [];
15058
15636
  for (const item of batch) {
15059
- const answer = await activeServer.handle(item);
15060
- if (answer !== null) answers.push(answer);
15637
+ const gated = isToolCall(item);
15638
+ if (gated && !acquireToolSlot()) {
15639
+ answers.push(busyResponse(item.id));
15640
+ continue;
15641
+ }
15642
+ try {
15643
+ const answer = await activeServer.handle(item);
15644
+ if (answer !== null) answers.push(answer);
15645
+ } finally {
15646
+ if (gated) releaseToolSlot();
15647
+ }
15061
15648
  }
15062
15649
  if (answers.length === 0) {
15063
15650
  send(202, "", sessionHeaders);
@@ -15076,11 +15663,11 @@ async function startHttpTransport(options) {
15076
15663
  }
15077
15664
  });
15078
15665
  });
15079
- await new Promise((resolve10, reject) => {
15666
+ await new Promise((resolve11, reject) => {
15080
15667
  httpServer.once("error", reject);
15081
15668
  httpServer.listen(port, host, () => {
15082
15669
  httpServer.removeListener("error", reject);
15083
- resolve10();
15670
+ resolve11();
15084
15671
  });
15085
15672
  });
15086
15673
  const address = httpServer.address();
@@ -15091,7 +15678,7 @@ async function startHttpTransport(options) {
15091
15678
  port: actualPort,
15092
15679
  host,
15093
15680
  token,
15094
- close: () => new Promise((resolve10) => {
15681
+ close: () => new Promise((resolve11) => {
15095
15682
  for (const [, session] of sseSessions) {
15096
15683
  try {
15097
15684
  session.end();
@@ -15099,7 +15686,7 @@ async function startHttpTransport(options) {
15099
15686
  }
15100
15687
  }
15101
15688
  sseSessions.clear();
15102
- httpServer.close(() => resolve10());
15689
+ httpServer.close(() => resolve11());
15103
15690
  httpServer.closeAllConnections();
15104
15691
  })
15105
15692
  };