codebase-snapshot 0.20.5 → 0.20.7

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
@@ -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") {
@@ -2334,7 +2334,7 @@ function redactStructuredValues(text, filePath, recordFinding) {
2334
2334
  }
2335
2335
  return segments.join("");
2336
2336
  }
2337
- 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;
2338
2338
  function redactDockerfileEnv(text, filePath, recordFinding) {
2339
2339
  if (!isDockerfile(filePath)) return text;
2340
2340
  const segments = text.split(LINE_BREAK);
@@ -2343,10 +2343,9 @@ function redactDockerfileEnv(text, filePath, recordFinding) {
2343
2343
  if (line === void 0) continue;
2344
2344
  const match = DOCKERFILE_ENV.exec(line);
2345
2345
  if (match === null) continue;
2346
- if (!CREDENTIAL_KEY_TAIL.test(match[2] ?? "")) continue;
2347
- const value = match[4] ?? "";
2348
- if (value.startsWith("=")) continue;
2349
- 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}`;
2350
2349
  recordFinding(index / 2 + 1, ["dockerfile-env-secret"]);
2351
2350
  }
2352
2351
  return segments.join("");
@@ -2431,6 +2430,7 @@ function isSourceCodeFile(filePath) {
2431
2430
  var PLACEHOLDER_PATTERNS = [
2432
2431
  /^<[^>]*>?$/,
2433
2432
  /^\.{3,}$/,
2433
+ /^(?:[A-Za-z0-9_-]{1,8}-)?\.{3,}$/,
2434
2434
  /^(?:x{4,}|X{4,}|\*{3,})$/,
2435
2435
  /^(?:replace|change)[-_ ]?me(?:[-_ ].*)?$/i,
2436
2436
  /^your[-_ ].*$/i,
@@ -2444,7 +2444,7 @@ function isPlaceholderValue(value) {
2444
2444
  if (trimmed.length === 0) return false;
2445
2445
  if (PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(trimmed))) return true;
2446
2446
  if (trimmed.includes(REDACTION_MARKER) || trimmed.includes(PEM_REDACTION_MARKER)) return true;
2447
- return trimmed.includes("...") || /^<[^>]*$/.test(trimmed);
2447
+ return false;
2448
2448
  }
2449
2449
  function quotesAreBalanced(text) {
2450
2450
  let single = 0;
@@ -2496,6 +2496,7 @@ var ASSIGNMENT_FILE = /\.(?:sh|bash|zsh|ksh|fish|env|ya?ml|toml|ini|conf|cfg|pro
2496
2496
  var ASSIGNMENT_BASENAME = /^(?:\.env(?:\.[^/]*)?|\.envrc|\.profile|\.bashrc|\.zshrc|\.bash_profile)$/i;
2497
2497
  function isAssignmentFile(filePath) {
2498
2498
  if (filePath === void 0) return false;
2499
+ if (isDockerfile(filePath)) return true;
2499
2500
  const normalised = filePath.replace(/\\/g, "/");
2500
2501
  if (ASSIGNMENT_FILE.test(normalised)) return true;
2501
2502
  const base = normalised.slice(normalised.lastIndexOf("/") + 1);
@@ -2579,6 +2580,15 @@ function verifySnapshotSignature(snapshotDir) {
2579
2580
  if (sha2562 !== record.manifestSha256) {
2580
2581
  return { ok: false, reason: "manifest.json changed after it was signed" };
2581
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
+ }
2582
2592
  let verified = false;
2583
2593
  try {
2584
2594
  const key = crypto5__namespace.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
@@ -2591,7 +2601,7 @@ function verifySnapshotSignature(snapshotDir) {
2591
2601
 
2592
2602
  // src/version.ts
2593
2603
  var GENERATOR_NAME = "codebase-snapshot";
2594
- var GENERATOR_VERSION = "0.20.5";
2604
+ var GENERATOR_VERSION = "0.20.7";
2595
2605
  var SCHEMA_VERSION = "3.0.0";
2596
2606
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2597
2607
  function isOurGeneratorName(name) {
@@ -2690,7 +2700,7 @@ var DEFAULT_IGNORED_FILES = [
2690
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;
2691
2701
  var SENSITIVE_PATH = /(?:^|\/)\.(?:aws|ssh|gnupg)\/|(?:^|\/)\.docker\/config\.json$|(?:^|\/)\.kube\/config$|(?:^|\/)\.config\/gcloud\/|(?:^|\/)\.composer\/|(?:^|\/)\.terraform\/credentials\.tfrc\.json$/i;
2692
2702
  var SENSITIVE_EXT = /\.(?:pem|key|p12|pfx|jks|keystore|ppk|asc|kdbx|tfstate|tfvars)$/i;
2693
- 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;
2694
2704
  var BACKUP_SUFFIX = /(?:~|\.(?:bak|backup|old|orig|save|copy|swp|swo|tmp|part))$/i;
2695
2705
  function normaliseName(name) {
2696
2706
  let normalised = name.trim().replace(/[. ]+$/, "");
@@ -3081,30 +3091,67 @@ function isToolOwnedDirectory2(dir) {
3081
3091
  }
3082
3092
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
3083
3093
  const marker = parsed;
3084
- 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 {
3085
3101
  return false;
3086
3102
  }
3087
- const accounted = /* @__PURE__ */ new Set();
3103
+ if (crypto5.createHash("sha256").update(manifestBytes).digest("hex") !== marker.manifestSha256) {
3104
+ return false;
3105
+ }
3106
+ const recordedFiles = /* @__PURE__ */ new Set();
3088
3107
  for (const item of marker.files) {
3089
3108
  if (!item || typeof item !== "object" || Array.isArray(item)) return false;
3090
- const entry = item.path;
3091
- if (typeof entry !== "string" || entry.length === 0) return false;
3092
- const parts = entry.split("/");
3093
- for (let depth = 1; depth <= parts.length; depth += 1) {
3094
- 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;
3095
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;
3127
+ }
3128
+ if (digest !== record.sha256) return false;
3129
+ recordedFiles.add(entry);
3096
3130
  }
3097
- let entries;
3098
- try {
3099
- entries = fs3__namespace.readdirSync(dir);
3100
- } catch {
3101
- 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
+ }
3102
3153
  }
3103
- return entries.every(
3104
- (entry) => entry === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry) || // A snapshot signed before signing moved into staging has a valid signature.json the old
3105
- // marker could not record. It is our artifact when the signature verifies.
3106
- entry === "signature.json" && verifySnapshotSignature(dir).ok || accounted.has(entry)
3107
- );
3154
+ return true;
3108
3155
  }
3109
3156
  function makeToolOwnedDecider(cwd, toolOwnedPaths) {
3110
3157
  const markers = /* @__PURE__ */ new Map();
@@ -3364,6 +3411,7 @@ function dropSymlinksToUnincludedTargets(cwd, files, skipped) {
3364
3411
  if (aliases.size === 0) return [...files];
3365
3412
  const includedTargets = /* @__PURE__ */ new Set();
3366
3413
  for (const file of files) {
3414
+ if (aliases.has(file)) continue;
3367
3415
  try {
3368
3416
  includedTargets.add(fs3__namespace.realpathSync(path6__namespace.join(cwd, file)));
3369
3417
  } catch {
@@ -3612,8 +3660,25 @@ function normalizeResolvedConfig(config) {
3612
3660
  monolithWanted,
3613
3661
  monolithWanted
3614
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
+ }
3615
3679
  return markResolvedConfig({
3616
3680
  ...config,
3681
+ maxPartTokens,
3617
3682
  discovery,
3618
3683
  // A spread copy built before the field existed carries no value; the default applies, and it
3619
3684
  // is re-validated because the number reaches a rendered artifact.
@@ -4061,9 +4126,16 @@ function readConfiguredBrief(cwd, value) {
4061
4126
  }
4062
4127
  let text;
4063
4128
  try {
4064
- if (!fs3__namespace.statSync(filePath).isFile()) throw new Error("not a file");
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
+ }
4065
4136
  text = fs3__namespace.readFileSync(filePath, "utf8");
4066
- } catch {
4137
+ } catch (error) {
4138
+ if (error instanceof Error && error.message.startsWith('brief "')) throw error;
4067
4139
  throw new Error(
4068
4140
  'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
4069
4141
  );
@@ -4466,7 +4538,10 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
4466
4538
  outDir,
4467
4539
  tmpDir,
4468
4540
  maxPartBytes: resolvedMaxPartBytes,
4469
- ...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),
4470
4545
  largeFileBytes: largeFileBytesFor(resolvedMaxPartBytes, cliOptions, userConfig),
4471
4546
  previewHeadLines: strictPositiveInteger(userConfig?.previewHeadLines, 80, "`previewHeadLines`"),
4472
4547
  previewTailLines: strictPositiveInteger(userConfig?.previewTailLines, 40, "`previewTailLines`"),
@@ -4687,7 +4762,7 @@ function finalizeSummary(summary) {
4687
4762
  }
4688
4763
  function eachLine(content, visit) {
4689
4764
  const text = content.length > MAX_SUMMARY_CHARS ? content.slice(0, MAX_SUMMARY_CHARS) : content;
4690
- for (const line of text.split(/\r?\n/)) visit(line);
4765
+ for (const line of text.split(/\r\n|\n|\r/)) visit(line);
4691
4766
  }
4692
4767
  function isTopLevel(line) {
4693
4768
  return !/^[\s]/.test(line);
@@ -5378,7 +5453,7 @@ function summarizeTypeScriptSource(relativePath, content) {
5378
5453
  routeHandlers: []
5379
5454
  };
5380
5455
  const lowerPath = relativePath.toLowerCase();
5381
- 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;
5382
5457
  const sourceFile = ts__default.default.createSourceFile(
5383
5458
  relativePath,
5384
5459
  content,
@@ -5967,17 +6042,17 @@ function decodeText(buffer) {
5967
6042
  };
5968
6043
  }
5969
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
+ }
5970
6055
  if (invalidBytes === 0) {
5971
- const controlBytes = countControlBytes(buffer);
5972
- if (controlBytes > CONTROL_BYTES_FLOOR && controlBytes * 100 > buffer.length) {
5973
- return {
5974
- text: "",
5975
- encoding: "utf-8",
5976
- invalidBytes: 0,
5977
- binary: true,
5978
- binaryReason: `${controlBytes} control byte(s) in ${buffer.length} B; valid UTF-8 but not text`
5979
- };
5980
- }
5981
6056
  return {
5982
6057
  text: new TextDecoder("utf-8").decode(buffer),
5983
6058
  encoding: "utf-8",
@@ -6100,9 +6175,15 @@ function skeletonizeTypeScript(source, fileName = "file.ts") {
6100
6175
  if (end > start) spans.push({ start, end });
6101
6176
  }
6102
6177
  }
6103
- ts__default.default.forEachChild(node, visit);
6104
6178
  };
6105
- 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
+ }
6106
6187
  if (spans.length === 0) return { text: source, collapsed: 0 };
6107
6188
  const outermost = [];
6108
6189
  for (const span of spans.sort((a, b) => a.start - b.start || b.end - a.end)) {
@@ -6419,7 +6500,9 @@ function planForQuestion(manifest, question, options = {}) {
6419
6500
  notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
6420
6501
  }
6421
6502
  }
6422
- 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
+ );
6423
6506
  const chosen = /* @__PURE__ */ new Map();
6424
6507
  const skipped = [];
6425
6508
  let used = 0;
@@ -6527,12 +6610,15 @@ function stripComments2(text, relativePath) {
6527
6610
  if (ranges_ === void 0) return;
6528
6611
  for (const range of ranges_) ranges.push([range.pos, range.end]);
6529
6612
  };
6530
- const visit = (node) => {
6613
+ const stack = [source];
6614
+ while (stack.length > 0) {
6615
+ const node = stack.pop();
6531
6616
  collect(ts__default.default.getLeadingCommentRanges(text, node.getFullStart()));
6532
6617
  collect(ts__default.default.getTrailingCommentRanges(text, node.getEnd()));
6533
- ts__default.default.forEachChild(node, visit);
6534
- };
6535
- visit(source);
6618
+ ts__default.default.forEachChild(node, (child) => {
6619
+ stack.push(child);
6620
+ });
6621
+ }
6536
6622
  collect(ts__default.default.getLeadingCommentRanges(text, source.endOfFileToken.getFullStart()));
6537
6623
  if (ranges.length === 0) return { text, removed: 0 };
6538
6624
  ranges.sort((left, right) => left[0] - right[0]);
@@ -6690,6 +6776,10 @@ function tsconfigPathsFor(cwd) {
6690
6776
  return null;
6691
6777
  }
6692
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
+ }
6693
6783
  const cached = TSCONFIG_CACHE.get(configPath);
6694
6784
  if (cached !== void 0 && cached.key === key) return cached.value;
6695
6785
  let value = null;
@@ -6849,6 +6939,75 @@ function importsChangedFile(importerPath, imports, changedPaths, resolver) {
6849
6939
  }
6850
6940
  return false;
6851
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
+ }
6852
7011
  var LANGUAGE_BY_EXTENSION = {
6853
7012
  ".ts": "typescript",
6854
7013
  ".mts": "typescript",
@@ -7162,6 +7321,9 @@ function describeManifestShapeProblem(value) {
7162
7321
  if (typeof fields.relativePath !== "string") {
7163
7322
  return 'a "files" entry has no "relativePath"';
7164
7323
  }
7324
+ if (!isConfinedRelative(fields.relativePath)) {
7325
+ return 'a "files" entry "relativePath" resolves outside the repository and was not inspected';
7326
+ }
7165
7327
  if (!currentSchema) continue;
7166
7328
  if (typeof fields.part !== "string" || fields.part.length === 0) {
7167
7329
  return 'a "files" entry records no "part"';
@@ -7180,6 +7342,18 @@ function describeManifestShapeProblem(value) {
7180
7342
  }
7181
7343
  }
7182
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
+ }
7183
7357
  if (!Array.isArray(candidate.parts)) return 'missing "parts" array';
7184
7358
  for (const entry of candidate.parts) {
7185
7359
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
@@ -7240,10 +7414,12 @@ function validateSnapshot(configInput) {
7240
7414
  }
7241
7415
  const shapeProblem = describeManifestShapeProblem(manifest);
7242
7416
  if (shapeProblem) {
7417
+ const drift2 = emptyDrift();
7418
+ drift2.partIssues.push({ part: "manifest.json", issue: shapeProblem });
7243
7419
  return {
7244
7420
  valid: false,
7245
7421
  manifestPresent: true,
7246
- drift: emptyDrift(),
7422
+ drift: drift2,
7247
7423
  errors: [`${manifestPath} is not a snapshot manifest: ${shapeProblem}`],
7248
7424
  warnings: []
7249
7425
  };
@@ -7471,13 +7647,15 @@ function validateSnapshot(configInput) {
7471
7647
  });
7472
7648
  continue;
7473
7649
  }
7474
- let buffer;
7475
- try {
7476
- buffer = fs3__namespace.readFileSync(partPath);
7477
- } catch {
7478
- 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
+ });
7479
7656
  continue;
7480
7657
  }
7658
+ const buffer = partRead.bytes;
7481
7659
  if (buffer.length !== part.byteSize) {
7482
7660
  drift.partIssues.push({
7483
7661
  part: part.filename,
@@ -7850,15 +8028,15 @@ function validateSnapshot(configInput) {
7850
8028
  ];
7851
8029
  for (const [key, artifact] of declaredArtifacts) {
7852
8030
  if (!artifact) continue;
7853
- const artifactPath = path6__namespace.join(snapshotDir, ...key.split("/"));
7854
- let buffer;
7855
- try {
7856
- if (!fs3__namespace.statSync(artifactPath).isFile()) throw new Error("not a regular file");
7857
- buffer = fs3__namespace.readFileSync(artifactPath);
7858
- } catch {
7859
- 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
+ });
7860
8037
  continue;
7861
8038
  }
8039
+ const buffer = artifactRead.bytes;
7862
8040
  if (sha256Hex(buffer) !== artifact.sha256 || buffer.length !== artifact.byteSize) {
7863
8041
  drift.partIssues.push({ part: key, issue: "artifact does not match its recorded digest" });
7864
8042
  continue;
@@ -7881,13 +8059,11 @@ function validateSnapshot(configInput) {
7881
8059
  const sarifArtifact = manifest.artifacts?.sarif;
7882
8060
  if (sarifArtifact) {
7883
8061
  const sarifKey = "reports/audit.sarif";
7884
- try {
7885
- const buffer = fs3__namespace.readFileSync(path6__namespace.join(snapshotDir, "reports", "audit.sarif"));
7886
- if (sha256Hex(buffer) !== sarifArtifact.sha256 || buffer.length !== sarifArtifact.byteSize) {
7887
- drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
7888
- }
7889
- } catch {
7890
- 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" });
7891
8067
  }
7892
8068
  }
7893
8069
  if (manifest.git && manifest.git.branch && manifest.git.branch !== config.branch) {
@@ -8235,7 +8411,7 @@ var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
8235
8411
  var META_PREFIX = "- Meta: ";
8236
8412
  var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
8237
8413
  var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
8238
- var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
8414
+ var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures", "comments-stripped"]);
8239
8415
  var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
8240
8416
  function readIncludedLines(fields) {
8241
8417
  const last = fields[fields.length - 1];
@@ -8330,17 +8506,10 @@ var ARTIFACT_FILES = {
8330
8506
  fullXml: "full-codebase.xml",
8331
8507
  sarif: "reports/audit.sarif"
8332
8508
  };
8333
- var TEXT_ARTIFACT = /\.(md|json|txt|sarif)$/i;
8509
+ var TEXT_ARTIFACT = /\.(md|json|txt|sarif|xml)$/i;
8334
8510
  function sha256(buffer) {
8335
8511
  return crypto5.createHash("sha256").update(buffer).digest("hex");
8336
8512
  }
8337
- function readBytes(file) {
8338
- try {
8339
- return fs3__namespace.readFileSync(file);
8340
- } catch {
8341
- return null;
8342
- }
8343
- }
8344
8513
  function readText(file) {
8345
8514
  try {
8346
8515
  return fs3__namespace.readFileSync(file, "utf8");
@@ -8348,8 +8517,17 @@ function readText(file) {
8348
8517
  return null;
8349
8518
  }
8350
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
+ }
8351
8528
  function readJson(file) {
8352
- const text = readText(file);
8529
+ const confined = readConfinedText(path6__namespace.dirname(file), path6__namespace.basename(file));
8530
+ const text = confined.ok ? confined.text : null;
8353
8531
  if (text === null) return null;
8354
8532
  try {
8355
8533
  return JSON.parse(text);
@@ -8406,16 +8584,28 @@ function secretTokens(text) {
8406
8584
  }
8407
8585
  return [...tokens];
8408
8586
  }
8409
- function readArtifactTexts(snapshotDir) {
8587
+ function readArtifactTexts(snapshotDir, maxBytes = 32 * 1024 * 1024) {
8410
8588
  const texts = [];
8589
+ let bytes = 0;
8411
8590
  for (const relative10 of walk(snapshotDir)) {
8412
8591
  if (!TEXT_ARTIFACT.test(relative10)) continue;
8413
- const text = readText(path6__namespace.join(snapshotDir, relative10));
8414
- if (text !== null) texts.push(text);
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
+ }
8415
8605
  }
8416
8606
  return texts;
8417
8607
  }
8418
- function findHostPaths(snapshotDir, repoDir) {
8608
+ function findHostPaths(snapshotDir, repoDir, maxBytes = 32 * 1024 * 1024) {
8419
8609
  const patterns = [
8420
8610
  /\/home\/[A-Za-z0-9._-]+/g,
8421
8611
  /\/Users\/[A-Za-z0-9._-]+/g,
@@ -8426,10 +8616,19 @@ function findHostPaths(snapshotDir, repoDir) {
8426
8616
  ];
8427
8617
  const repoPattern = new RegExp(escapeRegExp(repoDir), "g");
8428
8618
  const hits = /* @__PURE__ */ new Set();
8619
+ let scanned = 0;
8429
8620
  for (const relative10 of walk(snapshotDir)) {
8430
8621
  if (!TEXT_ARTIFACT.test(relative10)) continue;
8431
- const text = readText(path6__namespace.join(snapshotDir, relative10));
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);
8432
8630
  if (text === null) continue;
8631
+ scanned += Buffer.byteLength(text, "utf8");
8433
8632
  for (const pattern of patterns) {
8434
8633
  for (const match of text.match(pattern) ?? []) hits.add(relative10 + ": " + match);
8435
8634
  }
@@ -8616,7 +8815,7 @@ function auditSnapshot(options) {
8616
8815
  const missingParts = [];
8617
8816
  const mismatched = [];
8618
8817
  for (const part of manifest.parts) {
8619
- const bytes = readBytes(path6__namespace.join(snapshotDir, "parts", part.filename));
8818
+ const bytes = snapshotBytes(snapshotDir, "parts/" + part.filename);
8620
8819
  if (bytes === null) {
8621
8820
  missingParts.push(part.filename);
8622
8821
  continue;
@@ -8684,7 +8883,7 @@ function auditSnapshot(options) {
8684
8883
  const relative10 = ARTIFACT_FILES[key];
8685
8884
  if (relative10 === void 0) continue;
8686
8885
  artifactCount += 1;
8687
- const bytes = readBytes(path6__namespace.join(snapshotDir, relative10));
8886
+ const bytes = snapshotBytes(snapshotDir, relative10);
8688
8887
  if (bytes === null) artifactProblems.push(relative10 + " is missing");
8689
8888
  else if (typeof value.sha256 === "string" && sha256(bytes) !== value.sha256) {
8690
8889
  artifactProblems.push(relative10 + " changed");
@@ -8797,7 +8996,7 @@ function auditSnapshot(options) {
8797
8996
  manifest.files.map((file) => [anchorForPath(file.relativePath), file.relativePath])
8798
8997
  );
8799
8998
  for (const part of manifest.parts) {
8800
- const partText = readText(path6__namespace.join(snapshotDir, "parts", part.filename));
8999
+ const partText = snapshotText(snapshotDir, "parts/" + part.filename);
8801
9000
  if (partText === null) continue;
8802
9001
  const sections = parsePartSections(partText);
8803
9002
  partTexts.set(part.filename, partText);
@@ -8864,7 +9063,7 @@ function auditSnapshot(options) {
8864
9063
  }
8865
9064
  };
8866
9065
  if (manifest.artifacts?.readme != null) {
8867
- const text = readText(path6__namespace.join(snapshotDir, "README.md"));
9066
+ const text = snapshotText(snapshotDir, "README.md");
8868
9067
  if (text === null) {
8869
9068
  reportProblems.push("README.md is recorded but unreadable");
8870
9069
  } else {
@@ -8904,7 +9103,7 @@ function auditSnapshot(options) {
8904
9103
  }
8905
9104
  }
8906
9105
  if (manifest.artifacts?.prompt != null) {
8907
- const text = readText(path6__namespace.join(snapshotDir, "PROMPT.md"));
9106
+ const text = snapshotText(snapshotDir, "PROMPT.md");
8908
9107
  if (text === null) {
8909
9108
  reportProblems.push("PROMPT.md is recorded but unreadable");
8910
9109
  } else {
@@ -9093,7 +9292,7 @@ function auditSnapshot(options) {
9093
9292
  ];
9094
9293
  for (const reader of packReaders) {
9095
9294
  if (manifest.artifacts?.[reader.key] == null) continue;
9096
- const packText = readText(path6__namespace.join(snapshotDir, reader.file));
9295
+ const packText = snapshotText(snapshotDir, reader.file);
9097
9296
  const problems = [];
9098
9297
  if (packText === null) {
9099
9298
  problems.push(reader.file + " is recorded but unreadable");
@@ -9256,7 +9455,7 @@ function auditSnapshot(options) {
9256
9455
  let packBodies = 0;
9257
9456
  let packSkipped = 0;
9258
9457
  for (const pack of packsWanted) {
9259
- const text = readText(path6__namespace.join(snapshotDir, pack.file));
9458
+ const text = snapshotText(snapshotDir, pack.file);
9260
9459
  if (text === null) continue;
9261
9460
  const bodies = pack.read(text);
9262
9461
  if (bodies === null) {
@@ -9320,7 +9519,8 @@ function auditSnapshot(options) {
9320
9519
  unreplayable += 1;
9321
9520
  continue;
9322
9521
  }
9323
- const bytes = readBytes(path6__namespace.join(repoDir, file.relativePath));
9522
+ const repoBytes = readConfinedBytes(repoDir, file.relativePath);
9523
+ const bytes = repoBytes.ok ? repoBytes.bytes : null;
9324
9524
  if (bytes === null || sha256(bytes) !== file.hashSha256) {
9325
9525
  unreplayable += 1;
9326
9526
  continue;
@@ -9420,7 +9620,14 @@ function auditSnapshot(options) {
9420
9620
  for (const relative10 of walk(snapshotDir)) {
9421
9621
  if (!TEXT_ARTIFACT.test(relative10) || scannedBytes > scanBudget) continue;
9422
9622
  if (relative10 === SIGNATURE_FILE) continue;
9423
- const text = readText(path6__namespace.join(snapshotDir, relative10));
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);
9424
9631
  if (text === null) continue;
9425
9632
  scannedBytes += Buffer.byteLength(text, "utf8");
9426
9633
  let findingCount = 0;
@@ -9440,7 +9647,7 @@ function auditSnapshot(options) {
9440
9647
  }
9441
9648
  const signatureRecordPath = path6__namespace.join(snapshotDir, SIGNATURE_FILE);
9442
9649
  if (fs3__namespace.existsSync(signatureRecordPath)) {
9443
- const recordText = readText(signatureRecordPath);
9650
+ const recordText = snapshotText(snapshotDir, SIGNATURE_FILE);
9444
9651
  if (recordText !== null) {
9445
9652
  scannedBytes += Buffer.byteLength(recordText, "utf8");
9446
9653
  let scanText = recordText;
@@ -9480,11 +9687,17 @@ function auditSnapshot(options) {
9480
9687
  );
9481
9688
  const leakedFrom = [];
9482
9689
  let compared = 0;
9483
- const artifactTexts = readArtifactTexts(snapshotDir);
9690
+ const artifactTexts = readArtifactTexts(snapshotDir, scanBudget);
9484
9691
  const artifactContains = (token) => artifactTexts.some((text) => text.includes(token));
9485
9692
  for (const record of skippedSensitive.slice(0, 40)) {
9486
9693
  if (record.path.includes("[REDACTED") || compared > 400) continue;
9487
- 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;
9488
9701
  if (text === null) continue;
9489
9702
  for (const token of secretTokens(text)) {
9490
9703
  compared += 1;
@@ -9506,7 +9719,7 @@ function auditSnapshot(options) {
9506
9719
  "A value from " + sample([...new Set(leakedFrom)]) + " appears in the snapshot."
9507
9720
  )
9508
9721
  );
9509
- const pii = findHostPaths(snapshotDir, repoDir);
9722
+ const pii = findHostPaths(snapshotDir, repoDir, scanBudget);
9510
9723
  checks.push(
9511
9724
  pii.length === 0 ? check(
9512
9725
  "pii.paths",
@@ -9627,6 +9840,17 @@ function report(snapshotDir, repoDir, checks) {
9627
9840
  counts
9628
9841
  };
9629
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
+ }
9630
9854
  function describeMatcher(matcher) {
9631
9855
  if (typeof matcher === "string") return matcher;
9632
9856
  if (matcher instanceof RegExp) return String(matcher);
@@ -9682,9 +9906,13 @@ function explainPath(config, target) {
9682
9906
  };
9683
9907
  }
9684
9908
  const absolute = path6__namespace.join(config.cwd, relative10);
9909
+ const stagedBlob = config.staged === true ? readStagedBlob(config.cwd, relative10) : null;
9685
9910
  const result = {
9686
9911
  path: maskedPath2,
9687
- exists: fs3__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),
9688
9916
  included: false
9689
9917
  };
9690
9918
  const collection = collectFiles(config.cwd, {
@@ -9763,11 +9991,13 @@ function explainPath(config, target) {
9763
9991
  result.detail = "binary extension; generate skips it without reading and records `binary` in manifest.skipped[]";
9764
9992
  return result;
9765
9993
  }
9766
- let sizeOnDisk = null;
9767
- try {
9768
- sizeOnDisk = fs3__namespace.statSync(absolute).size;
9769
- } catch {
9770
- 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
+ }
9771
10001
  }
9772
10002
  if (sizeOnDisk !== null && sizeOnDisk > BINARY_SCAN_BYTES && isBinaryFile(absolute)) {
9773
10003
  result.included = false;
@@ -9775,10 +10005,10 @@ function explainPath(config, target) {
9775
10005
  result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
9776
10006
  return result;
9777
10007
  }
9778
- if (fs3__namespace.existsSync(absolute) && fs3__namespace.statSync(absolute).isFile()) {
10008
+ if (stagedBlob !== null || safeRegularFile(config.cwd, absolute)) {
9779
10009
  let buffer;
9780
10010
  try {
9781
- buffer = fs3__namespace.readFileSync(absolute);
10011
+ buffer = stagedBlob ?? fs3__namespace.readFileSync(absolute);
9782
10012
  } catch (err) {
9783
10013
  result.included = false;
9784
10014
  result.reason = "read-error";
@@ -9827,6 +10057,22 @@ function explainPath(config, target) {
9827
10057
  const record = manifest?.skipped?.find((skip) => skip.path === relative10);
9828
10058
  if (record !== void 0 && (record.reason === "not-selected" || record.reason === "unchanged")) {
9829
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;
9830
10076
  result.reason = record.reason;
9831
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");
9832
10078
  }
@@ -9877,7 +10123,10 @@ const { parentPort, workerData } = require("node:worker_threads");
9877
10123
  (async () => {
9878
10124
  try {
9879
10125
  const mod = await import(workerData.entryUrl);
9880
- 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: [] };
9881
10130
  if (loaded.errors.length > 0) {
9882
10131
  parentPort.postMessage({ ok: false, message: loaded.errors.join("; ") });
9883
10132
  return;
@@ -9889,6 +10138,7 @@ const { parentPort, workerData } = require("node:worker_threads");
9889
10138
  const manifest = mod.generateSnapshot(config, {
9890
10139
  dryRun: workerData.dryRun === true,
9891
10140
  ...(workerData.narrow ?? {}),
10141
+ ...(workerData.source === undefined ? {} : { source: workerData.source }),
9892
10142
  ...(workerData.runId === undefined ? {} : { runId: workerData.runId }),
9893
10143
  });
9894
10144
  const skipCounts = new Map();
@@ -9954,6 +10204,8 @@ function generateInWorker(cwd, cliOptions, options = {}) {
9954
10204
  cliOptions,
9955
10205
  dryRun: options.dryRun === true,
9956
10206
  narrow: options.narrow ?? {},
10207
+ ...options.config === void 0 ? {} : { config: options.config },
10208
+ ...options.source === void 0 ? {} : { source: options.source },
9957
10209
  ...options.runId === void 0 ? {} : { runId: options.runId }
9958
10210
  }
9959
10211
  });
@@ -10006,62 +10258,6 @@ function windowText(body, fromLine, lineCount) {
10006
10258
  pastEnd
10007
10259
  };
10008
10260
  }
10009
- function isInside2(parent, child) {
10010
- const relative10 = path6__namespace.relative(parent, child);
10011
- return relative10 === "" || !relative10.startsWith("..") && !path6__namespace.isAbsolute(relative10);
10012
- }
10013
- function readConfinedText(baseDir, relativePath) {
10014
- if (relativePath.length === 0 || relativePath.includes("\0")) {
10015
- return { ok: false, reason: "not-file", message: "the file name is empty or contains a NUL byte" };
10016
- }
10017
- if (path6__namespace.isAbsolute(relativePath)) {
10018
- return { ok: false, reason: "outside", message: "an absolute path is not a snapshot-relative file" };
10019
- }
10020
- let baseReal;
10021
- try {
10022
- baseReal = fs3__namespace.realpathSync(path6__namespace.resolve(baseDir));
10023
- } catch {
10024
- return { ok: false, reason: "missing", message: "the snapshot directory does not exist" };
10025
- }
10026
- const candidate = path6__namespace.resolve(baseReal, relativePath);
10027
- if (!isInside2(baseReal, candidate)) {
10028
- return { ok: false, reason: "outside", message: "the path resolves outside the snapshot directory" };
10029
- }
10030
- let stats;
10031
- try {
10032
- stats = fs3__namespace.lstatSync(candidate);
10033
- } catch (error) {
10034
- const code = error.code;
10035
- return {
10036
- ok: false,
10037
- reason: code === "ENOENT" || code === "ENOTDIR" ? "missing" : "unreadable",
10038
- message: code === "ENOENT" || code === "ENOTDIR" ? "the file does not exist" : "the file could not be inspected"
10039
- };
10040
- }
10041
- if (stats.isSymbolicLink()) {
10042
- return { ok: false, reason: "not-file", message: "the file is a symbolic link" };
10043
- }
10044
- if (!stats.isFile()) {
10045
- return { ok: false, reason: "not-file", message: "the path is not a regular file" };
10046
- }
10047
- let real;
10048
- try {
10049
- real = fs3__namespace.realpathSync(candidate);
10050
- } catch {
10051
- return { ok: false, reason: "unreadable", message: "the file could not be resolved" };
10052
- }
10053
- if (!isInside2(baseReal, real)) {
10054
- return { ok: false, reason: "outside", message: "the file resolves outside the snapshot directory" };
10055
- }
10056
- try {
10057
- const text = fs3__namespace.readFileSync(real, "utf8");
10058
- return { ok: true, text, path: real, stats: fs3__namespace.statSync(real) };
10059
- } catch {
10060
- return { ok: false, reason: "unreadable", message: "the file could not be read" };
10061
- }
10062
- }
10063
-
10064
- // src/mcp/workspace.ts
10065
10261
  function foldForComparison(value) {
10066
10262
  return process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
10067
10263
  }
@@ -10309,11 +10505,18 @@ function unsafeRegExpReason(source) {
10309
10505
  if (char === ")") {
10310
10506
  const group = groups.pop();
10311
10507
  if (group === void 0) continue;
10312
- const next = source[index + 1];
10313
- if (next === "*" || next === "+" || next === "{" && isUnboundedBrace(source, index + 1)) {
10508
+ if (isQuantifiedAt(source, index + 1)) {
10314
10509
  if (group.quantified || group.alternation) {
10315
10510
  return "a quantified group contains another quantifier or an alternation";
10316
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;
10317
10520
  }
10318
10521
  continue;
10319
10522
  }
@@ -10360,11 +10563,31 @@ function unsafeRegExpReason(source) {
10360
10563
  }
10361
10564
  return null;
10362
10565
  }
10363
- function isUnboundedBrace(source, start) {
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;
10364
10583
  const close = source.indexOf("}", start + 1);
10365
10584
  if (close === -1) return false;
10366
10585
  const body = source.slice(start + 1, close);
10367
- return /^\d+,$/.test(body);
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;
10368
10591
  }
10369
10592
 
10370
10593
  // src/mcp/tools.ts
@@ -10759,7 +10982,12 @@ var workspaceTool = {
10759
10982
  };
10760
10983
  }
10761
10984
  const text = read.text;
10762
- const document = JSON.parse(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
+ }
10763
10991
  const members = document.members ?? [];
10764
10992
  const links = document.links ?? [];
10765
10993
  const lines = [
@@ -11074,11 +11302,17 @@ var searchTool = {
11074
11302
  } catch {
11075
11303
  continue;
11076
11304
  }
11077
- if (Buffer.byteLength(text, "utf8") > MAX_SEARCH_BYTES) {
11305
+ const partBytes = Buffer.byteLength(text, "utf8");
11306
+ if (partBytes > MAX_SEARCH_BYTES) {
11078
11307
  skippedOversize.push(part.filename);
11308
+ truncated = true;
11079
11309
  continue;
11080
11310
  }
11081
- scanned += text.length;
11311
+ if (scanned + partBytes > MAX_SEARCH_BYTES) {
11312
+ truncated = true;
11313
+ break;
11314
+ }
11315
+ scanned += partBytes;
11082
11316
  for (const section of parsePartSections(text)) {
11083
11317
  if (matches.length >= cap) {
11084
11318
  truncated = true;
@@ -12041,7 +12275,12 @@ var planTool = {
12041
12275
  const prepared = await prepare(args, context, workspaceOverrides(args));
12042
12276
  if (!prepared.ok) return prepared.outcome;
12043
12277
  const workspace = prepared.workspace;
12044
- 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
+ });
12045
12284
  if (!result.ok) return failure(result.message);
12046
12285
  const summary = result.summary;
12047
12286
  const topReasons = summary.skipReasons;
@@ -12249,7 +12488,12 @@ function configAsGenerated(workspace, manifest) {
12249
12488
  ...cli.includeLogs !== void 0 || configured("logCount") || recorded?.logCount !== void 0 ? { logCount: choose("logCount", recorded?.logCount, workspace.config.logCount, cli.includeLogs) } : {},
12250
12489
  ...cli.skeleton === true || configured("skeleton") || recorded?.skeleton !== void 0 ? { skeleton: choose("skeleton", recorded?.skeleton, workspace.config.skeleton, cli.skeleton === true ? true : void 0) } : {},
12251
12490
  ...cli.sarif === true || configured("sarif") || recorded?.sarif !== void 0 ? { sarif: choose("sarif", recorded?.sarif, workspace.config.sarif, cli.sarif === true ? true : void 0) } : {},
12252
- ...configured("maxParts") || recorded?.maxParts !== void 0 ? { maxParts: choose("maxParts", recorded?.maxParts, workspace.config.maxParts) } : {}
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) } : {}
12253
12497
  };
12254
12498
  }
12255
12499
  var validateTool = {
@@ -12923,10 +13167,22 @@ async function runStdioServer(options) {
12923
13167
  )
12924
13168
  );
12925
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
+ };
12926
13178
  const stopReading = createLineReader(process.stdin, {
12927
13179
  onOverflow: (bytes) => log(`mcp: discarded an oversized message (${bytes} bytes)`),
12928
13180
  onLine: (line) => {
12929
13181
  if (inFlight >= MAX_IN_FLIGHT2) {
13182
+ if (isCancellation(line)) {
13183
+ void handleLine(line);
13184
+ return;
13185
+ }
12930
13186
  rejectOverloaded(line);
12931
13187
  return;
12932
13188
  }
@@ -12959,7 +13215,12 @@ function resolveSafeOutputDirs(config) {
12959
13215
  const outDir = path6__namespace.resolve(cwd, config.outDir);
12960
13216
  const tmpDir = path6__namespace.resolve(cwd, config.tmpDir);
12961
13217
  const root = path6__namespace.parse(cwd).root;
12962
- 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
+ };
12963
13224
  const reject = (reason) => {
12964
13225
  throw new Error(
12965
13226
  `Refusing to generate: ${reason}. outDir=${outDir} tmpDir=${tmpDir} cwd=${cwd}`
@@ -13274,7 +13535,7 @@ var COMMAND_OPTION_SCOPE = {
13274
13535
  "version"
13275
13536
  ],
13276
13537
  diff: ["format", "mode", "no-config", "no-update-check", "help", "version"],
13277
- describe: ["format", "mode", "help", "version"],
13538
+ describe: ["format", "mode", "no-update-check", "help", "version"],
13278
13539
  init: [
13279
13540
  "install-hook",
13280
13541
  "cwd",
@@ -13295,7 +13556,7 @@ var COMMAND_OPTION_SCOPE = {
13295
13556
  "help",
13296
13557
  "version"
13297
13558
  ],
13298
- skill: ["cwd", "format", "mode", "install", "target", "help", "version"],
13559
+ skill: ["cwd", "format", "mode", "install", "target", "no-update-check", "help", "version"],
13299
13560
  // `mcp` reads the repository, so it takes --cwd. It has no --format: stdout carries JSON-RPC
13300
13561
  // messages, and there is no second shape to choose, so offering the flag would be a lie.
13301
13562
  serve: ["port", "host", "token", "no-auth", "allow-private", "cwd", "no-update-check", "help"],
@@ -13354,6 +13615,7 @@ var COMMAND_ORDER = [
13354
13615
  "health",
13355
13616
  "report",
13356
13617
  "explain",
13618
+ "update",
13357
13619
  "init",
13358
13620
  "setup",
13359
13621
  "diff",
@@ -13746,24 +14008,28 @@ function buildAgentContract() {
13746
14008
  {
13747
14009
  flag: "--only",
13748
14010
  type: "string",
14011
+ default: "unset",
13749
14012
  summary: "Comma-separated globs to include: overrides the config include list for this run.",
13750
14013
  appliesTo: optionAppliesTo("only")
13751
14014
  },
13752
14015
  {
13753
14016
  flag: "--ignore",
13754
14017
  type: "string",
14018
+ default: "unset",
13755
14019
  summary: "Comma-separated globs to exclude, added to the config exclude list for this run.",
13756
14020
  appliesTo: optionAppliesTo("ignore")
13757
14021
  },
13758
14022
  {
13759
14023
  flag: "--remove-empty-lines",
13760
14024
  type: "boolean",
14025
+ default: false,
13761
14026
  summary: "Drop blank and whitespace-only lines from emitted bodies; line numbers no longer match the source.",
13762
14027
  appliesTo: optionAppliesTo("remove-empty-lines")
13763
14028
  },
13764
14029
  {
13765
14030
  flag: "--all-members",
13766
14031
  type: "boolean",
14032
+ default: false,
13767
14033
  summary: "Audit every snapshot a --workspace run wrote, not only the one at outDir.",
13768
14034
  appliesTo: optionAppliesTo("all-members")
13769
14035
  },
@@ -14976,6 +15242,7 @@ var RATE_LIMIT = 60;
14976
15242
  var RATE_WINDOW_MS = 1e4;
14977
15243
  var MAX_IN_FLIGHT = 4;
14978
15244
  var MAX_SESSION_ENTRIES = 64;
15245
+ var MAX_SSE_SESSIONS = 64;
14979
15246
  var MAX_RATE_WINDOWS = 1024;
14980
15247
  function generateToken() {
14981
15248
  return crypto5__namespace.randomBytes(24).toString("base64url");
@@ -15013,10 +15280,7 @@ async function startHttpTransport(options) {
15013
15280
  const mcpSessions = /* @__PURE__ */ new Map();
15014
15281
  const socketServers = /* @__PURE__ */ new WeakMap();
15015
15282
  const rememberSession = (id, server) => {
15016
- if (!mcpSessions.has(id) && mcpSessions.size >= MAX_SESSION_ENTRIES) {
15017
- const oldest = mcpSessions.keys().next().value;
15018
- if (oldest !== void 0) mcpSessions.delete(oldest);
15019
- }
15283
+ if (!mcpSessions.has(id) && mcpSessions.size >= MAX_SESSION_ENTRIES) return;
15020
15284
  mcpSessions.set(id, server);
15021
15285
  };
15022
15286
  const anonymousServers = /* @__PURE__ */ new Map();
@@ -15163,6 +15427,10 @@ async function startHttpTransport(options) {
15163
15427
  return;
15164
15428
  }
15165
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
+ }
15166
15434
  const lines = [
15167
15435
  "# HELP snapshot_uptime_seconds Seconds since the process started.",
15168
15436
  "# TYPE snapshot_uptime_seconds gauge",
@@ -15200,6 +15468,10 @@ async function startHttpTransport(options) {
15200
15468
  send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
15201
15469
  return;
15202
15470
  }
15471
+ if (sseSessions.size >= MAX_SSE_SESSIONS) {
15472
+ send(503, { error: "too many open SSE sessions" }, { ...cors, "retry-after": "10" });
15473
+ return;
15474
+ }
15203
15475
  const id = crypto5__namespace.randomBytes(12).toString("hex");
15204
15476
  response.writeHead(200, {
15205
15477
  ...cors,
@@ -15209,9 +15481,21 @@ async function startHttpTransport(options) {
15209
15481
  "x-accel-buffering": "no"
15210
15482
  });
15211
15483
  const write = (payload) => {
15212
- response.write(payload);
15484
+ try {
15485
+ response.write(payload);
15486
+ } catch {
15487
+ }
15213
15488
  };
15214
- 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
+ });
15215
15499
  const heartbeat = setInterval(() => write(": ping\n\n"), 15e3);
15216
15500
  const cleanup = () => {
15217
15501
  clearInterval(heartbeat);
@@ -15276,7 +15560,13 @@ async function startHttpTransport(options) {
15276
15560
  if (gated) releaseToolSlot();
15277
15561
  }
15278
15562
  send(202, "", cors);
15279
- })();
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
+ });
15280
15570
  });
15281
15571
  return;
15282
15572
  }