codebase-snapshot 0.20.4 → 0.20.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -3,9 +3,9 @@
3
3
  var crypto = require('crypto');
4
4
  var worker_threads = require('worker_threads');
5
5
  var async_hooks = require('async_hooks');
6
- var fs24 = require('fs');
6
+ var fs25 = require('fs');
7
7
  var os2 = require('os');
8
- var path25 = require('path');
8
+ var path26 = require('path');
9
9
  var ts = require('typescript');
10
10
  var module$1 = require('module');
11
11
  var url = require('url');
@@ -37,9 +37,9 @@ function _interopNamespace(e) {
37
37
  }
38
38
 
39
39
  var crypto__namespace = /*#__PURE__*/_interopNamespace(crypto);
40
- var fs24__namespace = /*#__PURE__*/_interopNamespace(fs24);
40
+ var fs25__namespace = /*#__PURE__*/_interopNamespace(fs25);
41
41
  var os2__namespace = /*#__PURE__*/_interopNamespace(os2);
42
- var path25__namespace = /*#__PURE__*/_interopNamespace(path25);
42
+ var path26__namespace = /*#__PURE__*/_interopNamespace(path26);
43
43
  var ts__default = /*#__PURE__*/_interopDefault(ts);
44
44
  var childProcess__namespace = /*#__PURE__*/_interopNamespace(childProcess);
45
45
  var http__namespace = /*#__PURE__*/_interopNamespace(http);
@@ -414,9 +414,9 @@ var JAVA_METHOD = /^\s+(?:public|private|protected)\s+(?:static\s+)?(?:final\s+)
414
414
  var jvmProfile = {
415
415
  id: "jvm",
416
416
  extensions: [".java", ".kt", ".kts", ".scala"],
417
- summarize(path26, content) {
417
+ summarize(path27, content) {
418
418
  const summary = emptySummary();
419
- const lower = path26.toLowerCase();
419
+ const lower = path27.toLowerCase();
420
420
  const isJava = lower.endsWith(".java");
421
421
  const isKotlin = lower.endsWith(".kt") || lower.endsWith(".kts");
422
422
  eachLine(content, (line) => {
@@ -639,9 +639,9 @@ var rubyProfile = {
639
639
  eachLine(content, (line) => {
640
640
  const trimmed = line.trim();
641
641
  if (!trimmed || trimmed.startsWith("#")) return;
642
- const relative14 = REQUIRE_RELATIVE.exec(trimmed);
643
- if (relative14) {
644
- summary.imports.push(`./${relative14[1]}`);
642
+ const relative15 = REQUIRE_RELATIVE.exec(trimmed);
643
+ if (relative15) {
644
+ summary.imports.push(`./${relative15[1]}`);
645
645
  return;
646
646
  }
647
647
  const required = REQUIRE.exec(trimmed);
@@ -1024,17 +1024,17 @@ function summarizeTypeScriptSource(relativePath, content) {
1024
1024
  var SCRIPT_BLOCK = /<script([^>]*)>([\s\S]*?)<\/script>/gi;
1025
1025
  var JSX_LANG = /\blang\s*=\s*["']?[tj]sx\b/i;
1026
1026
  var ASTRO_FRONTMATTER = /^\uFEFF?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?=\r?\n|$)/;
1027
- function componentName(path26) {
1028
- const base = path26.split("/").pop() ?? path26;
1027
+ function componentName(path27) {
1028
+ const base = path27.split("/").pop() ?? path27;
1029
1029
  return base.replace(/\.[^.]+$/, "");
1030
1030
  }
1031
1031
  var sfcProfile = {
1032
1032
  id: "sfc",
1033
1033
  extensions: [".vue", ".svelte", ".astro"],
1034
- summarize(path26, content) {
1034
+ summarize(path27, content) {
1035
1035
  let script = "";
1036
- let usesJsx = path26.toLowerCase().endsWith(".astro");
1037
- if (path26.toLowerCase().endsWith(".astro")) {
1036
+ let usesJsx = path27.toLowerCase().endsWith(".astro");
1037
+ if (path27.toLowerCase().endsWith(".astro")) {
1038
1038
  const frontmatter = ASTRO_FRONTMATTER.exec(content);
1039
1039
  if (frontmatter) script += `${frontmatter[1]}
1040
1040
  `;
@@ -1044,7 +1044,7 @@ var sfcProfile = {
1044
1044
  script += `${match[2]}
1045
1045
  `;
1046
1046
  }
1047
- const name = componentName(path26);
1047
+ const name = componentName(path27);
1048
1048
  if (!script.trim()) {
1049
1049
  const summary2 = emptySummary();
1050
1050
  if (name) {
@@ -1235,15 +1235,15 @@ for (const profile of LANGUAGE_PROFILES) {
1235
1235
  BY_EXTENSION.set(extension.toLowerCase(), profile);
1236
1236
  }
1237
1237
  }
1238
- function profileForPath(path26) {
1239
- const lower = path26.toLowerCase();
1238
+ function profileForPath(path27) {
1239
+ const lower = path27.toLowerCase();
1240
1240
  const dot = lower.lastIndexOf(".");
1241
1241
  if (dot === -1) return null;
1242
1242
  return BY_EXTENSION.get(lower.slice(dot)) ?? null;
1243
1243
  }
1244
- function summarizeWithProfile(path26, content) {
1245
- const profile = profileForPath(path26);
1246
- return profile ? profile.summarize(path26, content) : null;
1244
+ function summarizeWithProfile(path27, content) {
1245
+ const profile = profileForPath(path27);
1246
+ return profile ? profile.summarize(path27, content) : null;
1247
1247
  }
1248
1248
  var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
1249
1249
  ".png",
@@ -1288,7 +1288,7 @@ var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
1288
1288
  ".so"
1289
1289
  ]);
1290
1290
  function isBinaryExtension(filePath) {
1291
- const ext = path25__namespace.extname(filePath).toLowerCase();
1291
+ const ext = path26__namespace.extname(filePath).toLowerCase();
1292
1292
  return BINARY_EXTENSIONS.has(ext);
1293
1293
  }
1294
1294
  function isBinaryBuffer(buffer) {
@@ -1458,13 +1458,13 @@ function isBinaryFile(absolutePath) {
1458
1458
  if (isBinaryExtension(absolutePath)) return true;
1459
1459
  let fd;
1460
1460
  try {
1461
- fd = fs24__namespace.openSync(absolutePath, "r");
1461
+ fd = fs25__namespace.openSync(absolutePath, "r");
1462
1462
  const buffer = Buffer.alloc(CHUNK);
1463
1463
  let sample2;
1464
1464
  let position = 0;
1465
1465
  while (position < BINARY_SCAN_BYTES) {
1466
1466
  const wanted = Math.min(CHUNK, BINARY_SCAN_BYTES - position);
1467
- const bytesRead = fs24__namespace.readSync(fd, buffer, 0, wanted, position);
1467
+ const bytesRead = fs25__namespace.readSync(fd, buffer, 0, wanted, position);
1468
1468
  if (bytesRead === 0) return false;
1469
1469
  const chunk = buffer.subarray(0, bytesRead);
1470
1470
  if (sample2 === void 0) {
@@ -1482,7 +1482,7 @@ function isBinaryFile(absolutePath) {
1482
1482
  } finally {
1483
1483
  if (fd !== void 0) {
1484
1484
  try {
1485
- fs24__namespace.closeSync(fd);
1485
+ fs25__namespace.closeSync(fd);
1486
1486
  } catch {
1487
1487
  }
1488
1488
  }
@@ -1504,9 +1504,9 @@ function importsOfText(relativePath, text2) {
1504
1504
  function importsOfFile(relativePath, absolutePath) {
1505
1505
  let buffer;
1506
1506
  try {
1507
- const stats = fs24__namespace.statSync(absolutePath);
1507
+ const stats = fs25__namespace.statSync(absolutePath);
1508
1508
  if (!stats.isFile() || stats.size > SUMMARY_MAX_SOURCE_BYTES) return [];
1509
- buffer = fs24__namespace.readFileSync(absolutePath);
1509
+ buffer = fs25__namespace.readFileSync(absolutePath);
1510
1510
  } catch {
1511
1511
  return [];
1512
1512
  }
@@ -1885,15 +1885,15 @@ var SKIPPED_WALK_DIRS = /* @__PURE__ */ new Set([
1885
1885
  ]);
1886
1886
  function readSmallFile(fullPath) {
1887
1887
  try {
1888
- const stats = fs24__namespace.statSync(fullPath);
1888
+ const stats = fs25__namespace.statSync(fullPath);
1889
1889
  if (!stats.isFile() || stats.size > MANIFEST_MAX_BYTES) return null;
1890
- return fs24__namespace.readFileSync(fullPath, "utf8");
1890
+ return fs25__namespace.readFileSync(fullPath, "utf8");
1891
1891
  } catch {
1892
1892
  return null;
1893
1893
  }
1894
1894
  }
1895
1895
  function readManifest(cwd, name) {
1896
- return readSmallFile(path25__namespace.join(cwd, name));
1896
+ return readSmallFile(path26__namespace.join(cwd, name));
1897
1897
  }
1898
1898
  function dependenciesFromPackageJson(raw) {
1899
1899
  const names = /* @__PURE__ */ new Set();
@@ -1953,7 +1953,7 @@ function pnpmWorkspacePatterns(raw) {
1953
1953
  function childDirectories(cwd, parent) {
1954
1954
  let entries;
1955
1955
  try {
1956
- entries = fs24__namespace.readdirSync(path25__namespace.join(cwd, parent), { withFileTypes: true });
1956
+ entries = fs25__namespace.readdirSync(path26__namespace.join(cwd, parent), { withFileTypes: true });
1957
1957
  } catch {
1958
1958
  return [];
1959
1959
  }
@@ -1988,13 +1988,13 @@ function workspacePackageDirs(cwd, patterns) {
1988
1988
  function scanWorkspacePackages(cwd, patterns) {
1989
1989
  const files = /* @__PURE__ */ new Set();
1990
1990
  const dependencies = /* @__PURE__ */ new Set();
1991
- for (const relative14 of workspacePackageDirs(cwd, patterns)) {
1992
- const full = path25__namespace.join(cwd, relative14);
1991
+ for (const relative15 of workspacePackageDirs(cwd, patterns)) {
1992
+ const full = path26__namespace.join(cwd, relative15);
1993
1993
  try {
1994
- for (const entry of fs24__namespace.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
1994
+ for (const entry of fs25__namespace.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
1995
1995
  } catch {
1996
1996
  }
1997
- const raw = readSmallFile(path25__namespace.join(full, "package.json"));
1997
+ const raw = readSmallFile(path26__namespace.join(full, "package.json"));
1998
1998
  if (raw !== null) {
1999
1999
  for (const name of dependenciesFromPackageJson(raw)) dependencies.add(name);
2000
2000
  }
@@ -2004,7 +2004,7 @@ function scanWorkspacePackages(cwd, patterns) {
2004
2004
  var SNAPSHOT_MARKER = ".codebase-snapshot";
2005
2005
  function isToolOwnedDirectory(dir) {
2006
2006
  try {
2007
- return fs24__namespace.statSync(dir).isDirectory() && fs24__namespace.existsSync(path25__namespace.join(dir, SNAPSHOT_MARKER));
2007
+ return fs25__namespace.statSync(dir).isDirectory() && fs25__namespace.existsSync(path26__namespace.join(dir, SNAPSHOT_MARKER));
2008
2008
  } catch {
2009
2009
  return false;
2010
2010
  }
@@ -2019,7 +2019,7 @@ function countMarkdownFiles(cwd) {
2019
2019
  directoriesSeen += 1;
2020
2020
  let entries;
2021
2021
  try {
2022
- entries = fs24__namespace.readdirSync(current.dir, { withFileTypes: true });
2022
+ entries = fs25__namespace.readdirSync(current.dir, { withFileTypes: true });
2023
2023
  } catch {
2024
2024
  continue;
2025
2025
  }
@@ -2030,7 +2030,7 @@ function countMarkdownFiles(cwd) {
2030
2030
  }
2031
2031
  if (!entry.isDirectory() || current.depth >= 2) continue;
2032
2032
  if (entry.name.startsWith(".") || SKIPPED_WALK_DIRS.has(entry.name)) continue;
2033
- const child = path25__namespace.join(current.dir, entry.name);
2033
+ const child = path26__namespace.join(current.dir, entry.name);
2034
2034
  if (isToolOwnedDirectory(child)) continue;
2035
2035
  queue.push({ dir: child, depth: current.depth + 1 });
2036
2036
  }
@@ -2041,7 +2041,7 @@ function buildPresetContext(cwd) {
2041
2041
  const files = /* @__PURE__ */ new Set();
2042
2042
  const dirs = /* @__PURE__ */ new Set();
2043
2043
  try {
2044
- for (const entry of fs24__namespace.readdirSync(cwd, { withFileTypes: true })) {
2044
+ for (const entry of fs25__namespace.readdirSync(cwd, { withFileTypes: true })) {
2045
2045
  if (entry.isDirectory()) dirs.add(entry.name);
2046
2046
  else if (entry.isFile()) files.add(entry.name);
2047
2047
  }
@@ -2058,7 +2058,7 @@ function buildPresetContext(cwd) {
2058
2058
  const isWorkspace = files.has("pnpm-workspace.yaml") || files.has("nx.json") || files.has("turbo.json") || files.has("lerna.json") || packageJson !== void 0 && packageJson.includes('"workspaces"') || declaredWorkspaces.length > 0;
2059
2059
  let workspace = { files: /* @__PURE__ */ new Set(), dependencies: /* @__PURE__ */ new Set() };
2060
2060
  if (isWorkspace) {
2061
- const pnpmRaw = files.has("pnpm-workspace.yaml") ? readSmallFile(path25__namespace.join(cwd, "pnpm-workspace.yaml")) : null;
2061
+ const pnpmRaw = files.has("pnpm-workspace.yaml") ? readSmallFile(path26__namespace.join(cwd, "pnpm-workspace.yaml")) : null;
2062
2062
  const declared = pnpmRaw === null ? [] : pnpmWorkspacePatterns(pnpmRaw);
2063
2063
  const patterns = declared.length > 0 ? declared : declaredWorkspaces.length > 0 ? declaredWorkspaces : DEFAULT_WORKSPACE_PATTERNS;
2064
2064
  workspace = scanWorkspacePackages(cwd, patterns);
@@ -3203,7 +3203,7 @@ var DEFAULT_SECRET_PATTERNS = [
3203
3203
  // rendering of textual userinfo mixes cases, while the prose the earlier rules were
3204
3204
  // protecting (`Bearer authentication`) is a lowercase word.
3205
3205
  rule: "authorization-header",
3206
- 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_.+/=-])/
3206
+ 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_.+/=-])/
3207
3207
  },
3208
3208
  {
3209
3209
  // Broader names than before (`apiKey`, `clientSecret`, `privateKey` were
@@ -3781,6 +3781,7 @@ function redactStructuredValues(text2, filePath, recordFinding) {
3781
3781
  if (firstValue === void 0) continue;
3782
3782
  const valueIndent = (/^[ \t]*/.exec(firstValue)?.[0] ?? "").length;
3783
3783
  if (valueIndent <= baseIndent) continue;
3784
+ if (STRUCTURED_KEY.test(firstValue) || /^[ \t]*-[ \t]/.test(firstValue)) continue;
3784
3785
  let masked = false;
3785
3786
  while (cursor < segments.length) {
3786
3787
  const body = segments[cursor] ?? "";
@@ -4019,7 +4020,7 @@ function applySpansKeepingQuotes(line, spans) {
4019
4020
  }
4020
4021
  var SIGNATURE_FILE = "signature.json";
4021
4022
  function signManifest(manifestPath, options = {}) {
4022
- const bytes = fs24__namespace.readFileSync(manifestPath);
4023
+ const bytes = fs25__namespace.readFileSync(manifestPath);
4023
4024
  const manifest = JSON.parse(bytes.toString("utf8"));
4024
4025
  if (typeof manifest.fingerprint !== "string" || !/^[0-9a-f]{64}$/.test(manifest.fingerprint)) {
4025
4026
  throw new Error("refusing to sign: the manifest has no valid fingerprint");
@@ -4039,12 +4040,12 @@ function signManifest(manifestPath, options = {}) {
4039
4040
  };
4040
4041
  }
4041
4042
  function verifySnapshotSignature(snapshotDir) {
4042
- const signaturePath = path25__namespace.join(snapshotDir, SIGNATURE_FILE);
4043
- const manifestPath = path25__namespace.join(snapshotDir, "manifest.json");
4044
- if (!fs24__namespace.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
4043
+ const signaturePath = path26__namespace.join(snapshotDir, SIGNATURE_FILE);
4044
+ const manifestPath = path26__namespace.join(snapshotDir, "manifest.json");
4045
+ if (!fs25__namespace.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
4045
4046
  let record;
4046
4047
  try {
4047
- record = JSON.parse(fs24__namespace.readFileSync(signaturePath, "utf8"));
4048
+ record = JSON.parse(fs25__namespace.readFileSync(signaturePath, "utf8"));
4048
4049
  } catch (error) {
4049
4050
  return { ok: false, reason: "signature.json is not JSON: " + error.message };
4050
4051
  }
@@ -4053,7 +4054,7 @@ function verifySnapshotSignature(snapshotDir) {
4053
4054
  }
4054
4055
  let bytes;
4055
4056
  try {
4056
- bytes = fs24__namespace.readFileSync(manifestPath);
4057
+ bytes = fs25__namespace.readFileSync(manifestPath);
4057
4058
  } catch {
4058
4059
  return { ok: false, reason: "the signed manifest is missing" };
4059
4060
  }
@@ -4073,7 +4074,7 @@ function verifySnapshotSignature(snapshotDir) {
4073
4074
 
4074
4075
  // src/version.ts
4075
4076
  var GENERATOR_NAME = "codebase-snapshot";
4076
- var GENERATOR_VERSION = "0.20.4";
4077
+ var GENERATOR_VERSION = "0.20.5";
4077
4078
  var SCHEMA_VERSION = "3.0.0";
4078
4079
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
4079
4080
  function isOurGeneratorName(name) {
@@ -4090,14 +4091,14 @@ var PRESET_IGNORES = new Set(
4090
4091
  );
4091
4092
  function readLinkTarget(linkPath, fallback) {
4092
4093
  try {
4093
- return fs24__namespace.readlinkSync(linkPath);
4094
+ return fs25__namespace.readlinkSync(linkPath);
4094
4095
  } catch {
4095
4096
  return fallback;
4096
4097
  }
4097
4098
  }
4098
4099
  function brokenLinkRecord(linkPath, relativePath, rootReal) {
4099
4100
  const rawTarget = readLinkTarget(linkPath, linkPath);
4100
- const resolvedFallback = path25__namespace.resolve(path25__namespace.dirname(linkPath), rawTarget);
4101
+ const resolvedFallback = path26__namespace.resolve(path26__namespace.dirname(linkPath), rawTarget);
4101
4102
  return isInside(rootReal, resolvedFallback) ? { path: relativePath, reason: "read-error", detail: "broken symlink" } : {
4102
4103
  path: relativePath,
4103
4104
  reason: "outside-root",
@@ -4105,8 +4106,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
4105
4106
  };
4106
4107
  }
4107
4108
  function isInside(root, candidate) {
4108
- const relative14 = path25__namespace.relative(root, candidate);
4109
- return relative14 === "" || !relative14.startsWith(`..${path25__namespace.sep}`) && relative14 !== ".." && !path25__namespace.isAbsolute(relative14);
4109
+ const relative15 = path26__namespace.relative(root, candidate);
4110
+ return relative15 === "" || !relative15.startsWith(`..${path26__namespace.sep}`) && relative15 !== ".." && !path26__namespace.isAbsolute(relative15);
4110
4111
  }
4111
4112
  var GIT_OUTPUT_LIMIT = 68157440;
4112
4113
  function getGitInfo(cwd, fallbackBranch = "main") {
@@ -4366,10 +4367,10 @@ function trimUnescapedTrailingSpaces(line) {
4366
4367
  return line.slice(0, end);
4367
4368
  }
4368
4369
  function readGitignoreRules(dir) {
4369
- const gitignorePath2 = path25__namespace.join(dir, ".gitignore");
4370
+ const gitignorePath2 = path26__namespace.join(dir, ".gitignore");
4370
4371
  let raw;
4371
4372
  try {
4372
- raw = fs24__namespace.readFileSync(gitignorePath2, "utf8");
4373
+ raw = fs25__namespace.readFileSync(gitignorePath2, "utf8");
4373
4374
  } catch {
4374
4375
  return [];
4375
4376
  }
@@ -4580,7 +4581,7 @@ function listIgnoredPaths(cwd) {
4580
4581
  }
4581
4582
  function hasSnapshotMarker(target) {
4582
4583
  try {
4583
- return fs24__namespace.statSync(target).isDirectory() && isToolOwnedDirectory2(target);
4584
+ return fs25__namespace.statSync(target).isDirectory() && isToolOwnedDirectory2(target);
4584
4585
  } catch {
4585
4586
  return false;
4586
4587
  }
@@ -4589,7 +4590,7 @@ var IGNORABLE_DIRECTORY_ENTRIES = /* @__PURE__ */ new Set([".DS_Store"]);
4589
4590
  function isToolOwnedDirectory2(dir) {
4590
4591
  let raw;
4591
4592
  try {
4592
- raw = fs24__namespace.readFileSync(path25__namespace.join(dir, ".codebase-snapshot"), "utf8");
4593
+ raw = fs25__namespace.readFileSync(path26__namespace.join(dir, ".codebase-snapshot"), "utf8");
4593
4594
  } catch {
4594
4595
  return false;
4595
4596
  }
@@ -4616,7 +4617,7 @@ function isToolOwnedDirectory2(dir) {
4616
4617
  }
4617
4618
  let entries;
4618
4619
  try {
4619
- entries = fs24__namespace.readdirSync(dir);
4620
+ entries = fs25__namespace.readdirSync(dir);
4620
4621
  } catch {
4621
4622
  return false;
4622
4623
  }
@@ -4635,7 +4636,7 @@ function makeToolOwnedDecider(cwd, toolOwnedPaths) {
4635
4636
  const prefix = parts.slice(0, depth).join("/");
4636
4637
  let hasMarker = markers.get(prefix);
4637
4638
  if (hasMarker === void 0) {
4638
- hasMarker = isToolOwnedDirectory2(path25__namespace.join(cwd, prefix));
4639
+ hasMarker = isToolOwnedDirectory2(path26__namespace.join(cwd, prefix));
4639
4640
  markers.set(prefix, hasMarker);
4640
4641
  }
4641
4642
  if (hasMarker) return true;
@@ -4650,7 +4651,7 @@ function makeLinkProbe() {
4650
4651
  let known = cache.get(absolutePath);
4651
4652
  if (known === void 0) {
4652
4653
  try {
4653
- known = fs24__namespace.lstatSync(absolutePath).isSymbolicLink();
4654
+ known = fs25__namespace.lstatSync(absolutePath).isSymbolicLink();
4654
4655
  } catch {
4655
4656
  known = false;
4656
4657
  }
@@ -4663,7 +4664,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
4663
4664
  const isLink = makeLinkProbe();
4664
4665
  let rootReal = cwd;
4665
4666
  try {
4666
- rootReal = fs24__namespace.realpathSync(cwd);
4667
+ rootReal = fs25__namespace.realpathSync(cwd);
4667
4668
  } catch {
4668
4669
  }
4669
4670
  const reported = /* @__PURE__ */ new Set();
@@ -4678,7 +4679,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
4678
4679
  let linkedPath = null;
4679
4680
  for (let depth = 1; depth <= parts.length; depth += 1) {
4680
4681
  const prefix = parts.slice(0, depth).join("/");
4681
- if (isLink(path25__namespace.join(cwd, prefix))) {
4682
+ if (isLink(path26__namespace.join(cwd, prefix))) {
4682
4683
  linkedPath = prefix;
4683
4684
  break;
4684
4685
  }
@@ -4687,11 +4688,11 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
4687
4688
  kept.push(candidate);
4688
4689
  continue;
4689
4690
  }
4690
- const absolute = path25__namespace.join(cwd, linkedPath);
4691
+ const absolute = path26__namespace.join(cwd, linkedPath);
4691
4692
  const rawTarget = readLinkTarget(absolute, absolute);
4692
4693
  let targetReal = null;
4693
4694
  try {
4694
- targetReal = fs24__namespace.realpathSync(absolute);
4695
+ targetReal = fs25__namespace.realpathSync(absolute);
4695
4696
  } catch {
4696
4697
  targetReal = null;
4697
4698
  }
@@ -4709,7 +4710,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
4709
4710
  }
4710
4711
  let stats = null;
4711
4712
  try {
4712
- stats = fs24__namespace.statSync(absolute);
4713
+ stats = fs25__namespace.statSync(absolute);
4713
4714
  } catch {
4714
4715
  stats = null;
4715
4716
  }
@@ -4733,7 +4734,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
4733
4734
  });
4734
4735
  continue;
4735
4736
  }
4736
- const targetRelative = path25__namespace.relative(rootReal, targetReal).split(path25__namespace.sep).join("/");
4737
+ const targetRelative = path26__namespace.relative(rootReal, targetReal).split(path26__namespace.sep).join("/");
4737
4738
  if (isSensitivePath(targetRelative)) {
4738
4739
  report2(linkedPath, {
4739
4740
  path: linkedPath,
@@ -4806,7 +4807,7 @@ function collectFiles(cwd, options = {}) {
4806
4807
  "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."
4807
4808
  );
4808
4809
  }
4809
- if (fs24__namespace.existsSync(path25__namespace.join(cwd, ".git"))) {
4810
+ if (fs25__namespace.existsSync(path26__namespace.join(cwd, ".git"))) {
4810
4811
  throw new Error(
4811
4812
  "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."
4812
4813
  );
@@ -4825,7 +4826,7 @@ function collectFiles(cwd, options = {}) {
4825
4826
  candidates.push(extra);
4826
4827
  }
4827
4828
  }
4828
- const files = candidates.filter((file) => {
4829
+ let files = candidates.filter((file) => {
4829
4830
  if (isToolOwned(file)) return false;
4830
4831
  const ignored = defaultIgnoreReason(file, toolDirNames);
4831
4832
  if (ignored) {
@@ -4870,11 +4871,53 @@ function collectFiles(cwd, options = {}) {
4870
4871
  }
4871
4872
  return true;
4872
4873
  }).sort();
4874
+ files = dropSymlinksToUnincludedTargets(cwd, files, skipped);
4873
4875
  return { files, skipped: maskSkipPaths(skipped, pathRules) };
4874
4876
  }
4877
+ function dropSymlinksToUnincludedTargets(cwd, files, skipped) {
4878
+ const aliases = /* @__PURE__ */ new Set();
4879
+ for (const file of files) {
4880
+ try {
4881
+ if (fs25__namespace.lstatSync(path26__namespace.join(cwd, file)).isSymbolicLink()) aliases.add(file);
4882
+ } catch {
4883
+ }
4884
+ }
4885
+ if (aliases.size === 0) return [...files];
4886
+ const includedTargets = /* @__PURE__ */ new Set();
4887
+ for (const file of files) {
4888
+ try {
4889
+ includedTargets.add(fs25__namespace.realpathSync(path26__namespace.join(cwd, file)));
4890
+ } catch {
4891
+ }
4892
+ }
4893
+ const kept = [];
4894
+ for (const file of files) {
4895
+ if (!aliases.has(file)) {
4896
+ kept.push(file);
4897
+ continue;
4898
+ }
4899
+ let target;
4900
+ try {
4901
+ target = fs25__namespace.realpathSync(path26__namespace.join(cwd, file));
4902
+ } catch {
4903
+ skipped.push({ path: file, reason: "read-error", detail: "symlink target could not be resolved" });
4904
+ continue;
4905
+ }
4906
+ if (includedTargets.has(target)) {
4907
+ kept.push(file);
4908
+ continue;
4909
+ }
4910
+ skipped.push({
4911
+ path: file,
4912
+ reason: "symlink",
4913
+ detail: "link target was excluded from the snapshot; not followed"
4914
+ });
4915
+ }
4916
+ return kept;
4917
+ }
4875
4918
  function rootRealFor(root) {
4876
4919
  try {
4877
- return fs24__namespace.realpathSync(root);
4920
+ return fs25__namespace.realpathSync(root);
4878
4921
  } catch {
4879
4922
  return root;
4880
4923
  }
@@ -4883,18 +4926,18 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
4883
4926
  const results = { files: [], skipped: [] };
4884
4927
  const stack = [];
4885
4928
  const toolDirNames = toolDirNamesFor(reservedPaths);
4886
- const relativeToBase = (target) => path25__namespace.relative(baseDir, target).replace(/\\/g, "/") || ".";
4929
+ const relativeToBase = (target) => path26__namespace.relative(baseDir, target).replace(/\\/g, "/") || ".";
4887
4930
  const enter = (current, layers) => {
4888
4931
  if (visited.has(current)) return false;
4889
4932
  visited.add(current);
4890
4933
  const localRules = readGitignoreRules(current);
4891
4934
  const gitignoreLayers = localRules.length === 0 ? layers : [
4892
4935
  ...layers,
4893
- { prefix: path25__namespace.relative(baseDir, current).replace(/\\/g, "/"), rules: localRules }
4936
+ { prefix: path26__namespace.relative(baseDir, current).replace(/\\/g, "/"), rules: localRules }
4894
4937
  ];
4895
4938
  let entries;
4896
4939
  try {
4897
- entries = fs24__namespace.readdirSync(current, { withFileTypes: true });
4940
+ entries = fs25__namespace.readdirSync(current, { withFileTypes: true });
4898
4941
  } catch {
4899
4942
  results.skipped.push({
4900
4943
  path: relativeToBase(current),
@@ -4916,8 +4959,8 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
4916
4959
  }
4917
4960
  const entry = frame.entries[frame.index];
4918
4961
  frame.index += 1;
4919
- const fullPath = path25__namespace.join(frame.dir, entry.name);
4920
- const relPath = path25__namespace.relative(baseDir, fullPath).replace(/\\/g, "/");
4962
+ const fullPath = path26__namespace.join(frame.dir, entry.name);
4963
+ const relPath = path26__namespace.relative(baseDir, fullPath).replace(/\\/g, "/");
4921
4964
  if (reservedPaths.has(relPath)) continue;
4922
4965
  if (entry.isDirectory() && DEFAULT_IGNORED_DIRS.includes(entry.name)) {
4923
4966
  results.skipped.push({
@@ -4950,14 +4993,14 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
4950
4993
  if (entry.isSymbolicLink()) {
4951
4994
  let targetReal;
4952
4995
  try {
4953
- targetReal = fs24__namespace.realpathSync(fullPath);
4996
+ targetReal = fs25__namespace.realpathSync(fullPath);
4954
4997
  } catch {
4955
4998
  results.skipped.push(brokenLinkRecord(fullPath, relPath, rootReal));
4956
4999
  continue;
4957
5000
  }
4958
5001
  let stats;
4959
5002
  try {
4960
- stats = fs24__namespace.statSync(fullPath);
5003
+ stats = fs25__namespace.statSync(fullPath);
4961
5004
  } catch {
4962
5005
  results.skipped.push({ path: relPath, reason: "read-error", detail: "unreadable symlink" });
4963
5006
  continue;
@@ -4987,7 +5030,7 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
4987
5030
  });
4988
5031
  continue;
4989
5032
  }
4990
- const targetRelative = path25__namespace.relative(rootReal, targetReal).split(path25__namespace.sep).join("/");
5033
+ const targetRelative = path26__namespace.relative(rootReal, targetReal).split(path26__namespace.sep).join("/");
4991
5034
  if (isSensitivePath(targetRelative)) {
4992
5035
  results.skipped.push({
4993
5036
  path: relPath,
@@ -5249,10 +5292,10 @@ function readConfigExport(exported, file) {
5249
5292
  var lastModuleConfig = null;
5250
5293
  function moduleConfigKey(fullPath) {
5251
5294
  try {
5252
- return crypto.createHash("sha256").update(fs24__namespace.readFileSync(fullPath)).digest("hex").slice(0, 24);
5295
+ return crypto.createHash("sha256").update(fs25__namespace.readFileSync(fullPath)).digest("hex").slice(0, 24);
5253
5296
  } catch {
5254
5297
  try {
5255
- const stats = fs24__namespace.statSync(fullPath);
5298
+ const stats = fs25__namespace.statSync(fullPath);
5256
5299
  return `stat-${stats.mtimeMs}-${stats.size}`;
5257
5300
  } catch {
5258
5301
  return "unreadable";
@@ -5278,7 +5321,7 @@ async function importConfigModule(fullPath) {
5278
5321
  function attachConfigDir(config, filePath) {
5279
5322
  if (typeof config === "object" && config !== null) {
5280
5323
  Object.defineProperty(config, CONFIG_DIR_SYMBOL, {
5281
- value: path25__namespace.dirname(filePath),
5324
+ value: path26__namespace.dirname(filePath),
5282
5325
  enumerable: false,
5283
5326
  configurable: true
5284
5327
  });
@@ -5290,12 +5333,12 @@ async function loadConfigFileDetailed(cwd, options = {}) {
5290
5333
  const errors = [];
5291
5334
  const configDirectories = [];
5292
5335
  for (const filename of CONFIG_FILENAMES) {
5293
- const fullPath = path25__namespace.join(cwd, filename);
5336
+ const fullPath = path26__namespace.join(cwd, filename);
5294
5337
  let candidateStats = null;
5295
5338
  try {
5296
- candidateStats = fs24__namespace.statSync(fullPath);
5339
+ candidateStats = fs25__namespace.statSync(fullPath);
5297
5340
  } catch {
5298
- if (!fs24__namespace.existsSync(fullPath)) continue;
5341
+ if (!fs25__namespace.existsSync(fullPath)) continue;
5299
5342
  }
5300
5343
  if (candidateStats !== null && !candidateStats.isFile()) {
5301
5344
  configDirectories.push(fullPath);
@@ -5303,7 +5346,7 @@ async function loadConfigFileDetailed(cwd, options = {}) {
5303
5346
  }
5304
5347
  if (filename.endsWith(".json") || filename === ".snapshotrc") {
5305
5348
  try {
5306
- const config = parseJsonish(fs24__namespace.readFileSync(fullPath, "utf8"), fullPath);
5349
+ const config = parseJsonish(fs25__namespace.readFileSync(fullPath, "utf8"), fullPath);
5307
5350
  if (config === null || typeof config !== "object" || Array.isArray(config)) {
5308
5351
  throw new Error(
5309
5352
  `${fullPath} does not hold a configuration object (received ${describeValue2(config)}).`
@@ -5343,10 +5386,10 @@ async function loadConfigFileDetailed(cwd, options = {}) {
5343
5386
  continue;
5344
5387
  }
5345
5388
  }
5346
- const pkgJsonPath = path25__namespace.join(cwd, "package.json");
5347
- if (fs24__namespace.existsSync(pkgJsonPath)) {
5389
+ const pkgJsonPath = path26__namespace.join(cwd, "package.json");
5390
+ if (fs25__namespace.existsSync(pkgJsonPath)) {
5348
5391
  try {
5349
- const parsed = parseJsonish(fs24__namespace.readFileSync(pkgJsonPath, "utf8"), pkgJsonPath);
5392
+ const parsed = parseJsonish(fs25__namespace.readFileSync(pkgJsonPath, "utf8"), pkgJsonPath);
5350
5393
  const snapshotKey = parsed.snapshot;
5351
5394
  if (snapshotKey && typeof snapshotKey === "object" && !Array.isArray(snapshotKey)) {
5352
5395
  assertKnownConfigKeys(
@@ -5521,27 +5564,27 @@ function readConfiguredBrief(cwd, value) {
5521
5564
  }
5522
5565
  const rootReal = (() => {
5523
5566
  try {
5524
- return fs24__namespace.realpathSync(cwd);
5567
+ return fs25__namespace.realpathSync(cwd);
5525
5568
  } catch {
5526
- return path25__namespace.resolve(cwd);
5569
+ return path26__namespace.resolve(cwd);
5527
5570
  }
5528
5571
  })();
5529
- const requested = path25__namespace.resolve(cwd, value);
5572
+ const requested = path26__namespace.resolve(cwd, value);
5530
5573
  let filePath;
5531
5574
  try {
5532
- filePath = fs24__namespace.realpathSync(requested);
5575
+ filePath = fs25__namespace.realpathSync(requested);
5533
5576
  } catch {
5534
5577
  throw new Error(
5535
5578
  'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
5536
5579
  );
5537
5580
  }
5538
- const relative14 = path25__namespace.relative(rootReal, filePath);
5539
- if (relative14.length === 0 || relative14 === ".." || relative14.startsWith(`..${path25__namespace.sep}`) || path25__namespace.isAbsolute(relative14)) {
5581
+ const relative15 = path26__namespace.relative(rootReal, filePath);
5582
+ if (relative15.length === 0 || relative15 === ".." || relative15.startsWith(`..${path26__namespace.sep}`) || path26__namespace.isAbsolute(relative15)) {
5540
5583
  throw new Error(
5541
5584
  'brief "' + value + '" resolves outside the repository. A brief must be a file inside the repository being described; an absolute or parent path is refused.'
5542
5585
  );
5543
5586
  }
5544
- const posixRelative = relative14.split(path25__namespace.sep).join("/");
5587
+ const posixRelative = relative15.split(path26__namespace.sep).join("/");
5545
5588
  if (isSensitivePath(posixRelative) || isSensitivePath(value)) {
5546
5589
  throw new Error(
5547
5590
  'brief "' + value + '" is a credential-bearing file. A snapshot must not reproduce secrets, so it cannot be used as the owner brief.'
@@ -5549,8 +5592,8 @@ function readConfiguredBrief(cwd, value) {
5549
5592
  }
5550
5593
  let text2;
5551
5594
  try {
5552
- if (!fs24__namespace.statSync(filePath).isFile()) throw new Error("not a file");
5553
- text2 = fs24__namespace.readFileSync(filePath, "utf8");
5595
+ if (!fs25__namespace.statSync(filePath).isFile()) throw new Error("not a file");
5596
+ text2 = fs25__namespace.readFileSync(filePath, "utf8");
5554
5597
  } catch {
5555
5598
  throw new Error(
5556
5599
  'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
@@ -5662,12 +5705,12 @@ function resolveKindRules(value) {
5662
5705
  function outputExcludePatterns(cwd, outDir, tmpDir) {
5663
5706
  const patterns = [];
5664
5707
  for (const dir of [outDir, tmpDir]) {
5665
- const absolute = path25__namespace.resolve(cwd, dir);
5666
- const relative14 = path25__namespace.relative(cwd, absolute);
5667
- if (!relative14 || relative14 === ".." || relative14.startsWith(`..${path25__namespace.sep}`) || path25__namespace.isAbsolute(relative14)) {
5708
+ const absolute = path26__namespace.resolve(cwd, dir);
5709
+ const relative15 = path26__namespace.relative(cwd, absolute);
5710
+ if (!relative15 || relative15 === ".." || relative15.startsWith(`..${path26__namespace.sep}`) || path26__namespace.isAbsolute(relative15)) {
5668
5711
  continue;
5669
5712
  }
5670
- patterns.push(`${relative14.replace(/\\/g, "/")}/**`);
5713
+ patterns.push(`${relative15.replace(/\\/g, "/")}/**`);
5671
5714
  }
5672
5715
  return patterns;
5673
5716
  }
@@ -5797,11 +5840,11 @@ function resolveCandidateCwd(userConfig, cliOptions, baseDir) {
5797
5840
  );
5798
5841
  }
5799
5842
  const candidate = cliOptions?.cwd || userConfig?.cwd || baseDir || process.cwd();
5800
- const resolved = path25__namespace.resolve(candidate);
5801
- if (!fs24__namespace.existsSync(resolved)) {
5843
+ const resolved = path26__namespace.resolve(candidate);
5844
+ if (!fs25__namespace.existsSync(resolved)) {
5802
5845
  throw new Error(`Working directory does not exist: ${resolved}`);
5803
5846
  }
5804
- if (!fs24__namespace.statSync(resolved).isDirectory()) {
5847
+ if (!fs25__namespace.statSync(resolved).isDirectory()) {
5805
5848
  throw new Error(`Working directory is not a directory: ${resolved}`);
5806
5849
  }
5807
5850
  return resolved;
@@ -6427,6 +6470,9 @@ function countLines(content) {
6427
6470
  const last = content.charCodeAt(content.length - 1);
6428
6471
  return last === 10 || last === 13 ? breaks : breaks + 1;
6429
6472
  }
6473
+ function countBodyLines(content) {
6474
+ return content.length === 0 ? 0 : content.split("\n").length;
6475
+ }
6430
6476
  function truncateToBytes(content, maxBytes) {
6431
6477
  if (maxBytes <= 0) return { content: "", isTruncated: content.length > 0 };
6432
6478
  const buffer = Buffer.from(content, "utf8");
@@ -6785,7 +6831,7 @@ function applyTruncatedContent(file, content, reason) {
6785
6831
  file.truncationReason = reason;
6786
6832
  file.omittedRanges = keptLines >= file.originalLines ? file.originalLines > 0 ? [[file.originalLines, file.originalLines]] : [] : [[keptLines + 1, file.originalLines]];
6787
6833
  file.includedBytes = Buffer.byteLength(content, "utf8");
6788
- file.includedLines = countLines(content);
6834
+ file.includedLines = countBodyLines(content);
6789
6835
  }
6790
6836
  function rehashPart(part, markdown) {
6791
6837
  const estimatedTokens = estimateTokens(markdown.replace(TOKEN_LINE, ""));
@@ -6920,7 +6966,7 @@ function renderFileSection(file) {
6920
6966
  const content = file.content ?? "";
6921
6967
  const body = emittedBody(content);
6922
6968
  file.includedBytes = Buffer.byteLength(body, "utf8");
6923
- file.includedLines = countLines(body);
6969
+ file.includedLines = countBodyLines(body);
6924
6970
  const fence = fenceForContent(content);
6925
6971
  const anchor = anchorForPath(file.relativePath);
6926
6972
  return [
@@ -7215,10 +7261,10 @@ function resolveImport(from, specifier, byPath) {
7215
7261
  if (segment === "..") parts.pop();
7216
7262
  else parts.push(segment);
7217
7263
  }
7218
- const path26 = parts.join("/");
7219
- const withoutExtension = path26.replace(/\.[cm]?[jt]sx?$/, "");
7264
+ const path27 = parts.join("/");
7265
+ const withoutExtension = path27.replace(/\.[cm]?[jt]sx?$/, "");
7220
7266
  const candidates = [
7221
- path26,
7267
+ path27,
7222
7268
  withoutExtension + ".ts",
7223
7269
  withoutExtension + ".tsx",
7224
7270
  withoutExtension + ".js",
@@ -7227,18 +7273,18 @@ function resolveImport(from, specifier, byPath) {
7227
7273
  withoutExtension + ".go",
7228
7274
  withoutExtension + ".rs",
7229
7275
  withoutExtension + "/index.ts",
7230
- path26 + ".ts",
7231
- path26 + ".tsx",
7232
- path26 + ".js",
7233
- path26 + ".jsx",
7234
- path26 + ".mjs",
7235
- path26 + ".cjs",
7236
- path26 + ".py",
7237
- path26 + ".go",
7238
- path26 + ".rs",
7239
- path26 + ".java",
7240
- path26 + "/index.ts",
7241
- path26 + "/index.js"
7276
+ path27 + ".ts",
7277
+ path27 + ".tsx",
7278
+ path27 + ".js",
7279
+ path27 + ".jsx",
7280
+ path27 + ".mjs",
7281
+ path27 + ".cjs",
7282
+ path27 + ".py",
7283
+ path27 + ".go",
7284
+ path27 + ".rs",
7285
+ path27 + ".java",
7286
+ path27 + "/index.ts",
7287
+ path27 + "/index.js"
7242
7288
  ];
7243
7289
  for (const candidate of candidates) {
7244
7290
  const found = byPath.get(candidate);
@@ -7267,12 +7313,12 @@ function planForQuestion(manifest, question, options = {}) {
7267
7313
  const scored = [];
7268
7314
  for (const file of manifest.files) {
7269
7315
  if (isTest(file) && !wantsTests) continue;
7270
- const path26 = file.relativePath.toLowerCase();
7271
- const words = path26.split(/[^a-z0-9_]+/).filter((word) => word.length >= 3);
7316
+ const path27 = file.relativePath.toLowerCase();
7317
+ const words = path27.split(/[^a-z0-9_]+/).filter((word) => word.length >= 3);
7272
7318
  let score = 0;
7273
7319
  const reasons = [];
7274
7320
  for (const term of terms) {
7275
- if (path26.includes(term)) {
7321
+ if (path27.includes(term)) {
7276
7322
  score += 8;
7277
7323
  reasons.push("path:" + term);
7278
7324
  continue;
@@ -7459,24 +7505,119 @@ function stripComments2(text2, relativePath) {
7459
7505
  return { text: pieces.join(""), removed };
7460
7506
  }
7461
7507
  function runGit(cwd, args) {
7462
- const result = childProcess.spawnSync("git", args, { cwd, encoding: "utf8", windowsHide: true, maxBuffer: 64 * 1024 * 1024 });
7508
+ const result = childProcess.spawnSync(
7509
+ "git",
7510
+ ["-c", "core.quotepath=false", "-c", "diff.noprefix=false", ...args],
7511
+ { cwd, encoding: "utf8", windowsHide: true, maxBuffer: 64 * 1024 * 1024 }
7512
+ );
7463
7513
  if (result.status !== 0) return { ok: false, out: (result.stderr ?? "").trim() };
7464
7514
  return { ok: true, out: result.stdout ?? "" };
7465
7515
  }
7466
7516
  function isGitRepository(cwd) {
7467
7517
  return runGit(cwd, ["rev-parse", "--is-inside-work-tree"]).out.trim() === "true";
7468
7518
  }
7519
+ function unquoteGitPath(value) {
7520
+ if (!value.startsWith('"') || !value.endsWith('"')) return value;
7521
+ const body = value.slice(1, -1);
7522
+ let out = "";
7523
+ let bytes = [];
7524
+ const flushBytes = () => {
7525
+ if (bytes.length === 0) return;
7526
+ out += Buffer.from(bytes).toString("utf8");
7527
+ bytes = [];
7528
+ };
7529
+ const escapes = {
7530
+ a: "\x07",
7531
+ b: "\b",
7532
+ f: "\f",
7533
+ n: "\n",
7534
+ r: "\r",
7535
+ t: " ",
7536
+ v: "\v",
7537
+ "\\": "\\",
7538
+ '"': '"'
7539
+ };
7540
+ for (let index = 0; index < body.length; index += 1) {
7541
+ const char = body[index];
7542
+ if (char !== "\\") {
7543
+ flushBytes();
7544
+ out += char;
7545
+ continue;
7546
+ }
7547
+ const next = body[index + 1];
7548
+ if (next === void 0) {
7549
+ flushBytes();
7550
+ out += "\\";
7551
+ break;
7552
+ }
7553
+ index += 1;
7554
+ if (/[0-7]/.test(next)) {
7555
+ let octal = next;
7556
+ while (octal.length < 3 && /[0-7]/.test(body[index + 1] ?? "")) {
7557
+ index += 1;
7558
+ octal += body[index];
7559
+ }
7560
+ bytes.push(Number.parseInt(octal, 8) & 255);
7561
+ continue;
7562
+ }
7563
+ flushBytes();
7564
+ out += escapes[next] ?? next;
7565
+ }
7566
+ flushBytes();
7567
+ return out;
7568
+ }
7569
+ function takeGitPath(value) {
7570
+ if (value.length === 0) return null;
7571
+ if (value.startsWith('"')) {
7572
+ let index = 1;
7573
+ while (index < value.length) {
7574
+ if (value[index] === "\\") {
7575
+ index += 2;
7576
+ continue;
7577
+ }
7578
+ if (value[index] === '"') {
7579
+ return { token: value.slice(0, index + 1), rest: value.slice(index + 1).replace(/^ /, "") };
7580
+ }
7581
+ index += 1;
7582
+ }
7583
+ return null;
7584
+ }
7585
+ const space = value.indexOf(" ");
7586
+ if (space === -1) return { token: value, rest: "" };
7587
+ return { token: value.slice(0, space), rest: value.slice(space + 1) };
7588
+ }
7589
+ function pathFromGitToken(token, prefix) {
7590
+ const unquoted = unquoteGitPath(token);
7591
+ if (unquoted === "/dev/null") return null;
7592
+ if (!unquoted.startsWith(prefix)) return null;
7593
+ return unquoted.slice(prefix.length);
7594
+ }
7469
7595
  function diffSectionPaths(body) {
7470
7596
  const paths = /* @__PURE__ */ new Set();
7471
7597
  for (const line of body.split("\n")) {
7472
- const plus = /^\+\+\+ b\/(.*)$/.exec(line);
7473
- if (plus !== null) paths.add(plus[1]);
7474
- const minus = /^--- a\/(.*)$/.exec(line);
7475
- if (minus !== null) paths.add(minus[1]);
7476
- const header = /^diff --git a\/(.*?) b\/(.*)$/.exec(line);
7477
- if (header !== null) {
7478
- paths.add(header[1]);
7479
- paths.add(header[2]);
7598
+ if (line.startsWith("diff --git ")) {
7599
+ const first = takeGitPath(line.slice("diff --git ".length));
7600
+ if (first === null) continue;
7601
+ const second = takeGitPath(first.rest);
7602
+ if (second === null) continue;
7603
+ const left = pathFromGitToken(first.token, "a/");
7604
+ const right = pathFromGitToken(second.token, "b/");
7605
+ if (left !== null) paths.add(left);
7606
+ if (right !== null) paths.add(right);
7607
+ continue;
7608
+ }
7609
+ if (line.startsWith("+++ ")) {
7610
+ const token = takeGitPath(line.slice(4));
7611
+ if (token === null) continue;
7612
+ const path27 = pathFromGitToken(token.token, "b/");
7613
+ if (path27 !== null) paths.add(path27);
7614
+ continue;
7615
+ }
7616
+ if (line.startsWith("--- ")) {
7617
+ const token = takeGitPath(line.slice(4));
7618
+ if (token === null) continue;
7619
+ const path27 = pathFromGitToken(token.token, "a/");
7620
+ if (path27 !== null) paths.add(path27);
7480
7621
  }
7481
7622
  }
7482
7623
  return [...paths];
@@ -7487,6 +7628,7 @@ function generateDiffReport(cwd, options = {}) {
7487
7628
  const sections = [];
7488
7629
  let truncated = false;
7489
7630
  let omittedSensitive = 0;
7631
+ let omittedUnparseable = 0;
7490
7632
  const commands = [
7491
7633
  ["Unstaged", ["diff", "--no-color"]],
7492
7634
  ["Staged", ["diff", "--cached", "--no-color"]]
@@ -7497,7 +7639,11 @@ function generateDiffReport(cwd, options = {}) {
7497
7639
  const rawSections = result.out.split(/(?=^diff --git )/m).filter((section) => section.length > 0);
7498
7640
  for (const rawSection of rawSections) {
7499
7641
  const paths2 = diffSectionPaths(rawSection);
7500
- const blocked = paths2.some((path26) => isSensitivePath(path26) || options.excluded?.(path26) === true);
7642
+ if (paths2.length === 0) {
7643
+ omittedUnparseable += 1;
7644
+ continue;
7645
+ }
7646
+ const blocked = paths2.some((path27) => isSensitivePath(path27) || options.excluded?.(path27) === true);
7501
7647
  if (blocked) {
7502
7648
  omittedSensitive += 1;
7503
7649
  continue;
@@ -7508,7 +7654,13 @@ function generateDiffReport(cwd, options = {}) {
7508
7654
  truncated = true;
7509
7655
  break;
7510
7656
  }
7511
- const chunk = truncateToBytes(rawSection, remaining);
7657
+ const sourcePath = paths2[0] ?? "reports/diff.md";
7658
+ const redactedSection = scanAndRedactSecrets(
7659
+ rawSection,
7660
+ options.secretRules ?? [],
7661
+ sourcePath
7662
+ ).redacted;
7663
+ const chunk = truncateToBytes(redactedSection, remaining);
7512
7664
  if (chunk.isTruncated) truncated = true;
7513
7665
  sections.push(
7514
7666
  "## " + title + " changes\n\nRun: git " + args.join(" ") + "\n\n```diff\n" + chunk.content + "\n```"
@@ -7518,7 +7670,7 @@ function generateDiffReport(cwd, options = {}) {
7518
7670
  }
7519
7671
  if (sections.length === 0) return null;
7520
7672
  const paths = /* @__PURE__ */ new Set();
7521
- for (const section of sections) for (const path26 of diffSectionPaths(section)) paths.add(path26);
7673
+ for (const section of sections) for (const path27 of diffSectionPaths(section)) paths.add(path27);
7522
7674
  const joined = [
7523
7675
  "# Uncommitted changes",
7524
7676
  "",
@@ -7529,6 +7681,10 @@ function generateDiffReport(cwd, options = {}) {
7529
7681
  "> " + omittedSensitive + " file section(s) omitted: their path is credential-bearing or excluded from the snapshot.",
7530
7682
  ""
7531
7683
  ] : [],
7684
+ ...omittedUnparseable > 0 ? [
7685
+ "> " + omittedUnparseable + " file section(s) omitted: their diff header could not be attributed to a path, so the sensitive-path filter could not run.",
7686
+ ""
7687
+ ] : [],
7532
7688
  ...sections,
7533
7689
  ...truncated ? ["", "> Truncated at " + maxBytes + " bytes. Run git diff for the rest."] : [],
7534
7690
  ""
@@ -7801,7 +7957,7 @@ function systemSection(manifest, code, brief, escape, sawManifest) {
7801
7957
  " A change here reaches the most call sites; read it before judging anything that uses it."
7802
7958
  );
7803
7959
  }
7804
- const entryPoints = manifest.files.map((file) => file.relativePath).filter((path26) => ENTRY_POINT.test(path26)).sort((a, b) => a.split("/").length - b.split("/").length || a.length - b.length).slice(0, MAX_ENTRY_POINTS);
7960
+ const entryPoints = manifest.files.map((file) => file.relativePath).filter((path27) => ENTRY_POINT.test(path27)).sort((a, b) => a.split("/").length - b.split("/").length || a.length - b.length).slice(0, MAX_ENTRY_POINTS);
7805
7961
  out.push(
7806
7962
  entryPoints.length > 0 ? "- Entry points by convention: " + entryPoints.map(code).join(", ") + "." : "- No entry point was identifiable by name. The largest files below are where execution"
7807
7963
  );
@@ -8032,12 +8188,12 @@ function ownerNotesSection(brief, code, text2) {
8032
8188
  if (brief === void 0 || brief.notes.length === 0) return [];
8033
8189
  const out = ["## Owner notes", ""];
8034
8190
  for (const note of brief.notes) {
8035
- out.push("### " + note.heading, "", ...ownerBlock(note.body, brief.path, code, text2), "");
8191
+ out.push("### " + text2(note.heading), "", ...ownerBlock(note.body, brief.path, code, text2), "");
8036
8192
  }
8037
8193
  return out;
8038
8194
  }
8039
- function ownerBlock(body, path26, code, escape) {
8040
- return ["> Written by the project owner in " + code(path26) + ", not generated.", "", escape(body)];
8195
+ function ownerBlock(body, path27, code, escape) {
8196
+ return ["> Written by the project owner in " + code(path27) + ", not generated.", "", escape(body)];
8041
8197
  }
8042
8198
  function snapshotSection(manifest, code, partsWritten) {
8043
8199
  const out = ["## This snapshot", ""];
@@ -8253,27 +8409,31 @@ function generateReadme(manifest, artifacts) {
8253
8409
  const readOrder = [];
8254
8410
  if (wrote("prompt")) {
8255
8411
  readOrder.push(
8256
- "1. Hand `PROMPT.md` to the model that receives this snapshot: it names the parts, the partial files and the fingerprint of this run."
8412
+ "Hand `PROMPT.md` to the model that receives this snapshot: it names the parts, the partial files and the fingerprint of this run."
8257
8413
  );
8258
8414
  }
8259
8415
  if (wrote("navigation") || wrote("projectTree")) {
8260
8416
  const first = [wrote("navigation") ? "`reports/navigation.md`" : null, wrote("projectTree") ? "`reports/project-tree.md`" : null].filter(Boolean).join(" or ");
8261
- readOrder.push(`1. Read ${first} first to locate target features or files.`);
8417
+ readOrder.push(`Read ${first} first to locate target features or files.`);
8262
8418
  }
8263
8419
  if (wrote("parts")) {
8264
8420
  readOrder.push(
8265
- `${readOrder.length + 1}. Open only the specific \`parts/part-XXX.md\` file holding the target modules.`
8421
+ "Open only the specific `parts/part-XXX.md` file holding the target modules."
8266
8422
  );
8267
8423
  }
8268
8424
  if (wrote("manifest")) {
8269
- readOrder.push(
8270
- `${readOrder.length + 1}. Inspect \`manifest.json\` for precise dependency and AST symbol maps.`
8271
- );
8425
+ readOrder.push("Inspect `manifest.json` for precise dependency and AST symbol maps.");
8272
8426
  }
8273
8427
  readOrder.push(
8274
- wrote("manifest") ? `${readOrder.length + 1}. Check \`manifest.validation.status\` before trusting the snapshot; \`snapshot validate\` re-checks it against disk.` : `${readOrder.length + 1}. No manifest was written, so this snapshot cannot be re-checked; regenerate with the manifest artifact enabled before trusting it.`
8428
+ wrote("manifest") ? "Check `manifest.validation.status` before trusting the snapshot; `snapshot validate` re-checks it against disk." : "No manifest was written, so this snapshot cannot be re-checked; regenerate with the manifest artifact enabled before trusting it."
8429
+ );
8430
+ lines.push(
8431
+ "",
8432
+ "## AI Agent Ingestion Guide",
8433
+ "",
8434
+ ...readOrder.map((step, index) => `${index + 1}. ${step}`),
8435
+ ""
8275
8436
  );
8276
- lines.push("", "## AI Agent Ingestion Guide", "", ...readOrder, "");
8277
8437
  return lines.join("\n");
8278
8438
  }
8279
8439
 
@@ -8403,7 +8563,7 @@ function resolveChangedScope(cwd, request) {
8403
8563
  const descriptions = [];
8404
8564
  if (request.changedSince !== void 0) {
8405
8565
  assertUsableRef(request.changedSince);
8406
- for (const path26 of gitPaths(cwd, [
8566
+ for (const path27 of gitPaths(cwd, [
8407
8567
  "diff",
8408
8568
  "--name-only",
8409
8569
  "-z",
@@ -8411,9 +8571,9 @@ function resolveChangedScope(cwd, request) {
8411
8571
  `${request.changedSince}...HEAD`,
8412
8572
  "--"
8413
8573
  ])) {
8414
- paths.add(path26);
8574
+ paths.add(path27);
8415
8575
  }
8416
- for (const path26 of gitPaths(cwd, [
8576
+ for (const path27 of gitPaths(cwd, [
8417
8577
  "diff",
8418
8578
  "--name-only",
8419
8579
  "-z",
@@ -8421,15 +8581,15 @@ function resolveChangedScope(cwd, request) {
8421
8581
  "HEAD",
8422
8582
  "--"
8423
8583
  ])) {
8424
- paths.add(path26);
8584
+ paths.add(path27);
8425
8585
  }
8426
- for (const path26 of gitPaths(cwd, ["ls-files", "--others", "--exclude-standard", "-z", "--"])) {
8427
- paths.add(path26);
8586
+ for (const path27 of gitPaths(cwd, ["ls-files", "--others", "--exclude-standard", "-z", "--"])) {
8587
+ paths.add(path27);
8428
8588
  }
8429
8589
  descriptions.push(`changed since ${request.changedSince}`);
8430
8590
  }
8431
8591
  if (request.staged === true) {
8432
- for (const path26 of gitPaths(cwd, [
8592
+ for (const path27 of gitPaths(cwd, [
8433
8593
  "diff",
8434
8594
  "--cached",
8435
8595
  "--name-only",
@@ -8437,10 +8597,10 @@ function resolveChangedScope(cwd, request) {
8437
8597
  "--relative",
8438
8598
  "--"
8439
8599
  ])) {
8440
- paths.add(path26);
8441
- stagedPaths.add(path26);
8600
+ paths.add(path27);
8601
+ stagedPaths.add(path27);
8442
8602
  }
8443
- for (const path26 of gitPaths(cwd, [
8603
+ for (const path27 of gitPaths(cwd, [
8444
8604
  "diff",
8445
8605
  "--cached",
8446
8606
  "--name-only",
@@ -8449,7 +8609,7 @@ function resolveChangedScope(cwd, request) {
8449
8609
  "--diff-filter=D",
8450
8610
  "--"
8451
8611
  ])) {
8452
- deletedPaths.add(path26);
8612
+ deletedPaths.add(path27);
8453
8613
  }
8454
8614
  descriptions.push("staged");
8455
8615
  }
@@ -8487,10 +8647,10 @@ var PYTHON_SUFFIXES = [".py", ".pyi", "/__init__.py", "/__init__.pyi"];
8487
8647
  var CASE_INSENSITIVE_FILESYSTEM = process.platform === "win32" || process.platform === "darwin";
8488
8648
  var TSCONFIG_CACHE = /* @__PURE__ */ new Map();
8489
8649
  function tsconfigPathsFor(cwd) {
8490
- const configPath = path25__namespace.join(cwd, "tsconfig.json");
8650
+ const configPath = path26__namespace.join(cwd, "tsconfig.json");
8491
8651
  let stats;
8492
8652
  try {
8493
- stats = fs24__namespace.statSync(configPath);
8653
+ stats = fs25__namespace.statSync(configPath);
8494
8654
  } catch (err) {
8495
8655
  if (err.code === "ENOENT") return null;
8496
8656
  return null;
@@ -8524,8 +8684,8 @@ function tsconfigPathsFor(cwd) {
8524
8684
  return value;
8525
8685
  }
8526
8686
  function repositoryRelative(cwd, target) {
8527
- const relative14 = path25__namespace.relative(cwd, target).replace(/\\/g, "/");
8528
- return relative14.length === 0 || !relative14.startsWith("..") && !path25__namespace.isAbsolute(relative14) ? relative14 : null;
8687
+ const relative15 = path26__namespace.relative(cwd, target).replace(/\\/g, "/");
8688
+ return relative15.length === 0 || !relative15.startsWith("..") && !path26__namespace.isAbsolute(relative15) ? relative15 : null;
8529
8689
  }
8530
8690
  function rememberFirst(map, key, value) {
8531
8691
  if (!map.has(key)) map.set(key, value);
@@ -8540,15 +8700,15 @@ function buildImportResolver(files, options = {}) {
8540
8700
  if (CASE_INSENSITIVE_FILESYSTEM) {
8541
8701
  rememberFirst(byPathFolded, relativePath.toLowerCase(), relativePath);
8542
8702
  }
8543
- const extension = path25__namespace.posix.extname(relativePath);
8703
+ const extension = path26__namespace.posix.extname(relativePath);
8544
8704
  if (!SOURCE_EXTENSIONS.has(extension)) return;
8545
8705
  const stem = relativePath.slice(0, -extension.length);
8546
8706
  rememberFirst(byStem, stem, relativePath);
8547
8707
  if (CASE_INSENSITIVE_FILESYSTEM) {
8548
8708
  rememberFirst(byStemFolded, stem.toLowerCase(), relativePath);
8549
8709
  }
8550
- if (path25__namespace.posix.basename(stem) === "index") {
8551
- const directory = path25__namespace.posix.dirname(stem);
8710
+ if (path26__namespace.posix.basename(stem) === "index") {
8711
+ const directory = path26__namespace.posix.dirname(stem);
8552
8712
  rememberFirst(byStem, directory, relativePath);
8553
8713
  if (CASE_INSENSITIVE_FILESYSTEM) {
8554
8714
  rememberFirst(byStemFolded, directory.toLowerCase(), relativePath);
@@ -8564,7 +8724,7 @@ function buildImportResolver(files, options = {}) {
8564
8724
  return { byPath, byPathFolded, byStem, byStemFolded, tsconfig: options.tsconfig ?? null };
8565
8725
  }
8566
8726
  function resolveSpecifier(fromFile, specifier, resolver) {
8567
- const extension = path25__namespace.posix.extname(fromFile).toLowerCase();
8727
+ const extension = path26__namespace.posix.extname(fromFile).toLowerCase();
8568
8728
  const exact = (key) => resolver.byPath.get(key) ?? (CASE_INSENSITIVE_FILESYSTEM ? resolver.byPathFolded.get(key.toLowerCase()) : void 0) ?? null;
8569
8729
  const firstOf = (candidates) => {
8570
8730
  for (const candidate of candidates) {
@@ -8587,34 +8747,34 @@ function resolveSpecifier(fromFile, specifier, resolver) {
8587
8747
  if (PYTHON_EXTENSIONS.has(extension) && specifier.startsWith(".")) {
8588
8748
  const dots = /^\.+/.exec(specifier)?.[0].length ?? 0;
8589
8749
  const rest = specifier.slice(dots).replace(/\./g, "/");
8590
- let base = path25__namespace.posix.dirname(fromFile);
8591
- for (let up = 1; up < dots; up += 1) base = path25__namespace.posix.dirname(base);
8592
- const joined2 = rest ? path25__namespace.posix.normalize(path25__namespace.posix.join(base, rest)) : base;
8750
+ let base = path26__namespace.posix.dirname(fromFile);
8751
+ for (let up = 1; up < dots; up += 1) base = path26__namespace.posix.dirname(base);
8752
+ const joined2 = rest ? path26__namespace.posix.normalize(path26__namespace.posix.join(base, rest)) : base;
8593
8753
  return firstOf([joined2, ...PYTHON_SUFFIXES.map((suffix) => `${joined2}${suffix}`)]);
8594
8754
  }
8595
8755
  if (RUBY_EXTENSIONS.has(extension) && specifier.startsWith("./")) {
8596
- const joined2 = path25__namespace.posix.normalize(
8597
- path25__namespace.posix.join(path25__namespace.posix.dirname(fromFile), specifier)
8756
+ const joined2 = path26__namespace.posix.normalize(
8757
+ path26__namespace.posix.join(path26__namespace.posix.dirname(fromFile), specifier)
8598
8758
  );
8599
8759
  return firstOf([`${joined2}.rb`, joined2]);
8600
8760
  }
8601
8761
  if (C_EXTENSIONS.has(extension) && specifier.startsWith("./")) {
8602
- const joined2 = path25__namespace.posix.normalize(
8603
- path25__namespace.posix.join(path25__namespace.posix.dirname(fromFile), specifier)
8762
+ const joined2 = path26__namespace.posix.normalize(
8763
+ path26__namespace.posix.join(path26__namespace.posix.dirname(fromFile), specifier)
8604
8764
  );
8605
8765
  return exact(joined2);
8606
8766
  }
8607
8767
  if (extension === ".dart" && !specifier.includes(":")) {
8608
- const joined2 = path25__namespace.posix.normalize(
8609
- path25__namespace.posix.join(path25__namespace.posix.dirname(fromFile), specifier)
8768
+ const joined2 = path26__namespace.posix.normalize(
8769
+ path26__namespace.posix.join(path26__namespace.posix.dirname(fromFile), specifier)
8610
8770
  );
8611
8771
  return firstOf([joined2, `${joined2}.dart`]);
8612
8772
  }
8613
8773
  if (!RELATIVE_SPECIFIER.test(specifier)) {
8614
8774
  return resolveTsconfigSpecifier(specifier, resolver, lookupPath);
8615
8775
  }
8616
- const joined = path25__namespace.posix.normalize(
8617
- path25__namespace.posix.join(path25__namespace.posix.dirname(fromFile), specifier)
8776
+ const joined = path26__namespace.posix.normalize(
8777
+ path26__namespace.posix.join(path26__namespace.posix.dirname(fromFile), specifier)
8618
8778
  );
8619
8779
  return lookupPath(joined);
8620
8780
  }
@@ -8638,13 +8798,13 @@ function resolveTsconfigSpecifier(specifier, resolver, lookupPath) {
8638
8798
  if (captured === null) continue;
8639
8799
  for (const target of rule.targets) {
8640
8800
  const substituted = target.split("*").join(captured);
8641
- const base = config.baseUrl === null ? substituted : path25__namespace.posix.join(config.baseUrl, substituted);
8642
- const hit = lookupPath(path25__namespace.posix.normalize(base));
8801
+ const base = config.baseUrl === null ? substituted : path26__namespace.posix.join(config.baseUrl, substituted);
8802
+ const hit = lookupPath(path26__namespace.posix.normalize(base));
8643
8803
  if (hit) return hit;
8644
8804
  }
8645
8805
  }
8646
8806
  if (config.baseUrl !== null) {
8647
- return lookupPath(path25__namespace.posix.normalize(path25__namespace.posix.join(config.baseUrl, specifier)));
8807
+ return lookupPath(path26__namespace.posix.normalize(path26__namespace.posix.join(config.baseUrl, specifier)));
8648
8808
  }
8649
8809
  return null;
8650
8810
  }
@@ -8666,13 +8826,13 @@ function readProjectOverview(cwd) {
8666
8826
  }
8667
8827
  function readText(file) {
8668
8828
  try {
8669
- return fs24__namespace.readFileSync(file, "utf8");
8829
+ return fs25__namespace.readFileSync(file, "utf8");
8670
8830
  } catch {
8671
8831
  return null;
8672
8832
  }
8673
8833
  }
8674
8834
  function readDescription(cwd) {
8675
- const raw = readText(path25__namespace.join(cwd, "package.json"));
8835
+ const raw = readText(path26__namespace.join(cwd, "package.json"));
8676
8836
  if (raw === null) return {};
8677
8837
  try {
8678
8838
  const parsed = JSON.parse(stripJsonComments(raw));
@@ -8682,7 +8842,7 @@ function readDescription(cwd) {
8682
8842
  }
8683
8843
  }
8684
8844
  function readSummary(cwd) {
8685
- const raw = readText(path25__namespace.join(cwd, "README.md"));
8845
+ const raw = readText(path26__namespace.join(cwd, "README.md"));
8686
8846
  if (raw === null) return {};
8687
8847
  const text2 = raw.replace(/<h[1-6][^>]*>[\s\S]*?<\/h[1-6]>/gi, "\n").replace(/<\/(p|div|section|header|footer|li)>/gi, "\n").replace(/<br\s*\/?>/gi, " ").replace(/<[^>]*>/g, " ").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'");
8688
8848
  const paragraph = [];
@@ -8708,7 +8868,7 @@ function truncate(text2, limit) {
8708
8868
  return (space > limit / 2 ? window.slice(0, space) : window).trim() + "\u2026";
8709
8869
  }
8710
8870
  function readReleases(cwd) {
8711
- const raw = readText(path25__namespace.join(cwd, "CHANGELOG.md"));
8871
+ const raw = readText(path26__namespace.join(cwd, "CHANGELOG.md"));
8712
8872
  if (raw === null) return [];
8713
8873
  const headings = raw.split(/\r?\n/).map((line) => /^##\s+(.+?)\s*$/.exec(line)?.[1]?.trim()).filter((heading) => heading !== void 0 && /^v?\d+\.\d+/.test(heading));
8714
8874
  return headings.slice(0, MAX_RELEASES);
@@ -8770,10 +8930,10 @@ var LANGUAGE_BY_BASENAME = {
8770
8930
  };
8771
8931
  function detectLanguage(filePath) {
8772
8932
  const normalized = filePath.replace(/\\/g, "/");
8773
- const base = path25__namespace.posix.basename(normalized);
8933
+ const base = path26__namespace.posix.basename(normalized);
8774
8934
  if (LANGUAGE_BY_BASENAME[base]) return LANGUAGE_BY_BASENAME[base];
8775
8935
  if (base === ".env" || base.startsWith(".env.")) return "dotenv";
8776
- const ext = path25__namespace.posix.extname(base).toLowerCase();
8936
+ const ext = path26__namespace.posix.extname(base).toLowerCase();
8777
8937
  return LANGUAGE_BY_EXTENSION[ext] ?? "text";
8778
8938
  }
8779
8939
  function maskedPath(value, secretRules) {
@@ -8781,33 +8941,33 @@ function maskedPath(value, secretRules) {
8781
8941
  }
8782
8942
  function confineToDirectory(directory, filename) {
8783
8943
  if (filename.includes("\0")) return null;
8784
- if (path25__namespace.isAbsolute(filename)) return null;
8785
- const base = path25__namespace.resolve(directory);
8786
- const resolved = path25__namespace.resolve(base, filename);
8944
+ if (path26__namespace.isAbsolute(filename)) return null;
8945
+ const base = path26__namespace.resolve(directory);
8946
+ const resolved = path26__namespace.resolve(base, filename);
8787
8947
  const caseInsensitive = process.platform === "win32" || process.platform === "darwin";
8788
- const prefix = caseInsensitive ? `${base}${path25__namespace.sep}`.toLowerCase() : `${base}${path25__namespace.sep}`;
8948
+ const prefix = caseInsensitive ? `${base}${path26__namespace.sep}`.toLowerCase() : `${base}${path26__namespace.sep}`;
8789
8949
  const candidate = caseInsensitive ? resolved.toLowerCase() : resolved;
8790
8950
  return candidate.startsWith(prefix) ? resolved : null;
8791
8951
  }
8792
8952
  function findStagingDirectory(config) {
8793
- const tmpDir = path25__namespace.resolve(config.cwd, config.tmpDir);
8953
+ const tmpDir = path26__namespace.resolve(config.cwd, config.tmpDir);
8794
8954
  let entries;
8795
8955
  try {
8796
- entries = fs24__namespace.readdirSync(tmpDir);
8956
+ entries = fs25__namespace.readdirSync(tmpDir);
8797
8957
  } catch {
8798
8958
  return null;
8799
8959
  }
8800
8960
  const runs = entries.filter((name) => name.startsWith("run-")).sort();
8801
8961
  const newest = runs[runs.length - 1];
8802
- return newest ? path25__namespace.join(tmpDir, newest) : null;
8962
+ return newest ? path26__namespace.join(tmpDir, newest) : null;
8803
8963
  }
8804
8964
  function describeMissingManifest(config, manifestPath) {
8805
- const outDir = path25__namespace.resolve(config.cwd, config.outDir);
8806
- const markerPath = path25__namespace.join(outDir, ".codebase-snapshot");
8965
+ const outDir = path26__namespace.resolve(config.cwd, config.outDir);
8966
+ const markerPath = path26__namespace.join(outDir, ".codebase-snapshot");
8807
8967
  let marker2 = null;
8808
8968
  try {
8809
- if (fs24__namespace.existsSync(markerPath)) {
8810
- const parsed = JSON.parse(fs24__namespace.readFileSync(markerPath, "utf8"));
8969
+ if (fs25__namespace.existsSync(markerPath)) {
8970
+ const parsed = JSON.parse(fs25__namespace.readFileSync(markerPath, "utf8"));
8811
8971
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
8812
8972
  marker2 = parsed;
8813
8973
  }
@@ -8842,13 +9002,13 @@ function sha256Hex(buffer) {
8842
9002
  return crypto__namespace.createHash("sha256").update(buffer).digest("hex");
8843
9003
  }
8844
9004
  function wouldNowBeIncluded(cwd, relativePath) {
8845
- const absolutePath = path25__namespace.join(cwd, relativePath);
9005
+ const absolutePath = path26__namespace.join(cwd, relativePath);
8846
9006
  try {
8847
- const stats = fs24__namespace.statSync(absolutePath);
9007
+ const stats = fs25__namespace.statSync(absolutePath);
8848
9008
  if (!stats.isFile()) return false;
8849
9009
  if (isBinaryExtension(absolutePath)) return false;
8850
9010
  if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) return false;
8851
- return !decodeText(fs24__namespace.readFileSync(absolutePath)).binary;
9011
+ return !decodeText(fs25__namespace.readFileSync(absolutePath)).binary;
8852
9012
  } catch {
8853
9013
  return false;
8854
9014
  }
@@ -8860,7 +9020,7 @@ var TRUNCATION_REASONS = /* @__PURE__ */ new Set([
8860
9020
  ]);
8861
9021
  function isConfinedRelative(value) {
8862
9022
  if (value.length === 0 || value.includes("\0") || value.includes("\\")) return false;
8863
- if (path25__namespace.isAbsolute(value)) return false;
9023
+ if (path26__namespace.isAbsolute(value)) return false;
8864
9024
  return !value.split("/").includes("..");
8865
9025
  }
8866
9026
  function describeManifestShapeProblem(value) {
@@ -9054,7 +9214,7 @@ function describeManifestShapeProblem(value) {
9054
9214
  if (typeof filename !== "string" || filename.trim() === "") {
9055
9215
  return 'a "parts" entry has no "filename"';
9056
9216
  }
9057
- if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path25__namespace.isAbsolute(filename)) {
9217
+ if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path26__namespace.isAbsolute(filename)) {
9058
9218
  return 'a "parts" entry "filename" must be a bare filename inside parts/';
9059
9219
  }
9060
9220
  if (currentSchema) {
@@ -9080,8 +9240,8 @@ function describeManifestShapeProblem(value) {
9080
9240
  function validateSnapshot(configInput) {
9081
9241
  assertUsableConfigInput(configInput);
9082
9242
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput);
9083
- const manifestPath = path25__namespace.resolve(config.cwd, config.outDir, "manifest.json");
9084
- if (!fs24__namespace.existsSync(manifestPath)) {
9243
+ const manifestPath = path26__namespace.resolve(config.cwd, config.outDir, "manifest.json");
9244
+ if (!fs25__namespace.existsSync(manifestPath)) {
9085
9245
  return {
9086
9246
  valid: false,
9087
9247
  manifestPresent: false,
@@ -9092,7 +9252,7 @@ function validateSnapshot(configInput) {
9092
9252
  }
9093
9253
  let manifest;
9094
9254
  try {
9095
- manifest = JSON.parse(fs24__namespace.readFileSync(manifestPath, "utf8"));
9255
+ manifest = JSON.parse(fs25__namespace.readFileSync(manifestPath, "utf8"));
9096
9256
  } catch (err) {
9097
9257
  return {
9098
9258
  valid: false,
@@ -9114,7 +9274,7 @@ function validateSnapshot(configInput) {
9114
9274
  }
9115
9275
  const drift = emptyDrift();
9116
9276
  const warnings = [];
9117
- const snapshotDir = path25__namespace.resolve(config.cwd, config.outDir);
9277
+ const snapshotDir = path26__namespace.resolve(config.cwd, config.outDir);
9118
9278
  const unreadableSkips = manifest.skipped.filter(
9119
9279
  (entry) => entry.reason === "missing" || entry.reason === "read-error"
9120
9280
  );
@@ -9222,7 +9382,7 @@ function validateSnapshot(configInput) {
9222
9382
  );
9223
9383
  return importsChangedFile(
9224
9384
  diskFile,
9225
- importsOfFile(diskFile, path25__namespace.join(config.cwd, diskFile)),
9385
+ importsOfFile(diskFile, path26__namespace.join(config.cwd, diskFile)),
9226
9386
  unchangedScope,
9227
9387
  dependentResolver
9228
9388
  );
@@ -9236,12 +9396,16 @@ function validateSnapshot(configInput) {
9236
9396
  // discovery mode" meant `validate` could enumerate files one way while the snapshot
9237
9397
  // had been generated another way, and then blame the difference on drift.
9238
9398
  discovery: config.discovery,
9399
+ // `generate --staged` adds index-only paths to the candidate list. Without the same
9400
+ // extra paths, a staged file that is absent from the working tree was invisible to
9401
+ // this scan and then reported as deleted, although the snapshot matched the index.
9402
+ ...stagedScope === null ? {} : { extraPaths: [...stagedScope] },
9239
9403
  // The same exclusion `generate` applies: without it, `validate` recounted the tool's
9240
9404
  // own output directory as a set of files missing from the snapshot, so a correct
9241
9405
  // snapshot was reported as drifting.
9242
9406
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
9243
- (directory) => path25__namespace.relative(config.cwd, path25__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
9244
- ).filter((relative14) => relative14.length > 0 && !relative14.startsWith(".."))
9407
+ (directory) => path26__namespace.relative(config.cwd, path26__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
9408
+ ).filter((relative15) => relative15.length > 0 && !relative15.startsWith(".."))
9245
9409
  });
9246
9410
  for (const diskFile of collection.files) {
9247
9411
  const snapshotHash = manifestFileMap.get(diskFile);
@@ -9268,7 +9432,7 @@ function validateSnapshot(configInput) {
9268
9432
  let diskHash;
9269
9433
  try {
9270
9434
  const stagedBlob = recordedStaged && stagedScope?.has(diskFile) === true ? readStagedBlob(config.cwd, diskFile) : null;
9271
- diskHash = sha256Hex(stagedBlob ?? fs24__namespace.readFileSync(path25__namespace.join(config.cwd, diskFile)));
9435
+ diskHash = sha256Hex(stagedBlob ?? fs25__namespace.readFileSync(path26__namespace.join(config.cwd, diskFile)));
9272
9436
  } catch (err) {
9273
9437
  if (err.code === "ENOENT") {
9274
9438
  drift.missingOnDisk.push(diskFile);
@@ -9282,6 +9446,12 @@ function validateSnapshot(configInput) {
9282
9446
  }
9283
9447
  }
9284
9448
  for (const snapshotFile of manifestFileMap.keys()) {
9449
+ if (recordedStaged && stagedScope?.has(snapshotFile)) {
9450
+ if (readStagedBlob(config.cwd, snapshotFile) === null) {
9451
+ drift.missingOnDisk.push(snapshotFile);
9452
+ }
9453
+ continue;
9454
+ }
9285
9455
  const confined = confineToDirectory(config.cwd, snapshotFile);
9286
9456
  if (confined === null) {
9287
9457
  drift.partIssues.push({
@@ -9292,7 +9462,7 @@ function validateSnapshot(configInput) {
9292
9462
  }
9293
9463
  let statFailure = null;
9294
9464
  try {
9295
- fs24__namespace.statSync(confined);
9465
+ fs25__namespace.statSync(confined);
9296
9466
  } catch (err) {
9297
9467
  statFailure = err;
9298
9468
  }
@@ -9312,7 +9482,7 @@ function validateSnapshot(configInput) {
9312
9482
  ...Object.values(config.budgets.byLayer)
9313
9483
  );
9314
9484
  const partNames = /* @__PURE__ */ new Set();
9315
- const partsDir = path25__namespace.join(snapshotDir, "parts");
9485
+ const partsDir = path26__namespace.join(snapshotDir, "parts");
9316
9486
  for (const part of manifest.parts) {
9317
9487
  if (!part || typeof part.filename !== "string") continue;
9318
9488
  partNames.add(part.filename);
@@ -9327,7 +9497,7 @@ function validateSnapshot(configInput) {
9327
9497
  }
9328
9498
  let buffer;
9329
9499
  try {
9330
- buffer = fs24__namespace.readFileSync(partPath);
9500
+ buffer = fs25__namespace.readFileSync(partPath);
9331
9501
  } catch {
9332
9502
  drift.partIssues.push({ part: part.filename, issue: "missing from snapshot/parts" });
9333
9503
  continue;
@@ -9704,11 +9874,11 @@ function validateSnapshot(configInput) {
9704
9874
  ];
9705
9875
  for (const [key, artifact] of declaredArtifacts) {
9706
9876
  if (!artifact) continue;
9707
- const artifactPath = path25__namespace.join(snapshotDir, ...key.split("/"));
9877
+ const artifactPath = path26__namespace.join(snapshotDir, ...key.split("/"));
9708
9878
  let buffer;
9709
9879
  try {
9710
- if (!fs24__namespace.statSync(artifactPath).isFile()) throw new Error("not a regular file");
9711
- buffer = fs24__namespace.readFileSync(artifactPath);
9880
+ if (!fs25__namespace.statSync(artifactPath).isFile()) throw new Error("not a regular file");
9881
+ buffer = fs25__namespace.readFileSync(artifactPath);
9712
9882
  } catch {
9713
9883
  drift.partIssues.push({ part: key, issue: "declared artifact is missing" });
9714
9884
  continue;
@@ -9721,9 +9891,9 @@ function validateSnapshot(configInput) {
9721
9891
  for (const match of buffer.toString("utf8").matchAll(/\]\(([^)\s]+)\)/g)) {
9722
9892
  const target = match[1].split("#")[0];
9723
9893
  if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
9724
- const resolved = path25__namespace.resolve(snapshotDir, "reports", target);
9725
- const relative14 = path25__namespace.relative(snapshotDir, resolved);
9726
- if (relative14.startsWith("..") || path25__namespace.isAbsolute(relative14) || !fs24__namespace.existsSync(resolved)) {
9894
+ const resolved = path26__namespace.resolve(snapshotDir, "reports", target);
9895
+ const relative15 = path26__namespace.relative(snapshotDir, resolved);
9896
+ if (relative15.startsWith("..") || path26__namespace.isAbsolute(relative15) || !fs25__namespace.existsSync(resolved)) {
9727
9897
  drift.partIssues.push({
9728
9898
  part: key,
9729
9899
  issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
@@ -9736,7 +9906,7 @@ function validateSnapshot(configInput) {
9736
9906
  if (sarifArtifact) {
9737
9907
  const sarifKey = "reports/audit.sarif";
9738
9908
  try {
9739
- const buffer = fs24__namespace.readFileSync(path25__namespace.join(snapshotDir, "reports", "audit.sarif"));
9909
+ const buffer = fs25__namespace.readFileSync(path26__namespace.join(snapshotDir, "reports", "audit.sarif"));
9740
9910
  if (sha256Hex(buffer) !== sarifArtifact.sha256 || buffer.length !== sarifArtifact.byteSize) {
9741
9911
  drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
9742
9912
  }
@@ -9782,9 +9952,9 @@ function validateSnapshot(configInput) {
9782
9952
  `${drift.configMismatches.length} configuration mismatch(es) between the manifest and this run.`
9783
9953
  );
9784
9954
  }
9785
- const signaturePath = path25__namespace.join(path25__namespace.dirname(manifestPath), "signature.json");
9786
- if (fs24__namespace.existsSync(signaturePath)) {
9787
- const outcome = verifySnapshotSignature(path25__namespace.dirname(manifestPath));
9955
+ const signaturePath = path26__namespace.join(path26__namespace.dirname(manifestPath), "signature.json");
9956
+ if (fs25__namespace.existsSync(signaturePath)) {
9957
+ const outcome = verifySnapshotSignature(path26__namespace.dirname(manifestPath));
9788
9958
  if (!outcome.ok) errors.push("signature: " + outcome.reason + ".");
9789
9959
  }
9790
9960
  if (manifest.slice !== void 0 || manifest.budget !== void 0) {
@@ -9890,9 +10060,11 @@ function isPrivateIPv6(groups) {
9890
10060
  ]);
9891
10061
  if (allZeroThrough(5) && sixth === 65535) return mapped(6);
9892
10062
  if (allZeroThrough(6) && (seventh !== 0 || eighth !== 0)) return mapped(6);
10063
+ if (allZeroThrough(4) && fifth === 65535 && sixth === 0) return mapped(6);
9893
10064
  if (first === 100 && second === 65435 && third === 0 && fourth === 0 && fifth === 0 && sixth === 0) {
9894
10065
  return mapped(6);
9895
10066
  }
10067
+ if (first === 100 && second === 65435 && third === 1) return mapped(6);
9896
10068
  if (first === 8194) return mapped(1);
9897
10069
  return false;
9898
10070
  }
@@ -9925,7 +10097,7 @@ function parseRemoteSource(input, options = {}) {
9925
10097
  const directory = url.fileURLToPath(url2);
9926
10098
  return {
9927
10099
  ok: true,
9928
- source: { kind: "file", url: trimmed, host: "file", owner: "", repo: path25__namespace.basename(directory), ref: null }
10100
+ source: { kind: "file", url: trimmed, host: "file", owner: "", repo: path26__namespace.basename(directory), ref: null }
9929
10101
  };
9930
10102
  }
9931
10103
  let url$1;
@@ -10003,64 +10175,72 @@ function gitEnvironment(token, host) {
10003
10175
  async function cloneRepository(source, options) {
10004
10176
  const log = options.log ?? (() => {
10005
10177
  });
10006
- const dest = path25__namespace.resolve(options.dest);
10007
- fs24__namespace.rmSync(dest, { recursive: true, force: true });
10008
- fs24__namespace.mkdirSync(dest, { recursive: true });
10009
- const ref = options.ref ?? source.ref;
10010
- const args = [
10011
- "-c",
10012
- "http.followRedirects=false",
10013
- ...source.kind === "https" ? ["-c", "protocol.file.allow=never", "-c", "protocol.ssh.allow=never"] : [],
10014
- "clone",
10015
- "--depth",
10016
- "1",
10017
- "--single-branch",
10018
- "--no-tags",
10019
- "--quiet"
10020
- ];
10021
- if (ref !== void 0 && ref !== null && ref !== "") {
10022
- args.push("--branch", ref);
10023
- }
10024
- args.push(source.url, dest);
10025
- log("clone: " + source.url + (ref ? " (" + ref + ")" : ""));
10026
- const started = Date.now();
10027
- const result = childProcess.spawnSync("git", args, {
10028
- env: {
10029
- ...gitEnvironment(options.token, source.host === "file" ? "localhost" : source.host),
10030
- ...source.kind === "https" ? { GIT_ALLOW_PROTOCOL: "https" } : {}
10031
- },
10032
- timeout: options.timeoutMs ?? 18e4,
10033
- encoding: "utf8",
10034
- windowsHide: true
10035
- });
10036
- if (result.error !== void 0 && result.error !== null) {
10037
- throw new Error("git clone could not run: " + result.error.message);
10038
- }
10039
- if (result.status !== 0) {
10040
- const detail = (result.stderr ?? "").trim().split("\n").slice(-3).join(" ");
10041
- throw new Error("git clone failed (exit " + result.status + "): " + (detail || "no output"));
10042
- }
10043
- const head = childProcess.spawnSync("git", ["-C", dest, "rev-parse", "HEAD"], { encoding: "utf8", windowsHide: true });
10044
- const commit = head.status === 0 ? (head.stdout ?? "").trim() : "";
10045
- if (commit === "") throw new Error("the clone has no HEAD; refusing to describe it");
10046
- const bytes = directorySize(dest);
10047
- log("clone: " + (bytes / 1024 / 1024).toFixed(1) + " MB in " + ((Date.now() - started) / 1e3).toFixed(1) + "s");
10048
- if (bytes > 1e9) {
10049
- throw new Error("the clone is larger than 1 GB (" + Math.round(bytes / 1024 / 1024) + " MB); refusing to scan it");
10050
- }
10051
- return {
10052
- directory: dest,
10053
- commit,
10054
- provenance: {
10055
- url: source.url,
10056
- host: source.host,
10057
- owner: source.owner,
10058
- repo: source.repo,
10059
- ref: ref !== void 0 && ref !== null && ref !== "" ? ref : null,
10178
+ const dest = path26__namespace.resolve(options.dest);
10179
+ fs25__namespace.rmSync(dest, { recursive: true, force: true });
10180
+ fs25__namespace.mkdirSync(dest, { recursive: true });
10181
+ try {
10182
+ const ref = options.ref ?? source.ref;
10183
+ const args = [
10184
+ "-c",
10185
+ "http.followRedirects=false",
10186
+ ...source.kind === "https" ? ["-c", "protocol.file.allow=never", "-c", "protocol.ssh.allow=never"] : [],
10187
+ "clone",
10188
+ "--depth",
10189
+ "1",
10190
+ "--single-branch",
10191
+ "--no-tags",
10192
+ "--quiet"
10193
+ ];
10194
+ if (ref !== void 0 && ref !== null && ref !== "") {
10195
+ args.push("--branch", ref);
10196
+ }
10197
+ args.push(source.url, dest);
10198
+ log("clone: " + source.url + (ref ? " (" + ref + ")" : ""));
10199
+ const started = Date.now();
10200
+ const result = childProcess.spawnSync("git", args, {
10201
+ env: {
10202
+ ...gitEnvironment(options.token, source.host === "file" ? "localhost" : source.host),
10203
+ ...source.kind === "https" ? { GIT_ALLOW_PROTOCOL: "https" } : {}
10204
+ },
10205
+ timeout: options.timeoutMs ?? 18e4,
10206
+ encoding: "utf8",
10207
+ windowsHide: true
10208
+ });
10209
+ if (result.error !== void 0 && result.error !== null) {
10210
+ throw new Error("git clone could not run: " + result.error.message);
10211
+ }
10212
+ if (result.status !== 0) {
10213
+ const detail = (result.stderr ?? "").trim().split("\n").slice(-3).join(" ");
10214
+ throw new Error("git clone failed (exit " + result.status + "): " + (detail || "no output"));
10215
+ }
10216
+ const head = childProcess.spawnSync("git", ["-C", dest, "rev-parse", "HEAD"], { encoding: "utf8", windowsHide: true });
10217
+ const commit = head.status === 0 ? (head.stdout ?? "").trim() : "";
10218
+ if (commit === "") throw new Error("the clone has no HEAD; refusing to describe it");
10219
+ const bytes = directorySize(dest);
10220
+ log("clone: " + (bytes / 1024 / 1024).toFixed(1) + " MB in " + ((Date.now() - started) / 1e3).toFixed(1) + "s");
10221
+ if (bytes > 1e9) {
10222
+ throw new Error("the clone is larger than 1 GB (" + Math.round(bytes / 1024 / 1024) + " MB); refusing to scan it");
10223
+ }
10224
+ return {
10225
+ directory: dest,
10060
10226
  commit,
10061
- fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
10227
+ provenance: {
10228
+ url: source.url,
10229
+ host: source.host,
10230
+ owner: source.owner,
10231
+ repo: source.repo,
10232
+ ref: ref !== void 0 && ref !== null && ref !== "" ? ref : null,
10233
+ commit,
10234
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
10235
+ }
10236
+ };
10237
+ } catch (error) {
10238
+ try {
10239
+ fs25__namespace.rmSync(dest, { recursive: true, force: true });
10240
+ } catch {
10062
10241
  }
10063
- };
10242
+ throw error;
10243
+ }
10064
10244
  }
10065
10245
  function directorySize(root) {
10066
10246
  let total = 0;
@@ -10069,16 +10249,16 @@ function directorySize(root) {
10069
10249
  const current = stack.pop();
10070
10250
  let entries;
10071
10251
  try {
10072
- entries = fs24__namespace.readdirSync(current, { withFileTypes: true });
10252
+ entries = fs25__namespace.readdirSync(current, { withFileTypes: true });
10073
10253
  } catch {
10074
10254
  continue;
10075
10255
  }
10076
10256
  for (const entry of entries) {
10077
- const full = path25__namespace.join(current, entry.name);
10257
+ const full = path26__namespace.join(current, entry.name);
10078
10258
  if (entry.isDirectory()) stack.push(full);
10079
10259
  else if (entry.isFile()) {
10080
10260
  try {
10081
- total += fs24__namespace.statSync(full).size;
10261
+ total += fs25__namespace.statSync(full).size;
10082
10262
  } catch {
10083
10263
  }
10084
10264
  }
@@ -10087,7 +10267,7 @@ function directorySize(root) {
10087
10267
  return total;
10088
10268
  }
10089
10269
  function makeCloneDirectory() {
10090
- return fs24__namespace.mkdtempSync(path25__namespace.join(os2__namespace.tmpdir(), "codebase-snapshot-clone-"));
10270
+ return fs25__namespace.mkdtempSync(path26__namespace.join(os2__namespace.tmpdir(), "codebase-snapshot-clone-"));
10091
10271
  }
10092
10272
 
10093
10273
  // src/mcp/instructions.ts
@@ -10358,8 +10538,8 @@ function findSection(sections, relativePath) {
10358
10538
  if (exact) return exact;
10359
10539
  const foldedPath = rendered.toLowerCase();
10360
10540
  const folded = sections.filter((section) => {
10361
- const path26 = section.path.toLowerCase();
10362
- return path26 === relativePath.toLowerCase() || path26 === foldedPath;
10541
+ const path27 = section.path.toLowerCase();
10542
+ return path27 === relativePath.toLowerCase() || path27 === foldedPath;
10363
10543
  });
10364
10544
  return folded.length === 1 ? folded[0] : null;
10365
10545
  }
@@ -10386,14 +10566,14 @@ function sha256(buffer) {
10386
10566
  }
10387
10567
  function readBytes(file) {
10388
10568
  try {
10389
- return fs24__namespace.readFileSync(file);
10569
+ return fs25__namespace.readFileSync(file);
10390
10570
  } catch {
10391
10571
  return null;
10392
10572
  }
10393
10573
  }
10394
10574
  function readText2(file) {
10395
10575
  try {
10396
- return fs24__namespace.readFileSync(file, "utf8");
10576
+ return fs25__namespace.readFileSync(file, "utf8");
10397
10577
  } catch {
10398
10578
  return null;
10399
10579
  }
@@ -10410,15 +10590,15 @@ function readJson(file) {
10410
10590
  function walk(dir, prefix = "") {
10411
10591
  let entries;
10412
10592
  try {
10413
- entries = fs24__namespace.readdirSync(dir, { withFileTypes: true });
10593
+ entries = fs25__namespace.readdirSync(dir, { withFileTypes: true });
10414
10594
  } catch {
10415
10595
  return [];
10416
10596
  }
10417
10597
  const files = [];
10418
10598
  for (const entry of entries) {
10419
- const relative14 = prefix === "" ? entry.name : prefix + "/" + entry.name;
10420
- if (entry.isDirectory()) files.push(...walk(path25__namespace.join(dir, entry.name), relative14));
10421
- else if (entry.isFile()) files.push(relative14);
10599
+ const relative15 = prefix === "" ? entry.name : prefix + "/" + entry.name;
10600
+ if (entry.isDirectory()) files.push(...walk(path26__namespace.join(dir, entry.name), relative15));
10601
+ else if (entry.isFile()) files.push(relative15);
10422
10602
  }
10423
10603
  return files;
10424
10604
  }
@@ -10458,9 +10638,9 @@ function secretTokens(text2) {
10458
10638
  }
10459
10639
  function readArtifactTexts(snapshotDir) {
10460
10640
  const texts = [];
10461
- for (const relative14 of walk(snapshotDir)) {
10462
- if (!TEXT_ARTIFACT.test(relative14)) continue;
10463
- const text2 = readText2(path25__namespace.join(snapshotDir, relative14));
10641
+ for (const relative15 of walk(snapshotDir)) {
10642
+ if (!TEXT_ARTIFACT.test(relative15)) continue;
10643
+ const text2 = readText2(path26__namespace.join(snapshotDir, relative15));
10464
10644
  if (text2 !== null) texts.push(text2);
10465
10645
  }
10466
10646
  return texts;
@@ -10476,15 +10656,15 @@ function findHostPaths(snapshotDir, repoDir) {
10476
10656
  ];
10477
10657
  const repoPattern = new RegExp(escapeRegExp(repoDir), "g");
10478
10658
  const hits = /* @__PURE__ */ new Set();
10479
- for (const relative14 of walk(snapshotDir)) {
10480
- if (!TEXT_ARTIFACT.test(relative14)) continue;
10481
- const text2 = readText2(path25__namespace.join(snapshotDir, relative14));
10659
+ for (const relative15 of walk(snapshotDir)) {
10660
+ if (!TEXT_ARTIFACT.test(relative15)) continue;
10661
+ const text2 = readText2(path26__namespace.join(snapshotDir, relative15));
10482
10662
  if (text2 === null) continue;
10483
10663
  for (const pattern of patterns) {
10484
- for (const match of text2.match(pattern) ?? []) hits.add(relative14 + ": " + match);
10664
+ for (const match of text2.match(pattern) ?? []) hits.add(relative15 + ": " + match);
10485
10665
  }
10486
10666
  repoPattern.lastIndex = 0;
10487
- if (repoPattern.test(text2)) hits.add(relative14 + ": the repository absolute path");
10667
+ if (repoPattern.test(text2)) hits.add(relative15 + ": the repository absolute path");
10488
10668
  }
10489
10669
  return [...hits];
10490
10670
  }
@@ -10634,10 +10814,10 @@ function markdownPackBodies(text2) {
10634
10814
  return bodies.size === 0 ? null : bodies;
10635
10815
  }
10636
10816
  function auditSnapshot(options) {
10637
- const snapshotDir = path25__namespace.resolve(options.snapshotDir);
10638
- const repoDir = path25__namespace.resolve(options.repoDir);
10817
+ const snapshotDir = path26__namespace.resolve(options.snapshotDir);
10818
+ const repoDir = path26__namespace.resolve(options.repoDir);
10639
10819
  const checks = [];
10640
- const manifestFile = path25__namespace.join(snapshotDir, "manifest.json");
10820
+ const manifestFile = path26__namespace.join(snapshotDir, "manifest.json");
10641
10821
  const raw = readJson(manifestFile);
10642
10822
  const problem = raw === null ? "the file is missing or is not valid JSON" : describeManifestShapeProblem(raw);
10643
10823
  if (raw === null || problem !== null) {
@@ -10666,7 +10846,7 @@ function auditSnapshot(options) {
10666
10846
  const missingParts = [];
10667
10847
  const mismatched = [];
10668
10848
  for (const part of manifest.parts) {
10669
- const bytes = readBytes(path25__namespace.join(snapshotDir, "parts", part.filename));
10849
+ const bytes = readBytes(path26__namespace.join(snapshotDir, "parts", part.filename));
10670
10850
  if (bytes === null) {
10671
10851
  missingParts.push(part.filename);
10672
10852
  continue;
@@ -10731,13 +10911,13 @@ function auditSnapshot(options) {
10731
10911
  let artifactCount = 0;
10732
10912
  for (const [key, value] of Object.entries(artifacts)) {
10733
10913
  if (value === null || value === void 0) continue;
10734
- const relative14 = ARTIFACT_FILES[key];
10735
- if (relative14 === void 0) continue;
10914
+ const relative15 = ARTIFACT_FILES[key];
10915
+ if (relative15 === void 0) continue;
10736
10916
  artifactCount += 1;
10737
- const bytes = readBytes(path25__namespace.join(snapshotDir, relative14));
10738
- if (bytes === null) artifactProblems.push(relative14 + " is missing");
10917
+ const bytes = readBytes(path26__namespace.join(snapshotDir, relative15));
10918
+ if (bytes === null) artifactProblems.push(relative15 + " is missing");
10739
10919
  else if (typeof value.sha256 === "string" && sha256(bytes) !== value.sha256) {
10740
- artifactProblems.push(relative14 + " changed");
10920
+ artifactProblems.push(relative15 + " changed");
10741
10921
  }
10742
10922
  }
10743
10923
  checks.push(
@@ -10781,8 +10961,8 @@ function auditSnapshot(options) {
10781
10961
  unexpected.length + " unexpected path(s): " + sample(unexpected)
10782
10962
  )
10783
10963
  );
10784
- const signaturePath = path25__namespace.join(snapshotDir, "signature.json");
10785
- if (fs24__namespace.existsSync(signaturePath)) {
10964
+ const signaturePath = path26__namespace.join(snapshotDir, "signature.json");
10965
+ if (fs25__namespace.existsSync(signaturePath)) {
10786
10966
  const outcome = verifySnapshotSignature(snapshotDir);
10787
10967
  checks.push(
10788
10968
  outcome.ok ? check(
@@ -10847,7 +11027,7 @@ function auditSnapshot(options) {
10847
11027
  manifest.files.map((file) => [anchorForPath(file.relativePath), file.relativePath])
10848
11028
  );
10849
11029
  for (const part of manifest.parts) {
10850
- const partText = readText2(path25__namespace.join(snapshotDir, "parts", part.filename));
11030
+ const partText = readText2(path26__namespace.join(snapshotDir, "parts", part.filename));
10851
11031
  if (partText === null) continue;
10852
11032
  const sections = parsePartSections(partText);
10853
11033
  partTexts.set(part.filename, partText);
@@ -10914,7 +11094,7 @@ function auditSnapshot(options) {
10914
11094
  }
10915
11095
  };
10916
11096
  if (manifest.artifacts?.readme != null) {
10917
- const text2 = readText2(path25__namespace.join(snapshotDir, "README.md"));
11097
+ const text2 = readText2(path26__namespace.join(snapshotDir, "README.md"));
10918
11098
  if (text2 === null) {
10919
11099
  reportProblems.push("README.md is recorded but unreadable");
10920
11100
  } else {
@@ -10954,7 +11134,7 @@ function auditSnapshot(options) {
10954
11134
  }
10955
11135
  }
10956
11136
  if (manifest.artifacts?.prompt != null) {
10957
- const text2 = readText2(path25__namespace.join(snapshotDir, "PROMPT.md"));
11137
+ const text2 = readText2(path26__namespace.join(snapshotDir, "PROMPT.md"));
10958
11138
  if (text2 === null) {
10959
11139
  reportProblems.push("PROMPT.md is recorded but unreadable");
10960
11140
  } else {
@@ -11143,7 +11323,7 @@ function auditSnapshot(options) {
11143
11323
  ];
11144
11324
  for (const reader of packReaders) {
11145
11325
  if (manifest.artifacts?.[reader.key] == null) continue;
11146
- const packText = readText2(path25__namespace.join(snapshotDir, reader.file));
11326
+ const packText = readText2(path26__namespace.join(snapshotDir, reader.file));
11147
11327
  const problems = [];
11148
11328
  if (packText === null) {
11149
11329
  problems.push(reader.file + " is recorded but unreadable");
@@ -11156,8 +11336,8 @@ function auditSnapshot(options) {
11156
11336
  for (const file of manifest.files) {
11157
11337
  if (!packed.has(file.relativePath)) problems.push(file.relativePath + " is in the manifest but not the pack");
11158
11338
  }
11159
- for (const path26 of packed) {
11160
- if (!known2.has(path26)) problems.push(path26 + " is in the pack but not the manifest");
11339
+ for (const path27 of packed) {
11340
+ if (!known2.has(path27)) problems.push(path27 + " is in the pack but not the manifest");
11161
11341
  }
11162
11342
  }
11163
11343
  }
@@ -11193,7 +11373,7 @@ function auditSnapshot(options) {
11193
11373
  bodyByPath.set(file.relativePath, section.body);
11194
11374
  bodiesChecked += 1;
11195
11375
  const bytes = Buffer.byteLength(section.body, "utf8");
11196
- const bodyLines = section.body === "" ? 0 : section.body.split("\n").length - (section.body.endsWith("\n") ? 1 : 0);
11376
+ const bodyLines = countBodyLines(section.body);
11197
11377
  if (bytes !== file.includedBytes) {
11198
11378
  bodyProblems.push(file.relativePath + ": manifest says " + file.includedBytes + " B, part holds " + bytes + " B");
11199
11379
  } else if (bodyLines !== file.includedLines) {
@@ -11306,7 +11486,7 @@ function auditSnapshot(options) {
11306
11486
  let packBodies = 0;
11307
11487
  let packSkipped = 0;
11308
11488
  for (const pack of packsWanted) {
11309
- const text2 = readText2(path25__namespace.join(snapshotDir, pack.file));
11489
+ const text2 = readText2(path26__namespace.join(snapshotDir, pack.file));
11310
11490
  if (text2 === null) continue;
11311
11491
  const bodies = pack.read(text2);
11312
11492
  if (bodies === null) {
@@ -11370,7 +11550,7 @@ function auditSnapshot(options) {
11370
11550
  unreplayable += 1;
11371
11551
  continue;
11372
11552
  }
11373
- const bytes = readBytes(path25__namespace.join(repoDir, file.relativePath));
11553
+ const bytes = readBytes(path26__namespace.join(repoDir, file.relativePath));
11374
11554
  if (bytes === null || sha256(bytes) !== file.hashSha256) {
11375
11555
  unreplayable += 1;
11376
11556
  continue;
@@ -11408,9 +11588,9 @@ function auditSnapshot(options) {
11408
11588
  )
11409
11589
  );
11410
11590
  }
11411
- const indexParent = path25__namespace.dirname(snapshotDir);
11412
- const indexPath = path25__namespace.join(indexParent, "WORKSPACE.json");
11413
- if (fs24__namespace.existsSync(indexPath)) {
11591
+ const indexParent = path26__namespace.dirname(snapshotDir);
11592
+ const indexPath = path26__namespace.join(indexParent, "WORKSPACE.json");
11593
+ if (fs25__namespace.existsSync(indexPath)) {
11414
11594
  const indexText = readText2(indexPath);
11415
11595
  let members = [];
11416
11596
  let problem2 = null;
@@ -11421,7 +11601,7 @@ function auditSnapshot(options) {
11421
11601
  } catch (error) {
11422
11602
  problem2 = error.message;
11423
11603
  }
11424
- const memberName = path25__namespace.basename(snapshotDir);
11604
+ const memberName = path26__namespace.basename(snapshotDir);
11425
11605
  const member = members.find((entry) => entry.name === memberName);
11426
11606
  if (problem2 !== null) {
11427
11607
  checks.push(check(
@@ -11445,7 +11625,7 @@ function auditSnapshot(options) {
11445
11625
  if (typeof member.files === "number" && member.files !== manifest.counts.totalFiles) {
11446
11626
  disagreements.push("file count");
11447
11627
  }
11448
- const sourceGone = typeof member.path === "string" && !fs24__namespace.existsSync(member.path) ? "Member " + memberName + " source directory is gone (" + member.path + "); the snapshot still describes it. Regenerate the workspace." : null;
11628
+ const sourceGone = typeof member.path === "string" && !fs25__namespace.existsSync(member.path) ? "Member " + memberName + " source directory is gone (" + member.path + "); the snapshot still describes it. Regenerate the workspace." : null;
11449
11629
  checks.push(
11450
11630
  sourceGone !== null ? check("workspace.index", "The workspace index agrees with this member", "warning", "warn", sourceGone) : disagreements.length === 0 ? check(
11451
11631
  "workspace.index",
@@ -11467,29 +11647,29 @@ function auditSnapshot(options) {
11467
11647
  const scanBudget = options.maxScanBytes ?? 32 * 1024 * 1024;
11468
11648
  const leakHits = [];
11469
11649
  let scannedBytes = 0;
11470
- for (const relative14 of walk(snapshotDir)) {
11471
- if (!TEXT_ARTIFACT.test(relative14) || scannedBytes > scanBudget) continue;
11472
- if (relative14 === SIGNATURE_FILE) continue;
11473
- const text2 = readText2(path25__namespace.join(snapshotDir, relative14));
11650
+ for (const relative15 of walk(snapshotDir)) {
11651
+ if (!TEXT_ARTIFACT.test(relative15) || scannedBytes > scanBudget) continue;
11652
+ if (relative15 === SIGNATURE_FILE) continue;
11653
+ const text2 = readText2(path26__namespace.join(snapshotDir, relative15));
11474
11654
  if (text2 === null) continue;
11475
11655
  scannedBytes += Buffer.byteLength(text2, "utf8");
11476
11656
  let findingCount = 0;
11477
- if (/^parts[\\/].*\.md$/i.test(relative14)) {
11657
+ if (/^parts[\\/].*\.md$/i.test(relative15)) {
11478
11658
  let headerText = text2;
11479
11659
  for (const section of parsePartSections(text2)) {
11480
11660
  findingCount += scanAndRedactSecrets(section.body, rules, section.path).findings.length;
11481
11661
  headerText = headerText.replace(section.body, "");
11482
11662
  }
11483
- findingCount += scanAndRedactSecrets(headerText, rules, relative14).findings.length;
11663
+ findingCount += scanAndRedactSecrets(headerText, rules, relative15).findings.length;
11484
11664
  } else {
11485
- findingCount = scanAndRedactSecrets(text2, rules, relative14).findings.length;
11665
+ findingCount = scanAndRedactSecrets(text2, rules, relative15).findings.length;
11486
11666
  }
11487
11667
  if (findingCount > 0) {
11488
- leakHits.push(relative14 + " (" + findingCount + " line(s))");
11668
+ leakHits.push(relative15 + " (" + findingCount + " line(s))");
11489
11669
  }
11490
11670
  }
11491
- const signatureRecordPath = path25__namespace.join(snapshotDir, SIGNATURE_FILE);
11492
- if (fs24__namespace.existsSync(signatureRecordPath)) {
11671
+ const signatureRecordPath = path26__namespace.join(snapshotDir, SIGNATURE_FILE);
11672
+ if (fs25__namespace.existsSync(signatureRecordPath)) {
11493
11673
  const recordText = readText2(signatureRecordPath);
11494
11674
  if (recordText !== null) {
11495
11675
  scannedBytes += Buffer.byteLength(recordText, "utf8");
@@ -11534,7 +11714,7 @@ function auditSnapshot(options) {
11534
11714
  const artifactContains = (token) => artifactTexts.some((text2) => text2.includes(token));
11535
11715
  for (const record of skippedSensitive.slice(0, 40)) {
11536
11716
  if (record.path.includes("[REDACTED") || compared > 400) continue;
11537
- const text2 = readText2(path25__namespace.join(repoDir, record.path));
11717
+ const text2 = readText2(path26__namespace.join(repoDir, record.path));
11538
11718
  if (text2 === null) continue;
11539
11719
  for (const token of secretTokens(text2)) {
11540
11720
  compared += 1;
@@ -11686,42 +11866,42 @@ function describeMatcher(matcher) {
11686
11866
  return String(matcher);
11687
11867
  }
11688
11868
  function normalizeTarget(cwd, target) {
11689
- const resolvedCwd = path25__namespace.resolve(cwd);
11690
- const absolute = path25__namespace.resolve(resolvedCwd, target);
11691
- const relative14 = path25__namespace.relative(resolvedCwd, absolute);
11692
- if (relative14 === "" || relative14 === ".." || relative14.startsWith(`..${path25__namespace.sep}`) || path25__namespace.isAbsolute(relative14)) {
11869
+ const resolvedCwd = path26__namespace.resolve(cwd);
11870
+ const absolute = path26__namespace.resolve(resolvedCwd, target);
11871
+ const relative15 = path26__namespace.relative(resolvedCwd, absolute);
11872
+ if (relative15 === "" || relative15 === ".." || relative15.startsWith(`..${path26__namespace.sep}`) || path26__namespace.isAbsolute(relative15)) {
11693
11873
  return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
11694
11874
  }
11695
- return { relative: relative14.split(path25__namespace.sep).join("/"), outsideRoot: false };
11875
+ return { relative: relative15.split(path26__namespace.sep).join("/"), outsideRoot: false };
11696
11876
  }
11697
11877
  function findRuleMatch(rules, relativePath) {
11698
11878
  return rules.find(
11699
11879
  (rule) => matchRule(relativePath, rule.match)
11700
11880
  );
11701
11881
  }
11702
- function findRecordedAncestor(skipped, relative14, maskedPath2) {
11882
+ function findRecordedAncestor(skipped, relative15, maskedPath2) {
11703
11883
  let nearest;
11704
11884
  for (const record of skipped) {
11705
11885
  const ancestorPath = record.path;
11706
11886
  if (ancestorPath.length === 0) continue;
11707
- const isAncestor = relative14.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
11887
+ const isAncestor = relative15.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
11708
11888
  if (!isAncestor) continue;
11709
11889
  if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
11710
11890
  }
11711
11891
  return nearest;
11712
11892
  }
11713
11893
  function readManifest2(config) {
11714
- const manifestPath = path25__namespace.resolve(config.cwd, config.outDir, "manifest.json");
11894
+ const manifestPath = path26__namespace.resolve(config.cwd, config.outDir, "manifest.json");
11715
11895
  try {
11716
- return JSON.parse(fs24__namespace.readFileSync(manifestPath, "utf8"));
11896
+ return JSON.parse(fs25__namespace.readFileSync(manifestPath, "utf8"));
11717
11897
  } catch {
11718
11898
  return null;
11719
11899
  }
11720
11900
  }
11721
11901
  function explainPath(config, target) {
11722
11902
  const normalized = normalizeTarget(config.cwd, target);
11723
- const relative14 = normalized.relative;
11724
- const maskedPath2 = findSecretInPath(relative14, config.secretRules)?.masked ?? relative14;
11903
+ const relative15 = normalized.relative;
11904
+ const maskedPath2 = findSecretInPath(relative15, config.secretRules)?.masked ?? relative15;
11725
11905
  if (normalized.outsideRoot) {
11726
11906
  return {
11727
11907
  path: maskedPath2,
@@ -11731,10 +11911,10 @@ function explainPath(config, target) {
11731
11911
  detail: "path resolves outside the configured repository root and was not inspected"
11732
11912
  };
11733
11913
  }
11734
- const absolute = path25__namespace.join(config.cwd, relative14);
11914
+ const absolute = path26__namespace.join(config.cwd, relative15);
11735
11915
  const result = {
11736
11916
  path: maskedPath2,
11737
- exists: fs24__namespace.existsSync(absolute),
11917
+ exists: fs25__namespace.existsSync(absolute),
11738
11918
  included: false
11739
11919
  };
11740
11920
  const collection = collectFiles(config.cwd, {
@@ -11748,12 +11928,12 @@ function explainPath(config, target) {
11748
11928
  // Same exclusion `generate` applies, so `explain` never says "not-discovered" about a file
11749
11929
  // that is only missing because the walker dropped the tool's own output directory.
11750
11930
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
11751
- (directory) => path25__namespace.relative(config.cwd, path25__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
11752
- ).filter((relative15) => relative15.length > 0 && !relative15.startsWith(".."))
11931
+ (directory) => path26__namespace.relative(config.cwd, path26__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
11932
+ ).filter((relative16) => relative16.length > 0 && !relative16.startsWith(".."))
11753
11933
  });
11754
- if (!collection.files.includes(relative14)) {
11934
+ if (!collection.files.includes(relative15)) {
11755
11935
  const record = collection.skipped.find(
11756
- (entry2) => entry2.path === relative14 || entry2.path === maskedPath2
11936
+ (entry2) => entry2.path === relative15 || entry2.path === maskedPath2
11757
11937
  );
11758
11938
  if (record) {
11759
11939
  result.reason = record.reason;
@@ -11762,7 +11942,7 @@ function explainPath(config, target) {
11762
11942
  result.reason = "missing";
11763
11943
  result.detail = "no such file or directory, relative to the configured cwd";
11764
11944
  } else {
11765
- const ancestor = findRecordedAncestor(collection.skipped, relative14, maskedPath2);
11945
+ const ancestor = findRecordedAncestor(collection.skipped, relative15, maskedPath2);
11766
11946
  if (ancestor) {
11767
11947
  result.reason = ancestor.reason;
11768
11948
  result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
@@ -11782,11 +11962,11 @@ function explainPath(config, target) {
11782
11962
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
11783
11963
  ...config.staged === true ? { staged: true } : {}
11784
11964
  });
11785
- inScope = scope.paths.has(relative14);
11965
+ inScope = scope.paths.has(relative15);
11786
11966
  if (!inScope && config.withDependents === true) {
11787
11967
  inScope = importsChangedFile(
11788
- relative14,
11789
- importsOfFile(relative14, absolute),
11968
+ relative15,
11969
+ importsOfFile(relative15, absolute),
11790
11970
  scope.paths,
11791
11971
  buildImportResolver(collection.files.map((file) => ({ relativePath: file })), {
11792
11972
  tsconfig: tsconfigPathsFor(config.cwd)
@@ -11815,7 +11995,7 @@ function explainPath(config, target) {
11815
11995
  }
11816
11996
  let sizeOnDisk = null;
11817
11997
  try {
11818
- sizeOnDisk = fs24__namespace.statSync(absolute).size;
11998
+ sizeOnDisk = fs25__namespace.statSync(absolute).size;
11819
11999
  } catch {
11820
12000
  sizeOnDisk = null;
11821
12001
  }
@@ -11825,10 +12005,10 @@ function explainPath(config, target) {
11825
12005
  result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
11826
12006
  return result;
11827
12007
  }
11828
- if (fs24__namespace.existsSync(absolute) && fs24__namespace.statSync(absolute).isFile()) {
12008
+ if (fs25__namespace.existsSync(absolute) && fs25__namespace.statSync(absolute).isFile()) {
11829
12009
  let buffer;
11830
12010
  try {
11831
- buffer = fs24__namespace.readFileSync(absolute);
12011
+ buffer = fs25__namespace.readFileSync(absolute);
11832
12012
  } catch (err) {
11833
12013
  result.included = false;
11834
12014
  result.reason = "read-error";
@@ -11846,15 +12026,15 @@ function explainPath(config, target) {
11846
12026
  result.bytes = buffer.length;
11847
12027
  result.lines = countLines(text2);
11848
12028
  if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
11849
- const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative14);
12029
+ const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative15);
11850
12030
  result.secretCount = findings.length;
11851
12031
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
11852
12032
  let inclusionMode = "full";
11853
- if (config.skeleton === true && isSkeletonizable(relative14)) {
11854
- const skeleton = skeletonizeTypeScript(text2, relative14);
12033
+ if (config.skeleton === true && isSkeletonizable(relative15)) {
12034
+ const skeleton = skeletonizeTypeScript(text2, relative15);
11855
12035
  if (skeleton.collapsed > 0) inclusionMode = "signatures";
11856
12036
  }
11857
- if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative14) && stripComments2(text2, relative14).removed > 0) {
12037
+ if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative15) && stripComments2(text2, relative15).removed > 0) {
11858
12038
  inclusionMode = "comments-stripped";
11859
12039
  }
11860
12040
  if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
@@ -11863,18 +12043,18 @@ function explainPath(config, target) {
11863
12043
  }
11864
12044
  result.inclusionMode = inclusionMode;
11865
12045
  }
11866
- result.layer = classifyLayer(relative14, config.layers);
11867
- result.kind = classifyKind(relative14, config.kinds);
11868
- result.language = detectLanguage(relative14);
11869
- const layerRule = findRuleMatch(config.layers, relative14);
12046
+ result.layer = classifyLayer(relative15, config.layers);
12047
+ result.kind = classifyKind(relative15, config.kinds);
12048
+ result.language = detectLanguage(relative15);
12049
+ const layerRule = findRuleMatch(config.layers, relative15);
11870
12050
  if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
11871
- const kindRule = findRuleMatch(config.kinds, relative14);
12051
+ const kindRule = findRuleMatch(config.kinds, relative15);
11872
12052
  if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
11873
12053
  const manifest = readManifest2(config);
11874
- const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative14) : void 0;
12054
+ const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative15) : void 0;
11875
12055
  result.part = entry?.part ?? null;
11876
12056
  if (entry === void 0) {
11877
- const record = manifest?.skipped?.find((skip) => skip.path === relative14);
12057
+ const record = manifest?.skipped?.find((skip) => skip.path === relative15);
11878
12058
  if (record !== void 0 && (record.reason === "not-selected" || record.reason === "unchanged")) {
11879
12059
  result.included = false;
11880
12060
  result.reason = record.reason;
@@ -11918,7 +12098,7 @@ function renderExplainText(result) {
11918
12098
  return lines.join("\n");
11919
12099
  }
11920
12100
  function workerEntry(directory, isCjs) {
11921
- const entry = path25__namespace.join(directory, isCjs ? "index.cjs" : "index.js");
12101
+ const entry = path26__namespace.join(directory, isCjs ? "index.cjs" : "index.js");
11922
12102
  return { path: entry, url: url.pathToFileURL(entry).href };
11923
12103
  }
11924
12104
  var WORKER_SOURCE = `
@@ -11979,7 +12159,7 @@ const { parentPort, workerData } = require("node:worker_threads");
11979
12159
  })();
11980
12160
  `;
11981
12161
  function generateInWorker(cwd, cliOptions, options = {}) {
11982
- return new Promise((resolve14) => {
12162
+ return new Promise((resolve15) => {
11983
12163
  let settled = false;
11984
12164
  let worker = null;
11985
12165
  const finish = (result) => {
@@ -11990,11 +12170,11 @@ function generateInWorker(cwd, cliOptions, options = {}) {
11990
12170
  if (!result.ok && options.runId !== void 0 && options.lockRoots !== void 0) {
11991
12171
  releaseAbandonedRun(options.lockRoots, options.runId);
11992
12172
  }
11993
- resolve14(result);
12173
+ resolve15(result);
11994
12174
  });
11995
12175
  };
11996
12176
  const isCjs = typeof __dirname !== "undefined";
11997
- const directory = isCjs ? __dirname : path25__namespace.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));
12177
+ const directory = isCjs ? __dirname : path26__namespace.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));
11998
12178
  try {
11999
12179
  worker = new worker_threads.Worker(WORKER_SOURCE, {
12000
12180
  eval: true,
@@ -12056,43 +12236,99 @@ function windowText(body, fromLine, lineCount) {
12056
12236
  pastEnd
12057
12237
  };
12058
12238
  }
12239
+ function isInside2(parent, child) {
12240
+ const relative15 = path26__namespace.relative(parent, child);
12241
+ return relative15 === "" || !relative15.startsWith("..") && !path26__namespace.isAbsolute(relative15);
12242
+ }
12243
+ function readConfinedText(baseDir, relativePath) {
12244
+ if (relativePath.length === 0 || relativePath.includes("\0")) {
12245
+ return { ok: false, reason: "not-file", message: "the file name is empty or contains a NUL byte" };
12246
+ }
12247
+ if (path26__namespace.isAbsolute(relativePath)) {
12248
+ return { ok: false, reason: "outside", message: "an absolute path is not a snapshot-relative file" };
12249
+ }
12250
+ let baseReal;
12251
+ try {
12252
+ baseReal = fs25__namespace.realpathSync(path26__namespace.resolve(baseDir));
12253
+ } catch {
12254
+ return { ok: false, reason: "missing", message: "the snapshot directory does not exist" };
12255
+ }
12256
+ const candidate = path26__namespace.resolve(baseReal, relativePath);
12257
+ if (!isInside2(baseReal, candidate)) {
12258
+ return { ok: false, reason: "outside", message: "the path resolves outside the snapshot directory" };
12259
+ }
12260
+ let stats;
12261
+ try {
12262
+ stats = fs25__namespace.lstatSync(candidate);
12263
+ } catch (error) {
12264
+ const code = error.code;
12265
+ return {
12266
+ ok: false,
12267
+ reason: code === "ENOENT" || code === "ENOTDIR" ? "missing" : "unreadable",
12268
+ message: code === "ENOENT" || code === "ENOTDIR" ? "the file does not exist" : "the file could not be inspected"
12269
+ };
12270
+ }
12271
+ if (stats.isSymbolicLink()) {
12272
+ return { ok: false, reason: "not-file", message: "the file is a symbolic link" };
12273
+ }
12274
+ if (!stats.isFile()) {
12275
+ return { ok: false, reason: "not-file", message: "the path is not a regular file" };
12276
+ }
12277
+ let real;
12278
+ try {
12279
+ real = fs25__namespace.realpathSync(candidate);
12280
+ } catch {
12281
+ return { ok: false, reason: "unreadable", message: "the file could not be resolved" };
12282
+ }
12283
+ if (!isInside2(baseReal, real)) {
12284
+ return { ok: false, reason: "outside", message: "the file resolves outside the snapshot directory" };
12285
+ }
12286
+ try {
12287
+ const text2 = fs25__namespace.readFileSync(real, "utf8");
12288
+ return { ok: true, text: text2, path: real, stats: fs25__namespace.statSync(real) };
12289
+ } catch {
12290
+ return { ok: false, reason: "unreadable", message: "the file could not be read" };
12291
+ }
12292
+ }
12293
+
12294
+ // src/mcp/workspace.ts
12059
12295
  function foldForComparison(value) {
12060
12296
  return process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
12061
12297
  }
12062
12298
  function canonicalPath(value) {
12063
- const absolute = path25__namespace.resolve(value);
12299
+ const absolute = path26__namespace.resolve(value);
12064
12300
  try {
12065
- return fs24__namespace.realpathSync(absolute);
12301
+ return fs25__namespace.realpathSync(absolute);
12066
12302
  } catch {
12067
12303
  return absolute;
12068
12304
  }
12069
12305
  }
12070
- function isInside2(parent, child) {
12306
+ function isInside3(parent, child) {
12071
12307
  const foldedParent = foldForComparison(parent);
12072
12308
  const foldedChild = foldForComparison(child);
12073
- return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path25__namespace.sep}`);
12309
+ return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path26__namespace.sep}`);
12074
12310
  }
12075
12311
  function resolveThroughExistingAncestor(target) {
12076
12312
  let existing = target;
12077
12313
  const missing = [];
12078
- while (!fs24__namespace.existsSync(existing)) {
12079
- missing.unshift(path25__namespace.basename(existing));
12080
- const parent = path25__namespace.dirname(existing);
12314
+ while (!fs25__namespace.existsSync(existing)) {
12315
+ missing.unshift(path26__namespace.basename(existing));
12316
+ const parent = path26__namespace.dirname(existing);
12081
12317
  if (parent === existing) break;
12082
12318
  existing = parent;
12083
12319
  }
12084
12320
  const resolved = canonicalPath(existing);
12085
- return missing.length === 0 ? resolved : path25__namespace.join(resolved, ...missing);
12321
+ return missing.length === 0 ? resolved : path26__namespace.join(resolved, ...missing);
12086
12322
  }
12087
12323
  function resolveRoot(requested, context) {
12088
12324
  if (requested !== void 0 && (typeof requested !== "string" || requested.trim().length === 0)) {
12089
12325
  return { ok: false, message: '"root" must be a non-empty string when provided.' };
12090
12326
  }
12091
12327
  const wanted = typeof requested === "string" ? requested.trim() : context.cwd;
12092
- const absolute = path25__namespace.resolve(context.cwd, wanted);
12328
+ const absolute = path26__namespace.resolve(context.cwd, wanted);
12093
12329
  let stats;
12094
12330
  try {
12095
- stats = fs24__namespace.statSync(absolute);
12331
+ stats = fs25__namespace.statSync(absolute);
12096
12332
  } catch {
12097
12333
  return { ok: false, message: `"${wanted}" does not exist, so it cannot be a repository root.` };
12098
12334
  }
@@ -12101,7 +12337,7 @@ function resolveRoot(requested, context) {
12101
12337
  }
12102
12338
  const resolved = canonicalPath(absolute);
12103
12339
  for (const allowed of context.roots) {
12104
- if (isInside2(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
12340
+ if (isInside3(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
12105
12341
  }
12106
12342
  const shown = context.roots.join(", ");
12107
12343
  return {
@@ -12144,8 +12380,8 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
12144
12380
  }
12145
12381
  const requested = overrides.outDir.trim();
12146
12382
  const permitted = allowedRoots !== void 0 && allowedRoots.length > 0 ? allowedRoots : [root];
12147
- const resolved = resolveThroughExistingAncestor(path25__namespace.resolve(root, requested));
12148
- if (!permitted.some((allowed) => isInside2(canonicalPath(allowed), resolved))) {
12383
+ const resolved = resolveThroughExistingAncestor(path26__namespace.resolve(root, requested));
12384
+ if (!permitted.some((allowed) => isInside3(canonicalPath(allowed), resolved))) {
12149
12385
  const shown = permitted.map((allowed) => canonicalPath(allowed)).join(", ");
12150
12386
  return {
12151
12387
  ok: false,
@@ -12167,6 +12403,14 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
12167
12403
  if (overrides.sarif === true) cliOptions.sarif = true;
12168
12404
  if (overrides.staged === true) cliOptions.staged = true;
12169
12405
  if (overrides.withDependents === true) cliOptions.withDependents = true;
12406
+ for (const key of ["only", "ignore"]) {
12407
+ const value = overrides[key];
12408
+ if (value === void 0) continue;
12409
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
12410
+ return { ok: false, message: `"${key}" must be an array of glob strings.` };
12411
+ }
12412
+ cliOptions[key] = value;
12413
+ }
12170
12414
  try {
12171
12415
  const config = resolveConfig(loaded.config, cliOptions, root);
12172
12416
  return {
@@ -12186,25 +12430,25 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
12186
12430
  var MANIFEST_CACHE_LIMIT = 8;
12187
12431
  var manifestCache = /* @__PURE__ */ new Map();
12188
12432
  function manifestPathFor(workspace) {
12189
- return path25__namespace.resolve(workspace.root, workspace.config.outDir, "manifest.json");
12433
+ return path26__namespace.resolve(workspace.root, workspace.config.outDir, "manifest.json");
12190
12434
  }
12191
12435
  function partPathFor(workspace, filename) {
12192
12436
  if (filename.length === 0 || filename.includes("\0")) return null;
12193
- const partsDir = path25__namespace.resolve(workspace.root, workspace.config.outDir, "parts");
12194
- const resolved = path25__namespace.resolve(partsDir, filename);
12195
- const relative14 = path25__namespace.relative(partsDir, resolved);
12196
- if (relative14.length === 0 || relative14.includes(path25__namespace.sep) || relative14.includes("/") || relative14.includes("\\") || path25__namespace.isAbsolute(relative14)) {
12437
+ const partsDir = path26__namespace.resolve(workspace.root, workspace.config.outDir, "parts");
12438
+ const resolved = path26__namespace.resolve(partsDir, filename);
12439
+ const relative15 = path26__namespace.relative(partsDir, resolved);
12440
+ if (relative15.length === 0 || relative15.includes(path26__namespace.sep) || relative15.includes("/") || relative15.includes("\\") || path26__namespace.isAbsolute(relative15)) {
12197
12441
  return null;
12198
12442
  }
12199
12443
  let stats;
12200
12444
  try {
12201
- stats = fs24__namespace.lstatSync(resolved);
12445
+ stats = fs25__namespace.lstatSync(resolved);
12202
12446
  } catch {
12203
12447
  return null;
12204
12448
  }
12205
12449
  if (!stats.isFile()) return null;
12206
12450
  try {
12207
- if (path25__namespace.dirname(fs24__namespace.realpathSync(resolved)) !== fs24__namespace.realpathSync(partsDir)) return null;
12451
+ if (path26__namespace.dirname(fs25__namespace.realpathSync(resolved)) !== fs25__namespace.realpathSync(partsDir)) return null;
12208
12452
  } catch {
12209
12453
  return null;
12210
12454
  }
@@ -12212,31 +12456,28 @@ function partPathFor(workspace, filename) {
12212
12456
  }
12213
12457
  function readManifest3(workspace) {
12214
12458
  const file = manifestPathFor(workspace);
12215
- const shown = path25__namespace.relative(workspace.root, file).split(path25__namespace.sep).join("/") || file;
12216
- let stats;
12217
- try {
12218
- stats = fs24__namespace.statSync(file);
12219
- } catch {
12459
+ const shown = path26__namespace.relative(workspace.root, file).split(path26__namespace.sep).join("/") || file;
12460
+ const confined = readConfinedText(path26__namespace.dirname(file), path26__namespace.basename(file));
12461
+ if (!confined.ok) {
12462
+ if (confined.reason === "missing") {
12463
+ return {
12464
+ ok: false,
12465
+ missing: true,
12466
+ message: `There is no snapshot manifest at ${shown}. Call snapshot_plan to preview what would be included, or snapshot_generate to write it.`
12467
+ };
12468
+ }
12220
12469
  return {
12221
12470
  ok: false,
12222
- missing: true,
12223
- message: `There is no snapshot manifest at ${shown}. Call snapshot_plan to preview what would be included, or snapshot_generate to write it.`
12471
+ missing: false,
12472
+ message: `${shown} could not be read as a snapshot manifest: ${confined.message}.`
12224
12473
  };
12225
12474
  }
12475
+ const stats = confined.stats;
12476
+ const raw = confined.text;
12226
12477
  const cached = manifestCache.get(file);
12227
12478
  if (cached && cached.mtimeMs === stats.mtimeMs && cached.ctimeMs === stats.ctimeMs && cached.size === stats.size) {
12228
12479
  return { ok: true, manifest: cached.manifest, file };
12229
12480
  }
12230
- let raw;
12231
- try {
12232
- raw = fs24__namespace.readFileSync(file, "utf8");
12233
- } catch (error) {
12234
- return {
12235
- ok: false,
12236
- missing: false,
12237
- message: `${shown} exists but could not be read: ${error instanceof Error ? error.message : String(error)}`
12238
- };
12239
- }
12240
12481
  let parsed;
12241
12482
  try {
12242
12483
  parsed = JSON.parse(raw);
@@ -12266,6 +12507,96 @@ function forgetManifest(file) {
12266
12507
  manifestCache.delete(file);
12267
12508
  }
12268
12509
 
12510
+ // src/security/regex.ts
12511
+ var MAX_PATTERN_LENGTH = 256;
12512
+ var MAX_QUANTIFIER_REPEAT = 1e4;
12513
+ function unsafeRegExpReason(source) {
12514
+ if (source.length === 0) return null;
12515
+ if (source.length > MAX_PATTERN_LENGTH) {
12516
+ return `the pattern is longer than ${MAX_PATTERN_LENGTH} characters`;
12517
+ }
12518
+ let inClass = false;
12519
+ let unbounded = 0;
12520
+ const groups = [];
12521
+ for (let index = 0; index < source.length; index += 1) {
12522
+ const char = source[index];
12523
+ if (char === "\\") {
12524
+ index += 1;
12525
+ continue;
12526
+ }
12527
+ if (inClass) {
12528
+ if (char === "]") inClass = false;
12529
+ continue;
12530
+ }
12531
+ if (char === "[") {
12532
+ inClass = true;
12533
+ continue;
12534
+ }
12535
+ if (char === "(") {
12536
+ groups.push({ quantified: false, alternation: false });
12537
+ continue;
12538
+ }
12539
+ if (char === ")") {
12540
+ const group = groups.pop();
12541
+ if (group === void 0) continue;
12542
+ const next = source[index + 1];
12543
+ if (next === "*" || next === "+" || next === "{" && isUnboundedBrace(source, index + 1)) {
12544
+ if (group.quantified || group.alternation) {
12545
+ return "a quantified group contains another quantifier or an alternation";
12546
+ }
12547
+ }
12548
+ continue;
12549
+ }
12550
+ if (char === "|") {
12551
+ const group = groups[groups.length - 1];
12552
+ if (group !== void 0) group.alternation = true;
12553
+ continue;
12554
+ }
12555
+ if (char === "?") {
12556
+ const previous = source[index - 1];
12557
+ if (previous !== "(" && previous !== "?" && previous !== "*" && previous !== "+" && previous !== "}") {
12558
+ const group = groups[groups.length - 1];
12559
+ if (group !== void 0) group.quantified = true;
12560
+ }
12561
+ continue;
12562
+ }
12563
+ if (char === "*" || char === "+") {
12564
+ unbounded += 1;
12565
+ const group = groups[groups.length - 1];
12566
+ if (group !== void 0) group.quantified = true;
12567
+ continue;
12568
+ }
12569
+ if (char === "{") {
12570
+ const close = source.indexOf("}", index + 1);
12571
+ if (close === -1) continue;
12572
+ const body = source.slice(index + 1, close);
12573
+ const match = /^(\d+)(?:,(\d*))?$/.exec(body);
12574
+ if (match === null) {
12575
+ index = close;
12576
+ continue;
12577
+ }
12578
+ const max = match[2] === void 0 ? Number(match[1]) : match[2] === "" ? Infinity : Number(match[2]);
12579
+ if (max > MAX_QUANTIFIER_REPEAT) {
12580
+ return "a repetition bound is larger than the search budget can evaluate safely";
12581
+ }
12582
+ if (max === Infinity) unbounded += 1;
12583
+ const group = groups[groups.length - 1];
12584
+ if (group !== void 0) group.quantified = true;
12585
+ index = close;
12586
+ }
12587
+ }
12588
+ if (unbounded > 1) {
12589
+ return "the pattern has more than one unbounded repetition";
12590
+ }
12591
+ return null;
12592
+ }
12593
+ function isUnboundedBrace(source, start) {
12594
+ const close = source.indexOf("}", start + 1);
12595
+ if (close === -1) return false;
12596
+ const body = source.slice(start + 1, close);
12597
+ return /^\d+,$/.test(body);
12598
+ }
12599
+
12269
12600
  // src/mcp/tools.ts
12270
12601
  var MAX_SEARCH_BYTES = 4 * 1024 * 1024;
12271
12602
  var READ_ONLY = {
@@ -12297,6 +12628,16 @@ var OUT_DIR_PROPERTY = {
12297
12628
  };
12298
12629
  var outDirOverride = (args) => ({ outDir: args.outDir });
12299
12630
  var SCOPE_PROPERTIES = {
12631
+ only: {
12632
+ type: "array",
12633
+ items: { type: "string" },
12634
+ description: "Globs to include: replaces the config allow-list for this run."
12635
+ },
12636
+ ignore: {
12637
+ type: "array",
12638
+ items: { type: "string" },
12639
+ description: "Globs to exclude, added to the config deny-list for this run."
12640
+ },
12300
12641
  maxPartTokens: {
12301
12642
  type: "string",
12302
12643
  description: 'Token ceiling per part, for example 32000 or "32k". Narrower than maxPartBytes; it converts at four bytes per token.'
@@ -12331,7 +12672,9 @@ function workspaceOverrides(args) {
12331
12672
  sarif: args.sarif,
12332
12673
  changedSince: args.changedSince,
12333
12674
  staged: args.staged,
12334
- withDependents: args.withDependents
12675
+ withDependents: args.withDependents,
12676
+ only: args.only,
12677
+ ignore: args.ignore
12335
12678
  };
12336
12679
  }
12337
12680
  function failure(message) {
@@ -12346,7 +12689,7 @@ function formatBytes2(bytes) {
12346
12689
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
12347
12690
  }
12348
12691
  function relativeFor(workspace, absolute) {
12349
- return path25__namespace.relative(workspace.root, absolute).split(path25__namespace.sep).join("/");
12692
+ return path26__namespace.relative(workspace.root, absolute).split(path26__namespace.sep).join("/");
12350
12693
  }
12351
12694
  function capped(values, limit = 20) {
12352
12695
  return { count: values.length, sample: values.slice(0, limit) };
@@ -12365,13 +12708,13 @@ function summarizeDrift(drift) {
12365
12708
  function toRelativePath(root, value) {
12366
12709
  const cleaned = value.trim();
12367
12710
  if (cleaned.length === 0 || cleaned.includes("\0")) return null;
12368
- const resolvedRoot = path25__namespace.resolve(root);
12369
- const absolute = path25__namespace.resolve(resolvedRoot, cleaned);
12370
- const relative14 = path25__namespace.relative(resolvedRoot, absolute);
12371
- if (relative14 === "" || relative14 === ".." || relative14.startsWith(`..${path25__namespace.sep}`) || path25__namespace.isAbsolute(relative14)) {
12711
+ const resolvedRoot = path26__namespace.resolve(root);
12712
+ const absolute = path26__namespace.resolve(resolvedRoot, cleaned);
12713
+ const relative15 = path26__namespace.relative(resolvedRoot, absolute);
12714
+ if (relative15 === "" || relative15 === ".." || relative15.startsWith(`..${path26__namespace.sep}`) || path26__namespace.isAbsolute(relative15)) {
12372
12715
  return null;
12373
12716
  }
12374
- return relative14.split(path25__namespace.sep).join("/");
12717
+ return relative15.split(path26__namespace.sep).join("/");
12375
12718
  }
12376
12719
  function symbolsOf(entry) {
12377
12720
  const summary = entry.summary;
@@ -12464,16 +12807,15 @@ var historyTool = {
12464
12807
  async handler(args, context) {
12465
12808
  const prepared = await prepare(args, context, outDirOverride(args));
12466
12809
  if (!prepared.ok) return prepared.outcome;
12467
- const reportPath = path25__namespace.resolve(prepared.workspace.root, prepared.workspace.config.outDir, "reports", "log.md");
12468
- let text2;
12469
- try {
12470
- text2 = fs24__namespace.readFileSync(reportPath, "utf8");
12471
- } catch {
12810
+ const snapshotDir = path26__namespace.resolve(prepared.workspace.root, prepared.workspace.config.outDir);
12811
+ const reportRead = readConfinedText(snapshotDir, path26__namespace.posix.join("reports", "log.md"));
12812
+ if (!reportRead.ok) {
12472
12813
  return {
12473
- 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.",
12814
+ 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.",
12474
12815
  isError: true
12475
12816
  };
12476
12817
  }
12818
+ const text2 = reportRead.text;
12477
12819
  const manifestRead = readManifest3(prepared.workspace);
12478
12820
  const recordedLog = manifestRead.ok ? manifestRead.manifest.artifacts?.log : void 0;
12479
12821
  if (recordedLog !== void 0 && recordedLog !== null) {
@@ -12534,7 +12876,7 @@ var budgetTool = {
12534
12876
  ...args.includeTests === true ? { includeTests: true } : {}
12535
12877
  });
12536
12878
  const paths = new Set(plan.files.map((file) => file.path));
12537
- const gained = [...paths].filter((path26) => !previous.has(path26)).sort();
12879
+ const gained = [...paths].filter((path27) => !previous.has(path27)).sort();
12538
12880
  previous = paths;
12539
12881
  rows.push({
12540
12882
  budget,
@@ -12637,20 +12979,16 @@ var workspaceTool = {
12637
12979
  async handler(args, context) {
12638
12980
  const prepared = await prepare(args, context, outDirOverride(args));
12639
12981
  if (!prepared.ok) return prepared.outcome;
12640
- const index = path25__namespace.resolve(
12641
- prepared.workspace.root,
12642
- prepared.workspace.config.outDir,
12643
- "WORKSPACE.json"
12644
- );
12645
- let text2;
12646
- try {
12647
- text2 = fs24__namespace.readFileSync(index, "utf8");
12648
- } catch {
12982
+ const snapshotDir = path26__namespace.resolve(prepared.workspace.root, prepared.workspace.config.outDir);
12983
+ const index = path26__namespace.join(snapshotDir, "WORKSPACE.json");
12984
+ const read = readConfinedText(snapshotDir, "WORKSPACE.json");
12985
+ if (!read.ok) {
12649
12986
  return {
12650
- text: "No workspace index at " + index + ". Generate one with `generate --workspace member-a,member-b`; a single snapshot has no members to list.",
12987
+ 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.",
12651
12988
  isError: true
12652
12989
  };
12653
12990
  }
12991
+ const text2 = read.text;
12654
12992
  const document = JSON.parse(text2);
12655
12993
  const members = document.members ?? [];
12656
12994
  const links = document.links ?? [];
@@ -12791,6 +13129,10 @@ var routesTool = {
12791
13129
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
12792
13130
  let filter = null;
12793
13131
  if (typeof args.pattern === "string") {
13132
+ const unsafe = unsafeRegExpReason(args.pattern);
13133
+ if (unsafe !== null) {
13134
+ return { text: "pattern is refused: " + unsafe + ".", isError: true };
13135
+ }
12794
13136
  try {
12795
13137
  filter = new RegExp(args.pattern, "i");
12796
13138
  } catch (error) {
@@ -12846,7 +13188,7 @@ var cyclesTool = {
12846
13188
  tsconfig: tsconfigPathsFor(prepared.workspace.root)
12847
13189
  });
12848
13190
  const edges = /* @__PURE__ */ new Map();
12849
- for (const path26 of byPath.keys()) edges.set(path26, []);
13191
+ for (const path27 of byPath.keys()) edges.set(path27, []);
12850
13192
  for (const entry of read.manifest.indexes.imports.byFile) {
12851
13193
  const targets = edges.get(entry.path);
12852
13194
  if (targets === void 0) continue;
@@ -12934,6 +13276,12 @@ var searchTool = {
12934
13276
  const cap = Math.max(1, Math.min(500, typeof args.maxMatches === "number" ? args.maxMatches : 50));
12935
13277
  const contextLines = Math.max(0, Math.min(10, typeof args.contextLines === "number" ? args.contextLines : 0));
12936
13278
  let pattern;
13279
+ if (args.regex === true) {
13280
+ const unsafe = unsafeRegExpReason(query);
13281
+ if (unsafe !== null) {
13282
+ return { text: "regex is refused: " + unsafe + ".", isError: true };
13283
+ }
13284
+ }
12937
13285
  try {
12938
13286
  pattern = args.regex === true ? new RegExp(query, "i") : new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i");
12939
13287
  } catch (error) {
@@ -12952,7 +13300,7 @@ var searchTool = {
12952
13300
  if (partPath === null) continue;
12953
13301
  let text2;
12954
13302
  try {
12955
- text2 = fs24__namespace.readFileSync(partPath, "utf8");
13303
+ text2 = fs25__namespace.readFileSync(partPath, "utf8");
12956
13304
  } catch {
12957
13305
  continue;
12958
13306
  }
@@ -13083,7 +13431,7 @@ var reviewTool = {
13083
13431
  return { text: error.message, isError: true };
13084
13432
  }
13085
13433
  const report2 = auditSnapshot({
13086
- snapshotDir: path25__namespace.resolve(workspace.root, workspace.config.outDir),
13434
+ snapshotDir: path26__namespace.resolve(workspace.root, workspace.config.outDir),
13087
13435
  repoDir: workspace.root
13088
13436
  });
13089
13437
  const failed = report2.checks.filter((check2) => check2.status === "fail").map((check2) => check2.id + ": " + check2.detail);
@@ -13105,7 +13453,7 @@ var reviewTool = {
13105
13453
  }
13106
13454
  let section = null;
13107
13455
  try {
13108
- section = findSection(parsePartSections(fs24__namespace.readFileSync(partPath, "utf8")), file.relativePath);
13456
+ section = findSection(parsePartSections(fs25__namespace.readFileSync(partPath, "utf8")), file.relativePath);
13109
13457
  } catch {
13110
13458
  section = null;
13111
13459
  }
@@ -13195,31 +13543,31 @@ var diffContextTool = {
13195
13543
  const changed = [];
13196
13544
  const text2 = [];
13197
13545
  let used = 0;
13198
- for (const path26 of wanted) {
13199
- const file = byPath.get(path26.toLowerCase());
13546
+ for (const path27 of wanted) {
13547
+ const file = byPath.get(path27.toLowerCase());
13200
13548
  if (file === void 0) {
13201
- missing.push(path26);
13549
+ missing.push(path27);
13202
13550
  continue;
13203
13551
  }
13204
13552
  const partPath = partPathFor(workspace, file.part);
13205
13553
  if (partPath === null) {
13206
- missing.push(path26 + " (part missing)");
13554
+ missing.push(path27 + " (part missing)");
13207
13555
  continue;
13208
13556
  }
13209
13557
  let section;
13210
13558
  try {
13211
- section = findSection(parsePartSections(fs24__namespace.readFileSync(partPath, "utf8")), file.relativePath);
13559
+ section = findSection(parsePartSections(fs25__namespace.readFileSync(partPath, "utf8")), file.relativePath);
13212
13560
  } catch {
13213
13561
  section = null;
13214
13562
  }
13215
13563
  if (section === null) {
13216
- missing.push(path26 + " (section not found)");
13564
+ missing.push(path27 + " (section not found)");
13217
13565
  continue;
13218
13566
  }
13219
13567
  const window = windowText(section.body, 1, linesPerFile);
13220
13568
  const tokens = Math.max(1, Math.ceil(Buffer.byteLength(window.text, "utf8") / 4));
13221
13569
  if (used + tokens > budget) {
13222
- missing.push(path26 + " (budget)");
13570
+ missing.push(path27 + " (budget)");
13223
13571
  continue;
13224
13572
  }
13225
13573
  used += tokens;
@@ -13294,7 +13642,7 @@ var symbolTool = {
13294
13642
  if (partPath === null) continue;
13295
13643
  let partText;
13296
13644
  try {
13297
- partText = fs24__namespace.readFileSync(partPath, "utf8");
13645
+ partText = fs25__namespace.readFileSync(partPath, "utf8");
13298
13646
  } catch {
13299
13647
  continue;
13300
13648
  }
@@ -13326,28 +13674,39 @@ var symbolTool = {
13326
13674
  };
13327
13675
  }
13328
13676
  const callSites = [];
13677
+ let referencesTruncated = false;
13329
13678
  if (args.references !== false) {
13330
13679
  const limit = Math.max(1, typeof args.maxReferences === "number" ? args.maxReferences : 20);
13331
13680
  const definitionKeys = new Set(matches.map((match) => match.path + ":" + match.line));
13332
13681
  const word = new RegExp("\\b" + name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\b");
13333
- const parts = /* @__PURE__ */ new Map();
13682
+ const sectionsByPart = /* @__PURE__ */ new Map();
13334
13683
  let scanned = 0;
13335
13684
  for (const file of read.manifest.files) {
13336
13685
  if (callSites.length >= limit) break;
13337
13686
  const partPath = partPathFor(workspace, file.part);
13338
13687
  if (partPath === null) continue;
13339
- let partText = parts.get(partPath);
13340
- if (partText === void 0) {
13688
+ let sections = sectionsByPart.get(partPath);
13689
+ if (sections === void 0) {
13690
+ if (scanned >= MAX_SEARCH_BYTES) {
13691
+ referencesTruncated = true;
13692
+ break;
13693
+ }
13694
+ let partText;
13341
13695
  try {
13342
- partText = fs24__namespace.readFileSync(partPath, "utf8");
13696
+ partText = fs25__namespace.readFileSync(partPath, "utf8");
13343
13697
  } catch {
13344
13698
  continue;
13345
13699
  }
13346
- parts.set(partPath, partText);
13700
+ const bytes = Buffer.byteLength(partText, "utf8");
13701
+ if (scanned + bytes > MAX_SEARCH_BYTES) {
13702
+ referencesTruncated = true;
13703
+ break;
13704
+ }
13705
+ scanned += bytes;
13706
+ sections = parsePartSections(partText);
13707
+ sectionsByPart.set(partPath, sections);
13347
13708
  }
13348
- if (scanned > MAX_SEARCH_BYTES) break;
13349
- scanned += Buffer.byteLength(partText, "utf8");
13350
- const section = findSection(parsePartSections(partText), file.relativePath);
13709
+ const section = findSection(sections, file.relativePath);
13351
13710
  if (section === null) continue;
13352
13711
  const bodyLines = section.body.split("\n");
13353
13712
  for (let index = 0; index < bodyLines.length && callSites.length < limit; index += 1) {
@@ -13361,8 +13720,11 @@ var symbolTool = {
13361
13720
  }
13362
13721
  }
13363
13722
  }
13364
- const text2 = 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")));
13365
- return { text: text2, structured: { found: matches.length, matches, references: callSites } };
13723
+ const text2 = 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." : "");
13724
+ return {
13725
+ text: text2,
13726
+ structured: { found: matches.length, matches, references: callSites, truncated: referencesTruncated }
13727
+ };
13366
13728
  }
13367
13729
  };
13368
13730
  var contextTool = {
@@ -13435,7 +13797,7 @@ var contextTool = {
13435
13797
  }
13436
13798
  if (!sectionsByPart.has(file.part)) {
13437
13799
  try {
13438
- sectionsByPart.set(file.part, parsePartSections(fs24__namespace.readFileSync(partPath, "utf8")));
13800
+ sectionsByPart.set(file.part, parsePartSections(fs25__namespace.readFileSync(partPath, "utf8")));
13439
13801
  } catch {
13440
13802
  sectionsByPart.set(file.part, null);
13441
13803
  }
@@ -13520,6 +13882,10 @@ var queryTool = {
13520
13882
  const maxFiles = typeof args.maxFiles === "number" ? Math.min(200, Math.max(1, args.maxFiles)) : 40;
13521
13883
  let pattern = null;
13522
13884
  if (typeof args.pathPattern === "string") {
13885
+ const unsafe = unsafeRegExpReason(args.pathPattern);
13886
+ if (unsafe !== null) {
13887
+ return { text: "pathPattern is refused: " + unsafe + ".", isError: true };
13888
+ }
13523
13889
  try {
13524
13890
  pattern = new RegExp(args.pathPattern, "i");
13525
13891
  } catch (error) {
@@ -13669,7 +14035,7 @@ var answerTool = {
13669
14035
  let partText = parts.get(partPath);
13670
14036
  if (partText === void 0) {
13671
14037
  try {
13672
- partText = fs24__namespace.readFileSync(partPath, "utf8");
14038
+ partText = fs25__namespace.readFileSync(partPath, "utf8");
13673
14039
  } catch {
13674
14040
  omitted.push({ path: planned.path, reason: "its part could not be read" });
13675
14041
  continue;
@@ -13766,7 +14132,7 @@ var healthTool = {
13766
14132
  if (!prepared.ok) return prepared.outcome;
13767
14133
  const workspace = prepared.workspace;
13768
14134
  const report2 = auditSnapshot({
13769
- snapshotDir: path25__namespace.resolve(workspace.root, workspace.config.outDir),
14135
+ snapshotDir: path26__namespace.resolve(workspace.root, workspace.config.outDir),
13770
14136
  repoDir: workspace.root,
13771
14137
  ...typeof args.maxScanBytes === "number" ? { maxScanBytes: args.maxScanBytes } : {},
13772
14138
  ...args.deep === true ? { deep: true } : {}
@@ -13995,16 +14361,6 @@ var generateTool = {
13995
14361
  minimum: 500,
13996
14362
  description: "Fit the snapshot into this token budget, highest value first."
13997
14363
  },
13998
- only: {
13999
- type: "array",
14000
- items: { type: "string" },
14001
- description: "Globs to include: replaces the config allow-list for this run."
14002
- },
14003
- ignore: {
14004
- type: "array",
14005
- items: { type: "string" },
14006
- description: "Globs to exclude, added to the config deny-list for this run."
14007
- },
14008
14364
  ...SCOPE_PROPERTIES
14009
14365
  },
14010
14366
  additionalProperties: false
@@ -14060,7 +14416,7 @@ var generateTool = {
14060
14416
  context.notify?.({ message: "writing the snapshot", progress: 2, total: 2 });
14061
14417
  const summary = result.summary;
14062
14418
  forgetManifest(manifestPathFor(workspace));
14063
- const written = relativeFor(workspace, path25__namespace.resolve(workspace.root, workspace.config.outDir));
14419
+ const written = relativeFor(workspace, path26__namespace.resolve(workspace.root, workspace.config.outDir));
14064
14420
  const lines = [
14065
14421
  `Wrote ${written}/`,
14066
14422
  `Files: ${summary.totalFiles} included, ${summary.skippedCount} skipped, ${plural(summary.partsCount, "part")}`,
@@ -14505,7 +14861,7 @@ var readTool = {
14505
14861
  }
14506
14862
  let partText;
14507
14863
  try {
14508
- partText = fs24__namespace.readFileSync(partPath, "utf8");
14864
+ partText = fs25__namespace.readFileSync(partPath, "utf8");
14509
14865
  } catch {
14510
14866
  return failure(
14511
14867
  `${entry.part} could not be read, so the snapshot is damaged. Run snapshot_generate to rebuild it.`
@@ -16114,7 +16470,7 @@ async function workspaceFor(context) {
16114
16470
  }
16115
16471
  function readFileIfPresent(file) {
16116
16472
  try {
16117
- return fs24__namespace.readFileSync(file, "utf8");
16473
+ return fs25__namespace.readFileSync(file, "utf8");
16118
16474
  } catch {
16119
16475
  return null;
16120
16476
  }
@@ -16153,9 +16509,9 @@ function buildResourceProvider() {
16153
16509
  }
16154
16510
  ];
16155
16511
  const workspace = await workspaceFor(context);
16156
- const reportsDir = "error" in workspace ? null : path25__namespace.resolve(workspace.root, workspace.config.outDir, "reports");
16512
+ const reportsDir = "error" in workspace ? null : path26__namespace.resolve(workspace.root, workspace.config.outDir, "reports");
16157
16513
  for (const [uri, report2] of REPORT_URIS) {
16158
- const present = reportsDir !== null && fs24__namespace.existsSync(path25__namespace.join(reportsDir, report2.file));
16514
+ const present = reportsDir !== null && fs25__namespace.existsSync(path26__namespace.join(reportsDir, report2.file));
16159
16515
  if (!present) continue;
16160
16516
  resources.push({
16161
16517
  uri,
@@ -16217,36 +16573,46 @@ function buildResourceProvider() {
16217
16573
  }
16218
16574
  const workspace = await workspaceFor(context);
16219
16575
  if ("error" in workspace) return null;
16576
+ const snapshotDir = path26__namespace.resolve(workspace.root, workspace.config.outDir);
16220
16577
  if (uri === PROMPT_URI) {
16221
- const text2 = readFileIfPresent(
16222
- path25__namespace.resolve(workspace.root, workspace.config.outDir, "PROMPT.md")
16223
- );
16224
- if (text2 === null) {
16578
+ const read = readConfinedText(snapshotDir, "PROMPT.md");
16579
+ if (!read.ok) {
16225
16580
  throw new ResourceNotFoundError(
16226
16581
  uri,
16227
- "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."
16582
+ "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."
16228
16583
  );
16229
16584
  }
16230
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, PROMPT_ADVICE) };
16585
+ return {
16586
+ uri,
16587
+ mimeType: "text/markdown",
16588
+ text: ensureSingleRead(uri, read.text, PROMPT_ADVICE)
16589
+ };
16231
16590
  }
16232
16591
  const report2 = REPORT_URIS.get(uri);
16233
16592
  if (report2) {
16234
- const text2 = readFileIfPresent(
16235
- path25__namespace.resolve(workspace.root, workspace.config.outDir, "reports", report2.file)
16236
- );
16237
- if (text2 === null) {
16593
+ const read = readConfinedText(snapshotDir, path26__namespace.posix.join("reports", report2.file));
16594
+ if (!read.ok) {
16238
16595
  throw new ResourceNotFoundError(
16239
16596
  uri,
16240
- "This snapshot contains no " + report2.file + ": that report was disabled, or nothing has been generated yet. Run snapshot_generate first."
16597
+ "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."
16241
16598
  );
16242
16599
  }
16243
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, REPORT_ADVICE) };
16600
+ return {
16601
+ uri,
16602
+ mimeType: "text/markdown",
16603
+ text: ensureSingleRead(uri, read.text, REPORT_ADVICE)
16604
+ };
16244
16605
  }
16245
16606
  if (uri === "snapshot://manifest") {
16246
16607
  const read = readManifest3(workspace);
16247
16608
  if (!read.ok) return null;
16248
- const text2 = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
16249
- return { uri, mimeType: "application/json", text: ensureSingleRead(uri, text2, MANIFEST_ADVICE) };
16609
+ const confined = readConfinedText(path26__namespace.dirname(read.file), path26__namespace.basename(read.file));
16610
+ if (!confined.ok) return null;
16611
+ return {
16612
+ uri,
16613
+ mimeType: "application/json",
16614
+ text: ensureSingleRead(uri, confined.text, MANIFEST_ADVICE)
16615
+ };
16250
16616
  }
16251
16617
  const partMatch = PART_URI.exec(uri);
16252
16618
  if (partMatch) {
@@ -16259,7 +16625,7 @@ function buildResourceProvider() {
16259
16625
  if (partPath === null) return null;
16260
16626
  let partBytes;
16261
16627
  try {
16262
- partBytes = fs24__namespace.statSync(partPath).size;
16628
+ partBytes = fs25__namespace.statSync(partPath).size;
16263
16629
  } catch {
16264
16630
  return null;
16265
16631
  }
@@ -16295,52 +16661,52 @@ function validateArguments(schema, value) {
16295
16661
  }
16296
16662
  return problems;
16297
16663
  }
16298
- function checkValue(path26, schema, value) {
16664
+ function checkValue(path27, schema, value) {
16299
16665
  if (schema.enum && !schema.enum.includes(value)) {
16300
- return [`"${path26}" must be one of: ${schema.enum.join(", ")}`];
16666
+ return [`"${path27}" must be one of: ${schema.enum.join(", ")}`];
16301
16667
  }
16302
16668
  switch (schema.type) {
16303
16669
  case "string": {
16304
- if (typeof value !== "string") return [`"${path26}" must be a string`];
16670
+ if (typeof value !== "string") return [`"${path27}" must be a string`];
16305
16671
  const problems = [];
16306
16672
  if (schema.minLength !== void 0 && value.length < schema.minLength) {
16307
- problems.push(`"${path26}" must be at least ${schema.minLength} character(s)`);
16673
+ problems.push(`"${path27}" must be at least ${schema.minLength} character(s)`);
16308
16674
  }
16309
16675
  if (schema.maxLength !== void 0 && value.length > schema.maxLength) {
16310
- problems.push(`"${path26}" must be at most ${schema.maxLength} character(s)`);
16676
+ problems.push(`"${path27}" must be at most ${schema.maxLength} character(s)`);
16311
16677
  }
16312
16678
  return problems;
16313
16679
  }
16314
16680
  case "number":
16315
16681
  case "integer": {
16316
16682
  if (typeof value !== "number" || Number.isNaN(value)) {
16317
- return [`"${path26}" must be a number`];
16683
+ return [`"${path27}" must be a number`];
16318
16684
  }
16319
16685
  if (schema.type === "integer" && !Number.isInteger(value)) {
16320
- return [`"${path26}" must be an integer`];
16686
+ return [`"${path27}" must be an integer`];
16321
16687
  }
16322
16688
  const problems = [];
16323
16689
  if (schema.minimum !== void 0 && value < schema.minimum) {
16324
- problems.push(`"${path26}" must be >= ${schema.minimum}`);
16690
+ problems.push(`"${path27}" must be >= ${schema.minimum}`);
16325
16691
  }
16326
16692
  if (schema.maximum !== void 0 && value > schema.maximum) {
16327
- problems.push(`"${path26}" must be <= ${schema.maximum}`);
16693
+ problems.push(`"${path27}" must be <= ${schema.maximum}`);
16328
16694
  }
16329
16695
  return problems;
16330
16696
  }
16331
16697
  case "boolean":
16332
- return typeof value === "boolean" ? [] : [`"${path26}" must be a boolean`];
16698
+ return typeof value === "boolean" ? [] : [`"${path27}" must be a boolean`];
16333
16699
  case "array": {
16334
- if (!Array.isArray(value)) return [`"${path26}" must be an array`];
16700
+ if (!Array.isArray(value)) return [`"${path27}" must be an array`];
16335
16701
  if (!schema.items) return [];
16336
16702
  const problems = [];
16337
16703
  value.forEach((item, index) => {
16338
- problems.push(...checkValue(`${path26}[${index}]`, schema.items, item));
16704
+ problems.push(...checkValue(`${path27}[${index}]`, schema.items, item));
16339
16705
  });
16340
16706
  return problems;
16341
16707
  }
16342
16708
  case "object":
16343
- return isJsonObject(value) ? [] : [`"${path26}" must be an object`];
16709
+ return isJsonObject(value) ? [] : [`"${path27}" must be an object`];
16344
16710
  default:
16345
16711
  return [];
16346
16712
  }
@@ -16756,10 +17122,10 @@ function dosDateTime(date) {
16756
17122
  }
16757
17123
  function walkFiles(root, prefix = "") {
16758
17124
  const files = [];
16759
- for (const entry of fs24__namespace.readdirSync(path25__namespace.join(root, prefix), { withFileTypes: true })) {
16760
- const relative14 = prefix === "" ? entry.name : prefix + "/" + entry.name;
16761
- if (entry.isDirectory()) files.push(...walkFiles(root, relative14));
16762
- else if (entry.isFile()) files.push(relative14);
17125
+ for (const entry of fs25__namespace.readdirSync(path26__namespace.join(root, prefix), { withFileTypes: true })) {
17126
+ const relative15 = prefix === "" ? entry.name : prefix + "/" + entry.name;
17127
+ if (entry.isDirectory()) files.push(...walkFiles(root, relative15));
17128
+ else if (entry.isFile()) files.push(relative15);
16763
17129
  }
16764
17130
  return files;
16765
17131
  }
@@ -16767,11 +17133,11 @@ function writeZip(options) {
16767
17133
  const entries = [...options.entries ?? []];
16768
17134
  if (options.directory !== void 0) {
16769
17135
  const root = options.directory;
16770
- for (const relative14 of walkFiles(root)) {
16771
- if (options.skip !== void 0 && options.skip(relative14)) continue;
16772
- const full = path25__namespace.join(root, relative14);
16773
- const stat = fs24__namespace.statSync(full);
16774
- entries.push({ name: relative14, content: fs24__namespace.readFileSync(full), mtime: stat.mtime });
17136
+ for (const relative15 of walkFiles(root)) {
17137
+ if (options.skip !== void 0 && options.skip(relative15)) continue;
17138
+ const full = path26__namespace.join(root, relative15);
17139
+ const stat = fs25__namespace.statSync(full);
17140
+ entries.push({ name: relative15, content: fs25__namespace.readFileSync(full), mtime: stat.mtime });
16775
17141
  }
16776
17142
  }
16777
17143
  if (entries.length > 65535) {
@@ -16991,6 +17357,7 @@ var SERVE_PAGE = `<!doctype html>
16991
17357
  var DEFAULT_PORT = 4788;
16992
17358
  var MAX_BODY = 64 * 1024;
16993
17359
  var MAX_PREVIEW = 64 * 1024;
17360
+ var MAX_MCP_IN_FLIGHT = 4;
16994
17361
  function isLoopback(origin) {
16995
17362
  try {
16996
17363
  const url = new URL(origin);
@@ -17018,10 +17385,11 @@ async function startWebServer(options) {
17018
17385
  return server2;
17019
17386
  };
17020
17387
  const temporaryClones = /* @__PURE__ */ new Set();
17021
- const allowedRoots = [path25__namespace.resolve(options.cwd)];
17388
+ let mcpInFlight = 0;
17389
+ const allowedRoots = [path26__namespace.resolve(options.cwd)];
17022
17390
  const canonical = (candidate) => {
17023
17391
  try {
17024
- return fs24__namespace.realpathSync(candidate);
17392
+ return fs25__namespace.realpathSync(candidate);
17025
17393
  } catch {
17026
17394
  return null;
17027
17395
  }
@@ -17029,32 +17397,32 @@ async function startWebServer(options) {
17029
17397
  const inside = (resolved) => allowedRoots.some((root) => {
17030
17398
  const canonicalRoot = canonical(root);
17031
17399
  if (canonicalRoot === null) return false;
17032
- const relative14 = path25__namespace.relative(canonicalRoot, resolved);
17033
- return relative14 === "" || !relative14.startsWith(`..${path25__namespace.sep}`) && relative14 !== ".." && !path25__namespace.isAbsolute(relative14);
17400
+ const relative15 = path26__namespace.relative(canonicalRoot, resolved);
17401
+ return relative15 === "" || !relative15.startsWith(`..${path26__namespace.sep}`) && relative15 !== ".." && !path26__namespace.isAbsolute(relative15);
17034
17402
  });
17035
17403
  const insideAllowedRoots = (candidate) => {
17036
17404
  const resolved = canonical(candidate);
17037
17405
  return resolved === null ? false : inside(resolved);
17038
17406
  };
17039
17407
  const lexicallyInside = (candidate) => {
17040
- const resolved = path25__namespace.resolve(candidate);
17408
+ const resolved = path26__namespace.resolve(candidate);
17041
17409
  return allowedRoots.some((root) => {
17042
- const prefix = path25__namespace.resolve(root) + path25__namespace.sep;
17043
- return resolved === path25__namespace.resolve(root) || resolved.startsWith(prefix);
17410
+ const prefix = path26__namespace.resolve(root) + path26__namespace.sep;
17411
+ return resolved === path26__namespace.resolve(root) || resolved.startsWith(prefix);
17044
17412
  });
17045
17413
  };
17046
17414
  const insideAllowedRootsForWrite = (candidate) => {
17047
- let existing = path25__namespace.resolve(candidate);
17415
+ let existing = path26__namespace.resolve(candidate);
17048
17416
  const tail = [];
17049
- while (!fs24__namespace.existsSync(existing)) {
17050
- tail.unshift(path25__namespace.basename(existing));
17051
- const parent = path25__namespace.dirname(existing);
17417
+ while (!fs25__namespace.existsSync(existing)) {
17418
+ tail.unshift(path26__namespace.basename(existing));
17419
+ const parent = path26__namespace.dirname(existing);
17052
17420
  if (parent === existing) break;
17053
17421
  existing = parent;
17054
17422
  }
17055
17423
  const resolved = canonical(existing);
17056
17424
  if (resolved === null) return false;
17057
- return inside(tail.length === 0 ? resolved : path25__namespace.join(resolved, ...tail));
17425
+ return inside(tail.length === 0 ? resolved : path26__namespace.join(resolved, ...tail));
17058
17426
  };
17059
17427
  const authorized = (request) => {
17060
17428
  if (token === null) return true;
@@ -17144,8 +17512,25 @@ async function startWebServer(options) {
17144
17512
  const server2 = mcpFor(request.socket);
17145
17513
  const answers = [];
17146
17514
  for (const item of batch) {
17147
- const answer = await server2.handle(item);
17148
- if (answer !== null) answers.push(answer);
17515
+ const gated = item !== null && typeof item === "object" && item.method === "tools/call";
17516
+ if (gated && mcpInFlight >= MAX_MCP_IN_FLIGHT) {
17517
+ answers.push({
17518
+ jsonrpc: "2.0",
17519
+ id: item.id ?? null,
17520
+ error: {
17521
+ code: -32001,
17522
+ message: "server busy: too many tool calls are already in flight"
17523
+ }
17524
+ });
17525
+ continue;
17526
+ }
17527
+ if (gated) mcpInFlight += 1;
17528
+ try {
17529
+ const answer = await server2.handle(item);
17530
+ if (answer !== null) answers.push(answer);
17531
+ } finally {
17532
+ if (gated) mcpInFlight -= 1;
17533
+ }
17149
17534
  }
17150
17535
  if (answers.length === 0) send(202, "");
17151
17536
  else send(200, Array.isArray(message) ? answers : answers[0]);
@@ -17225,7 +17610,7 @@ async function startWebServer(options) {
17225
17610
  return;
17226
17611
  }
17227
17612
  } else {
17228
- target = path25__namespace.resolve(options.cwd, source);
17613
+ target = path26__namespace.resolve(options.cwd, source);
17229
17614
  if (!insideAllowedRoots(target)) {
17230
17615
  send(403, { error: "outside the served directory: " + target });
17231
17616
  return;
@@ -17233,7 +17618,7 @@ async function startWebServer(options) {
17233
17618
  }
17234
17619
  let stat;
17235
17620
  try {
17236
- stat = fs24__namespace.statSync(target);
17621
+ stat = fs25__namespace.statSync(target);
17237
17622
  } catch {
17238
17623
  send(404, { error: "no such path: " + target });
17239
17624
  return;
@@ -17254,11 +17639,17 @@ async function startWebServer(options) {
17254
17639
  hooks: {}
17255
17640
  } : loaded.config ?? {};
17256
17641
  const configuredOutDir = typeof runConfig.outDir === "string" && runConfig.outDir.trim() !== "" ? runConfig.outDir : "snapshot";
17257
- const snapshotDir = path25__namespace.resolve(target, configuredOutDir);
17642
+ const snapshotDir = path26__namespace.resolve(target, configuredOutDir);
17258
17643
  if (!insideAllowedRootsForWrite(snapshotDir)) {
17259
17644
  send(403, { error: "the configured outDir resolves outside the served directory" });
17260
17645
  return;
17261
17646
  }
17647
+ const configuredTmpDir = typeof runConfig.tmpDir === "string" && runConfig.tmpDir.trim() !== "" ? runConfig.tmpDir : "snapshot.tmp";
17648
+ const stagingDir = path26__namespace.resolve(target, configuredTmpDir);
17649
+ if (!insideAllowedRootsForWrite(stagingDir)) {
17650
+ send(403, { error: "the configured tmpDir resolves outside the served directory" });
17651
+ return;
17652
+ }
17262
17653
  const started = Date.now();
17263
17654
  try {
17264
17655
  const manifest = generateSnapshot({ ...runConfig, cwd: target }, {
@@ -17293,12 +17684,12 @@ async function startWebServer(options) {
17293
17684
  return;
17294
17685
  }
17295
17686
  if (request.method === "GET" && request.url?.startsWith("/api/health?") === true) {
17296
- const target = path25__namespace.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
17687
+ const target = path26__namespace.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
17297
17688
  if (!lexicallyInside(target)) {
17298
17689
  send(403, { error: "outside the served directory: " + target });
17299
17690
  return;
17300
17691
  }
17301
- if (!fs24__namespace.existsSync(path25__namespace.join(target, "manifest.json"))) {
17692
+ if (!fs25__namespace.existsSync(path26__namespace.join(target, "manifest.json"))) {
17302
17693
  send(404, { error: "no manifest.json under " + target });
17303
17694
  return;
17304
17695
  }
@@ -17306,17 +17697,17 @@ async function startWebServer(options) {
17306
17697
  send(403, { error: "outside the served directory: " + target });
17307
17698
  return;
17308
17699
  }
17309
- const report2 = auditSnapshot({ snapshotDir: target, repoDir: path25__namespace.dirname(target) });
17700
+ const report2 = auditSnapshot({ snapshotDir: target, repoDir: path26__namespace.dirname(target) });
17310
17701
  send(200, { score: report2.score, counts: report2.counts, checks: report2.checks });
17311
17702
  return;
17312
17703
  }
17313
17704
  if (request.method === "GET" && (request.url?.startsWith("/api/snapshot?") === true || request.url === "/api/snapshot")) {
17314
- const target = path25__namespace.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
17705
+ const target = path26__namespace.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
17315
17706
  if (!lexicallyInside(target)) {
17316
17707
  send(403, { error: "outside the served directory: " + target });
17317
17708
  return;
17318
17709
  }
17319
- if (!fs24__namespace.existsSync(path25__namespace.join(target, "manifest.json"))) {
17710
+ if (!fs25__namespace.existsSync(path26__namespace.join(target, "manifest.json"))) {
17320
17711
  send(404, { error: "no manifest.json under " + target });
17321
17712
  return;
17322
17713
  }
@@ -17324,10 +17715,18 @@ async function startWebServer(options) {
17324
17715
  send(403, { error: "outside the served directory: " + target });
17325
17716
  return;
17326
17717
  }
17327
- const manifestFile = path25__namespace.join(target, "manifest.json");
17718
+ const manifestRead = readConfinedText(target, "manifest.json");
17719
+ if (!manifestRead.ok) {
17720
+ if (manifestRead.reason === "outside") {
17721
+ send(403, { error: "manifest.json resolves outside the snapshot directory" });
17722
+ } else {
17723
+ send(404, { error: "no readable manifest.json under " + target });
17724
+ }
17725
+ return;
17726
+ }
17328
17727
  let manifest;
17329
17728
  try {
17330
- manifest = JSON.parse(fs24__namespace.readFileSync(manifestFile, "utf8"));
17729
+ manifest = JSON.parse(manifestRead.text);
17331
17730
  } catch {
17332
17731
  send(404, { error: "no manifest.json under " + target });
17333
17732
  return;
@@ -17337,12 +17736,8 @@ async function startWebServer(options) {
17337
17736
  send(400, { error: "manifest.json is not a snapshot manifest: " + shapeProblem });
17338
17737
  return;
17339
17738
  }
17340
- let prompt = "";
17341
- try {
17342
- prompt = fs24__namespace.readFileSync(path25__namespace.join(target, "PROMPT.md"), "utf8").slice(0, MAX_PREVIEW);
17343
- } catch {
17344
- prompt = "(this snapshot has no PROMPT.md)";
17345
- }
17739
+ const promptRead = readConfinedText(target, "PROMPT.md");
17740
+ const prompt = promptRead.ok ? promptRead.text.slice(0, MAX_PREVIEW) : "(this snapshot has no readable PROMPT.md)";
17346
17741
  send(200, {
17347
17742
  fingerprint: manifest.fingerprint ?? "",
17348
17743
  generatedAt: manifest.generatedAt ?? "",
@@ -17355,12 +17750,12 @@ async function startWebServer(options) {
17355
17750
  return;
17356
17751
  }
17357
17752
  if (request.method === "GET" && request.url?.startsWith("/api/snapshot.zip") === true) {
17358
- const target = path25__namespace.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
17753
+ const target = path26__namespace.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
17359
17754
  if (!lexicallyInside(target)) {
17360
17755
  send(403, { error: "outside the served directory: " + target });
17361
17756
  return;
17362
17757
  }
17363
- if (!fs24__namespace.existsSync(path25__namespace.join(target, "manifest.json")) && !fs24__namespace.existsSync(path25__namespace.join(target, ".codebase-snapshot"))) {
17758
+ if (!fs25__namespace.existsSync(path26__namespace.join(target, "manifest.json")) && !fs25__namespace.existsSync(path26__namespace.join(target, ".codebase-snapshot"))) {
17364
17759
  send(404, { error: "not a snapshot directory: " + target });
17365
17760
  return;
17366
17761
  }
@@ -17384,11 +17779,11 @@ async function startWebServer(options) {
17384
17779
  }
17385
17780
  send(404, { error: "not found" });
17386
17781
  });
17387
- await new Promise((resolve14, reject) => {
17782
+ await new Promise((resolve15, reject) => {
17388
17783
  server.once("error", reject);
17389
17784
  server.listen(port, host, () => {
17390
17785
  server.removeListener("error", reject);
17391
- resolve14();
17786
+ resolve15();
17392
17787
  });
17393
17788
  });
17394
17789
  const address = server.address();
@@ -17400,14 +17795,14 @@ async function startWebServer(options) {
17400
17795
  port: actualPort,
17401
17796
  host,
17402
17797
  token,
17403
- close: () => new Promise((resolve14) => {
17798
+ close: () => new Promise((resolve15) => {
17404
17799
  for (const directory of temporaryClones) {
17405
17800
  try {
17406
- fs24__namespace.rmSync(directory, { recursive: true, force: true });
17801
+ fs25__namespace.rmSync(directory, { recursive: true, force: true });
17407
17802
  } catch {
17408
17803
  }
17409
17804
  }
17410
- server.close(() => resolve14());
17805
+ server.close(() => resolve15());
17411
17806
  })
17412
17807
  };
17413
17808
  }
@@ -17459,17 +17854,17 @@ function isNewer(candidate, current) {
17459
17854
  }
17460
17855
  function cacheDirectory(env = process.env, platform = process.platform) {
17461
17856
  if (platform === "win32") {
17462
- const base2 = env.LOCALAPPDATA ?? path25__namespace.join(os2__namespace.homedir(), "AppData", "Local");
17463
- return path25__namespace.join(base2, "codebase-snapshot");
17857
+ const base2 = env.LOCALAPPDATA ?? path26__namespace.join(os2__namespace.homedir(), "AppData", "Local");
17858
+ return path26__namespace.join(base2, "codebase-snapshot");
17464
17859
  }
17465
17860
  if (platform === "darwin") {
17466
- return path25__namespace.join(os2__namespace.homedir(), "Library", "Caches", "codebase-snapshot");
17861
+ return path26__namespace.join(os2__namespace.homedir(), "Library", "Caches", "codebase-snapshot");
17467
17862
  }
17468
- const base = env.XDG_CACHE_HOME ?? path25__namespace.join(os2__namespace.homedir(), ".cache");
17469
- return path25__namespace.join(base, "codebase-snapshot");
17863
+ const base = env.XDG_CACHE_HOME ?? path26__namespace.join(os2__namespace.homedir(), ".cache");
17864
+ return path26__namespace.join(base, "codebase-snapshot");
17470
17865
  }
17471
17866
  function cacheFilePath(env = process.env) {
17472
- return path25__namespace.join(cacheDirectory(env), "update-check.json");
17867
+ return path26__namespace.join(cacheDirectory(env), "update-check.json");
17473
17868
  }
17474
17869
  function shouldCheck(argv, env) {
17475
17870
  const disabled = ["1", "true", "yes"].includes(
@@ -17499,7 +17894,7 @@ function shouldCheck(argv, env) {
17499
17894
  function readCache(file) {
17500
17895
  let raw;
17501
17896
  try {
17502
- raw = fs24__namespace.readFileSync(file, "utf8");
17897
+ raw = fs25__namespace.readFileSync(file, "utf8");
17503
17898
  } catch {
17504
17899
  return null;
17505
17900
  }
@@ -17516,21 +17911,21 @@ function readCache(file) {
17516
17911
  }
17517
17912
  function writeCache(file, entry) {
17518
17913
  try {
17519
- fs24__namespace.mkdirSync(path25__namespace.dirname(file), { recursive: true });
17520
- fs24__namespace.writeFileSync(file, `${JSON.stringify(entry)}
17914
+ fs25__namespace.mkdirSync(path26__namespace.dirname(file), { recursive: true });
17915
+ fs25__namespace.writeFileSync(file, `${JSON.stringify(entry)}
17521
17916
  `, "utf8");
17522
17917
  } catch {
17523
17918
  }
17524
17919
  }
17525
17920
  function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOUT_MS) {
17526
- return new Promise((resolve14) => {
17921
+ return new Promise((resolve15) => {
17527
17922
  let settled = false;
17528
17923
  let request = null;
17529
17924
  const finish = (value) => {
17530
17925
  if (settled) return;
17531
17926
  settled = true;
17532
17927
  clearTimeout(deadline);
17533
- resolve14(value);
17928
+ resolve15(value);
17534
17929
  };
17535
17930
  const deadline = setTimeout(() => {
17536
17931
  request?.destroy();
@@ -17825,14 +18220,14 @@ function compareManifests(before, after, secretRules) {
17825
18220
  function loadManifest(target) {
17826
18221
  let isDirectory;
17827
18222
  try {
17828
- isDirectory = fs24__namespace.statSync(target).isDirectory();
18223
+ isDirectory = fs25__namespace.statSync(target).isDirectory();
17829
18224
  } catch {
17830
18225
  throw new Error(`No snapshot found at ${target}: the path does not exist.`);
17831
18226
  }
17832
- const manifestPath = isDirectory ? path25__namespace.join(target, "manifest.json") : target;
18227
+ const manifestPath = isDirectory ? path26__namespace.join(target, "manifest.json") : target;
17833
18228
  let raw;
17834
18229
  try {
17835
- raw = fs24__namespace.readFileSync(manifestPath, "utf8");
18230
+ raw = fs25__namespace.readFileSync(manifestPath, "utf8");
17836
18231
  } catch {
17837
18232
  throw new Error(`Could not read a manifest at ${manifestPath}.`);
17838
18233
  }
@@ -17934,15 +18329,15 @@ function canonicalIgnorePattern(line) {
17934
18329
  function appendGitignoreEntries(cwd, entries) {
17935
18330
  const wanted = [...new Set(entries)].filter((entry) => entry.trim().length > 0);
17936
18331
  if (wanted.length === 0) return { added: [], note: null };
17937
- const ignorePath = path25__namespace.join(cwd, ".gitignore");
18332
+ const ignorePath = path26__namespace.join(cwd, ".gitignore");
17938
18333
  const manual = `Add ${wanted.map((entry) => `"${entry}"`).join(" and ")} to your .gitignore yourself.`;
17939
18334
  let decoded = { text: "", bom: Buffer.alloc(0), encoding: "utf8" };
17940
18335
  try {
17941
- if (fs24__namespace.existsSync(ignorePath)) {
17942
- if (fs24__namespace.statSync(ignorePath).isDirectory()) {
18336
+ if (fs25__namespace.existsSync(ignorePath)) {
18337
+ if (fs25__namespace.statSync(ignorePath).isDirectory()) {
17943
18338
  return { added: [], note: `${ignorePath} is a directory, so it was not updated. ${manual}` };
17944
18339
  }
17945
- const read = decodeGitignore(fs24__namespace.readFileSync(ignorePath));
18340
+ const read = decodeGitignore(fs25__namespace.readFileSync(ignorePath));
17946
18341
  if (read === null) {
17947
18342
  return {
17948
18343
  added: [],
@@ -17964,7 +18359,7 @@ function appendGitignoreEntries(cwd, entries) {
17964
18359
  const newline = existing.includes("\r\n") ? "\r\n" : "\n";
17965
18360
  const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : newline;
17966
18361
  try {
17967
- fs24__namespace.writeFileSync(
18362
+ fs25__namespace.writeFileSync(
17968
18363
  ignorePath,
17969
18364
  encodeGitignore(decoded, `${existing}${prefix}${added.join(newline)}${newline}`)
17970
18365
  );
@@ -17974,7 +18369,7 @@ function appendGitignoreEntries(cwd, entries) {
17974
18369
  return { added, note: null };
17975
18370
  }
17976
18371
  function gitignorePath(cwd, filePath) {
17977
- return path25__namespace.relative(cwd, filePath).split(path25__namespace.sep).join("/");
18372
+ return path26__namespace.relative(cwd, filePath).split(path26__namespace.sep).join("/");
17978
18373
  }
17979
18374
 
17980
18375
  // src/wizard/brief-template.ts
@@ -18364,7 +18759,7 @@ function keyReader(input) {
18364
18759
  next() {
18365
18760
  const queued = queue.shift();
18366
18761
  if (queued) return Promise.resolve(queued);
18367
- return new Promise((resolve14) => waiters.push(resolve14));
18762
+ return new Promise((resolve15) => waiters.push(resolve15));
18368
18763
  },
18369
18764
  close() {
18370
18765
  input.off("keypress", onKey);
@@ -18590,7 +18985,7 @@ function parsePackageJson(raw) {
18590
18985
  }
18591
18986
  function readPackageJson(cwd) {
18592
18987
  try {
18593
- return parsePackageJson(fs24__namespace.readFileSync(path25__namespace.join(cwd, "package.json"), "utf8"));
18988
+ return parsePackageJson(fs25__namespace.readFileSync(path26__namespace.join(cwd, "package.json"), "utf8"));
18594
18989
  } catch {
18595
18990
  return null;
18596
18991
  }
@@ -18627,7 +19022,7 @@ function artifactAnswers(options) {
18627
19022
  }
18628
19023
  function topLevelDirs(cwd) {
18629
19024
  try {
18630
- return fs24__namespace.readdirSync(cwd, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules").map((entry) => entry.name).sort();
19025
+ return fs25__namespace.readdirSync(cwd, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules").map((entry) => entry.name).sort();
18631
19026
  } catch {
18632
19027
  return [];
18633
19028
  }
@@ -18642,7 +19037,7 @@ function writeFileOrExplain(target, content) {
18642
19037
  try {
18643
19038
  let stats = null;
18644
19039
  try {
18645
- stats = fs24__namespace.lstatSync(target);
19040
+ stats = fs25__namespace.lstatSync(target);
18646
19041
  } catch {
18647
19042
  stats = null;
18648
19043
  }
@@ -18657,12 +19052,12 @@ function writeFileOrExplain(target, content) {
18657
19052
  );
18658
19053
  }
18659
19054
  const temporary = `${target}.tmp-${process.pid}-${Date.now()}`;
18660
- fs24__namespace.writeFileSync(temporary, content, { encoding: "utf8", flag: "wx" });
19055
+ fs25__namespace.writeFileSync(temporary, content, { encoding: "utf8", flag: "wx" });
18661
19056
  try {
18662
- fs24__namespace.renameSync(temporary, target);
19057
+ fs25__namespace.renameSync(temporary, target);
18663
19058
  } catch (err) {
18664
19059
  try {
18665
- fs24__namespace.unlinkSync(temporary);
19060
+ fs25__namespace.unlinkSync(temporary);
18666
19061
  } catch {
18667
19062
  }
18668
19063
  throw err;
@@ -18710,19 +19105,19 @@ function serializePackageJson(raw, value) {
18710
19105
  return `${bom}${text2}${raw.endsWith("\n") ? crlf ? "\r\n" : "\n" : ""}`;
18711
19106
  }
18712
19107
  function updatePackageJson(cwd, notes) {
18713
- const packagePath = path25__namespace.join(cwd, "package.json");
19108
+ const packagePath = path26__namespace.join(cwd, "package.json");
18714
19109
  const unchanged = {
18715
19110
  scripts: [],
18716
19111
  dependency: { name: GENERATOR_NAME, range: null, added: false }
18717
19112
  };
18718
- if (!fs24__namespace.existsSync(packagePath)) {
19113
+ if (!fs25__namespace.existsSync(packagePath)) {
18719
19114
  notes.push("No package.json found, so npm scripts and the devDependency were not added.");
18720
19115
  return unchanged;
18721
19116
  }
18722
19117
  let raw;
18723
19118
  let parsed;
18724
19119
  try {
18725
- raw = fs24__namespace.readFileSync(packagePath, "utf8");
19120
+ raw = fs25__namespace.readFileSync(packagePath, "utf8");
18726
19121
  parsed = parsePackageJson(raw);
18727
19122
  } catch {
18728
19123
  notes.push("Could not parse package.json; npm scripts and the devDependency were not added.");
@@ -18797,11 +19192,11 @@ function gitignoreEntriesFor(cwd, outDir, tmpDir) {
18797
19192
  const entries = [];
18798
19193
  for (const directory of [outDir, tmpDir]) {
18799
19194
  if (directory === null) continue;
18800
- const relative14 = path25__namespace.relative(cwd, path25__namespace.resolve(cwd, directory)).replace(/\\/g, "/");
18801
- if (relative14 === "" || relative14 === "." || relative14.startsWith("..") || path25__namespace.isAbsolute(relative14)) {
19195
+ const relative15 = path26__namespace.relative(cwd, path26__namespace.resolve(cwd, directory)).replace(/\\/g, "/");
19196
+ if (relative15 === "" || relative15 === "." || relative15.startsWith("..") || path26__namespace.isAbsolute(relative15)) {
18802
19197
  continue;
18803
19198
  }
18804
- entries.push(`/${relative14}/`);
19199
+ entries.push(`/${relative15}/`);
18805
19200
  }
18806
19201
  return [...new Set(entries)];
18807
19202
  }
@@ -19053,7 +19448,7 @@ async function runInit(options) {
19053
19448
  const configText = renderConfig(answers);
19054
19449
  const preferredName = chooseConfigFileName(options.cwd);
19055
19450
  const presentConfigs = CONFIG_CANDIDATES.filter(
19056
- (name) => fs24__namespace.existsSync(path25__namespace.join(options.cwd, name))
19451
+ (name) => fs25__namespace.existsSync(path26__namespace.join(options.cwd, name))
19057
19452
  );
19058
19453
  const present = presentConfigs[0] ?? null;
19059
19454
  if (presentConfigs.length > 1) {
@@ -19062,7 +19457,7 @@ async function runInit(options) {
19062
19457
  );
19063
19458
  }
19064
19459
  const configName = present !== null && options.force ? present : preferredName;
19065
- const configPath = path25__namespace.join(options.cwd, configName);
19460
+ const configPath = path26__namespace.join(options.cwd, configName);
19066
19461
  const reused = present !== null && options.force !== true && options.reuseConfig === true;
19067
19462
  if (reused) notes.push(`Kept the existing ${present} instead of writing a new one.`);
19068
19463
  if (options.dryRun) {
@@ -19079,7 +19474,7 @@ async function runInit(options) {
19079
19474
  dependency: { name: GENERATOR_NAME, range: `^${GENERATOR_VERSION}`, added: false },
19080
19475
  notes,
19081
19476
  outDir: answers.outDir,
19082
- briefPath: path25__namespace.join(options.cwd, BRIEF_SCAFFOLD_FILE),
19477
+ briefPath: path26__namespace.join(options.cwd, BRIEF_SCAFFOLD_FILE),
19083
19478
  briefWritten: false
19084
19479
  };
19085
19480
  }
@@ -19098,13 +19493,13 @@ async function runInit(options) {
19098
19493
  'package.json already defines a "snapshot" config. Remove that key, or re-run with --force to write a config file that takes precedence over it.'
19099
19494
  );
19100
19495
  }
19101
- if (fs24__namespace.existsSync(configPath) && !options.force && !reused) {
19496
+ if (fs25__namespace.existsSync(configPath) && !options.force && !reused) {
19102
19497
  throw new Error(`${configName} already exists. Re-run with --force to replace it.`);
19103
19498
  }
19104
19499
  if (!reused) writeFileOrExplain(configPath, configText);
19105
- const briefPath = path25__namespace.join(options.cwd, BRIEF_SCAFFOLD_FILE);
19500
+ const briefPath = path26__namespace.join(options.cwd, BRIEF_SCAFFOLD_FILE);
19106
19501
  let briefWritten = false;
19107
- if (!fs24__namespace.existsSync(briefPath)) {
19502
+ if (!fs25__namespace.existsSync(briefPath)) {
19108
19503
  writeFileOrExplain(briefPath, BRIEF_SCAFFOLD);
19109
19504
  briefWritten = true;
19110
19505
  }
@@ -19132,10 +19527,10 @@ async function runInit(options) {
19132
19527
  };
19133
19528
  }
19134
19529
  function describeTarget(cwd) {
19135
- const relative14 = path25__namespace.relative(process.cwd(), cwd);
19136
- if (relative14 === "") return "this directory";
19137
- if (relative14.startsWith("..") || path25__namespace.isAbsolute(relative14)) return cwd;
19138
- return relative14;
19530
+ const relative15 = path26__namespace.relative(process.cwd(), cwd);
19531
+ if (relative15 === "") return "this directory";
19532
+ if (relative15.startsWith("..") || path26__namespace.isAbsolute(relative15)) return cwd;
19533
+ return relative15;
19139
19534
  }
19140
19535
  function firstRunMessage(reason, cwd) {
19141
19536
  const where = describeTarget(cwd);
@@ -19158,7 +19553,7 @@ function planFirstRun(facts) {
19158
19553
  var NOT_CONTENT = /* @__PURE__ */ new Set([".git", ".hg", ".svn", ".bzr", ".DS_Store", "Thumbs.db"]);
19159
19554
  function isEffectivelyEmpty(cwd) {
19160
19555
  try {
19161
- return fs24__namespace.readdirSync(cwd).every((entry) => NOT_CONTENT.has(entry));
19556
+ return fs25__namespace.readdirSync(cwd).every((entry) => NOT_CONTENT.has(entry));
19162
19557
  } catch {
19163
19558
  return false;
19164
19559
  }
@@ -19166,7 +19561,7 @@ function isEffectivelyEmpty(cwd) {
19166
19561
  function hasPriorSnapshot(cwd, outDir) {
19167
19562
  let parsed;
19168
19563
  try {
19169
- parsed = JSON.parse(fs24__namespace.readFileSync(path25__namespace.join(cwd, outDir, ".codebase-snapshot"), "utf8"));
19564
+ parsed = JSON.parse(fs25__namespace.readFileSync(path26__namespace.join(cwd, outDir, ".codebase-snapshot"), "utf8"));
19170
19565
  } catch {
19171
19566
  return false;
19172
19567
  }
@@ -19214,36 +19609,52 @@ fi
19214
19609
  `;
19215
19610
  }
19216
19611
  function gitDirectory(cwd) {
19217
- const dotGit = path25__namespace.join(cwd, ".git");
19612
+ const dotGit = path26__namespace.join(cwd, ".git");
19218
19613
  let stats;
19219
19614
  try {
19220
- stats = fs24__namespace.statSync(dotGit);
19615
+ stats = fs25__namespace.statSync(dotGit);
19221
19616
  } catch {
19222
19617
  return null;
19223
19618
  }
19224
19619
  if (stats.isDirectory()) return dotGit;
19225
19620
  if (!stats.isFile()) return null;
19226
19621
  try {
19227
- const contents = fs24__namespace.readFileSync(dotGit, "utf8");
19622
+ const contents = fs25__namespace.readFileSync(dotGit, "utf8");
19228
19623
  const match = /^gitdir:\s*(.+)$/m.exec(contents);
19229
19624
  if (!match) return null;
19230
19625
  const target = match[1];
19231
- const resolved = path25__namespace.isAbsolute(target.trim()) ? target.trim() : path25__namespace.join(cwd, target.trim());
19232
- if (!fs24__namespace.statSync(resolved).isDirectory()) return null;
19233
- if (isInside3(path25__namespace.resolve(cwd), path25__namespace.resolve(resolved))) return resolved;
19234
- return isRegisteredWorktree(path25__namespace.resolve(resolved), cwd) ? resolved : null;
19626
+ const resolved = path26__namespace.isAbsolute(target.trim()) ? target.trim() : path26__namespace.join(cwd, target.trim());
19627
+ if (!fs25__namespace.statSync(resolved).isDirectory()) return null;
19628
+ if (isInside4(path26__namespace.resolve(cwd), path26__namespace.resolve(resolved))) return resolved;
19629
+ return isRegisteredWorktree(path26__namespace.resolve(resolved), cwd) ? resolved : null;
19235
19630
  } catch {
19236
19631
  return null;
19237
19632
  }
19238
19633
  }
19239
- function isInside3(parent, child) {
19240
- const relative14 = path25__namespace.relative(parent, child);
19241
- return relative14 === "" || !relative14.startsWith("..") && !path25__namespace.isAbsolute(relative14);
19634
+ function isInside4(parent, child) {
19635
+ const relative15 = path26__namespace.relative(parent, child);
19636
+ return relative15 === "" || !relative15.startsWith("..") && !path26__namespace.isAbsolute(relative15);
19637
+ }
19638
+ function canonicalForWrite(target) {
19639
+ let existing = path26__namespace.resolve(target);
19640
+ const tail = [];
19641
+ while (!fs25__namespace.existsSync(existing)) {
19642
+ tail.unshift(path26__namespace.basename(existing));
19643
+ const parent = path26__namespace.dirname(existing);
19644
+ if (parent === existing) break;
19645
+ existing = parent;
19646
+ }
19647
+ try {
19648
+ const real = fs25__namespace.realpathSync(existing);
19649
+ return tail.length === 0 ? real : path26__namespace.join(real, ...tail);
19650
+ } catch {
19651
+ return null;
19652
+ }
19242
19653
  }
19243
19654
  function isRegisteredWorktree(gitDir, cwd) {
19244
19655
  try {
19245
- const back = fs24__namespace.readFileSync(path25__namespace.join(gitDir, "gitdir"), "utf8").trim();
19246
- return path25__namespace.resolve(gitDir, back) === path25__namespace.join(path25__namespace.resolve(cwd), ".git");
19656
+ const back = fs25__namespace.readFileSync(path26__namespace.join(gitDir, "gitdir"), "utf8").trim();
19657
+ return path26__namespace.resolve(gitDir, back) === path26__namespace.join(path26__namespace.resolve(cwd), ".git");
19247
19658
  } catch {
19248
19659
  return false;
19249
19660
  }
@@ -19264,11 +19675,18 @@ function gitOutput(cwd, args) {
19264
19675
  function configuredHooksDirectory(cwd) {
19265
19676
  const hooks = gitOutput(cwd, ["rev-parse", "--git-path", "hooks"]);
19266
19677
  if (hooks === null) return null;
19267
- const resolved = path25__namespace.resolve(cwd, hooks);
19678
+ const resolved = path26__namespace.resolve(cwd, hooks);
19268
19679
  const common = gitOutput(cwd, ["rev-parse", "--git-common-dir"]);
19269
- const commonDir = common === null ? null : path25__namespace.resolve(cwd, common);
19270
- if (isInside3(path25__namespace.resolve(cwd), resolved)) return { dir: resolved };
19271
- if (commonDir !== null && isInside3(commonDir, resolved)) return { dir: resolved };
19680
+ const commonDir = common === null ? null : canonicalForWrite(path26__namespace.resolve(cwd, common));
19681
+ const cwdReal = canonicalForWrite(cwd);
19682
+ const hooksReal = canonicalForWrite(resolved);
19683
+ if (hooksReal === null || cwdReal === null) {
19684
+ return {
19685
+ refusal: `The hooks directory git reports (${resolved}) could not be resolved, so no hook was written.`
19686
+ };
19687
+ }
19688
+ if (isInside4(cwdReal, hooksReal)) return { dir: hooksReal };
19689
+ if (commonDir !== null && isInside4(commonDir, hooksReal)) return { dir: hooksReal };
19272
19690
  return {
19273
19691
  refusal: `The hooks directory git reports (${resolved}) is outside this repository, so no hook was written. Add \`npx ${GENERATOR_NAME} validate\` to the hook manager that owns it instead.`
19274
19692
  };
@@ -19288,10 +19706,42 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
19288
19706
  ]
19289
19707
  };
19290
19708
  }
19291
- const hooksDir = configured === null ? path25__namespace.join(gitDir, "hooks") : configured.dir;
19292
- const hookPath = path25__namespace.join(hooksDir, "pre-commit");
19709
+ const hooksDir = configured === null ? path26__namespace.join(gitDir, "hooks") : configured.dir;
19710
+ const hookPath = path26__namespace.join(hooksDir, "pre-commit");
19711
+ try {
19712
+ const existingStats = fs25__namespace.lstatSync(hookPath);
19713
+ if (existingStats.isSymbolicLink()) {
19714
+ return {
19715
+ path: hookPath,
19716
+ written: false,
19717
+ notes: [`Refusing to write ${hookPath}: it is a symbolic link.`]
19718
+ };
19719
+ }
19720
+ if (existingStats.isFile() && existingStats.nlink > 1) {
19721
+ return {
19722
+ path: hookPath,
19723
+ written: false,
19724
+ notes: [`Refusing to write ${hookPath}: it has ${existingStats.nlink} hard links.`]
19725
+ };
19726
+ }
19727
+ if (!existingStats.isFile()) {
19728
+ return {
19729
+ path: hookPath,
19730
+ written: false,
19731
+ notes: [`Refusing to write ${hookPath}: it is not a regular file.`]
19732
+ };
19733
+ }
19734
+ } catch (error) {
19735
+ if (error.code !== "ENOENT") {
19736
+ return {
19737
+ path: hookPath,
19738
+ written: false,
19739
+ notes: [`Refusing to write ${hookPath}: ${error.message}`]
19740
+ };
19741
+ }
19742
+ }
19293
19743
  try {
19294
- fs24__namespace.mkdirSync(hooksDir, { recursive: true });
19744
+ fs25__namespace.mkdirSync(hooksDir, { recursive: true });
19295
19745
  } catch (err) {
19296
19746
  return {
19297
19747
  path: hookPath,
@@ -19301,7 +19751,7 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
19301
19751
  }
19302
19752
  let existing = null;
19303
19753
  try {
19304
- existing = fs24__namespace.readFileSync(hookPath, "utf8");
19754
+ existing = fs25__namespace.readFileSync(hookPath, "utf8");
19305
19755
  } catch {
19306
19756
  existing = null;
19307
19757
  }
@@ -19316,8 +19766,8 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
19316
19766
  };
19317
19767
  }
19318
19768
  try {
19319
- fs24__namespace.writeFileSync(hookPath, hookScript(outDir), "utf8");
19320
- fs24__namespace.chmodSync(hookPath, 493);
19769
+ fs25__namespace.writeFileSync(hookPath, hookScript(outDir), "utf8");
19770
+ fs25__namespace.chmodSync(hookPath, 493);
19321
19771
  } catch (err) {
19322
19772
  return {
19323
19773
  path: hookPath,
@@ -19339,23 +19789,23 @@ var SUMMARY_MAX_SOURCE_BYTES2 = SUMMARY_MAX_SOURCE_BYTES;
19339
19789
  var FILE_DERIVATIONS = /* @__PURE__ */ new Map();
19340
19790
  var FILE_DERIVATION_LIMIT_BYTES = 64 * 1024 * 1024;
19341
19791
  var fileDerivationBytes = 0;
19342
- function takeDerivation(path26, hash, settings) {
19343
- const cached = FILE_DERIVATIONS.get(path26);
19792
+ function takeDerivation(path27, hash, settings) {
19793
+ const cached = FILE_DERIVATIONS.get(path27);
19344
19794
  if (cached === void 0 || cached.hash !== hash || cached.settings !== settings) return void 0;
19345
- FILE_DERIVATIONS.delete(path26);
19346
- FILE_DERIVATIONS.set(path26, cached);
19795
+ FILE_DERIVATIONS.delete(path27);
19796
+ FILE_DERIVATIONS.set(path27, cached);
19347
19797
  return cached;
19348
19798
  }
19349
- function rememberDerivation(path26, hash, settings, derivation) {
19799
+ function rememberDerivation(path27, hash, settings, derivation) {
19350
19800
  const bodyBytes = derivation.finalContent === derivation.redacted ? derivation.redacted.length : derivation.redacted.length + derivation.finalContent.length;
19351
19801
  const bytes = bodyBytes * 2 + 512;
19352
19802
  if (bytes > FILE_DERIVATION_LIMIT_BYTES / 4) return;
19353
- const previous = FILE_DERIVATIONS.get(path26);
19803
+ const previous = FILE_DERIVATIONS.get(path27);
19354
19804
  if (previous !== void 0) {
19355
- FILE_DERIVATIONS.delete(path26);
19805
+ FILE_DERIVATIONS.delete(path27);
19356
19806
  fileDerivationBytes -= previous.bytes;
19357
19807
  } else {
19358
- FILE_DERIVATIONS.delete(path26);
19808
+ FILE_DERIVATIONS.delete(path27);
19359
19809
  }
19360
19810
  while (fileDerivationBytes + bytes > FILE_DERIVATION_LIMIT_BYTES) {
19361
19811
  const oldest = FILE_DERIVATIONS.keys().next();
@@ -19364,7 +19814,7 @@ function rememberDerivation(path26, hash, settings, derivation) {
19364
19814
  FILE_DERIVATIONS.delete(oldest.value);
19365
19815
  if (evicted !== void 0) fileDerivationBytes -= evicted.bytes;
19366
19816
  }
19367
- FILE_DERIVATIONS.set(path26, { ...derivation, hash, settings, bytes });
19817
+ FILE_DERIVATIONS.set(path27, { ...derivation, hash, settings, bytes });
19368
19818
  fileDerivationBytes += bytes;
19369
19819
  }
19370
19820
  function derivationSettings(config) {
@@ -19644,11 +20094,11 @@ function verifyInMemory(files, parts, unaccounted) {
19644
20094
  return errors;
19645
20095
  }
19646
20096
  function resolveSafeOutputDirs(config) {
19647
- const cwd = path25__namespace.resolve(config.cwd);
19648
- const outDir = path25__namespace.resolve(cwd, config.outDir);
19649
- const tmpDir = path25__namespace.resolve(cwd, config.tmpDir);
19650
- const root = path25__namespace.parse(cwd).root;
19651
- const contains = (parent, child) => child === parent || child.startsWith(`${parent}${path25__namespace.sep}`);
20097
+ const cwd = path26__namespace.resolve(config.cwd);
20098
+ const outDir = path26__namespace.resolve(cwd, config.outDir);
20099
+ const tmpDir = path26__namespace.resolve(cwd, config.tmpDir);
20100
+ const root = path26__namespace.parse(cwd).root;
20101
+ const contains = (parent, child) => child === parent || child.startsWith(`${parent}${path26__namespace.sep}`);
19652
20102
  const reject = (reason) => {
19653
20103
  throw new Error(
19654
20104
  `Refusing to generate: ${reason}. outDir=${outDir} tmpDir=${tmpDir} cwd=${cwd}`
@@ -19690,7 +20140,7 @@ function maskPathText(value, secretRules) {
19690
20140
  }
19691
20141
  function maskOwnerBrief(brief, secretRules) {
19692
20142
  if (brief === void 0) return void 0;
19693
- const mask = (value) => scanAndRedactSecrets(value, secretRules ?? [], "owner-brief").redacted;
20143
+ const mask = (value) => maskProse(value, secretRules, "owner-brief");
19694
20144
  return {
19695
20145
  ...brief,
19696
20146
  path: mask(brief.path),
@@ -19700,11 +20150,17 @@ function maskOwnerBrief(brief, secretRules) {
19700
20150
  ...brief.bar === void 0 ? {} : { bar: mask(brief.bar) },
19701
20151
  ...brief.calibration === void 0 ? {} : { calibration: mask(brief.calibration) },
19702
20152
  ...brief.preamble === void 0 ? {} : { preamble: mask(brief.preamble) },
19703
- notes: brief.notes.map((note) => ({ heading: note.heading, body: mask(note.body) }))
20153
+ // The heading is prose too. Masking only the body left `## Incident ghp_…` in PROMPT.md:
20154
+ // ownerNotesSection reproduced the heading as a Markdown title, where no line rule that
20155
+ // expects `key: value` can see it.
20156
+ notes: brief.notes.map((note) => ({ heading: mask(note.heading), body: mask(note.body) }))
19704
20157
  };
19705
20158
  }
20159
+ function maskProse(value, secretRules, scope) {
20160
+ return scanAndRedactSecrets(value, secretRules ?? [], scope).redacted;
20161
+ }
19706
20162
  function maskOverview(overview, secretRules) {
19707
- const mask = (value) => maskPathText(value, secretRules);
20163
+ const mask = (value) => maskProse(value, secretRules, "overview");
19708
20164
  return {
19709
20165
  ...overview.description === void 0 ? {} : { description: mask(overview.description) },
19710
20166
  ...overview.summary === void 0 ? {} : { summary: mask(overview.summary) },
@@ -19731,14 +20187,14 @@ function listEntries(dir) {
19731
20187
  const walk2 = (absolute, prefix) => {
19732
20188
  let children;
19733
20189
  try {
19734
- children = fs24__namespace.readdirSync(absolute, { withFileTypes: true });
20190
+ children = fs25__namespace.readdirSync(absolute, { withFileTypes: true });
19735
20191
  } catch {
19736
20192
  return;
19737
20193
  }
19738
20194
  for (const child of children) {
19739
- const relative14 = prefix === "" ? child.name : `${prefix}/${child.name}`;
19740
- entries.push(relative14);
19741
- if (child.isDirectory()) walk2(path25__namespace.join(absolute, child.name), relative14);
20195
+ const relative15 = prefix === "" ? child.name : `${prefix}/${child.name}`;
20196
+ entries.push(relative15);
20197
+ if (child.isDirectory()) walk2(path26__namespace.join(absolute, child.name), relative15);
19742
20198
  }
19743
20199
  };
19744
20200
  walk2(dir, "");
@@ -19750,10 +20206,10 @@ function markerInventory(dir, written) {
19750
20206
  for (const entry of entries) {
19751
20207
  if (entry === OWNERSHIP_MARKER) continue;
19752
20208
  if (isIgnorableEntry(entry)) continue;
19753
- const full = path25__namespace.join(dir, ...entry.split("/"));
20209
+ const full = path26__namespace.join(dir, ...entry.split("/"));
19754
20210
  let stats;
19755
20211
  try {
19756
- stats = fs24__namespace.lstatSync(full);
20212
+ stats = fs25__namespace.lstatSync(full);
19757
20213
  } catch {
19758
20214
  continue;
19759
20215
  }
@@ -19765,7 +20221,7 @@ function markerInventory(dir, written) {
19765
20221
  }
19766
20222
  let digest;
19767
20223
  try {
19768
- digest = sha256Hex2(fs24__namespace.readFileSync(full));
20224
+ digest = sha256Hex2(fs25__namespace.readFileSync(full));
19769
20225
  } catch {
19770
20226
  continue;
19771
20227
  }
@@ -19787,15 +20243,15 @@ function markerPayload(dir, state, id, createdAt, written, runId) {
19787
20243
  entries,
19788
20244
  files
19789
20245
  };
19790
- const manifestPath = path25__namespace.join(dir, "manifest.json");
19791
- if (fs24__namespace.existsSync(manifestPath)) {
19792
- marker2.manifestSha256 = sha256Hex2(fs24__namespace.readFileSync(manifestPath));
20246
+ const manifestPath = path26__namespace.join(dir, "manifest.json");
20247
+ if (fs25__namespace.existsSync(manifestPath)) {
20248
+ marker2.manifestSha256 = sha256Hex2(fs25__namespace.readFileSync(manifestPath));
19793
20249
  }
19794
20250
  return marker2;
19795
20251
  }
19796
20252
  function writeOwnershipMarker(dir, marker2) {
19797
- fs24__namespace.writeFileSync(
19798
- path25__namespace.join(dir, OWNERSHIP_MARKER),
20253
+ fs25__namespace.writeFileSync(
20254
+ path26__namespace.join(dir, OWNERSHIP_MARKER),
19799
20255
  `${JSON.stringify(marker2, null, 2)}
19800
20256
  `,
19801
20257
  "utf8"
@@ -19807,13 +20263,13 @@ function markerBelongsTo(dir, id) {
19807
20263
  return evidence.marker.id === id;
19808
20264
  }
19809
20265
  function readOwnershipMarker(dir) {
19810
- const markerPath = path25__namespace.join(dir, OWNERSHIP_MARKER);
19811
- if (!fs24__namespace.existsSync(markerPath)) {
20266
+ const markerPath = path26__namespace.join(dir, OWNERSHIP_MARKER);
20267
+ if (!fs25__namespace.existsSync(markerPath)) {
19812
20268
  return { marker: null, problem: "it holds no .codebase-snapshot marker" };
19813
20269
  }
19814
20270
  let raw;
19815
20271
  try {
19816
- raw = fs24__namespace.readFileSync(markerPath, "utf8");
20272
+ raw = fs25__namespace.readFileSync(markerPath, "utf8");
19817
20273
  } catch {
19818
20274
  return { marker: null, problem: "its .codebase-snapshot marker could not be read" };
19819
20275
  }
@@ -19914,10 +20370,10 @@ function verifyMarkerInventory(dir, entries, files) {
19914
20370
  for (const entry of entries) {
19915
20371
  if (entry === OWNERSHIP_MARKER) continue;
19916
20372
  if (IGNORABLE_ENTRIES.has(entry.slice(entry.lastIndexOf("/") + 1))) continue;
19917
- const full = path25__namespace.join(dir, ...entry.split("/"));
20373
+ const full = path26__namespace.join(dir, ...entry.split("/"));
19918
20374
  let stats;
19919
20375
  try {
19920
- stats = fs24__namespace.lstatSync(full);
20376
+ stats = fs25__namespace.lstatSync(full);
19921
20377
  } catch {
19922
20378
  return `its .codebase-snapshot inventory lists ${entry}, which cannot be read`;
19923
20379
  }
@@ -19942,7 +20398,7 @@ function verifyMarkerInventory(dir, entries, files) {
19942
20398
  }
19943
20399
  let digest;
19944
20400
  try {
19945
- digest = sha256Hex2(fs24__namespace.readFileSync(full));
20401
+ digest = sha256Hex2(fs25__namespace.readFileSync(full));
19946
20402
  } catch {
19947
20403
  return `its .codebase-snapshot inventory cannot verify ${entry}: the file could not be read`;
19948
20404
  }
@@ -19963,12 +20419,12 @@ function assessSnapshotDirectory(dir) {
19963
20419
  marker: marker2
19964
20420
  };
19965
20421
  }
19966
- const manifestPath = path25__namespace.join(dir, "manifest.json");
19967
- const hasManifest = fs24__namespace.existsSync(manifestPath);
20422
+ const manifestPath = path26__namespace.join(dir, "manifest.json");
20423
+ const hasManifest = fs25__namespace.existsSync(manifestPath);
19968
20424
  if (hasManifest) {
19969
20425
  let raw;
19970
20426
  try {
19971
- raw = fs24__namespace.readFileSync(manifestPath, "utf8");
20427
+ raw = fs25__namespace.readFileSync(manifestPath, "utf8");
19972
20428
  } catch {
19973
20429
  return {
19974
20430
  owned: false,
@@ -20069,13 +20525,13 @@ function containsNoFiles(dir) {
20069
20525
  const current = pending.pop();
20070
20526
  let entries;
20071
20527
  try {
20072
- entries = fs24__namespace.readdirSync(current, { withFileTypes: true });
20528
+ entries = fs25__namespace.readdirSync(current, { withFileTypes: true });
20073
20529
  } catch {
20074
20530
  return false;
20075
20531
  }
20076
20532
  for (const entry of entries) {
20077
20533
  if (entry.isDirectory()) {
20078
- pending.push(path25__namespace.join(current, entry.name));
20534
+ pending.push(path26__namespace.join(current, entry.name));
20079
20535
  } else if (!IGNORABLE_ENTRIES.has(entry.name)) {
20080
20536
  return false;
20081
20537
  }
@@ -20084,13 +20540,13 @@ function containsNoFiles(dir) {
20084
20540
  return true;
20085
20541
  }
20086
20542
  function assertReplaceable(target, label, secretRules) {
20087
- if (!fs24__namespace.existsSync(target)) return;
20088
- if (!fs24__namespace.statSync(target).isDirectory()) {
20543
+ if (!fs25__namespace.existsSync(target)) return;
20544
+ if (!fs25__namespace.statSync(target).isDirectory()) {
20089
20545
  throw new Error(
20090
20546
  `Refusing to write into ${label} ${target}: it exists but is not a directory.`
20091
20547
  );
20092
20548
  }
20093
- const entries = fs24__namespace.readdirSync(target);
20549
+ const entries = fs25__namespace.readdirSync(target);
20094
20550
  if (entries.length === 0) return;
20095
20551
  if (entries.every((name) => IGNORABLE_ENTRIES.has(name))) return;
20096
20552
  if (containsNoFiles(target)) return;
@@ -20110,18 +20566,18 @@ function assertReplaceable(target, label, secretRules) {
20110
20566
  );
20111
20567
  }
20112
20568
  function assertStagingRootUsable(tmpDir, secretRules) {
20113
- if (!fs24__namespace.existsSync(tmpDir)) return;
20114
- if (!fs24__namespace.statSync(tmpDir).isDirectory()) {
20569
+ if (!fs25__namespace.existsSync(tmpDir)) return;
20570
+ if (!fs25__namespace.statSync(tmpDir).isDirectory()) {
20115
20571
  throw new Error(`Refusing to write into tmpDir ${tmpDir}: it exists but is not a directory.`);
20116
20572
  }
20117
- const entries = fs24__namespace.readdirSync(tmpDir);
20573
+ const entries = fs25__namespace.readdirSync(tmpDir);
20118
20574
  if (entries.length === 0) return;
20119
20575
  const foreign = entries.filter((name) => {
20120
- const full = path25__namespace.join(tmpDir, name);
20576
+ const full = path26__namespace.join(tmpDir, name);
20121
20577
  if (!name.startsWith(RUN_DIR_PREFIX)) return true;
20122
20578
  let stats;
20123
20579
  try {
20124
- stats = fs24__namespace.statSync(full);
20580
+ stats = fs25__namespace.statSync(full);
20125
20581
  } catch {
20126
20582
  return true;
20127
20583
  }
@@ -20129,7 +20585,7 @@ function assertStagingRootUsable(tmpDir, secretRules) {
20129
20585
  const { marker: marker2 } = readOwnershipMarker(full);
20130
20586
  if (marker2) return false;
20131
20587
  try {
20132
- return fs24__namespace.readdirSync(full).length > 0;
20588
+ return fs25__namespace.readdirSync(full).length > 0;
20133
20589
  } catch {
20134
20590
  return true;
20135
20591
  }
@@ -20144,13 +20600,13 @@ function assertStagingRootUsable(tmpDir, secretRules) {
20144
20600
  function cleanStaleRunDirs(tmpDir) {
20145
20601
  let entries;
20146
20602
  try {
20147
- entries = fs24__namespace.readdirSync(tmpDir);
20603
+ entries = fs25__namespace.readdirSync(tmpDir);
20148
20604
  } catch {
20149
20605
  return;
20150
20606
  }
20151
20607
  for (const name of entries) {
20152
20608
  if (!name.startsWith(RUN_DIR_PREFIX)) continue;
20153
- const full = path25__namespace.join(tmpDir, name);
20609
+ const full = path26__namespace.join(tmpDir, name);
20154
20610
  const { marker: marker2 } = readOwnershipMarker(full);
20155
20611
  if (marker2) {
20156
20612
  const created = Date.parse(marker2.createdAt);
@@ -20158,33 +20614,33 @@ function cleanStaleRunDirs(tmpDir) {
20158
20614
  const abandoned = typeof marker2.pid === "number" && !isProcessAlive(marker2.pid);
20159
20615
  if (aged || abandoned) {
20160
20616
  try {
20161
- fs24__namespace.rmSync(full, { recursive: true, force: true });
20617
+ fs25__namespace.rmSync(full, { recursive: true, force: true });
20162
20618
  } catch {
20163
20619
  }
20164
20620
  }
20165
20621
  continue;
20166
20622
  }
20167
20623
  try {
20168
- if (fs24__namespace.readdirSync(full).length === 0) fs24__namespace.rmSync(full, { recursive: true, force: true });
20624
+ if (fs25__namespace.readdirSync(full).length === 0) fs25__namespace.rmSync(full, { recursive: true, force: true });
20169
20625
  } catch {
20170
20626
  }
20171
20627
  }
20172
20628
  }
20173
20629
  function removeIfEmpty(dir) {
20174
20630
  try {
20175
- if (fs24__namespace.readdirSync(dir).length === 0) fs24__namespace.rmSync(dir, { recursive: true, force: true });
20631
+ if (fs25__namespace.readdirSync(dir).length === 0) fs25__namespace.rmSync(dir, { recursive: true, force: true });
20176
20632
  } catch {
20177
20633
  }
20178
20634
  }
20179
20635
  function ensureParentDirectory(target, label) {
20180
- const parent = path25__namespace.dirname(target);
20181
- if (fs24__namespace.existsSync(parent) && !fs24__namespace.statSync(parent).isDirectory()) {
20636
+ const parent = path26__namespace.dirname(target);
20637
+ if (fs25__namespace.existsSync(parent) && !fs25__namespace.statSync(parent).isDirectory()) {
20182
20638
  throw new Error(
20183
20639
  `Refusing to create ${label} ${target}: ${parent} exists but is not a directory.`
20184
20640
  );
20185
20641
  }
20186
20642
  try {
20187
- fs24__namespace.mkdirSync(parent, { recursive: true });
20643
+ fs25__namespace.mkdirSync(parent, { recursive: true });
20188
20644
  } catch (err) {
20189
20645
  throw new Error(
20190
20646
  `Refusing to create ${label} ${target}: its parent ${parent} could not be created (${err.message}).`
@@ -20193,6 +20649,7 @@ function ensureParentDirectory(target, label) {
20193
20649
  }
20194
20650
  var LOCK_HEARTBEAT_MS = 5e3;
20195
20651
  var LOCK_STALE_HEARTBEAT_MS = 12e4;
20652
+ var LOCK_EMPTY_GRACE_MS = 5e3;
20196
20653
  var LOCK_HEARTBEAT_SOURCE = `
20197
20654
  const { parentPort, workerData } = require("node:worker_threads");
20198
20655
  const fs = require("node:fs");
@@ -20242,17 +20699,17 @@ function acquireRunLock(stagingRoot, runId) {
20242
20699
  `;
20243
20700
  for (let attempt = 0; attempt < 2; attempt += 1) {
20244
20701
  try {
20245
- const handle = fs24__namespace.openSync(lockPath, "wx");
20702
+ const handle = fs25__namespace.openSync(lockPath, "wx");
20246
20703
  try {
20247
- fs24__namespace.writeSync(handle, payload);
20704
+ fs25__namespace.writeSync(handle, payload);
20248
20705
  } finally {
20249
- fs24__namespace.closeSync(handle);
20706
+ fs25__namespace.closeSync(handle);
20250
20707
  }
20251
20708
  const stopHeartbeat = startLockHeartbeat(lockPath);
20252
20709
  return () => {
20253
20710
  stopHeartbeat();
20254
20711
  try {
20255
- fs24__namespace.rmSync(lockPath, { force: true });
20712
+ fs25__namespace.rmSync(lockPath, { force: true });
20256
20713
  } catch {
20257
20714
  }
20258
20715
  };
@@ -20272,45 +20729,45 @@ function lockKeyFor(stagingRoot) {
20272
20729
  return sha256Hex2(key).slice(0, 16);
20273
20730
  }
20274
20731
  function canonicalLockTarget(targetPath) {
20275
- const resolved = path25__namespace.resolve(targetPath);
20732
+ const resolved = path26__namespace.resolve(targetPath);
20276
20733
  let existing = resolved;
20277
20734
  const tail = [];
20278
20735
  for (; ; ) {
20279
20736
  try {
20280
- return path25__namespace.join(fs24__namespace.realpathSync(existing), ...tail);
20737
+ return path26__namespace.join(fs25__namespace.realpathSync(existing), ...tail);
20281
20738
  } catch {
20282
- const parent = path25__namespace.dirname(existing);
20739
+ const parent = path26__namespace.dirname(existing);
20283
20740
  if (parent === existing) return resolved;
20284
- tail.unshift(path25__namespace.basename(existing));
20741
+ tail.unshift(path26__namespace.basename(existing));
20285
20742
  existing = parent;
20286
20743
  }
20287
20744
  }
20288
20745
  }
20289
20746
  function lockPathFor(stagingRoot) {
20290
- return path25__namespace.join(os2__namespace.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
20747
+ return path26__namespace.join(os2__namespace.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
20291
20748
  }
20292
20749
  function releaseAbandonedRun(stagingRoots, runId) {
20293
20750
  if (runId.length === 0) return;
20294
20751
  for (const root of new Set(stagingRoots)) {
20295
20752
  const lockPath = lockPathFor(root);
20296
20753
  try {
20297
- const payload = JSON.parse(fs24__namespace.readFileSync(lockPath, "utf8"));
20298
- if (payload.runId === runId) fs24__namespace.rmSync(lockPath, { force: true });
20754
+ const payload = JSON.parse(fs25__namespace.readFileSync(lockPath, "utf8"));
20755
+ if (payload.runId === runId) fs25__namespace.rmSync(lockPath, { force: true });
20299
20756
  } catch {
20300
20757
  }
20301
20758
  let entries;
20302
20759
  try {
20303
- entries = fs24__namespace.readdirSync(root);
20760
+ entries = fs25__namespace.readdirSync(root);
20304
20761
  } catch {
20305
20762
  continue;
20306
20763
  }
20307
20764
  for (const name of entries) {
20308
20765
  if (!name.startsWith(RUN_DIR_PREFIX)) continue;
20309
- const directory = path25__namespace.join(root, name);
20766
+ const directory = path26__namespace.join(root, name);
20310
20767
  const { marker: marker2 } = readOwnershipMarker(directory);
20311
20768
  if (marker2?.runId !== runId) continue;
20312
20769
  try {
20313
- fs24__namespace.rmSync(directory, { recursive: true, force: true });
20770
+ fs25__namespace.rmSync(directory, { recursive: true, force: true });
20314
20771
  } catch {
20315
20772
  }
20316
20773
  }
@@ -20318,7 +20775,7 @@ function releaseAbandonedRun(stagingRoots, runId) {
20318
20775
  }
20319
20776
  function lockHeartbeatAgeMs(lockPath) {
20320
20777
  try {
20321
- return Date.now() - fs24__namespace.statSync(lockPath).mtimeMs;
20778
+ return Date.now() - fs25__namespace.statSync(lockPath).mtimeMs;
20322
20779
  } catch {
20323
20780
  return Number.POSITIVE_INFINITY;
20324
20781
  }
@@ -20326,7 +20783,7 @@ function lockHeartbeatAgeMs(lockPath) {
20326
20783
  function lockOwnerIsGone(lockPath) {
20327
20784
  let raw;
20328
20785
  try {
20329
- raw = fs24__namespace.readFileSync(lockPath, "utf8");
20786
+ raw = fs25__namespace.readFileSync(lockPath, "utf8");
20330
20787
  } catch {
20331
20788
  return false;
20332
20789
  }
@@ -20334,9 +20791,11 @@ function lockOwnerIsGone(lockPath) {
20334
20791
  try {
20335
20792
  pid = JSON.parse(raw).pid;
20336
20793
  } catch {
20337
- return lockFileIsAncient(lockPath);
20794
+ return lockFileIsAncient(lockPath, LOCK_EMPTY_GRACE_MS);
20795
+ }
20796
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) {
20797
+ return lockFileIsAncient(lockPath, LOCK_EMPTY_GRACE_MS);
20338
20798
  }
20339
- if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return lockFileIsAncient(lockPath);
20340
20799
  try {
20341
20800
  process.kill(pid, 0);
20342
20801
  return lockFileIsAncient(lockPath);
@@ -20348,44 +20807,44 @@ function lockOwnerIsGone(lockPath) {
20348
20807
  function reclaimStaleLock(lockPath) {
20349
20808
  let before;
20350
20809
  try {
20351
- before = fs24__namespace.statSync(lockPath);
20810
+ before = fs25__namespace.statSync(lockPath);
20352
20811
  } catch {
20353
20812
  return true;
20354
20813
  }
20355
20814
  if (!lockOwnerIsGone(lockPath)) return false;
20356
20815
  try {
20357
- const current = fs24__namespace.statSync(lockPath);
20816
+ const current = fs25__namespace.statSync(lockPath);
20358
20817
  const sameFile = current.ino === before.ino && current.birthtimeMs === before.birthtimeMs && current.mtimeMs === before.mtimeMs;
20359
20818
  if (!sameFile) return false;
20360
- fs24__namespace.rmSync(lockPath, { force: true });
20819
+ fs25__namespace.rmSync(lockPath, { force: true });
20361
20820
  return true;
20362
20821
  } catch {
20363
20822
  return false;
20364
20823
  }
20365
20824
  }
20366
- function lockFileIsAncient(lockPath) {
20367
- return lockHeartbeatAgeMs(lockPath) > LOCK_STALE_HEARTBEAT_MS;
20825
+ function lockFileIsAncient(lockPath, thresholdMs = LOCK_STALE_HEARTBEAT_MS) {
20826
+ return lockHeartbeatAgeMs(lockPath) > thresholdMs;
20368
20827
  }
20369
20828
  function writeManifestAtomically(manifestPath, manifest) {
20370
20829
  const tempPath = `${manifestPath}.${process.pid}.tmp`;
20371
- fs24__namespace.writeFileSync(tempPath, JSON.stringify(manifest, null, 2), "utf8");
20830
+ fs25__namespace.writeFileSync(tempPath, JSON.stringify(manifest, null, 2), "utf8");
20372
20831
  try {
20373
- fs24__namespace.renameSync(tempPath, manifestPath);
20832
+ fs25__namespace.renameSync(tempPath, manifestPath);
20374
20833
  } catch (err) {
20375
20834
  try {
20376
- fs24__namespace.rmSync(tempPath, { force: true });
20835
+ fs25__namespace.rmSync(tempPath, { force: true });
20377
20836
  } catch {
20378
20837
  }
20379
20838
  throw err;
20380
20839
  }
20381
20840
  }
20382
- function swapIntoPlace(stagingDir, outDir, beforeSwap) {
20841
+ function swapIntoPlace(stagingDir, outDir, beforeSwap, onStagingPreserved) {
20383
20842
  ensureParentDirectory(outDir, "outDir");
20384
20843
  const deadline = Date.now() + 3e3;
20385
20844
  let delay = 25;
20386
20845
  for (; ; ) {
20387
20846
  try {
20388
- swapOnce(stagingDir, outDir, beforeSwap);
20847
+ swapOnce(stagingDir, outDir, beforeSwap, onStagingPreserved);
20389
20848
  return;
20390
20849
  } catch (err) {
20391
20850
  const code = err.code;
@@ -20398,21 +20857,21 @@ function swapIntoPlace(stagingDir, outDir, beforeSwap) {
20398
20857
  }
20399
20858
  }
20400
20859
  function recoverInterruptedPublish(outDir) {
20401
- if (fs24__namespace.existsSync(outDir)) return;
20402
- const parent = path25__namespace.dirname(outDir);
20403
- const base = path25__namespace.basename(outDir);
20860
+ if (fs25__namespace.existsSync(outDir)) return;
20861
+ const parent = path26__namespace.dirname(outDir);
20862
+ const base = path26__namespace.basename(outDir);
20404
20863
  let backups;
20405
20864
  try {
20406
- backups = fs24__namespace.readdirSync(parent).filter((name) => name.startsWith(`${base}.backup-`));
20865
+ backups = fs25__namespace.readdirSync(parent).filter((name) => name.startsWith(`${base}.backup-`));
20407
20866
  } catch {
20408
20867
  return;
20409
20868
  }
20410
20869
  if (backups.length !== 1) return;
20411
- const backupDir = path25__namespace.join(parent, backups[0]);
20870
+ const backupDir = path26__namespace.join(parent, backups[0]);
20412
20871
  const { marker: marker2, problem } = readOwnershipMarker(backupDir);
20413
20872
  if (problem !== null || marker2 === null || marker2.state !== "complete") return;
20414
20873
  try {
20415
- fs24__namespace.renameSync(backupDir, outDir);
20874
+ fs25__namespace.renameSync(backupDir, outDir);
20416
20875
  process.stderr.write(
20417
20876
  `\u26A0 Recovered ${outDir} from ${backupDir}, left by an interrupted run. That snapshot is the one from before the interrupted run.
20418
20877
  `
@@ -20420,18 +20879,19 @@ function recoverInterruptedPublish(outDir) {
20420
20879
  } catch {
20421
20880
  }
20422
20881
  }
20423
- function swapOnce(stagingDir, outDir, beforeSwap) {
20882
+ function swapOnce(stagingDir, outDir, beforeSwap, onStagingPreserved) {
20424
20883
  const backupDir = `${outDir}.backup-${process.pid}-${Date.now()}`;
20425
- const hadPrevious = fs24__namespace.existsSync(outDir);
20884
+ const hadPrevious = fs25__namespace.existsSync(outDir);
20426
20885
  if (hadPrevious) beforeSwap?.();
20427
20886
  let movedAside = false;
20428
20887
  if (hadPrevious) {
20429
20888
  try {
20430
- fs24__namespace.renameSync(outDir, backupDir);
20889
+ fs25__namespace.renameSync(outDir, backupDir);
20431
20890
  movedAside = true;
20432
20891
  } catch (err) {
20433
20892
  if (!isLockError(err)) throw err;
20434
- fs24__namespace.rmSync(outDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
20893
+ onStagingPreserved?.();
20894
+ fs25__namespace.rmSync(outDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
20435
20895
  process.stderr.write(
20436
20896
  `\u26A0 ${outDir} could not be moved aside (${err.message}), so it was replaced in place. Close anything holding the old snapshot open to avoid this next time.
20437
20897
  `
@@ -20440,27 +20900,28 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
20440
20900
  }
20441
20901
  try {
20442
20902
  try {
20443
- fs24__namespace.renameSync(stagingDir, outDir);
20903
+ fs25__namespace.renameSync(stagingDir, outDir);
20444
20904
  } catch (err) {
20445
20905
  if (err.code !== "EXDEV") throw err;
20446
20906
  const partialDir = `${outDir}.partial-${process.pid}-${Date.now()}`;
20447
20907
  try {
20448
- fs24__namespace.cpSync(stagingDir, partialDir, { recursive: true });
20449
- fs24__namespace.renameSync(partialDir, outDir);
20450
- fs24__namespace.rmSync(stagingDir, { recursive: true, force: true });
20908
+ fs25__namespace.cpSync(stagingDir, partialDir, { recursive: true });
20909
+ fs25__namespace.renameSync(partialDir, outDir);
20910
+ fs25__namespace.rmSync(stagingDir, { recursive: true, force: true });
20451
20911
  } catch (copyErr) {
20452
20912
  try {
20453
- fs24__namespace.rmSync(partialDir, { recursive: true, force: true });
20913
+ fs25__namespace.rmSync(partialDir, { recursive: true, force: true });
20454
20914
  } catch {
20455
20915
  }
20456
20916
  throw copyErr;
20457
20917
  }
20458
20918
  }
20459
20919
  } catch (err) {
20460
- if (hadPrevious && movedAside && fs24__namespace.existsSync(backupDir)) {
20461
- if (fs24__namespace.existsSync(outDir)) fs24__namespace.rmSync(outDir, { recursive: true, force: true });
20462
- fs24__namespace.renameSync(backupDir, outDir);
20920
+ if (hadPrevious && movedAside && fs25__namespace.existsSync(backupDir)) {
20921
+ if (fs25__namespace.existsSync(outDir)) fs25__namespace.rmSync(outDir, { recursive: true, force: true });
20922
+ fs25__namespace.renameSync(backupDir, outDir);
20463
20923
  } else if (hadPrevious && !movedAside) {
20924
+ onStagingPreserved?.();
20464
20925
  process.stderr.write(
20465
20926
  `\u26A0 The previous snapshot at ${outDir} was removed and the new one could not be moved into place. It is complete at ${stagingDir}.
20466
20927
  `
@@ -20470,7 +20931,7 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
20470
20931
  }
20471
20932
  if (hadPrevious) {
20472
20933
  try {
20473
- fs24__namespace.rmSync(backupDir, { recursive: true, force: true });
20934
+ fs25__namespace.rmSync(backupDir, { recursive: true, force: true });
20474
20935
  } catch (err) {
20475
20936
  process.stderr.write(
20476
20937
  `\u26A0 The previous snapshot could not be removed from ${backupDir} (${err.message}). The new snapshot is in place; delete that directory by hand when convenient.
@@ -20649,8 +21110,8 @@ function generateSnapshot(configInput, options) {
20649
21110
  // first run cannot have marked them yet, so the name alone keeps a run from recording its own
20650
21111
  // output — but only at these exact paths, not at every directory that shares the name.
20651
21112
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
20652
- (directory) => path25__namespace.relative(config.cwd, path25__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
20653
- ).filter((relative14) => relative14.length > 0 && !relative14.startsWith("..")),
21113
+ (directory) => path26__namespace.relative(config.cwd, path26__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
21114
+ ).filter((relative15) => relative15.length > 0 && !relative15.startsWith("..")),
20654
21115
  // A staged path can be absent from the working tree while its index blob exists. Discovery
20655
21116
  // lists the working tree, so those paths would never reach the scan at all.
20656
21117
  ...stagedPaths.size > 0 ? { extraPaths: [...stagedPaths] } : {}
@@ -20678,7 +21139,7 @@ function generateSnapshot(configInput, options) {
20678
21139
  let totalSizeBytes = 0;
20679
21140
  let largeFileCount = 0;
20680
21141
  for (const relativePath of candidateFiles) {
20681
- const absolutePath = path25__namespace.join(config.cwd, relativePath);
21142
+ const absolutePath = path26__namespace.join(config.cwd, relativePath);
20682
21143
  const fromIndex = stagedPaths.has(relativePath);
20683
21144
  let buffer;
20684
21145
  let sizeBytes;
@@ -20709,9 +21170,9 @@ function generateSnapshot(configInput, options) {
20709
21170
  } else {
20710
21171
  let stats;
20711
21172
  try {
20712
- stats = fs24__namespace.statSync(absolutePath);
21173
+ stats = fs25__namespace.statSync(absolutePath);
20713
21174
  if (!stats.isFile()) {
20714
- const nestedRepository = stats.isDirectory() && fs24__namespace.existsSync(path25__namespace.join(absolutePath, ".git"));
21175
+ const nestedRepository = stats.isDirectory() && fs25__namespace.existsSync(path26__namespace.join(absolutePath, ".git"));
20715
21176
  skipped.push(
20716
21177
  nestedRepository ? {
20717
21178
  path: relativePath,
@@ -20747,7 +21208,7 @@ function generateSnapshot(configInput, options) {
20747
21208
  continue;
20748
21209
  }
20749
21210
  try {
20750
- buffer = fs24__namespace.readFileSync(absolutePath);
21211
+ buffer = fs25__namespace.readFileSync(absolutePath);
20751
21212
  } catch (err) {
20752
21213
  const code = err.code;
20753
21214
  skipped.push({
@@ -20862,14 +21323,14 @@ function generateSnapshot(configInput, options) {
20862
21323
  }
20863
21324
  retain(secretFindings, (finding) => finding.path === void 0 || keep.has(finding.path));
20864
21325
  retain(encodingNotes, (note) => keep.has(note.path));
20865
- retain(oversizeSummaryPaths, (path26) => keep.has(path26));
20866
- retain(previewSummaryPaths, (path26) => keep.has(path26));
21326
+ retain(oversizeSummaryPaths, (path27) => keep.has(path27));
21327
+ retain(previewSummaryPaths, (path27) => keep.has(path27));
20867
21328
  retain(fileWarnings, (warning) => keep.has(warning.path));
20868
- for (const path26 of [...monolithBodies.keys()]) {
20869
- if (!keep.has(path26)) monolithBodies.delete(path26);
21329
+ for (const path27 of [...monolithBodies.keys()]) {
21330
+ if (!keep.has(path27)) monolithBodies.delete(path27);
20870
21331
  }
20871
- for (const path26 of [...skippedSummaryImports.keys()]) {
20872
- if (!keep.has(path26)) skippedSummaryImports.delete(path26);
21332
+ for (const path27 of [...skippedSummaryImports.keys()]) {
21333
+ if (!keep.has(path27)) skippedSummaryImports.delete(path27);
20873
21334
  }
20874
21335
  };
20875
21336
  if (changedScope !== null && changedPaths !== null && config.withDependents === true) {
@@ -21340,7 +21801,7 @@ function generateSnapshot(configInput, options) {
21340
21801
  const reportExcludes = [...config.excludePatterns, ...config.presetExclude];
21341
21802
  const diffReport = artifacts.diff ? generateDiffReport(config.cwd, {
21342
21803
  secretRules: config.secretRules,
21343
- excluded: (relativePath) => reportExcludes.some((pattern) => matchesExclude(relativePath, pattern))
21804
+ excluded: (relativePath) => isSensitivePath(relativePath) || defaultIgnoreReason(relativePath) !== null || config.include.length > 0 && !config.include.some((pattern) => matchesExclude(relativePath, pattern)) || reportExcludes.some((pattern) => matchesExclude(relativePath, pattern))
21344
21805
  }) : null;
21345
21806
  if (diffReport !== null) manifest.artifacts.diff = artifactRecord(diffReport.text);
21346
21807
  const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount, secretRules: config.secretRules }) : null;
@@ -21366,8 +21827,8 @@ function generateSnapshot(configInput, options) {
21366
21827
  task: config.promptTask,
21367
21828
  brief: maskOwnerBrief(config.brief, config.secretRules),
21368
21829
  history: recentCommits(config.cwd).map((commit) => ({
21369
- subject: maskPathText(commit.subject, config.secretRules),
21370
- body: maskPathText(commit.body, config.secretRules)
21830
+ subject: maskProse(commit.subject, config.secretRules, "git-log"),
21831
+ body: maskProse(commit.body, config.secretRules, "git-log")
21371
21832
  })),
21372
21833
  overview: maskOverview(readProjectOverview(config.cwd), config.secretRules)
21373
21834
  }) : null;
@@ -21467,15 +21928,16 @@ function generateSnapshot(configInput, options) {
21467
21928
  recoverInterruptedPublish(outDir);
21468
21929
  assertReplaceable(outDir, "outDir", config.secretRules);
21469
21930
  let stagingDir = null;
21931
+ let stagingPreserved = false;
21470
21932
  let releaseDeferred = false;
21471
21933
  try {
21472
21934
  ensureParentDirectory(outDir, "outDir");
21473
- fs24__namespace.mkdirSync(tmpDir, { recursive: true });
21935
+ fs25__namespace.mkdirSync(tmpDir, { recursive: true });
21474
21936
  cleanStaleRunDirs(tmpDir);
21475
21937
  const snapshotId = crypto__namespace.randomUUID();
21476
21938
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
21477
- stagingDir = path25__namespace.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
21478
- fs24__namespace.mkdirSync(stagingDir);
21939
+ stagingDir = path26__namespace.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
21940
+ fs25__namespace.mkdirSync(stagingDir);
21479
21941
  writeOwnershipMarker(stagingDir, {
21480
21942
  generator: GENERATOR_NAME,
21481
21943
  version: GENERATOR_VERSION,
@@ -21486,30 +21948,30 @@ function generateSnapshot(configInput, options) {
21486
21948
  runId,
21487
21949
  pid: process.pid
21488
21950
  });
21489
- const partsDir = path25__namespace.join(stagingDir, "parts");
21490
- const reportsDir = path25__namespace.join(stagingDir, "reports");
21491
- if (artifacts.parts) fs24__namespace.mkdirSync(partsDir, { recursive: true });
21951
+ const partsDir = path26__namespace.join(stagingDir, "parts");
21952
+ const reportsDir = path26__namespace.join(stagingDir, "reports");
21953
+ if (artifacts.parts) fs25__namespace.mkdirSync(partsDir, { recursive: true });
21492
21954
  if (artifacts.navigation || artifacts.projectTree || artifacts.audit || artifacts.diff || artifacts.log || artifacts.tokenTree || config.sarif === true) {
21493
- fs24__namespace.mkdirSync(reportsDir, { recursive: true });
21955
+ fs25__namespace.mkdirSync(reportsDir, { recursive: true });
21494
21956
  }
21495
21957
  const writtenArtifacts = /* @__PURE__ */ new Map();
21496
21958
  const writeArtifact = (targetDir, relativeEntry, data) => {
21497
- const full = path25__namespace.join(targetDir, ...relativeEntry.split("/"));
21498
- fs24__namespace.writeFileSync(full, data, "utf8");
21499
- const stats = fs24__namespace.statSync(full);
21959
+ const full = path26__namespace.join(targetDir, ...relativeEntry.split("/"));
21960
+ fs25__namespace.writeFileSync(full, data, "utf8");
21961
+ const stats = fs25__namespace.statSync(full);
21500
21962
  writtenArtifacts.set(relativeEntry, {
21501
21963
  digest: { path: relativeEntry, bytes: stats.size, sha256: sha256Hex2(data) },
21502
21964
  mtimeMs: stats.mtimeMs
21503
21965
  });
21504
21966
  };
21505
21967
  const recordArtifact = (targetDir, relativeEntry) => {
21506
- const full = path25__namespace.join(targetDir, ...relativeEntry.split("/"));
21507
- const stats = fs24__namespace.statSync(full);
21968
+ const full = path26__namespace.join(targetDir, ...relativeEntry.split("/"));
21969
+ const stats = fs25__namespace.statSync(full);
21508
21970
  writtenArtifacts.set(relativeEntry, {
21509
21971
  digest: {
21510
21972
  path: relativeEntry,
21511
21973
  bytes: stats.size,
21512
- sha256: sha256Hex2(fs24__namespace.readFileSync(full))
21974
+ sha256: sha256Hex2(fs25__namespace.readFileSync(full))
21513
21975
  },
21514
21976
  mtimeMs: stats.mtimeMs
21515
21977
  });
@@ -21558,7 +22020,7 @@ function generateSnapshot(configInput, options) {
21558
22020
  "Refusing to sign: manifest.json is disabled for this run. Signing covers the manifest, so enable the manifest artifact or drop --sign."
21559
22021
  );
21560
22022
  }
21561
- const record = signManifest(path25__namespace.join(stagingDir, "manifest.json"), {
22023
+ const record = signManifest(path26__namespace.join(stagingDir, "manifest.json"), {
21562
22024
  key: options.sign.key ?? null
21563
22025
  });
21564
22026
  writeArtifact(stagingDir, SIGNATURE_FILE, JSON.stringify(record, null, 2) + "\n");
@@ -21576,17 +22038,24 @@ function generateSnapshot(configInput, options) {
21576
22038
  stagingDir,
21577
22039
  markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts, runId)
21578
22040
  );
21579
- swapIntoPlace(stagingDir, outDir, () => assertReplaceable(outDir, "outDir", config.secretRules));
22041
+ swapIntoPlace(
22042
+ stagingDir,
22043
+ outDir,
22044
+ () => assertReplaceable(outDir, "outDir", config.secretRules),
22045
+ () => {
22046
+ stagingPreserved = true;
22047
+ }
22048
+ );
21580
22049
  stagingDir = null;
21581
22050
  const warningsBeforeHook = manifest.warnings.length;
21582
22051
  const pendingHook = runAfterGenerate(config, manifest);
21583
22052
  const shipHookState = () => {
21584
22053
  if (!markerBelongsTo(outDir, snapshotId)) return;
21585
22054
  if (artifacts.manifest && manifest.warnings.length !== warningsBeforeHook) {
21586
- writeManifestAtomically(path25__namespace.join(outDir, "manifest.json"), manifest);
22055
+ writeManifestAtomically(path26__namespace.join(outDir, "manifest.json"), manifest);
21587
22056
  recordArtifact(outDir, "manifest.json");
21588
22057
  if (options?.sign !== void 0) {
21589
- const record = signManifest(path25__namespace.join(outDir, "manifest.json"), {
22058
+ const record = signManifest(path26__namespace.join(outDir, "manifest.json"), {
21590
22059
  key: options.sign.key ?? null
21591
22060
  });
21592
22061
  writeArtifact(outDir, SIGNATURE_FILE, JSON.stringify(record, null, 2) + "\n");
@@ -21630,9 +22099,9 @@ function generateSnapshot(configInput, options) {
21630
22099
  }
21631
22100
  return manifest;
21632
22101
  } catch (err) {
21633
- if (stagingDir !== null) {
22102
+ if (stagingDir !== null && !stagingPreserved) {
21634
22103
  try {
21635
- fs24__namespace.rmSync(stagingDir, { recursive: true, force: true });
22104
+ fs25__namespace.rmSync(stagingDir, { recursive: true, force: true });
21636
22105
  } catch {
21637
22106
  }
21638
22107
  }