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.
@@ -2,9 +2,9 @@ import * as crypto from 'crypto';
2
2
  import { createHash, randomBytes, timingSafeEqual, randomUUID } from 'crypto';
3
3
  import { Worker } from 'worker_threads';
4
4
  import { AsyncLocalStorage } from 'async_hooks';
5
- import * as fs24 from 'fs';
5
+ import * as fs25 from 'fs';
6
6
  import * as os2 from 'os';
7
- import * as path25 from 'path';
7
+ import * as path26 from 'path';
8
8
  import ts from 'typescript';
9
9
  import { createRequire } from 'module';
10
10
  import { fileURLToPath, pathToFileURL } from 'url';
@@ -396,9 +396,9 @@ var JAVA_METHOD = /^\s+(?:public|private|protected)\s+(?:static\s+)?(?:final\s+)
396
396
  var jvmProfile = {
397
397
  id: "jvm",
398
398
  extensions: [".java", ".kt", ".kts", ".scala"],
399
- summarize(path26, content) {
399
+ summarize(path27, content) {
400
400
  const summary = emptySummary();
401
- const lower = path26.toLowerCase();
401
+ const lower = path27.toLowerCase();
402
402
  const isJava = lower.endsWith(".java");
403
403
  const isKotlin = lower.endsWith(".kt") || lower.endsWith(".kts");
404
404
  eachLine(content, (line) => {
@@ -621,9 +621,9 @@ var rubyProfile = {
621
621
  eachLine(content, (line) => {
622
622
  const trimmed = line.trim();
623
623
  if (!trimmed || trimmed.startsWith("#")) return;
624
- const relative14 = REQUIRE_RELATIVE.exec(trimmed);
625
- if (relative14) {
626
- summary.imports.push(`./${relative14[1]}`);
624
+ const relative15 = REQUIRE_RELATIVE.exec(trimmed);
625
+ if (relative15) {
626
+ summary.imports.push(`./${relative15[1]}`);
627
627
  return;
628
628
  }
629
629
  const required = REQUIRE.exec(trimmed);
@@ -1006,17 +1006,17 @@ function summarizeTypeScriptSource(relativePath, content) {
1006
1006
  var SCRIPT_BLOCK = /<script([^>]*)>([\s\S]*?)<\/script>/gi;
1007
1007
  var JSX_LANG = /\blang\s*=\s*["']?[tj]sx\b/i;
1008
1008
  var ASTRO_FRONTMATTER = /^\uFEFF?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?=\r?\n|$)/;
1009
- function componentName(path26) {
1010
- const base = path26.split("/").pop() ?? path26;
1009
+ function componentName(path27) {
1010
+ const base = path27.split("/").pop() ?? path27;
1011
1011
  return base.replace(/\.[^.]+$/, "");
1012
1012
  }
1013
1013
  var sfcProfile = {
1014
1014
  id: "sfc",
1015
1015
  extensions: [".vue", ".svelte", ".astro"],
1016
- summarize(path26, content) {
1016
+ summarize(path27, content) {
1017
1017
  let script = "";
1018
- let usesJsx = path26.toLowerCase().endsWith(".astro");
1019
- if (path26.toLowerCase().endsWith(".astro")) {
1018
+ let usesJsx = path27.toLowerCase().endsWith(".astro");
1019
+ if (path27.toLowerCase().endsWith(".astro")) {
1020
1020
  const frontmatter = ASTRO_FRONTMATTER.exec(content);
1021
1021
  if (frontmatter) script += `${frontmatter[1]}
1022
1022
  `;
@@ -1026,7 +1026,7 @@ var sfcProfile = {
1026
1026
  script += `${match[2]}
1027
1027
  `;
1028
1028
  }
1029
- const name = componentName(path26);
1029
+ const name = componentName(path27);
1030
1030
  if (!script.trim()) {
1031
1031
  const summary2 = emptySummary();
1032
1032
  if (name) {
@@ -1217,15 +1217,15 @@ for (const profile of LANGUAGE_PROFILES) {
1217
1217
  BY_EXTENSION.set(extension.toLowerCase(), profile);
1218
1218
  }
1219
1219
  }
1220
- function profileForPath(path26) {
1221
- const lower = path26.toLowerCase();
1220
+ function profileForPath(path27) {
1221
+ const lower = path27.toLowerCase();
1222
1222
  const dot = lower.lastIndexOf(".");
1223
1223
  if (dot === -1) return null;
1224
1224
  return BY_EXTENSION.get(lower.slice(dot)) ?? null;
1225
1225
  }
1226
- function summarizeWithProfile(path26, content) {
1227
- const profile = profileForPath(path26);
1228
- return profile ? profile.summarize(path26, content) : null;
1226
+ function summarizeWithProfile(path27, content) {
1227
+ const profile = profileForPath(path27);
1228
+ return profile ? profile.summarize(path27, content) : null;
1229
1229
  }
1230
1230
  var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
1231
1231
  ".png",
@@ -1270,7 +1270,7 @@ var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
1270
1270
  ".so"
1271
1271
  ]);
1272
1272
  function isBinaryExtension(filePath) {
1273
- const ext = path25.extname(filePath).toLowerCase();
1273
+ const ext = path26.extname(filePath).toLowerCase();
1274
1274
  return BINARY_EXTENSIONS.has(ext);
1275
1275
  }
1276
1276
  function isBinaryBuffer(buffer) {
@@ -1440,13 +1440,13 @@ function isBinaryFile(absolutePath) {
1440
1440
  if (isBinaryExtension(absolutePath)) return true;
1441
1441
  let fd;
1442
1442
  try {
1443
- fd = fs24.openSync(absolutePath, "r");
1443
+ fd = fs25.openSync(absolutePath, "r");
1444
1444
  const buffer = Buffer.alloc(CHUNK);
1445
1445
  let sample2;
1446
1446
  let position = 0;
1447
1447
  while (position < BINARY_SCAN_BYTES) {
1448
1448
  const wanted = Math.min(CHUNK, BINARY_SCAN_BYTES - position);
1449
- const bytesRead = fs24.readSync(fd, buffer, 0, wanted, position);
1449
+ const bytesRead = fs25.readSync(fd, buffer, 0, wanted, position);
1450
1450
  if (bytesRead === 0) return false;
1451
1451
  const chunk = buffer.subarray(0, bytesRead);
1452
1452
  if (sample2 === void 0) {
@@ -1464,7 +1464,7 @@ function isBinaryFile(absolutePath) {
1464
1464
  } finally {
1465
1465
  if (fd !== void 0) {
1466
1466
  try {
1467
- fs24.closeSync(fd);
1467
+ fs25.closeSync(fd);
1468
1468
  } catch {
1469
1469
  }
1470
1470
  }
@@ -1486,9 +1486,9 @@ function importsOfText(relativePath, text2) {
1486
1486
  function importsOfFile(relativePath, absolutePath) {
1487
1487
  let buffer;
1488
1488
  try {
1489
- const stats = fs24.statSync(absolutePath);
1489
+ const stats = fs25.statSync(absolutePath);
1490
1490
  if (!stats.isFile() || stats.size > SUMMARY_MAX_SOURCE_BYTES) return [];
1491
- buffer = fs24.readFileSync(absolutePath);
1491
+ buffer = fs25.readFileSync(absolutePath);
1492
1492
  } catch {
1493
1493
  return [];
1494
1494
  }
@@ -1867,15 +1867,15 @@ var SKIPPED_WALK_DIRS = /* @__PURE__ */ new Set([
1867
1867
  ]);
1868
1868
  function readSmallFile(fullPath) {
1869
1869
  try {
1870
- const stats = fs24.statSync(fullPath);
1870
+ const stats = fs25.statSync(fullPath);
1871
1871
  if (!stats.isFile() || stats.size > MANIFEST_MAX_BYTES) return null;
1872
- return fs24.readFileSync(fullPath, "utf8");
1872
+ return fs25.readFileSync(fullPath, "utf8");
1873
1873
  } catch {
1874
1874
  return null;
1875
1875
  }
1876
1876
  }
1877
1877
  function readManifest(cwd, name) {
1878
- return readSmallFile(path25.join(cwd, name));
1878
+ return readSmallFile(path26.join(cwd, name));
1879
1879
  }
1880
1880
  function dependenciesFromPackageJson(raw) {
1881
1881
  const names = /* @__PURE__ */ new Set();
@@ -1935,7 +1935,7 @@ function pnpmWorkspacePatterns(raw) {
1935
1935
  function childDirectories(cwd, parent) {
1936
1936
  let entries;
1937
1937
  try {
1938
- entries = fs24.readdirSync(path25.join(cwd, parent), { withFileTypes: true });
1938
+ entries = fs25.readdirSync(path26.join(cwd, parent), { withFileTypes: true });
1939
1939
  } catch {
1940
1940
  return [];
1941
1941
  }
@@ -1970,13 +1970,13 @@ function workspacePackageDirs(cwd, patterns) {
1970
1970
  function scanWorkspacePackages(cwd, patterns) {
1971
1971
  const files = /* @__PURE__ */ new Set();
1972
1972
  const dependencies = /* @__PURE__ */ new Set();
1973
- for (const relative14 of workspacePackageDirs(cwd, patterns)) {
1974
- const full = path25.join(cwd, relative14);
1973
+ for (const relative15 of workspacePackageDirs(cwd, patterns)) {
1974
+ const full = path26.join(cwd, relative15);
1975
1975
  try {
1976
- for (const entry of fs24.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
1976
+ for (const entry of fs25.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
1977
1977
  } catch {
1978
1978
  }
1979
- const raw = readSmallFile(path25.join(full, "package.json"));
1979
+ const raw = readSmallFile(path26.join(full, "package.json"));
1980
1980
  if (raw !== null) {
1981
1981
  for (const name of dependenciesFromPackageJson(raw)) dependencies.add(name);
1982
1982
  }
@@ -1986,7 +1986,7 @@ function scanWorkspacePackages(cwd, patterns) {
1986
1986
  var SNAPSHOT_MARKER = ".codebase-snapshot";
1987
1987
  function isToolOwnedDirectory(dir) {
1988
1988
  try {
1989
- return fs24.statSync(dir).isDirectory() && fs24.existsSync(path25.join(dir, SNAPSHOT_MARKER));
1989
+ return fs25.statSync(dir).isDirectory() && fs25.existsSync(path26.join(dir, SNAPSHOT_MARKER));
1990
1990
  } catch {
1991
1991
  return false;
1992
1992
  }
@@ -2001,7 +2001,7 @@ function countMarkdownFiles(cwd) {
2001
2001
  directoriesSeen += 1;
2002
2002
  let entries;
2003
2003
  try {
2004
- entries = fs24.readdirSync(current.dir, { withFileTypes: true });
2004
+ entries = fs25.readdirSync(current.dir, { withFileTypes: true });
2005
2005
  } catch {
2006
2006
  continue;
2007
2007
  }
@@ -2012,7 +2012,7 @@ function countMarkdownFiles(cwd) {
2012
2012
  }
2013
2013
  if (!entry.isDirectory() || current.depth >= 2) continue;
2014
2014
  if (entry.name.startsWith(".") || SKIPPED_WALK_DIRS.has(entry.name)) continue;
2015
- const child = path25.join(current.dir, entry.name);
2015
+ const child = path26.join(current.dir, entry.name);
2016
2016
  if (isToolOwnedDirectory(child)) continue;
2017
2017
  queue.push({ dir: child, depth: current.depth + 1 });
2018
2018
  }
@@ -2023,7 +2023,7 @@ function buildPresetContext(cwd) {
2023
2023
  const files = /* @__PURE__ */ new Set();
2024
2024
  const dirs = /* @__PURE__ */ new Set();
2025
2025
  try {
2026
- for (const entry of fs24.readdirSync(cwd, { withFileTypes: true })) {
2026
+ for (const entry of fs25.readdirSync(cwd, { withFileTypes: true })) {
2027
2027
  if (entry.isDirectory()) dirs.add(entry.name);
2028
2028
  else if (entry.isFile()) files.add(entry.name);
2029
2029
  }
@@ -2040,7 +2040,7 @@ function buildPresetContext(cwd) {
2040
2040
  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;
2041
2041
  let workspace = { files: /* @__PURE__ */ new Set(), dependencies: /* @__PURE__ */ new Set() };
2042
2042
  if (isWorkspace) {
2043
- const pnpmRaw = files.has("pnpm-workspace.yaml") ? readSmallFile(path25.join(cwd, "pnpm-workspace.yaml")) : null;
2043
+ const pnpmRaw = files.has("pnpm-workspace.yaml") ? readSmallFile(path26.join(cwd, "pnpm-workspace.yaml")) : null;
2044
2044
  const declared = pnpmRaw === null ? [] : pnpmWorkspacePatterns(pnpmRaw);
2045
2045
  const patterns = declared.length > 0 ? declared : declaredWorkspaces.length > 0 ? declaredWorkspaces : DEFAULT_WORKSPACE_PATTERNS;
2046
2046
  workspace = scanWorkspacePackages(cwd, patterns);
@@ -3185,7 +3185,7 @@ var DEFAULT_SECRET_PATTERNS = [
3185
3185
  // rendering of textual userinfo mixes cases, while the prose the earlier rules were
3186
3186
  // protecting (`Bearer authentication`) is a lowercase word.
3187
3187
  rule: "authorization-header",
3188
- 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_.+/=-])/
3188
+ 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_.+/=-])/
3189
3189
  },
3190
3190
  {
3191
3191
  // Broader names than before (`apiKey`, `clientSecret`, `privateKey` were
@@ -3763,6 +3763,7 @@ function redactStructuredValues(text2, filePath, recordFinding) {
3763
3763
  if (firstValue === void 0) continue;
3764
3764
  const valueIndent = (/^[ \t]*/.exec(firstValue)?.[0] ?? "").length;
3765
3765
  if (valueIndent <= baseIndent) continue;
3766
+ if (STRUCTURED_KEY.test(firstValue) || /^[ \t]*-[ \t]/.test(firstValue)) continue;
3766
3767
  let masked = false;
3767
3768
  while (cursor < segments.length) {
3768
3769
  const body = segments[cursor] ?? "";
@@ -4006,7 +4007,7 @@ function loadSigningKey(environment = process.env) {
4006
4007
  return crypto.createPrivateKey({ key: pem, format: "pem" });
4007
4008
  }
4008
4009
  function signManifest(manifestPath, options = {}) {
4009
- const bytes = fs24.readFileSync(manifestPath);
4010
+ const bytes = fs25.readFileSync(manifestPath);
4010
4011
  const manifest = JSON.parse(bytes.toString("utf8"));
4011
4012
  if (typeof manifest.fingerprint !== "string" || !/^[0-9a-f]{64}$/.test(manifest.fingerprint)) {
4012
4013
  throw new Error("refusing to sign: the manifest has no valid fingerprint");
@@ -4026,12 +4027,12 @@ function signManifest(manifestPath, options = {}) {
4026
4027
  };
4027
4028
  }
4028
4029
  function verifySnapshotSignature(snapshotDir) {
4029
- const signaturePath = path25.join(snapshotDir, SIGNATURE_FILE);
4030
- const manifestPath = path25.join(snapshotDir, "manifest.json");
4031
- if (!fs24.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
4030
+ const signaturePath = path26.join(snapshotDir, SIGNATURE_FILE);
4031
+ const manifestPath = path26.join(snapshotDir, "manifest.json");
4032
+ if (!fs25.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
4032
4033
  let record;
4033
4034
  try {
4034
- record = JSON.parse(fs24.readFileSync(signaturePath, "utf8"));
4035
+ record = JSON.parse(fs25.readFileSync(signaturePath, "utf8"));
4035
4036
  } catch (error) {
4036
4037
  return { ok: false, reason: "signature.json is not JSON: " + error.message };
4037
4038
  }
@@ -4040,7 +4041,7 @@ function verifySnapshotSignature(snapshotDir) {
4040
4041
  }
4041
4042
  let bytes;
4042
4043
  try {
4043
- bytes = fs24.readFileSync(manifestPath);
4044
+ bytes = fs25.readFileSync(manifestPath);
4044
4045
  } catch {
4045
4046
  return { ok: false, reason: "the signed manifest is missing" };
4046
4047
  }
@@ -4060,7 +4061,7 @@ function verifySnapshotSignature(snapshotDir) {
4060
4061
 
4061
4062
  // src/version.ts
4062
4063
  var GENERATOR_NAME = "codebase-snapshot";
4063
- var GENERATOR_VERSION = "0.20.4";
4064
+ var GENERATOR_VERSION = "0.20.5";
4064
4065
  var SCHEMA_VERSION = "3.0.0";
4065
4066
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
4066
4067
  function isOurGeneratorName(name) {
@@ -4077,14 +4078,14 @@ var PRESET_IGNORES = new Set(
4077
4078
  );
4078
4079
  function readLinkTarget(linkPath, fallback) {
4079
4080
  try {
4080
- return fs24.readlinkSync(linkPath);
4081
+ return fs25.readlinkSync(linkPath);
4081
4082
  } catch {
4082
4083
  return fallback;
4083
4084
  }
4084
4085
  }
4085
4086
  function brokenLinkRecord(linkPath, relativePath, rootReal) {
4086
4087
  const rawTarget = readLinkTarget(linkPath, linkPath);
4087
- const resolvedFallback = path25.resolve(path25.dirname(linkPath), rawTarget);
4088
+ const resolvedFallback = path26.resolve(path26.dirname(linkPath), rawTarget);
4088
4089
  return isInside(rootReal, resolvedFallback) ? { path: relativePath, reason: "read-error", detail: "broken symlink" } : {
4089
4090
  path: relativePath,
4090
4091
  reason: "outside-root",
@@ -4092,8 +4093,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
4092
4093
  };
4093
4094
  }
4094
4095
  function isInside(root, candidate) {
4095
- const relative14 = path25.relative(root, candidate);
4096
- return relative14 === "" || !relative14.startsWith(`..${path25.sep}`) && relative14 !== ".." && !path25.isAbsolute(relative14);
4096
+ const relative15 = path26.relative(root, candidate);
4097
+ return relative15 === "" || !relative15.startsWith(`..${path26.sep}`) && relative15 !== ".." && !path26.isAbsolute(relative15);
4097
4098
  }
4098
4099
  var GIT_OUTPUT_LIMIT = 68157440;
4099
4100
  function getGitInfo(cwd, fallbackBranch = "main") {
@@ -4353,10 +4354,10 @@ function trimUnescapedTrailingSpaces(line) {
4353
4354
  return line.slice(0, end);
4354
4355
  }
4355
4356
  function readGitignoreRules(dir) {
4356
- const gitignorePath2 = path25.join(dir, ".gitignore");
4357
+ const gitignorePath2 = path26.join(dir, ".gitignore");
4357
4358
  let raw;
4358
4359
  try {
4359
- raw = fs24.readFileSync(gitignorePath2, "utf8");
4360
+ raw = fs25.readFileSync(gitignorePath2, "utf8");
4360
4361
  } catch {
4361
4362
  return [];
4362
4363
  }
@@ -4567,7 +4568,7 @@ function listIgnoredPaths(cwd) {
4567
4568
  }
4568
4569
  function hasSnapshotMarker(target) {
4569
4570
  try {
4570
- return fs24.statSync(target).isDirectory() && isToolOwnedDirectory2(target);
4571
+ return fs25.statSync(target).isDirectory() && isToolOwnedDirectory2(target);
4571
4572
  } catch {
4572
4573
  return false;
4573
4574
  }
@@ -4576,7 +4577,7 @@ var IGNORABLE_DIRECTORY_ENTRIES = /* @__PURE__ */ new Set([".DS_Store"]);
4576
4577
  function isToolOwnedDirectory2(dir) {
4577
4578
  let raw;
4578
4579
  try {
4579
- raw = fs24.readFileSync(path25.join(dir, ".codebase-snapshot"), "utf8");
4580
+ raw = fs25.readFileSync(path26.join(dir, ".codebase-snapshot"), "utf8");
4580
4581
  } catch {
4581
4582
  return false;
4582
4583
  }
@@ -4603,7 +4604,7 @@ function isToolOwnedDirectory2(dir) {
4603
4604
  }
4604
4605
  let entries;
4605
4606
  try {
4606
- entries = fs24.readdirSync(dir);
4607
+ entries = fs25.readdirSync(dir);
4607
4608
  } catch {
4608
4609
  return false;
4609
4610
  }
@@ -4622,7 +4623,7 @@ function makeToolOwnedDecider(cwd, toolOwnedPaths) {
4622
4623
  const prefix = parts.slice(0, depth).join("/");
4623
4624
  let hasMarker = markers.get(prefix);
4624
4625
  if (hasMarker === void 0) {
4625
- hasMarker = isToolOwnedDirectory2(path25.join(cwd, prefix));
4626
+ hasMarker = isToolOwnedDirectory2(path26.join(cwd, prefix));
4626
4627
  markers.set(prefix, hasMarker);
4627
4628
  }
4628
4629
  if (hasMarker) return true;
@@ -4637,7 +4638,7 @@ function makeLinkProbe() {
4637
4638
  let known = cache.get(absolutePath);
4638
4639
  if (known === void 0) {
4639
4640
  try {
4640
- known = fs24.lstatSync(absolutePath).isSymbolicLink();
4641
+ known = fs25.lstatSync(absolutePath).isSymbolicLink();
4641
4642
  } catch {
4642
4643
  known = false;
4643
4644
  }
@@ -4650,7 +4651,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
4650
4651
  const isLink = makeLinkProbe();
4651
4652
  let rootReal = cwd;
4652
4653
  try {
4653
- rootReal = fs24.realpathSync(cwd);
4654
+ rootReal = fs25.realpathSync(cwd);
4654
4655
  } catch {
4655
4656
  }
4656
4657
  const reported = /* @__PURE__ */ new Set();
@@ -4665,7 +4666,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
4665
4666
  let linkedPath = null;
4666
4667
  for (let depth = 1; depth <= parts.length; depth += 1) {
4667
4668
  const prefix = parts.slice(0, depth).join("/");
4668
- if (isLink(path25.join(cwd, prefix))) {
4669
+ if (isLink(path26.join(cwd, prefix))) {
4669
4670
  linkedPath = prefix;
4670
4671
  break;
4671
4672
  }
@@ -4674,11 +4675,11 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
4674
4675
  kept.push(candidate);
4675
4676
  continue;
4676
4677
  }
4677
- const absolute = path25.join(cwd, linkedPath);
4678
+ const absolute = path26.join(cwd, linkedPath);
4678
4679
  const rawTarget = readLinkTarget(absolute, absolute);
4679
4680
  let targetReal = null;
4680
4681
  try {
4681
- targetReal = fs24.realpathSync(absolute);
4682
+ targetReal = fs25.realpathSync(absolute);
4682
4683
  } catch {
4683
4684
  targetReal = null;
4684
4685
  }
@@ -4696,7 +4697,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
4696
4697
  }
4697
4698
  let stats = null;
4698
4699
  try {
4699
- stats = fs24.statSync(absolute);
4700
+ stats = fs25.statSync(absolute);
4700
4701
  } catch {
4701
4702
  stats = null;
4702
4703
  }
@@ -4720,7 +4721,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
4720
4721
  });
4721
4722
  continue;
4722
4723
  }
4723
- const targetRelative = path25.relative(rootReal, targetReal).split(path25.sep).join("/");
4724
+ const targetRelative = path26.relative(rootReal, targetReal).split(path26.sep).join("/");
4724
4725
  if (isSensitivePath(targetRelative)) {
4725
4726
  report2(linkedPath, {
4726
4727
  path: linkedPath,
@@ -4793,7 +4794,7 @@ function collectFiles(cwd, options = {}) {
4793
4794
  "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."
4794
4795
  );
4795
4796
  }
4796
- if (fs24.existsSync(path25.join(cwd, ".git"))) {
4797
+ if (fs25.existsSync(path26.join(cwd, ".git"))) {
4797
4798
  throw new Error(
4798
4799
  "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."
4799
4800
  );
@@ -4812,7 +4813,7 @@ function collectFiles(cwd, options = {}) {
4812
4813
  candidates.push(extra);
4813
4814
  }
4814
4815
  }
4815
- const files = candidates.filter((file) => {
4816
+ let files = candidates.filter((file) => {
4816
4817
  if (isToolOwned(file)) return false;
4817
4818
  const ignored = defaultIgnoreReason(file, toolDirNames);
4818
4819
  if (ignored) {
@@ -4857,11 +4858,53 @@ function collectFiles(cwd, options = {}) {
4857
4858
  }
4858
4859
  return true;
4859
4860
  }).sort();
4861
+ files = dropSymlinksToUnincludedTargets(cwd, files, skipped);
4860
4862
  return { files, skipped: maskSkipPaths(skipped, pathRules) };
4861
4863
  }
4864
+ function dropSymlinksToUnincludedTargets(cwd, files, skipped) {
4865
+ const aliases = /* @__PURE__ */ new Set();
4866
+ for (const file of files) {
4867
+ try {
4868
+ if (fs25.lstatSync(path26.join(cwd, file)).isSymbolicLink()) aliases.add(file);
4869
+ } catch {
4870
+ }
4871
+ }
4872
+ if (aliases.size === 0) return [...files];
4873
+ const includedTargets = /* @__PURE__ */ new Set();
4874
+ for (const file of files) {
4875
+ try {
4876
+ includedTargets.add(fs25.realpathSync(path26.join(cwd, file)));
4877
+ } catch {
4878
+ }
4879
+ }
4880
+ const kept = [];
4881
+ for (const file of files) {
4882
+ if (!aliases.has(file)) {
4883
+ kept.push(file);
4884
+ continue;
4885
+ }
4886
+ let target;
4887
+ try {
4888
+ target = fs25.realpathSync(path26.join(cwd, file));
4889
+ } catch {
4890
+ skipped.push({ path: file, reason: "read-error", detail: "symlink target could not be resolved" });
4891
+ continue;
4892
+ }
4893
+ if (includedTargets.has(target)) {
4894
+ kept.push(file);
4895
+ continue;
4896
+ }
4897
+ skipped.push({
4898
+ path: file,
4899
+ reason: "symlink",
4900
+ detail: "link target was excluded from the snapshot; not followed"
4901
+ });
4902
+ }
4903
+ return kept;
4904
+ }
4862
4905
  function rootRealFor(root) {
4863
4906
  try {
4864
- return fs24.realpathSync(root);
4907
+ return fs25.realpathSync(root);
4865
4908
  } catch {
4866
4909
  return root;
4867
4910
  }
@@ -4870,18 +4913,18 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
4870
4913
  const results = { files: [], skipped: [] };
4871
4914
  const stack = [];
4872
4915
  const toolDirNames = toolDirNamesFor(reservedPaths);
4873
- const relativeToBase = (target) => path25.relative(baseDir, target).replace(/\\/g, "/") || ".";
4916
+ const relativeToBase = (target) => path26.relative(baseDir, target).replace(/\\/g, "/") || ".";
4874
4917
  const enter = (current, layers) => {
4875
4918
  if (visited.has(current)) return false;
4876
4919
  visited.add(current);
4877
4920
  const localRules = readGitignoreRules(current);
4878
4921
  const gitignoreLayers = localRules.length === 0 ? layers : [
4879
4922
  ...layers,
4880
- { prefix: path25.relative(baseDir, current).replace(/\\/g, "/"), rules: localRules }
4923
+ { prefix: path26.relative(baseDir, current).replace(/\\/g, "/"), rules: localRules }
4881
4924
  ];
4882
4925
  let entries;
4883
4926
  try {
4884
- entries = fs24.readdirSync(current, { withFileTypes: true });
4927
+ entries = fs25.readdirSync(current, { withFileTypes: true });
4885
4928
  } catch {
4886
4929
  results.skipped.push({
4887
4930
  path: relativeToBase(current),
@@ -4903,8 +4946,8 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
4903
4946
  }
4904
4947
  const entry = frame.entries[frame.index];
4905
4948
  frame.index += 1;
4906
- const fullPath = path25.join(frame.dir, entry.name);
4907
- const relPath = path25.relative(baseDir, fullPath).replace(/\\/g, "/");
4949
+ const fullPath = path26.join(frame.dir, entry.name);
4950
+ const relPath = path26.relative(baseDir, fullPath).replace(/\\/g, "/");
4908
4951
  if (reservedPaths.has(relPath)) continue;
4909
4952
  if (entry.isDirectory() && DEFAULT_IGNORED_DIRS.includes(entry.name)) {
4910
4953
  results.skipped.push({
@@ -4937,14 +4980,14 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
4937
4980
  if (entry.isSymbolicLink()) {
4938
4981
  let targetReal;
4939
4982
  try {
4940
- targetReal = fs24.realpathSync(fullPath);
4983
+ targetReal = fs25.realpathSync(fullPath);
4941
4984
  } catch {
4942
4985
  results.skipped.push(brokenLinkRecord(fullPath, relPath, rootReal));
4943
4986
  continue;
4944
4987
  }
4945
4988
  let stats;
4946
4989
  try {
4947
- stats = fs24.statSync(fullPath);
4990
+ stats = fs25.statSync(fullPath);
4948
4991
  } catch {
4949
4992
  results.skipped.push({ path: relPath, reason: "read-error", detail: "unreadable symlink" });
4950
4993
  continue;
@@ -4974,7 +5017,7 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
4974
5017
  });
4975
5018
  continue;
4976
5019
  }
4977
- const targetRelative = path25.relative(rootReal, targetReal).split(path25.sep).join("/");
5020
+ const targetRelative = path26.relative(rootReal, targetReal).split(path26.sep).join("/");
4978
5021
  if (isSensitivePath(targetRelative)) {
4979
5022
  results.skipped.push({
4980
5023
  path: relPath,
@@ -5030,20 +5073,20 @@ var CONFIG_FILENAMES = [
5030
5073
  ];
5031
5074
  function findConfigFile(cwd) {
5032
5075
  for (const filename of CONFIG_FILENAMES) {
5033
- const fullPath = path25.join(cwd, filename);
5076
+ const fullPath = path26.join(cwd, filename);
5034
5077
  let stats = null;
5035
5078
  try {
5036
- stats = fs24.statSync(fullPath);
5079
+ stats = fs25.statSync(fullPath);
5037
5080
  } catch {
5038
- if (fs24.existsSync(fullPath)) return fullPath;
5081
+ if (fs25.existsSync(fullPath)) return fullPath;
5039
5082
  continue;
5040
5083
  }
5041
5084
  if (stats.isFile()) return fullPath;
5042
5085
  }
5043
- const pkgJsonPath = path25.join(cwd, "package.json");
5044
- if (!fs24.existsSync(pkgJsonPath)) return null;
5086
+ const pkgJsonPath = path26.join(cwd, "package.json");
5087
+ if (!fs25.existsSync(pkgJsonPath)) return null;
5045
5088
  try {
5046
- const parsed = JSON.parse(stripJsonComments(fs24.readFileSync(pkgJsonPath, "utf8")));
5089
+ const parsed = JSON.parse(stripJsonComments(fs25.readFileSync(pkgJsonPath, "utf8")));
5047
5090
  const snapshot = parsed?.snapshot;
5048
5091
  return typeof snapshot === "object" && snapshot !== null && !Array.isArray(snapshot) ? pkgJsonPath : null;
5049
5092
  } catch {
@@ -5258,10 +5301,10 @@ function readConfigExport(exported, file) {
5258
5301
  var lastModuleConfig = null;
5259
5302
  function moduleConfigKey(fullPath) {
5260
5303
  try {
5261
- return createHash("sha256").update(fs24.readFileSync(fullPath)).digest("hex").slice(0, 24);
5304
+ return createHash("sha256").update(fs25.readFileSync(fullPath)).digest("hex").slice(0, 24);
5262
5305
  } catch {
5263
5306
  try {
5264
- const stats = fs24.statSync(fullPath);
5307
+ const stats = fs25.statSync(fullPath);
5265
5308
  return `stat-${stats.mtimeMs}-${stats.size}`;
5266
5309
  } catch {
5267
5310
  return "unreadable";
@@ -5287,7 +5330,7 @@ async function importConfigModule(fullPath) {
5287
5330
  function attachConfigDir(config, filePath) {
5288
5331
  if (typeof config === "object" && config !== null) {
5289
5332
  Object.defineProperty(config, CONFIG_DIR_SYMBOL, {
5290
- value: path25.dirname(filePath),
5333
+ value: path26.dirname(filePath),
5291
5334
  enumerable: false,
5292
5335
  configurable: true
5293
5336
  });
@@ -5299,12 +5342,12 @@ async function loadConfigFileDetailed(cwd, options = {}) {
5299
5342
  const errors = [];
5300
5343
  const configDirectories = [];
5301
5344
  for (const filename of CONFIG_FILENAMES) {
5302
- const fullPath = path25.join(cwd, filename);
5345
+ const fullPath = path26.join(cwd, filename);
5303
5346
  let candidateStats = null;
5304
5347
  try {
5305
- candidateStats = fs24.statSync(fullPath);
5348
+ candidateStats = fs25.statSync(fullPath);
5306
5349
  } catch {
5307
- if (!fs24.existsSync(fullPath)) continue;
5350
+ if (!fs25.existsSync(fullPath)) continue;
5308
5351
  }
5309
5352
  if (candidateStats !== null && !candidateStats.isFile()) {
5310
5353
  configDirectories.push(fullPath);
@@ -5312,7 +5355,7 @@ async function loadConfigFileDetailed(cwd, options = {}) {
5312
5355
  }
5313
5356
  if (filename.endsWith(".json") || filename === ".snapshotrc") {
5314
5357
  try {
5315
- const config = parseJsonish(fs24.readFileSync(fullPath, "utf8"), fullPath);
5358
+ const config = parseJsonish(fs25.readFileSync(fullPath, "utf8"), fullPath);
5316
5359
  if (config === null || typeof config !== "object" || Array.isArray(config)) {
5317
5360
  throw new Error(
5318
5361
  `${fullPath} does not hold a configuration object (received ${describeValue2(config)}).`
@@ -5352,10 +5395,10 @@ async function loadConfigFileDetailed(cwd, options = {}) {
5352
5395
  continue;
5353
5396
  }
5354
5397
  }
5355
- const pkgJsonPath = path25.join(cwd, "package.json");
5356
- if (fs24.existsSync(pkgJsonPath)) {
5398
+ const pkgJsonPath = path26.join(cwd, "package.json");
5399
+ if (fs25.existsSync(pkgJsonPath)) {
5357
5400
  try {
5358
- const parsed = parseJsonish(fs24.readFileSync(pkgJsonPath, "utf8"), pkgJsonPath);
5401
+ const parsed = parseJsonish(fs25.readFileSync(pkgJsonPath, "utf8"), pkgJsonPath);
5359
5402
  const snapshotKey = parsed.snapshot;
5360
5403
  if (snapshotKey && typeof snapshotKey === "object" && !Array.isArray(snapshotKey)) {
5361
5404
  assertKnownConfigKeys(
@@ -5530,27 +5573,27 @@ function readConfiguredBrief(cwd, value) {
5530
5573
  }
5531
5574
  const rootReal = (() => {
5532
5575
  try {
5533
- return fs24.realpathSync(cwd);
5576
+ return fs25.realpathSync(cwd);
5534
5577
  } catch {
5535
- return path25.resolve(cwd);
5578
+ return path26.resolve(cwd);
5536
5579
  }
5537
5580
  })();
5538
- const requested = path25.resolve(cwd, value);
5581
+ const requested = path26.resolve(cwd, value);
5539
5582
  let filePath;
5540
5583
  try {
5541
- filePath = fs24.realpathSync(requested);
5584
+ filePath = fs25.realpathSync(requested);
5542
5585
  } catch {
5543
5586
  throw new Error(
5544
5587
  'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
5545
5588
  );
5546
5589
  }
5547
- const relative14 = path25.relative(rootReal, filePath);
5548
- if (relative14.length === 0 || relative14 === ".." || relative14.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative14)) {
5590
+ const relative15 = path26.relative(rootReal, filePath);
5591
+ if (relative15.length === 0 || relative15 === ".." || relative15.startsWith(`..${path26.sep}`) || path26.isAbsolute(relative15)) {
5549
5592
  throw new Error(
5550
5593
  'brief "' + value + '" resolves outside the repository. A brief must be a file inside the repository being described; an absolute or parent path is refused.'
5551
5594
  );
5552
5595
  }
5553
- const posixRelative = relative14.split(path25.sep).join("/");
5596
+ const posixRelative = relative15.split(path26.sep).join("/");
5554
5597
  if (isSensitivePath(posixRelative) || isSensitivePath(value)) {
5555
5598
  throw new Error(
5556
5599
  'brief "' + value + '" is a credential-bearing file. A snapshot must not reproduce secrets, so it cannot be used as the owner brief.'
@@ -5558,8 +5601,8 @@ function readConfiguredBrief(cwd, value) {
5558
5601
  }
5559
5602
  let text2;
5560
5603
  try {
5561
- if (!fs24.statSync(filePath).isFile()) throw new Error("not a file");
5562
- text2 = fs24.readFileSync(filePath, "utf8");
5604
+ if (!fs25.statSync(filePath).isFile()) throw new Error("not a file");
5605
+ text2 = fs25.readFileSync(filePath, "utf8");
5563
5606
  } catch {
5564
5607
  throw new Error(
5565
5608
  'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
@@ -5671,12 +5714,12 @@ function resolveKindRules(value) {
5671
5714
  function outputExcludePatterns(cwd, outDir, tmpDir) {
5672
5715
  const patterns = [];
5673
5716
  for (const dir of [outDir, tmpDir]) {
5674
- const absolute = path25.resolve(cwd, dir);
5675
- const relative14 = path25.relative(cwd, absolute);
5676
- if (!relative14 || relative14 === ".." || relative14.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative14)) {
5717
+ const absolute = path26.resolve(cwd, dir);
5718
+ const relative15 = path26.relative(cwd, absolute);
5719
+ if (!relative15 || relative15 === ".." || relative15.startsWith(`..${path26.sep}`) || path26.isAbsolute(relative15)) {
5677
5720
  continue;
5678
5721
  }
5679
- patterns.push(`${relative14.replace(/\\/g, "/")}/**`);
5722
+ patterns.push(`${relative15.replace(/\\/g, "/")}/**`);
5680
5723
  }
5681
5724
  return patterns;
5682
5725
  }
@@ -5806,11 +5849,11 @@ function resolveCandidateCwd(userConfig, cliOptions, baseDir) {
5806
5849
  );
5807
5850
  }
5808
5851
  const candidate = cliOptions?.cwd || userConfig?.cwd || baseDir || process.cwd();
5809
- const resolved = path25.resolve(candidate);
5810
- if (!fs24.existsSync(resolved)) {
5852
+ const resolved = path26.resolve(candidate);
5853
+ if (!fs25.existsSync(resolved)) {
5811
5854
  throw new Error(`Working directory does not exist: ${resolved}`);
5812
5855
  }
5813
- if (!fs24.statSync(resolved).isDirectory()) {
5856
+ if (!fs25.statSync(resolved).isDirectory()) {
5814
5857
  throw new Error(`Working directory is not a directory: ${resolved}`);
5815
5858
  }
5816
5859
  return resolved;
@@ -6436,6 +6479,9 @@ function countLines(content) {
6436
6479
  const last = content.charCodeAt(content.length - 1);
6437
6480
  return last === 10 || last === 13 ? breaks : breaks + 1;
6438
6481
  }
6482
+ function countBodyLines(content) {
6483
+ return content.length === 0 ? 0 : content.split("\n").length;
6484
+ }
6439
6485
  function truncateToBytes(content, maxBytes) {
6440
6486
  if (maxBytes <= 0) return { content: "", isTruncated: content.length > 0 };
6441
6487
  const buffer = Buffer.from(content, "utf8");
@@ -6794,7 +6840,7 @@ function applyTruncatedContent(file, content, reason) {
6794
6840
  file.truncationReason = reason;
6795
6841
  file.omittedRanges = keptLines >= file.originalLines ? file.originalLines > 0 ? [[file.originalLines, file.originalLines]] : [] : [[keptLines + 1, file.originalLines]];
6796
6842
  file.includedBytes = Buffer.byteLength(content, "utf8");
6797
- file.includedLines = countLines(content);
6843
+ file.includedLines = countBodyLines(content);
6798
6844
  }
6799
6845
  function rehashPart(part, markdown) {
6800
6846
  const estimatedTokens = estimateTokens(markdown.replace(TOKEN_LINE, ""));
@@ -6929,7 +6975,7 @@ function renderFileSection(file) {
6929
6975
  const content = file.content ?? "";
6930
6976
  const body = emittedBody(content);
6931
6977
  file.includedBytes = Buffer.byteLength(body, "utf8");
6932
- file.includedLines = countLines(body);
6978
+ file.includedLines = countBodyLines(body);
6933
6979
  const fence = fenceForContent(content);
6934
6980
  const anchor = anchorForPath(file.relativePath);
6935
6981
  return [
@@ -7224,10 +7270,10 @@ function resolveImport(from, specifier, byPath) {
7224
7270
  if (segment === "..") parts.pop();
7225
7271
  else parts.push(segment);
7226
7272
  }
7227
- const path26 = parts.join("/");
7228
- const withoutExtension = path26.replace(/\.[cm]?[jt]sx?$/, "");
7273
+ const path27 = parts.join("/");
7274
+ const withoutExtension = path27.replace(/\.[cm]?[jt]sx?$/, "");
7229
7275
  const candidates = [
7230
- path26,
7276
+ path27,
7231
7277
  withoutExtension + ".ts",
7232
7278
  withoutExtension + ".tsx",
7233
7279
  withoutExtension + ".js",
@@ -7236,18 +7282,18 @@ function resolveImport(from, specifier, byPath) {
7236
7282
  withoutExtension + ".go",
7237
7283
  withoutExtension + ".rs",
7238
7284
  withoutExtension + "/index.ts",
7239
- path26 + ".ts",
7240
- path26 + ".tsx",
7241
- path26 + ".js",
7242
- path26 + ".jsx",
7243
- path26 + ".mjs",
7244
- path26 + ".cjs",
7245
- path26 + ".py",
7246
- path26 + ".go",
7247
- path26 + ".rs",
7248
- path26 + ".java",
7249
- path26 + "/index.ts",
7250
- path26 + "/index.js"
7285
+ path27 + ".ts",
7286
+ path27 + ".tsx",
7287
+ path27 + ".js",
7288
+ path27 + ".jsx",
7289
+ path27 + ".mjs",
7290
+ path27 + ".cjs",
7291
+ path27 + ".py",
7292
+ path27 + ".go",
7293
+ path27 + ".rs",
7294
+ path27 + ".java",
7295
+ path27 + "/index.ts",
7296
+ path27 + "/index.js"
7251
7297
  ];
7252
7298
  for (const candidate of candidates) {
7253
7299
  const found = byPath.get(candidate);
@@ -7276,12 +7322,12 @@ function planForQuestion(manifest, question, options = {}) {
7276
7322
  const scored = [];
7277
7323
  for (const file of manifest.files) {
7278
7324
  if (isTest(file) && !wantsTests) continue;
7279
- const path26 = file.relativePath.toLowerCase();
7280
- const words = path26.split(/[^a-z0-9_]+/).filter((word) => word.length >= 3);
7325
+ const path27 = file.relativePath.toLowerCase();
7326
+ const words = path27.split(/[^a-z0-9_]+/).filter((word) => word.length >= 3);
7281
7327
  let score = 0;
7282
7328
  const reasons = [];
7283
7329
  for (const term of terms) {
7284
- if (path26.includes(term)) {
7330
+ if (path27.includes(term)) {
7285
7331
  score += 8;
7286
7332
  reasons.push("path:" + term);
7287
7333
  continue;
@@ -7468,24 +7514,119 @@ function stripComments2(text2, relativePath) {
7468
7514
  return { text: pieces.join(""), removed };
7469
7515
  }
7470
7516
  function runGit(cwd, args) {
7471
- const result = spawnSync("git", args, { cwd, encoding: "utf8", windowsHide: true, maxBuffer: 64 * 1024 * 1024 });
7517
+ const result = spawnSync(
7518
+ "git",
7519
+ ["-c", "core.quotepath=false", "-c", "diff.noprefix=false", ...args],
7520
+ { cwd, encoding: "utf8", windowsHide: true, maxBuffer: 64 * 1024 * 1024 }
7521
+ );
7472
7522
  if (result.status !== 0) return { ok: false, out: (result.stderr ?? "").trim() };
7473
7523
  return { ok: true, out: result.stdout ?? "" };
7474
7524
  }
7475
7525
  function isGitRepository(cwd) {
7476
7526
  return runGit(cwd, ["rev-parse", "--is-inside-work-tree"]).out.trim() === "true";
7477
7527
  }
7528
+ function unquoteGitPath(value) {
7529
+ if (!value.startsWith('"') || !value.endsWith('"')) return value;
7530
+ const body = value.slice(1, -1);
7531
+ let out = "";
7532
+ let bytes = [];
7533
+ const flushBytes = () => {
7534
+ if (bytes.length === 0) return;
7535
+ out += Buffer.from(bytes).toString("utf8");
7536
+ bytes = [];
7537
+ };
7538
+ const escapes = {
7539
+ a: "\x07",
7540
+ b: "\b",
7541
+ f: "\f",
7542
+ n: "\n",
7543
+ r: "\r",
7544
+ t: " ",
7545
+ v: "\v",
7546
+ "\\": "\\",
7547
+ '"': '"'
7548
+ };
7549
+ for (let index = 0; index < body.length; index += 1) {
7550
+ const char = body[index];
7551
+ if (char !== "\\") {
7552
+ flushBytes();
7553
+ out += char;
7554
+ continue;
7555
+ }
7556
+ const next = body[index + 1];
7557
+ if (next === void 0) {
7558
+ flushBytes();
7559
+ out += "\\";
7560
+ break;
7561
+ }
7562
+ index += 1;
7563
+ if (/[0-7]/.test(next)) {
7564
+ let octal = next;
7565
+ while (octal.length < 3 && /[0-7]/.test(body[index + 1] ?? "")) {
7566
+ index += 1;
7567
+ octal += body[index];
7568
+ }
7569
+ bytes.push(Number.parseInt(octal, 8) & 255);
7570
+ continue;
7571
+ }
7572
+ flushBytes();
7573
+ out += escapes[next] ?? next;
7574
+ }
7575
+ flushBytes();
7576
+ return out;
7577
+ }
7578
+ function takeGitPath(value) {
7579
+ if (value.length === 0) return null;
7580
+ if (value.startsWith('"')) {
7581
+ let index = 1;
7582
+ while (index < value.length) {
7583
+ if (value[index] === "\\") {
7584
+ index += 2;
7585
+ continue;
7586
+ }
7587
+ if (value[index] === '"') {
7588
+ return { token: value.slice(0, index + 1), rest: value.slice(index + 1).replace(/^ /, "") };
7589
+ }
7590
+ index += 1;
7591
+ }
7592
+ return null;
7593
+ }
7594
+ const space = value.indexOf(" ");
7595
+ if (space === -1) return { token: value, rest: "" };
7596
+ return { token: value.slice(0, space), rest: value.slice(space + 1) };
7597
+ }
7598
+ function pathFromGitToken(token, prefix) {
7599
+ const unquoted = unquoteGitPath(token);
7600
+ if (unquoted === "/dev/null") return null;
7601
+ if (!unquoted.startsWith(prefix)) return null;
7602
+ return unquoted.slice(prefix.length);
7603
+ }
7478
7604
  function diffSectionPaths(body) {
7479
7605
  const paths = /* @__PURE__ */ new Set();
7480
7606
  for (const line of body.split("\n")) {
7481
- const plus = /^\+\+\+ b\/(.*)$/.exec(line);
7482
- if (plus !== null) paths.add(plus[1]);
7483
- const minus = /^--- a\/(.*)$/.exec(line);
7484
- if (minus !== null) paths.add(minus[1]);
7485
- const header = /^diff --git a\/(.*?) b\/(.*)$/.exec(line);
7486
- if (header !== null) {
7487
- paths.add(header[1]);
7488
- paths.add(header[2]);
7607
+ if (line.startsWith("diff --git ")) {
7608
+ const first = takeGitPath(line.slice("diff --git ".length));
7609
+ if (first === null) continue;
7610
+ const second = takeGitPath(first.rest);
7611
+ if (second === null) continue;
7612
+ const left = pathFromGitToken(first.token, "a/");
7613
+ const right = pathFromGitToken(second.token, "b/");
7614
+ if (left !== null) paths.add(left);
7615
+ if (right !== null) paths.add(right);
7616
+ continue;
7617
+ }
7618
+ if (line.startsWith("+++ ")) {
7619
+ const token = takeGitPath(line.slice(4));
7620
+ if (token === null) continue;
7621
+ const path27 = pathFromGitToken(token.token, "b/");
7622
+ if (path27 !== null) paths.add(path27);
7623
+ continue;
7624
+ }
7625
+ if (line.startsWith("--- ")) {
7626
+ const token = takeGitPath(line.slice(4));
7627
+ if (token === null) continue;
7628
+ const path27 = pathFromGitToken(token.token, "a/");
7629
+ if (path27 !== null) paths.add(path27);
7489
7630
  }
7490
7631
  }
7491
7632
  return [...paths];
@@ -7496,6 +7637,7 @@ function generateDiffReport(cwd, options = {}) {
7496
7637
  const sections = [];
7497
7638
  let truncated = false;
7498
7639
  let omittedSensitive = 0;
7640
+ let omittedUnparseable = 0;
7499
7641
  const commands = [
7500
7642
  ["Unstaged", ["diff", "--no-color"]],
7501
7643
  ["Staged", ["diff", "--cached", "--no-color"]]
@@ -7506,7 +7648,11 @@ function generateDiffReport(cwd, options = {}) {
7506
7648
  const rawSections = result.out.split(/(?=^diff --git )/m).filter((section) => section.length > 0);
7507
7649
  for (const rawSection of rawSections) {
7508
7650
  const paths2 = diffSectionPaths(rawSection);
7509
- const blocked = paths2.some((path26) => isSensitivePath(path26) || options.excluded?.(path26) === true);
7651
+ if (paths2.length === 0) {
7652
+ omittedUnparseable += 1;
7653
+ continue;
7654
+ }
7655
+ const blocked = paths2.some((path27) => isSensitivePath(path27) || options.excluded?.(path27) === true);
7510
7656
  if (blocked) {
7511
7657
  omittedSensitive += 1;
7512
7658
  continue;
@@ -7517,7 +7663,13 @@ function generateDiffReport(cwd, options = {}) {
7517
7663
  truncated = true;
7518
7664
  break;
7519
7665
  }
7520
- const chunk = truncateToBytes(rawSection, remaining);
7666
+ const sourcePath = paths2[0] ?? "reports/diff.md";
7667
+ const redactedSection = scanAndRedactSecrets(
7668
+ rawSection,
7669
+ options.secretRules ?? [],
7670
+ sourcePath
7671
+ ).redacted;
7672
+ const chunk = truncateToBytes(redactedSection, remaining);
7521
7673
  if (chunk.isTruncated) truncated = true;
7522
7674
  sections.push(
7523
7675
  "## " + title + " changes\n\nRun: git " + args.join(" ") + "\n\n```diff\n" + chunk.content + "\n```"
@@ -7527,7 +7679,7 @@ function generateDiffReport(cwd, options = {}) {
7527
7679
  }
7528
7680
  if (sections.length === 0) return null;
7529
7681
  const paths = /* @__PURE__ */ new Set();
7530
- for (const section of sections) for (const path26 of diffSectionPaths(section)) paths.add(path26);
7682
+ for (const section of sections) for (const path27 of diffSectionPaths(section)) paths.add(path27);
7531
7683
  const joined = [
7532
7684
  "# Uncommitted changes",
7533
7685
  "",
@@ -7538,6 +7690,10 @@ function generateDiffReport(cwd, options = {}) {
7538
7690
  "> " + omittedSensitive + " file section(s) omitted: their path is credential-bearing or excluded from the snapshot.",
7539
7691
  ""
7540
7692
  ] : [],
7693
+ ...omittedUnparseable > 0 ? [
7694
+ "> " + omittedUnparseable + " file section(s) omitted: their diff header could not be attributed to a path, so the sensitive-path filter could not run.",
7695
+ ""
7696
+ ] : [],
7541
7697
  ...sections,
7542
7698
  ...truncated ? ["", "> Truncated at " + maxBytes + " bytes. Run git diff for the rest."] : [],
7543
7699
  ""
@@ -7810,7 +7966,7 @@ function systemSection(manifest, code, brief, escape, sawManifest) {
7810
7966
  " A change here reaches the most call sites; read it before judging anything that uses it."
7811
7967
  );
7812
7968
  }
7813
- 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);
7969
+ 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);
7814
7970
  out.push(
7815
7971
  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"
7816
7972
  );
@@ -8041,12 +8197,12 @@ function ownerNotesSection(brief, code, text2) {
8041
8197
  if (brief === void 0 || brief.notes.length === 0) return [];
8042
8198
  const out = ["## Owner notes", ""];
8043
8199
  for (const note of brief.notes) {
8044
- out.push("### " + note.heading, "", ...ownerBlock(note.body, brief.path, code, text2), "");
8200
+ out.push("### " + text2(note.heading), "", ...ownerBlock(note.body, brief.path, code, text2), "");
8045
8201
  }
8046
8202
  return out;
8047
8203
  }
8048
- function ownerBlock(body, path26, code, escape) {
8049
- return ["> Written by the project owner in " + code(path26) + ", not generated.", "", escape(body)];
8204
+ function ownerBlock(body, path27, code, escape) {
8205
+ return ["> Written by the project owner in " + code(path27) + ", not generated.", "", escape(body)];
8050
8206
  }
8051
8207
  function snapshotSection(manifest, code, partsWritten) {
8052
8208
  const out = ["## This snapshot", ""];
@@ -8262,27 +8418,31 @@ function generateReadme(manifest, artifacts) {
8262
8418
  const readOrder = [];
8263
8419
  if (wrote("prompt")) {
8264
8420
  readOrder.push(
8265
- "1. Hand `PROMPT.md` to the model that receives this snapshot: it names the parts, the partial files and the fingerprint of this run."
8421
+ "Hand `PROMPT.md` to the model that receives this snapshot: it names the parts, the partial files and the fingerprint of this run."
8266
8422
  );
8267
8423
  }
8268
8424
  if (wrote("navigation") || wrote("projectTree")) {
8269
8425
  const first = [wrote("navigation") ? "`reports/navigation.md`" : null, wrote("projectTree") ? "`reports/project-tree.md`" : null].filter(Boolean).join(" or ");
8270
- readOrder.push(`1. Read ${first} first to locate target features or files.`);
8426
+ readOrder.push(`Read ${first} first to locate target features or files.`);
8271
8427
  }
8272
8428
  if (wrote("parts")) {
8273
8429
  readOrder.push(
8274
- `${readOrder.length + 1}. Open only the specific \`parts/part-XXX.md\` file holding the target modules.`
8430
+ "Open only the specific `parts/part-XXX.md` file holding the target modules."
8275
8431
  );
8276
8432
  }
8277
8433
  if (wrote("manifest")) {
8278
- readOrder.push(
8279
- `${readOrder.length + 1}. Inspect \`manifest.json\` for precise dependency and AST symbol maps.`
8280
- );
8434
+ readOrder.push("Inspect `manifest.json` for precise dependency and AST symbol maps.");
8281
8435
  }
8282
8436
  readOrder.push(
8283
- 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.`
8437
+ 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."
8438
+ );
8439
+ lines.push(
8440
+ "",
8441
+ "## AI Agent Ingestion Guide",
8442
+ "",
8443
+ ...readOrder.map((step, index) => `${index + 1}. ${step}`),
8444
+ ""
8284
8445
  );
8285
- lines.push("", "## AI Agent Ingestion Guide", "", ...readOrder, "");
8286
8446
  return lines.join("\n");
8287
8447
  }
8288
8448
 
@@ -8412,7 +8572,7 @@ function resolveChangedScope(cwd, request) {
8412
8572
  const descriptions = [];
8413
8573
  if (request.changedSince !== void 0) {
8414
8574
  assertUsableRef(request.changedSince);
8415
- for (const path26 of gitPaths(cwd, [
8575
+ for (const path27 of gitPaths(cwd, [
8416
8576
  "diff",
8417
8577
  "--name-only",
8418
8578
  "-z",
@@ -8420,9 +8580,9 @@ function resolveChangedScope(cwd, request) {
8420
8580
  `${request.changedSince}...HEAD`,
8421
8581
  "--"
8422
8582
  ])) {
8423
- paths.add(path26);
8583
+ paths.add(path27);
8424
8584
  }
8425
- for (const path26 of gitPaths(cwd, [
8585
+ for (const path27 of gitPaths(cwd, [
8426
8586
  "diff",
8427
8587
  "--name-only",
8428
8588
  "-z",
@@ -8430,15 +8590,15 @@ function resolveChangedScope(cwd, request) {
8430
8590
  "HEAD",
8431
8591
  "--"
8432
8592
  ])) {
8433
- paths.add(path26);
8593
+ paths.add(path27);
8434
8594
  }
8435
- for (const path26 of gitPaths(cwd, ["ls-files", "--others", "--exclude-standard", "-z", "--"])) {
8436
- paths.add(path26);
8595
+ for (const path27 of gitPaths(cwd, ["ls-files", "--others", "--exclude-standard", "-z", "--"])) {
8596
+ paths.add(path27);
8437
8597
  }
8438
8598
  descriptions.push(`changed since ${request.changedSince}`);
8439
8599
  }
8440
8600
  if (request.staged === true) {
8441
- for (const path26 of gitPaths(cwd, [
8601
+ for (const path27 of gitPaths(cwd, [
8442
8602
  "diff",
8443
8603
  "--cached",
8444
8604
  "--name-only",
@@ -8446,10 +8606,10 @@ function resolveChangedScope(cwd, request) {
8446
8606
  "--relative",
8447
8607
  "--"
8448
8608
  ])) {
8449
- paths.add(path26);
8450
- stagedPaths.add(path26);
8609
+ paths.add(path27);
8610
+ stagedPaths.add(path27);
8451
8611
  }
8452
- for (const path26 of gitPaths(cwd, [
8612
+ for (const path27 of gitPaths(cwd, [
8453
8613
  "diff",
8454
8614
  "--cached",
8455
8615
  "--name-only",
@@ -8458,7 +8618,7 @@ function resolveChangedScope(cwd, request) {
8458
8618
  "--diff-filter=D",
8459
8619
  "--"
8460
8620
  ])) {
8461
- deletedPaths.add(path26);
8621
+ deletedPaths.add(path27);
8462
8622
  }
8463
8623
  descriptions.push("staged");
8464
8624
  }
@@ -8496,10 +8656,10 @@ var PYTHON_SUFFIXES = [".py", ".pyi", "/__init__.py", "/__init__.pyi"];
8496
8656
  var CASE_INSENSITIVE_FILESYSTEM = process.platform === "win32" || process.platform === "darwin";
8497
8657
  var TSCONFIG_CACHE = /* @__PURE__ */ new Map();
8498
8658
  function tsconfigPathsFor(cwd) {
8499
- const configPath = path25.join(cwd, "tsconfig.json");
8659
+ const configPath = path26.join(cwd, "tsconfig.json");
8500
8660
  let stats;
8501
8661
  try {
8502
- stats = fs24.statSync(configPath);
8662
+ stats = fs25.statSync(configPath);
8503
8663
  } catch (err) {
8504
8664
  if (err.code === "ENOENT") return null;
8505
8665
  return null;
@@ -8533,8 +8693,8 @@ function tsconfigPathsFor(cwd) {
8533
8693
  return value;
8534
8694
  }
8535
8695
  function repositoryRelative(cwd, target) {
8536
- const relative14 = path25.relative(cwd, target).replace(/\\/g, "/");
8537
- return relative14.length === 0 || !relative14.startsWith("..") && !path25.isAbsolute(relative14) ? relative14 : null;
8696
+ const relative15 = path26.relative(cwd, target).replace(/\\/g, "/");
8697
+ return relative15.length === 0 || !relative15.startsWith("..") && !path26.isAbsolute(relative15) ? relative15 : null;
8538
8698
  }
8539
8699
  function rememberFirst(map, key, value) {
8540
8700
  if (!map.has(key)) map.set(key, value);
@@ -8549,15 +8709,15 @@ function buildImportResolver(files, options = {}) {
8549
8709
  if (CASE_INSENSITIVE_FILESYSTEM) {
8550
8710
  rememberFirst(byPathFolded, relativePath.toLowerCase(), relativePath);
8551
8711
  }
8552
- const extension = path25.posix.extname(relativePath);
8712
+ const extension = path26.posix.extname(relativePath);
8553
8713
  if (!SOURCE_EXTENSIONS.has(extension)) return;
8554
8714
  const stem = relativePath.slice(0, -extension.length);
8555
8715
  rememberFirst(byStem, stem, relativePath);
8556
8716
  if (CASE_INSENSITIVE_FILESYSTEM) {
8557
8717
  rememberFirst(byStemFolded, stem.toLowerCase(), relativePath);
8558
8718
  }
8559
- if (path25.posix.basename(stem) === "index") {
8560
- const directory = path25.posix.dirname(stem);
8719
+ if (path26.posix.basename(stem) === "index") {
8720
+ const directory = path26.posix.dirname(stem);
8561
8721
  rememberFirst(byStem, directory, relativePath);
8562
8722
  if (CASE_INSENSITIVE_FILESYSTEM) {
8563
8723
  rememberFirst(byStemFolded, directory.toLowerCase(), relativePath);
@@ -8573,7 +8733,7 @@ function buildImportResolver(files, options = {}) {
8573
8733
  return { byPath, byPathFolded, byStem, byStemFolded, tsconfig: options.tsconfig ?? null };
8574
8734
  }
8575
8735
  function resolveSpecifier(fromFile, specifier, resolver) {
8576
- const extension = path25.posix.extname(fromFile).toLowerCase();
8736
+ const extension = path26.posix.extname(fromFile).toLowerCase();
8577
8737
  const exact = (key) => resolver.byPath.get(key) ?? (CASE_INSENSITIVE_FILESYSTEM ? resolver.byPathFolded.get(key.toLowerCase()) : void 0) ?? null;
8578
8738
  const firstOf = (candidates) => {
8579
8739
  for (const candidate of candidates) {
@@ -8596,34 +8756,34 @@ function resolveSpecifier(fromFile, specifier, resolver) {
8596
8756
  if (PYTHON_EXTENSIONS.has(extension) && specifier.startsWith(".")) {
8597
8757
  const dots = /^\.+/.exec(specifier)?.[0].length ?? 0;
8598
8758
  const rest = specifier.slice(dots).replace(/\./g, "/");
8599
- let base = path25.posix.dirname(fromFile);
8600
- for (let up = 1; up < dots; up += 1) base = path25.posix.dirname(base);
8601
- const joined2 = rest ? path25.posix.normalize(path25.posix.join(base, rest)) : base;
8759
+ let base = path26.posix.dirname(fromFile);
8760
+ for (let up = 1; up < dots; up += 1) base = path26.posix.dirname(base);
8761
+ const joined2 = rest ? path26.posix.normalize(path26.posix.join(base, rest)) : base;
8602
8762
  return firstOf([joined2, ...PYTHON_SUFFIXES.map((suffix) => `${joined2}${suffix}`)]);
8603
8763
  }
8604
8764
  if (RUBY_EXTENSIONS.has(extension) && specifier.startsWith("./")) {
8605
- const joined2 = path25.posix.normalize(
8606
- path25.posix.join(path25.posix.dirname(fromFile), specifier)
8765
+ const joined2 = path26.posix.normalize(
8766
+ path26.posix.join(path26.posix.dirname(fromFile), specifier)
8607
8767
  );
8608
8768
  return firstOf([`${joined2}.rb`, joined2]);
8609
8769
  }
8610
8770
  if (C_EXTENSIONS.has(extension) && specifier.startsWith("./")) {
8611
- const joined2 = path25.posix.normalize(
8612
- path25.posix.join(path25.posix.dirname(fromFile), specifier)
8771
+ const joined2 = path26.posix.normalize(
8772
+ path26.posix.join(path26.posix.dirname(fromFile), specifier)
8613
8773
  );
8614
8774
  return exact(joined2);
8615
8775
  }
8616
8776
  if (extension === ".dart" && !specifier.includes(":")) {
8617
- const joined2 = path25.posix.normalize(
8618
- path25.posix.join(path25.posix.dirname(fromFile), specifier)
8777
+ const joined2 = path26.posix.normalize(
8778
+ path26.posix.join(path26.posix.dirname(fromFile), specifier)
8619
8779
  );
8620
8780
  return firstOf([joined2, `${joined2}.dart`]);
8621
8781
  }
8622
8782
  if (!RELATIVE_SPECIFIER.test(specifier)) {
8623
8783
  return resolveTsconfigSpecifier(specifier, resolver, lookupPath);
8624
8784
  }
8625
- const joined = path25.posix.normalize(
8626
- path25.posix.join(path25.posix.dirname(fromFile), specifier)
8785
+ const joined = path26.posix.normalize(
8786
+ path26.posix.join(path26.posix.dirname(fromFile), specifier)
8627
8787
  );
8628
8788
  return lookupPath(joined);
8629
8789
  }
@@ -8647,13 +8807,13 @@ function resolveTsconfigSpecifier(specifier, resolver, lookupPath) {
8647
8807
  if (captured === null) continue;
8648
8808
  for (const target of rule.targets) {
8649
8809
  const substituted = target.split("*").join(captured);
8650
- const base = config.baseUrl === null ? substituted : path25.posix.join(config.baseUrl, substituted);
8651
- const hit = lookupPath(path25.posix.normalize(base));
8810
+ const base = config.baseUrl === null ? substituted : path26.posix.join(config.baseUrl, substituted);
8811
+ const hit = lookupPath(path26.posix.normalize(base));
8652
8812
  if (hit) return hit;
8653
8813
  }
8654
8814
  }
8655
8815
  if (config.baseUrl !== null) {
8656
- return lookupPath(path25.posix.normalize(path25.posix.join(config.baseUrl, specifier)));
8816
+ return lookupPath(path26.posix.normalize(path26.posix.join(config.baseUrl, specifier)));
8657
8817
  }
8658
8818
  return null;
8659
8819
  }
@@ -8675,13 +8835,13 @@ function readProjectOverview(cwd) {
8675
8835
  }
8676
8836
  function readText(file) {
8677
8837
  try {
8678
- return fs24.readFileSync(file, "utf8");
8838
+ return fs25.readFileSync(file, "utf8");
8679
8839
  } catch {
8680
8840
  return null;
8681
8841
  }
8682
8842
  }
8683
8843
  function readDescription(cwd) {
8684
- const raw = readText(path25.join(cwd, "package.json"));
8844
+ const raw = readText(path26.join(cwd, "package.json"));
8685
8845
  if (raw === null) return {};
8686
8846
  try {
8687
8847
  const parsed = JSON.parse(stripJsonComments(raw));
@@ -8691,7 +8851,7 @@ function readDescription(cwd) {
8691
8851
  }
8692
8852
  }
8693
8853
  function readSummary(cwd) {
8694
- const raw = readText(path25.join(cwd, "README.md"));
8854
+ const raw = readText(path26.join(cwd, "README.md"));
8695
8855
  if (raw === null) return {};
8696
8856
  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, "'");
8697
8857
  const paragraph = [];
@@ -8717,7 +8877,7 @@ function truncate(text2, limit) {
8717
8877
  return (space > limit / 2 ? window.slice(0, space) : window).trim() + "\u2026";
8718
8878
  }
8719
8879
  function readReleases(cwd) {
8720
- const raw = readText(path25.join(cwd, "CHANGELOG.md"));
8880
+ const raw = readText(path26.join(cwd, "CHANGELOG.md"));
8721
8881
  if (raw === null) return [];
8722
8882
  const headings = raw.split(/\r?\n/).map((line) => /^##\s+(.+?)\s*$/.exec(line)?.[1]?.trim()).filter((heading) => heading !== void 0 && /^v?\d+\.\d+/.test(heading));
8723
8883
  return headings.slice(0, MAX_RELEASES);
@@ -8779,10 +8939,10 @@ var LANGUAGE_BY_BASENAME = {
8779
8939
  };
8780
8940
  function detectLanguage(filePath) {
8781
8941
  const normalized = filePath.replace(/\\/g, "/");
8782
- const base = path25.posix.basename(normalized);
8942
+ const base = path26.posix.basename(normalized);
8783
8943
  if (LANGUAGE_BY_BASENAME[base]) return LANGUAGE_BY_BASENAME[base];
8784
8944
  if (base === ".env" || base.startsWith(".env.")) return "dotenv";
8785
- const ext = path25.posix.extname(base).toLowerCase();
8945
+ const ext = path26.posix.extname(base).toLowerCase();
8786
8946
  return LANGUAGE_BY_EXTENSION[ext] ?? "text";
8787
8947
  }
8788
8948
  function maskedPath(value, secretRules) {
@@ -8790,33 +8950,33 @@ function maskedPath(value, secretRules) {
8790
8950
  }
8791
8951
  function confineToDirectory(directory, filename) {
8792
8952
  if (filename.includes("\0")) return null;
8793
- if (path25.isAbsolute(filename)) return null;
8794
- const base = path25.resolve(directory);
8795
- const resolved = path25.resolve(base, filename);
8953
+ if (path26.isAbsolute(filename)) return null;
8954
+ const base = path26.resolve(directory);
8955
+ const resolved = path26.resolve(base, filename);
8796
8956
  const caseInsensitive = process.platform === "win32" || process.platform === "darwin";
8797
- const prefix = caseInsensitive ? `${base}${path25.sep}`.toLowerCase() : `${base}${path25.sep}`;
8957
+ const prefix = caseInsensitive ? `${base}${path26.sep}`.toLowerCase() : `${base}${path26.sep}`;
8798
8958
  const candidate = caseInsensitive ? resolved.toLowerCase() : resolved;
8799
8959
  return candidate.startsWith(prefix) ? resolved : null;
8800
8960
  }
8801
8961
  function findStagingDirectory(config) {
8802
- const tmpDir = path25.resolve(config.cwd, config.tmpDir);
8962
+ const tmpDir = path26.resolve(config.cwd, config.tmpDir);
8803
8963
  let entries;
8804
8964
  try {
8805
- entries = fs24.readdirSync(tmpDir);
8965
+ entries = fs25.readdirSync(tmpDir);
8806
8966
  } catch {
8807
8967
  return null;
8808
8968
  }
8809
8969
  const runs = entries.filter((name) => name.startsWith("run-")).sort();
8810
8970
  const newest = runs[runs.length - 1];
8811
- return newest ? path25.join(tmpDir, newest) : null;
8971
+ return newest ? path26.join(tmpDir, newest) : null;
8812
8972
  }
8813
8973
  function describeMissingManifest(config, manifestPath) {
8814
- const outDir = path25.resolve(config.cwd, config.outDir);
8815
- const markerPath = path25.join(outDir, ".codebase-snapshot");
8974
+ const outDir = path26.resolve(config.cwd, config.outDir);
8975
+ const markerPath = path26.join(outDir, ".codebase-snapshot");
8816
8976
  let marker2 = null;
8817
8977
  try {
8818
- if (fs24.existsSync(markerPath)) {
8819
- const parsed = JSON.parse(fs24.readFileSync(markerPath, "utf8"));
8978
+ if (fs25.existsSync(markerPath)) {
8979
+ const parsed = JSON.parse(fs25.readFileSync(markerPath, "utf8"));
8820
8980
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
8821
8981
  marker2 = parsed;
8822
8982
  }
@@ -8851,13 +9011,13 @@ function sha256Hex(buffer) {
8851
9011
  return crypto.createHash("sha256").update(buffer).digest("hex");
8852
9012
  }
8853
9013
  function wouldNowBeIncluded(cwd, relativePath) {
8854
- const absolutePath = path25.join(cwd, relativePath);
9014
+ const absolutePath = path26.join(cwd, relativePath);
8855
9015
  try {
8856
- const stats = fs24.statSync(absolutePath);
9016
+ const stats = fs25.statSync(absolutePath);
8857
9017
  if (!stats.isFile()) return false;
8858
9018
  if (isBinaryExtension(absolutePath)) return false;
8859
9019
  if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) return false;
8860
- return !decodeText(fs24.readFileSync(absolutePath)).binary;
9020
+ return !decodeText(fs25.readFileSync(absolutePath)).binary;
8861
9021
  } catch {
8862
9022
  return false;
8863
9023
  }
@@ -8869,7 +9029,7 @@ var TRUNCATION_REASONS = /* @__PURE__ */ new Set([
8869
9029
  ]);
8870
9030
  function isConfinedRelative(value) {
8871
9031
  if (value.length === 0 || value.includes("\0") || value.includes("\\")) return false;
8872
- if (path25.isAbsolute(value)) return false;
9032
+ if (path26.isAbsolute(value)) return false;
8873
9033
  return !value.split("/").includes("..");
8874
9034
  }
8875
9035
  function describeManifestShapeProblem(value) {
@@ -9063,7 +9223,7 @@ function describeManifestShapeProblem(value) {
9063
9223
  if (typeof filename !== "string" || filename.trim() === "") {
9064
9224
  return 'a "parts" entry has no "filename"';
9065
9225
  }
9066
- if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path25.isAbsolute(filename)) {
9226
+ if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path26.isAbsolute(filename)) {
9067
9227
  return 'a "parts" entry "filename" must be a bare filename inside parts/';
9068
9228
  }
9069
9229
  if (currentSchema) {
@@ -9089,8 +9249,8 @@ function describeManifestShapeProblem(value) {
9089
9249
  function validateSnapshot(configInput) {
9090
9250
  assertUsableConfigInput(configInput);
9091
9251
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput);
9092
- const manifestPath = path25.resolve(config.cwd, config.outDir, "manifest.json");
9093
- if (!fs24.existsSync(manifestPath)) {
9252
+ const manifestPath = path26.resolve(config.cwd, config.outDir, "manifest.json");
9253
+ if (!fs25.existsSync(manifestPath)) {
9094
9254
  return {
9095
9255
  valid: false,
9096
9256
  manifestPresent: false,
@@ -9101,7 +9261,7 @@ function validateSnapshot(configInput) {
9101
9261
  }
9102
9262
  let manifest;
9103
9263
  try {
9104
- manifest = JSON.parse(fs24.readFileSync(manifestPath, "utf8"));
9264
+ manifest = JSON.parse(fs25.readFileSync(manifestPath, "utf8"));
9105
9265
  } catch (err) {
9106
9266
  return {
9107
9267
  valid: false,
@@ -9123,7 +9283,7 @@ function validateSnapshot(configInput) {
9123
9283
  }
9124
9284
  const drift = emptyDrift();
9125
9285
  const warnings = [];
9126
- const snapshotDir = path25.resolve(config.cwd, config.outDir);
9286
+ const snapshotDir = path26.resolve(config.cwd, config.outDir);
9127
9287
  const unreadableSkips = manifest.skipped.filter(
9128
9288
  (entry) => entry.reason === "missing" || entry.reason === "read-error"
9129
9289
  );
@@ -9231,7 +9391,7 @@ function validateSnapshot(configInput) {
9231
9391
  );
9232
9392
  return importsChangedFile(
9233
9393
  diskFile,
9234
- importsOfFile(diskFile, path25.join(config.cwd, diskFile)),
9394
+ importsOfFile(diskFile, path26.join(config.cwd, diskFile)),
9235
9395
  unchangedScope,
9236
9396
  dependentResolver
9237
9397
  );
@@ -9245,12 +9405,16 @@ function validateSnapshot(configInput) {
9245
9405
  // discovery mode" meant `validate` could enumerate files one way while the snapshot
9246
9406
  // had been generated another way, and then blame the difference on drift.
9247
9407
  discovery: config.discovery,
9408
+ // `generate --staged` adds index-only paths to the candidate list. Without the same
9409
+ // extra paths, a staged file that is absent from the working tree was invisible to
9410
+ // this scan and then reported as deleted, although the snapshot matched the index.
9411
+ ...stagedScope === null ? {} : { extraPaths: [...stagedScope] },
9248
9412
  // The same exclusion `generate` applies: without it, `validate` recounted the tool's
9249
9413
  // own output directory as a set of files missing from the snapshot, so a correct
9250
9414
  // snapshot was reported as drifting.
9251
9415
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
9252
- (directory) => path25.relative(config.cwd, path25.resolve(config.cwd, directory)).replace(/\\/g, "/")
9253
- ).filter((relative14) => relative14.length > 0 && !relative14.startsWith(".."))
9416
+ (directory) => path26.relative(config.cwd, path26.resolve(config.cwd, directory)).replace(/\\/g, "/")
9417
+ ).filter((relative15) => relative15.length > 0 && !relative15.startsWith(".."))
9254
9418
  });
9255
9419
  for (const diskFile of collection.files) {
9256
9420
  const snapshotHash = manifestFileMap.get(diskFile);
@@ -9277,7 +9441,7 @@ function validateSnapshot(configInput) {
9277
9441
  let diskHash;
9278
9442
  try {
9279
9443
  const stagedBlob = recordedStaged && stagedScope?.has(diskFile) === true ? readStagedBlob(config.cwd, diskFile) : null;
9280
- diskHash = sha256Hex(stagedBlob ?? fs24.readFileSync(path25.join(config.cwd, diskFile)));
9444
+ diskHash = sha256Hex(stagedBlob ?? fs25.readFileSync(path26.join(config.cwd, diskFile)));
9281
9445
  } catch (err) {
9282
9446
  if (err.code === "ENOENT") {
9283
9447
  drift.missingOnDisk.push(diskFile);
@@ -9291,6 +9455,12 @@ function validateSnapshot(configInput) {
9291
9455
  }
9292
9456
  }
9293
9457
  for (const snapshotFile of manifestFileMap.keys()) {
9458
+ if (recordedStaged && stagedScope?.has(snapshotFile)) {
9459
+ if (readStagedBlob(config.cwd, snapshotFile) === null) {
9460
+ drift.missingOnDisk.push(snapshotFile);
9461
+ }
9462
+ continue;
9463
+ }
9294
9464
  const confined = confineToDirectory(config.cwd, snapshotFile);
9295
9465
  if (confined === null) {
9296
9466
  drift.partIssues.push({
@@ -9301,7 +9471,7 @@ function validateSnapshot(configInput) {
9301
9471
  }
9302
9472
  let statFailure = null;
9303
9473
  try {
9304
- fs24.statSync(confined);
9474
+ fs25.statSync(confined);
9305
9475
  } catch (err) {
9306
9476
  statFailure = err;
9307
9477
  }
@@ -9321,7 +9491,7 @@ function validateSnapshot(configInput) {
9321
9491
  ...Object.values(config.budgets.byLayer)
9322
9492
  );
9323
9493
  const partNames = /* @__PURE__ */ new Set();
9324
- const partsDir = path25.join(snapshotDir, "parts");
9494
+ const partsDir = path26.join(snapshotDir, "parts");
9325
9495
  for (const part of manifest.parts) {
9326
9496
  if (!part || typeof part.filename !== "string") continue;
9327
9497
  partNames.add(part.filename);
@@ -9336,7 +9506,7 @@ function validateSnapshot(configInput) {
9336
9506
  }
9337
9507
  let buffer;
9338
9508
  try {
9339
- buffer = fs24.readFileSync(partPath);
9509
+ buffer = fs25.readFileSync(partPath);
9340
9510
  } catch {
9341
9511
  drift.partIssues.push({ part: part.filename, issue: "missing from snapshot/parts" });
9342
9512
  continue;
@@ -9713,11 +9883,11 @@ function validateSnapshot(configInput) {
9713
9883
  ];
9714
9884
  for (const [key, artifact] of declaredArtifacts) {
9715
9885
  if (!artifact) continue;
9716
- const artifactPath = path25.join(snapshotDir, ...key.split("/"));
9886
+ const artifactPath = path26.join(snapshotDir, ...key.split("/"));
9717
9887
  let buffer;
9718
9888
  try {
9719
- if (!fs24.statSync(artifactPath).isFile()) throw new Error("not a regular file");
9720
- buffer = fs24.readFileSync(artifactPath);
9889
+ if (!fs25.statSync(artifactPath).isFile()) throw new Error("not a regular file");
9890
+ buffer = fs25.readFileSync(artifactPath);
9721
9891
  } catch {
9722
9892
  drift.partIssues.push({ part: key, issue: "declared artifact is missing" });
9723
9893
  continue;
@@ -9730,9 +9900,9 @@ function validateSnapshot(configInput) {
9730
9900
  for (const match of buffer.toString("utf8").matchAll(/\]\(([^)\s]+)\)/g)) {
9731
9901
  const target = match[1].split("#")[0];
9732
9902
  if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
9733
- const resolved = path25.resolve(snapshotDir, "reports", target);
9734
- const relative14 = path25.relative(snapshotDir, resolved);
9735
- if (relative14.startsWith("..") || path25.isAbsolute(relative14) || !fs24.existsSync(resolved)) {
9903
+ const resolved = path26.resolve(snapshotDir, "reports", target);
9904
+ const relative15 = path26.relative(snapshotDir, resolved);
9905
+ if (relative15.startsWith("..") || path26.isAbsolute(relative15) || !fs25.existsSync(resolved)) {
9736
9906
  drift.partIssues.push({
9737
9907
  part: key,
9738
9908
  issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
@@ -9745,7 +9915,7 @@ function validateSnapshot(configInput) {
9745
9915
  if (sarifArtifact) {
9746
9916
  const sarifKey = "reports/audit.sarif";
9747
9917
  try {
9748
- const buffer = fs24.readFileSync(path25.join(snapshotDir, "reports", "audit.sarif"));
9918
+ const buffer = fs25.readFileSync(path26.join(snapshotDir, "reports", "audit.sarif"));
9749
9919
  if (sha256Hex(buffer) !== sarifArtifact.sha256 || buffer.length !== sarifArtifact.byteSize) {
9750
9920
  drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
9751
9921
  }
@@ -9791,9 +9961,9 @@ function validateSnapshot(configInput) {
9791
9961
  `${drift.configMismatches.length} configuration mismatch(es) between the manifest and this run.`
9792
9962
  );
9793
9963
  }
9794
- const signaturePath = path25.join(path25.dirname(manifestPath), "signature.json");
9795
- if (fs24.existsSync(signaturePath)) {
9796
- const outcome = verifySnapshotSignature(path25.dirname(manifestPath));
9964
+ const signaturePath = path26.join(path26.dirname(manifestPath), "signature.json");
9965
+ if (fs25.existsSync(signaturePath)) {
9966
+ const outcome = verifySnapshotSignature(path26.dirname(manifestPath));
9797
9967
  if (!outcome.ok) errors.push("signature: " + outcome.reason + ".");
9798
9968
  }
9799
9969
  if (manifest.slice !== void 0 || manifest.budget !== void 0) {
@@ -9899,9 +10069,11 @@ function isPrivateIPv6(groups) {
9899
10069
  ]);
9900
10070
  if (allZeroThrough(5) && sixth === 65535) return mapped(6);
9901
10071
  if (allZeroThrough(6) && (seventh !== 0 || eighth !== 0)) return mapped(6);
10072
+ if (allZeroThrough(4) && fifth === 65535 && sixth === 0) return mapped(6);
9902
10073
  if (first === 100 && second === 65435 && third === 0 && fourth === 0 && fifth === 0 && sixth === 0) {
9903
10074
  return mapped(6);
9904
10075
  }
10076
+ if (first === 100 && second === 65435 && third === 1) return mapped(6);
9905
10077
  if (first === 8194) return mapped(1);
9906
10078
  return false;
9907
10079
  }
@@ -9934,7 +10106,7 @@ function parseRemoteSource(input, options = {}) {
9934
10106
  const directory = fileURLToPath(url2);
9935
10107
  return {
9936
10108
  ok: true,
9937
- source: { kind: "file", url: trimmed, host: "file", owner: "", repo: path25.basename(directory), ref: null }
10109
+ source: { kind: "file", url: trimmed, host: "file", owner: "", repo: path26.basename(directory), ref: null }
9938
10110
  };
9939
10111
  }
9940
10112
  let url;
@@ -10012,64 +10184,72 @@ function gitEnvironment(token, host) {
10012
10184
  async function cloneRepository(source, options) {
10013
10185
  const log = options.log ?? (() => {
10014
10186
  });
10015
- const dest = path25.resolve(options.dest);
10016
- fs24.rmSync(dest, { recursive: true, force: true });
10017
- fs24.mkdirSync(dest, { recursive: true });
10018
- const ref = options.ref ?? source.ref;
10019
- const args = [
10020
- "-c",
10021
- "http.followRedirects=false",
10022
- ...source.kind === "https" ? ["-c", "protocol.file.allow=never", "-c", "protocol.ssh.allow=never"] : [],
10023
- "clone",
10024
- "--depth",
10025
- "1",
10026
- "--single-branch",
10027
- "--no-tags",
10028
- "--quiet"
10029
- ];
10030
- if (ref !== void 0 && ref !== null && ref !== "") {
10031
- args.push("--branch", ref);
10032
- }
10033
- args.push(source.url, dest);
10034
- log("clone: " + source.url + (ref ? " (" + ref + ")" : ""));
10035
- const started = Date.now();
10036
- const result = spawnSync("git", args, {
10037
- env: {
10038
- ...gitEnvironment(options.token, source.host === "file" ? "localhost" : source.host),
10039
- ...source.kind === "https" ? { GIT_ALLOW_PROTOCOL: "https" } : {}
10040
- },
10041
- timeout: options.timeoutMs ?? 18e4,
10042
- encoding: "utf8",
10043
- windowsHide: true
10044
- });
10045
- if (result.error !== void 0 && result.error !== null) {
10046
- throw new Error("git clone could not run: " + result.error.message);
10047
- }
10048
- if (result.status !== 0) {
10049
- const detail = (result.stderr ?? "").trim().split("\n").slice(-3).join(" ");
10050
- throw new Error("git clone failed (exit " + result.status + "): " + (detail || "no output"));
10051
- }
10052
- const head = spawnSync("git", ["-C", dest, "rev-parse", "HEAD"], { encoding: "utf8", windowsHide: true });
10053
- const commit = head.status === 0 ? (head.stdout ?? "").trim() : "";
10054
- if (commit === "") throw new Error("the clone has no HEAD; refusing to describe it");
10055
- const bytes = directorySize(dest);
10056
- log("clone: " + (bytes / 1024 / 1024).toFixed(1) + " MB in " + ((Date.now() - started) / 1e3).toFixed(1) + "s");
10057
- if (bytes > 1e9) {
10058
- throw new Error("the clone is larger than 1 GB (" + Math.round(bytes / 1024 / 1024) + " MB); refusing to scan it");
10059
- }
10060
- return {
10061
- directory: dest,
10062
- commit,
10063
- provenance: {
10064
- url: source.url,
10065
- host: source.host,
10066
- owner: source.owner,
10067
- repo: source.repo,
10068
- ref: ref !== void 0 && ref !== null && ref !== "" ? ref : null,
10187
+ const dest = path26.resolve(options.dest);
10188
+ fs25.rmSync(dest, { recursive: true, force: true });
10189
+ fs25.mkdirSync(dest, { recursive: true });
10190
+ try {
10191
+ const ref = options.ref ?? source.ref;
10192
+ const args = [
10193
+ "-c",
10194
+ "http.followRedirects=false",
10195
+ ...source.kind === "https" ? ["-c", "protocol.file.allow=never", "-c", "protocol.ssh.allow=never"] : [],
10196
+ "clone",
10197
+ "--depth",
10198
+ "1",
10199
+ "--single-branch",
10200
+ "--no-tags",
10201
+ "--quiet"
10202
+ ];
10203
+ if (ref !== void 0 && ref !== null && ref !== "") {
10204
+ args.push("--branch", ref);
10205
+ }
10206
+ args.push(source.url, dest);
10207
+ log("clone: " + source.url + (ref ? " (" + ref + ")" : ""));
10208
+ const started = Date.now();
10209
+ const result = spawnSync("git", args, {
10210
+ env: {
10211
+ ...gitEnvironment(options.token, source.host === "file" ? "localhost" : source.host),
10212
+ ...source.kind === "https" ? { GIT_ALLOW_PROTOCOL: "https" } : {}
10213
+ },
10214
+ timeout: options.timeoutMs ?? 18e4,
10215
+ encoding: "utf8",
10216
+ windowsHide: true
10217
+ });
10218
+ if (result.error !== void 0 && result.error !== null) {
10219
+ throw new Error("git clone could not run: " + result.error.message);
10220
+ }
10221
+ if (result.status !== 0) {
10222
+ const detail = (result.stderr ?? "").trim().split("\n").slice(-3).join(" ");
10223
+ throw new Error("git clone failed (exit " + result.status + "): " + (detail || "no output"));
10224
+ }
10225
+ const head = spawnSync("git", ["-C", dest, "rev-parse", "HEAD"], { encoding: "utf8", windowsHide: true });
10226
+ const commit = head.status === 0 ? (head.stdout ?? "").trim() : "";
10227
+ if (commit === "") throw new Error("the clone has no HEAD; refusing to describe it");
10228
+ const bytes = directorySize(dest);
10229
+ log("clone: " + (bytes / 1024 / 1024).toFixed(1) + " MB in " + ((Date.now() - started) / 1e3).toFixed(1) + "s");
10230
+ if (bytes > 1e9) {
10231
+ throw new Error("the clone is larger than 1 GB (" + Math.round(bytes / 1024 / 1024) + " MB); refusing to scan it");
10232
+ }
10233
+ return {
10234
+ directory: dest,
10069
10235
  commit,
10070
- fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
10236
+ provenance: {
10237
+ url: source.url,
10238
+ host: source.host,
10239
+ owner: source.owner,
10240
+ repo: source.repo,
10241
+ ref: ref !== void 0 && ref !== null && ref !== "" ? ref : null,
10242
+ commit,
10243
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
10244
+ }
10245
+ };
10246
+ } catch (error) {
10247
+ try {
10248
+ fs25.rmSync(dest, { recursive: true, force: true });
10249
+ } catch {
10071
10250
  }
10072
- };
10251
+ throw error;
10252
+ }
10073
10253
  }
10074
10254
  function directorySize(root) {
10075
10255
  let total = 0;
@@ -10078,16 +10258,16 @@ function directorySize(root) {
10078
10258
  const current = stack.pop();
10079
10259
  let entries;
10080
10260
  try {
10081
- entries = fs24.readdirSync(current, { withFileTypes: true });
10261
+ entries = fs25.readdirSync(current, { withFileTypes: true });
10082
10262
  } catch {
10083
10263
  continue;
10084
10264
  }
10085
10265
  for (const entry of entries) {
10086
- const full = path25.join(current, entry.name);
10266
+ const full = path26.join(current, entry.name);
10087
10267
  if (entry.isDirectory()) stack.push(full);
10088
10268
  else if (entry.isFile()) {
10089
10269
  try {
10090
- total += fs24.statSync(full).size;
10270
+ total += fs25.statSync(full).size;
10091
10271
  } catch {
10092
10272
  }
10093
10273
  }
@@ -10096,7 +10276,7 @@ function directorySize(root) {
10096
10276
  return total;
10097
10277
  }
10098
10278
  function makeCloneDirectory() {
10099
- return fs24.mkdtempSync(path25.join(os2.tmpdir(), "codebase-snapshot-clone-"));
10279
+ return fs25.mkdtempSync(path26.join(os2.tmpdir(), "codebase-snapshot-clone-"));
10100
10280
  }
10101
10281
 
10102
10282
  // src/mcp/instructions.ts
@@ -10377,8 +10557,8 @@ function findSection(sections, relativePath) {
10377
10557
  if (exact) return exact;
10378
10558
  const foldedPath = rendered.toLowerCase();
10379
10559
  const folded = sections.filter((section) => {
10380
- const path26 = section.path.toLowerCase();
10381
- return path26 === relativePath.toLowerCase() || path26 === foldedPath;
10560
+ const path27 = section.path.toLowerCase();
10561
+ return path27 === relativePath.toLowerCase() || path27 === foldedPath;
10382
10562
  });
10383
10563
  return folded.length === 1 ? folded[0] : null;
10384
10564
  }
@@ -10405,14 +10585,14 @@ function sha256(buffer) {
10405
10585
  }
10406
10586
  function readBytes(file) {
10407
10587
  try {
10408
- return fs24.readFileSync(file);
10588
+ return fs25.readFileSync(file);
10409
10589
  } catch {
10410
10590
  return null;
10411
10591
  }
10412
10592
  }
10413
10593
  function readText2(file) {
10414
10594
  try {
10415
- return fs24.readFileSync(file, "utf8");
10595
+ return fs25.readFileSync(file, "utf8");
10416
10596
  } catch {
10417
10597
  return null;
10418
10598
  }
@@ -10429,15 +10609,15 @@ function readJson(file) {
10429
10609
  function walk(dir, prefix = "") {
10430
10610
  let entries;
10431
10611
  try {
10432
- entries = fs24.readdirSync(dir, { withFileTypes: true });
10612
+ entries = fs25.readdirSync(dir, { withFileTypes: true });
10433
10613
  } catch {
10434
10614
  return [];
10435
10615
  }
10436
10616
  const files = [];
10437
10617
  for (const entry of entries) {
10438
- const relative14 = prefix === "" ? entry.name : prefix + "/" + entry.name;
10439
- if (entry.isDirectory()) files.push(...walk(path25.join(dir, entry.name), relative14));
10440
- else if (entry.isFile()) files.push(relative14);
10618
+ const relative15 = prefix === "" ? entry.name : prefix + "/" + entry.name;
10619
+ if (entry.isDirectory()) files.push(...walk(path26.join(dir, entry.name), relative15));
10620
+ else if (entry.isFile()) files.push(relative15);
10441
10621
  }
10442
10622
  return files;
10443
10623
  }
@@ -10477,9 +10657,9 @@ function secretTokens(text2) {
10477
10657
  }
10478
10658
  function readArtifactTexts(snapshotDir) {
10479
10659
  const texts = [];
10480
- for (const relative14 of walk(snapshotDir)) {
10481
- if (!TEXT_ARTIFACT.test(relative14)) continue;
10482
- const text2 = readText2(path25.join(snapshotDir, relative14));
10660
+ for (const relative15 of walk(snapshotDir)) {
10661
+ if (!TEXT_ARTIFACT.test(relative15)) continue;
10662
+ const text2 = readText2(path26.join(snapshotDir, relative15));
10483
10663
  if (text2 !== null) texts.push(text2);
10484
10664
  }
10485
10665
  return texts;
@@ -10495,15 +10675,15 @@ function findHostPaths(snapshotDir, repoDir) {
10495
10675
  ];
10496
10676
  const repoPattern = new RegExp(escapeRegExp(repoDir), "g");
10497
10677
  const hits = /* @__PURE__ */ new Set();
10498
- for (const relative14 of walk(snapshotDir)) {
10499
- if (!TEXT_ARTIFACT.test(relative14)) continue;
10500
- const text2 = readText2(path25.join(snapshotDir, relative14));
10678
+ for (const relative15 of walk(snapshotDir)) {
10679
+ if (!TEXT_ARTIFACT.test(relative15)) continue;
10680
+ const text2 = readText2(path26.join(snapshotDir, relative15));
10501
10681
  if (text2 === null) continue;
10502
10682
  for (const pattern of patterns) {
10503
- for (const match of text2.match(pattern) ?? []) hits.add(relative14 + ": " + match);
10683
+ for (const match of text2.match(pattern) ?? []) hits.add(relative15 + ": " + match);
10504
10684
  }
10505
10685
  repoPattern.lastIndex = 0;
10506
- if (repoPattern.test(text2)) hits.add(relative14 + ": the repository absolute path");
10686
+ if (repoPattern.test(text2)) hits.add(relative15 + ": the repository absolute path");
10507
10687
  }
10508
10688
  return [...hits];
10509
10689
  }
@@ -10653,10 +10833,10 @@ function markdownPackBodies(text2) {
10653
10833
  return bodies.size === 0 ? null : bodies;
10654
10834
  }
10655
10835
  function auditSnapshot(options) {
10656
- const snapshotDir = path25.resolve(options.snapshotDir);
10657
- const repoDir = path25.resolve(options.repoDir);
10836
+ const snapshotDir = path26.resolve(options.snapshotDir);
10837
+ const repoDir = path26.resolve(options.repoDir);
10658
10838
  const checks = [];
10659
- const manifestFile = path25.join(snapshotDir, "manifest.json");
10839
+ const manifestFile = path26.join(snapshotDir, "manifest.json");
10660
10840
  const raw = readJson(manifestFile);
10661
10841
  const problem = raw === null ? "the file is missing or is not valid JSON" : describeManifestShapeProblem(raw);
10662
10842
  if (raw === null || problem !== null) {
@@ -10685,7 +10865,7 @@ function auditSnapshot(options) {
10685
10865
  const missingParts = [];
10686
10866
  const mismatched = [];
10687
10867
  for (const part of manifest.parts) {
10688
- const bytes = readBytes(path25.join(snapshotDir, "parts", part.filename));
10868
+ const bytes = readBytes(path26.join(snapshotDir, "parts", part.filename));
10689
10869
  if (bytes === null) {
10690
10870
  missingParts.push(part.filename);
10691
10871
  continue;
@@ -10750,13 +10930,13 @@ function auditSnapshot(options) {
10750
10930
  let artifactCount = 0;
10751
10931
  for (const [key, value] of Object.entries(artifacts)) {
10752
10932
  if (value === null || value === void 0) continue;
10753
- const relative14 = ARTIFACT_FILES[key];
10754
- if (relative14 === void 0) continue;
10933
+ const relative15 = ARTIFACT_FILES[key];
10934
+ if (relative15 === void 0) continue;
10755
10935
  artifactCount += 1;
10756
- const bytes = readBytes(path25.join(snapshotDir, relative14));
10757
- if (bytes === null) artifactProblems.push(relative14 + " is missing");
10936
+ const bytes = readBytes(path26.join(snapshotDir, relative15));
10937
+ if (bytes === null) artifactProblems.push(relative15 + " is missing");
10758
10938
  else if (typeof value.sha256 === "string" && sha256(bytes) !== value.sha256) {
10759
- artifactProblems.push(relative14 + " changed");
10939
+ artifactProblems.push(relative15 + " changed");
10760
10940
  }
10761
10941
  }
10762
10942
  checks.push(
@@ -10800,8 +10980,8 @@ function auditSnapshot(options) {
10800
10980
  unexpected.length + " unexpected path(s): " + sample(unexpected)
10801
10981
  )
10802
10982
  );
10803
- const signaturePath = path25.join(snapshotDir, "signature.json");
10804
- if (fs24.existsSync(signaturePath)) {
10983
+ const signaturePath = path26.join(snapshotDir, "signature.json");
10984
+ if (fs25.existsSync(signaturePath)) {
10805
10985
  const outcome = verifySnapshotSignature(snapshotDir);
10806
10986
  checks.push(
10807
10987
  outcome.ok ? check(
@@ -10866,7 +11046,7 @@ function auditSnapshot(options) {
10866
11046
  manifest.files.map((file) => [anchorForPath(file.relativePath), file.relativePath])
10867
11047
  );
10868
11048
  for (const part of manifest.parts) {
10869
- const partText = readText2(path25.join(snapshotDir, "parts", part.filename));
11049
+ const partText = readText2(path26.join(snapshotDir, "parts", part.filename));
10870
11050
  if (partText === null) continue;
10871
11051
  const sections = parsePartSections(partText);
10872
11052
  partTexts.set(part.filename, partText);
@@ -10933,7 +11113,7 @@ function auditSnapshot(options) {
10933
11113
  }
10934
11114
  };
10935
11115
  if (manifest.artifacts?.readme != null) {
10936
- const text2 = readText2(path25.join(snapshotDir, "README.md"));
11116
+ const text2 = readText2(path26.join(snapshotDir, "README.md"));
10937
11117
  if (text2 === null) {
10938
11118
  reportProblems.push("README.md is recorded but unreadable");
10939
11119
  } else {
@@ -10973,7 +11153,7 @@ function auditSnapshot(options) {
10973
11153
  }
10974
11154
  }
10975
11155
  if (manifest.artifacts?.prompt != null) {
10976
- const text2 = readText2(path25.join(snapshotDir, "PROMPT.md"));
11156
+ const text2 = readText2(path26.join(snapshotDir, "PROMPT.md"));
10977
11157
  if (text2 === null) {
10978
11158
  reportProblems.push("PROMPT.md is recorded but unreadable");
10979
11159
  } else {
@@ -11162,7 +11342,7 @@ function auditSnapshot(options) {
11162
11342
  ];
11163
11343
  for (const reader of packReaders) {
11164
11344
  if (manifest.artifacts?.[reader.key] == null) continue;
11165
- const packText = readText2(path25.join(snapshotDir, reader.file));
11345
+ const packText = readText2(path26.join(snapshotDir, reader.file));
11166
11346
  const problems = [];
11167
11347
  if (packText === null) {
11168
11348
  problems.push(reader.file + " is recorded but unreadable");
@@ -11175,8 +11355,8 @@ function auditSnapshot(options) {
11175
11355
  for (const file of manifest.files) {
11176
11356
  if (!packed.has(file.relativePath)) problems.push(file.relativePath + " is in the manifest but not the pack");
11177
11357
  }
11178
- for (const path26 of packed) {
11179
- if (!known2.has(path26)) problems.push(path26 + " is in the pack but not the manifest");
11358
+ for (const path27 of packed) {
11359
+ if (!known2.has(path27)) problems.push(path27 + " is in the pack but not the manifest");
11180
11360
  }
11181
11361
  }
11182
11362
  }
@@ -11212,7 +11392,7 @@ function auditSnapshot(options) {
11212
11392
  bodyByPath.set(file.relativePath, section.body);
11213
11393
  bodiesChecked += 1;
11214
11394
  const bytes = Buffer.byteLength(section.body, "utf8");
11215
- const bodyLines = section.body === "" ? 0 : section.body.split("\n").length - (section.body.endsWith("\n") ? 1 : 0);
11395
+ const bodyLines = countBodyLines(section.body);
11216
11396
  if (bytes !== file.includedBytes) {
11217
11397
  bodyProblems.push(file.relativePath + ": manifest says " + file.includedBytes + " B, part holds " + bytes + " B");
11218
11398
  } else if (bodyLines !== file.includedLines) {
@@ -11325,7 +11505,7 @@ function auditSnapshot(options) {
11325
11505
  let packBodies = 0;
11326
11506
  let packSkipped = 0;
11327
11507
  for (const pack of packsWanted) {
11328
- const text2 = readText2(path25.join(snapshotDir, pack.file));
11508
+ const text2 = readText2(path26.join(snapshotDir, pack.file));
11329
11509
  if (text2 === null) continue;
11330
11510
  const bodies = pack.read(text2);
11331
11511
  if (bodies === null) {
@@ -11389,7 +11569,7 @@ function auditSnapshot(options) {
11389
11569
  unreplayable += 1;
11390
11570
  continue;
11391
11571
  }
11392
- const bytes = readBytes(path25.join(repoDir, file.relativePath));
11572
+ const bytes = readBytes(path26.join(repoDir, file.relativePath));
11393
11573
  if (bytes === null || sha256(bytes) !== file.hashSha256) {
11394
11574
  unreplayable += 1;
11395
11575
  continue;
@@ -11427,9 +11607,9 @@ function auditSnapshot(options) {
11427
11607
  )
11428
11608
  );
11429
11609
  }
11430
- const indexParent = path25.dirname(snapshotDir);
11431
- const indexPath = path25.join(indexParent, "WORKSPACE.json");
11432
- if (fs24.existsSync(indexPath)) {
11610
+ const indexParent = path26.dirname(snapshotDir);
11611
+ const indexPath = path26.join(indexParent, "WORKSPACE.json");
11612
+ if (fs25.existsSync(indexPath)) {
11433
11613
  const indexText = readText2(indexPath);
11434
11614
  let members = [];
11435
11615
  let problem2 = null;
@@ -11440,7 +11620,7 @@ function auditSnapshot(options) {
11440
11620
  } catch (error) {
11441
11621
  problem2 = error.message;
11442
11622
  }
11443
- const memberName = path25.basename(snapshotDir);
11623
+ const memberName = path26.basename(snapshotDir);
11444
11624
  const member = members.find((entry) => entry.name === memberName);
11445
11625
  if (problem2 !== null) {
11446
11626
  checks.push(check(
@@ -11464,7 +11644,7 @@ function auditSnapshot(options) {
11464
11644
  if (typeof member.files === "number" && member.files !== manifest.counts.totalFiles) {
11465
11645
  disagreements.push("file count");
11466
11646
  }
11467
- const sourceGone = typeof member.path === "string" && !fs24.existsSync(member.path) ? "Member " + memberName + " source directory is gone (" + member.path + "); the snapshot still describes it. Regenerate the workspace." : null;
11647
+ const sourceGone = typeof member.path === "string" && !fs25.existsSync(member.path) ? "Member " + memberName + " source directory is gone (" + member.path + "); the snapshot still describes it. Regenerate the workspace." : null;
11468
11648
  checks.push(
11469
11649
  sourceGone !== null ? check("workspace.index", "The workspace index agrees with this member", "warning", "warn", sourceGone) : disagreements.length === 0 ? check(
11470
11650
  "workspace.index",
@@ -11486,29 +11666,29 @@ function auditSnapshot(options) {
11486
11666
  const scanBudget = options.maxScanBytes ?? 32 * 1024 * 1024;
11487
11667
  const leakHits = [];
11488
11668
  let scannedBytes = 0;
11489
- for (const relative14 of walk(snapshotDir)) {
11490
- if (!TEXT_ARTIFACT.test(relative14) || scannedBytes > scanBudget) continue;
11491
- if (relative14 === SIGNATURE_FILE) continue;
11492
- const text2 = readText2(path25.join(snapshotDir, relative14));
11669
+ for (const relative15 of walk(snapshotDir)) {
11670
+ if (!TEXT_ARTIFACT.test(relative15) || scannedBytes > scanBudget) continue;
11671
+ if (relative15 === SIGNATURE_FILE) continue;
11672
+ const text2 = readText2(path26.join(snapshotDir, relative15));
11493
11673
  if (text2 === null) continue;
11494
11674
  scannedBytes += Buffer.byteLength(text2, "utf8");
11495
11675
  let findingCount = 0;
11496
- if (/^parts[\\/].*\.md$/i.test(relative14)) {
11676
+ if (/^parts[\\/].*\.md$/i.test(relative15)) {
11497
11677
  let headerText = text2;
11498
11678
  for (const section of parsePartSections(text2)) {
11499
11679
  findingCount += scanAndRedactSecrets(section.body, rules, section.path).findings.length;
11500
11680
  headerText = headerText.replace(section.body, "");
11501
11681
  }
11502
- findingCount += scanAndRedactSecrets(headerText, rules, relative14).findings.length;
11682
+ findingCount += scanAndRedactSecrets(headerText, rules, relative15).findings.length;
11503
11683
  } else {
11504
- findingCount = scanAndRedactSecrets(text2, rules, relative14).findings.length;
11684
+ findingCount = scanAndRedactSecrets(text2, rules, relative15).findings.length;
11505
11685
  }
11506
11686
  if (findingCount > 0) {
11507
- leakHits.push(relative14 + " (" + findingCount + " line(s))");
11687
+ leakHits.push(relative15 + " (" + findingCount + " line(s))");
11508
11688
  }
11509
11689
  }
11510
- const signatureRecordPath = path25.join(snapshotDir, SIGNATURE_FILE);
11511
- if (fs24.existsSync(signatureRecordPath)) {
11690
+ const signatureRecordPath = path26.join(snapshotDir, SIGNATURE_FILE);
11691
+ if (fs25.existsSync(signatureRecordPath)) {
11512
11692
  const recordText = readText2(signatureRecordPath);
11513
11693
  if (recordText !== null) {
11514
11694
  scannedBytes += Buffer.byteLength(recordText, "utf8");
@@ -11553,7 +11733,7 @@ function auditSnapshot(options) {
11553
11733
  const artifactContains = (token) => artifactTexts.some((text2) => text2.includes(token));
11554
11734
  for (const record of skippedSensitive.slice(0, 40)) {
11555
11735
  if (record.path.includes("[REDACTED") || compared > 400) continue;
11556
- const text2 = readText2(path25.join(repoDir, record.path));
11736
+ const text2 = readText2(path26.join(repoDir, record.path));
11557
11737
  if (text2 === null) continue;
11558
11738
  for (const token of secretTokens(text2)) {
11559
11739
  compared += 1;
@@ -11705,42 +11885,42 @@ function describeMatcher(matcher) {
11705
11885
  return String(matcher);
11706
11886
  }
11707
11887
  function normalizeTarget(cwd, target) {
11708
- const resolvedCwd = path25.resolve(cwd);
11709
- const absolute = path25.resolve(resolvedCwd, target);
11710
- const relative14 = path25.relative(resolvedCwd, absolute);
11711
- if (relative14 === "" || relative14 === ".." || relative14.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative14)) {
11888
+ const resolvedCwd = path26.resolve(cwd);
11889
+ const absolute = path26.resolve(resolvedCwd, target);
11890
+ const relative15 = path26.relative(resolvedCwd, absolute);
11891
+ if (relative15 === "" || relative15 === ".." || relative15.startsWith(`..${path26.sep}`) || path26.isAbsolute(relative15)) {
11712
11892
  return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
11713
11893
  }
11714
- return { relative: relative14.split(path25.sep).join("/"), outsideRoot: false };
11894
+ return { relative: relative15.split(path26.sep).join("/"), outsideRoot: false };
11715
11895
  }
11716
11896
  function findRuleMatch(rules, relativePath) {
11717
11897
  return rules.find(
11718
11898
  (rule) => matchRule(relativePath, rule.match)
11719
11899
  );
11720
11900
  }
11721
- function findRecordedAncestor(skipped, relative14, maskedPath2) {
11901
+ function findRecordedAncestor(skipped, relative15, maskedPath2) {
11722
11902
  let nearest;
11723
11903
  for (const record of skipped) {
11724
11904
  const ancestorPath = record.path;
11725
11905
  if (ancestorPath.length === 0) continue;
11726
- const isAncestor = relative14.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
11906
+ const isAncestor = relative15.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
11727
11907
  if (!isAncestor) continue;
11728
11908
  if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
11729
11909
  }
11730
11910
  return nearest;
11731
11911
  }
11732
11912
  function readManifest2(config) {
11733
- const manifestPath = path25.resolve(config.cwd, config.outDir, "manifest.json");
11913
+ const manifestPath = path26.resolve(config.cwd, config.outDir, "manifest.json");
11734
11914
  try {
11735
- return JSON.parse(fs24.readFileSync(manifestPath, "utf8"));
11915
+ return JSON.parse(fs25.readFileSync(manifestPath, "utf8"));
11736
11916
  } catch {
11737
11917
  return null;
11738
11918
  }
11739
11919
  }
11740
11920
  function explainPath(config, target) {
11741
11921
  const normalized = normalizeTarget(config.cwd, target);
11742
- const relative14 = normalized.relative;
11743
- const maskedPath2 = findSecretInPath(relative14, config.secretRules)?.masked ?? relative14;
11922
+ const relative15 = normalized.relative;
11923
+ const maskedPath2 = findSecretInPath(relative15, config.secretRules)?.masked ?? relative15;
11744
11924
  if (normalized.outsideRoot) {
11745
11925
  return {
11746
11926
  path: maskedPath2,
@@ -11750,10 +11930,10 @@ function explainPath(config, target) {
11750
11930
  detail: "path resolves outside the configured repository root and was not inspected"
11751
11931
  };
11752
11932
  }
11753
- const absolute = path25.join(config.cwd, relative14);
11933
+ const absolute = path26.join(config.cwd, relative15);
11754
11934
  const result = {
11755
11935
  path: maskedPath2,
11756
- exists: fs24.existsSync(absolute),
11936
+ exists: fs25.existsSync(absolute),
11757
11937
  included: false
11758
11938
  };
11759
11939
  const collection = collectFiles(config.cwd, {
@@ -11767,12 +11947,12 @@ function explainPath(config, target) {
11767
11947
  // Same exclusion `generate` applies, so `explain` never says "not-discovered" about a file
11768
11948
  // that is only missing because the walker dropped the tool's own output directory.
11769
11949
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
11770
- (directory) => path25.relative(config.cwd, path25.resolve(config.cwd, directory)).replace(/\\/g, "/")
11771
- ).filter((relative15) => relative15.length > 0 && !relative15.startsWith(".."))
11950
+ (directory) => path26.relative(config.cwd, path26.resolve(config.cwd, directory)).replace(/\\/g, "/")
11951
+ ).filter((relative16) => relative16.length > 0 && !relative16.startsWith(".."))
11772
11952
  });
11773
- if (!collection.files.includes(relative14)) {
11953
+ if (!collection.files.includes(relative15)) {
11774
11954
  const record = collection.skipped.find(
11775
- (entry2) => entry2.path === relative14 || entry2.path === maskedPath2
11955
+ (entry2) => entry2.path === relative15 || entry2.path === maskedPath2
11776
11956
  );
11777
11957
  if (record) {
11778
11958
  result.reason = record.reason;
@@ -11781,7 +11961,7 @@ function explainPath(config, target) {
11781
11961
  result.reason = "missing";
11782
11962
  result.detail = "no such file or directory, relative to the configured cwd";
11783
11963
  } else {
11784
- const ancestor = findRecordedAncestor(collection.skipped, relative14, maskedPath2);
11964
+ const ancestor = findRecordedAncestor(collection.skipped, relative15, maskedPath2);
11785
11965
  if (ancestor) {
11786
11966
  result.reason = ancestor.reason;
11787
11967
  result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
@@ -11801,11 +11981,11 @@ function explainPath(config, target) {
11801
11981
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
11802
11982
  ...config.staged === true ? { staged: true } : {}
11803
11983
  });
11804
- inScope = scope.paths.has(relative14);
11984
+ inScope = scope.paths.has(relative15);
11805
11985
  if (!inScope && config.withDependents === true) {
11806
11986
  inScope = importsChangedFile(
11807
- relative14,
11808
- importsOfFile(relative14, absolute),
11987
+ relative15,
11988
+ importsOfFile(relative15, absolute),
11809
11989
  scope.paths,
11810
11990
  buildImportResolver(collection.files.map((file) => ({ relativePath: file })), {
11811
11991
  tsconfig: tsconfigPathsFor(config.cwd)
@@ -11834,7 +12014,7 @@ function explainPath(config, target) {
11834
12014
  }
11835
12015
  let sizeOnDisk = null;
11836
12016
  try {
11837
- sizeOnDisk = fs24.statSync(absolute).size;
12017
+ sizeOnDisk = fs25.statSync(absolute).size;
11838
12018
  } catch {
11839
12019
  sizeOnDisk = null;
11840
12020
  }
@@ -11844,10 +12024,10 @@ function explainPath(config, target) {
11844
12024
  result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
11845
12025
  return result;
11846
12026
  }
11847
- if (fs24.existsSync(absolute) && fs24.statSync(absolute).isFile()) {
12027
+ if (fs25.existsSync(absolute) && fs25.statSync(absolute).isFile()) {
11848
12028
  let buffer;
11849
12029
  try {
11850
- buffer = fs24.readFileSync(absolute);
12030
+ buffer = fs25.readFileSync(absolute);
11851
12031
  } catch (err) {
11852
12032
  result.included = false;
11853
12033
  result.reason = "read-error";
@@ -11865,15 +12045,15 @@ function explainPath(config, target) {
11865
12045
  result.bytes = buffer.length;
11866
12046
  result.lines = countLines(text2);
11867
12047
  if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
11868
- const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative14);
12048
+ const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative15);
11869
12049
  result.secretCount = findings.length;
11870
12050
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
11871
12051
  let inclusionMode = "full";
11872
- if (config.skeleton === true && isSkeletonizable(relative14)) {
11873
- const skeleton = skeletonizeTypeScript(text2, relative14);
12052
+ if (config.skeleton === true && isSkeletonizable(relative15)) {
12053
+ const skeleton = skeletonizeTypeScript(text2, relative15);
11874
12054
  if (skeleton.collapsed > 0) inclusionMode = "signatures";
11875
12055
  }
11876
- if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative14) && stripComments2(text2, relative14).removed > 0) {
12056
+ if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative15) && stripComments2(text2, relative15).removed > 0) {
11877
12057
  inclusionMode = "comments-stripped";
11878
12058
  }
11879
12059
  if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
@@ -11882,18 +12062,18 @@ function explainPath(config, target) {
11882
12062
  }
11883
12063
  result.inclusionMode = inclusionMode;
11884
12064
  }
11885
- result.layer = classifyLayer(relative14, config.layers);
11886
- result.kind = classifyKind(relative14, config.kinds);
11887
- result.language = detectLanguage(relative14);
11888
- const layerRule = findRuleMatch(config.layers, relative14);
12065
+ result.layer = classifyLayer(relative15, config.layers);
12066
+ result.kind = classifyKind(relative15, config.kinds);
12067
+ result.language = detectLanguage(relative15);
12068
+ const layerRule = findRuleMatch(config.layers, relative15);
11889
12069
  if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
11890
- const kindRule = findRuleMatch(config.kinds, relative14);
12070
+ const kindRule = findRuleMatch(config.kinds, relative15);
11891
12071
  if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
11892
12072
  const manifest = readManifest2(config);
11893
- const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative14) : void 0;
12073
+ const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative15) : void 0;
11894
12074
  result.part = entry?.part ?? null;
11895
12075
  if (entry === void 0) {
11896
- const record = manifest?.skipped?.find((skip) => skip.path === relative14);
12076
+ const record = manifest?.skipped?.find((skip) => skip.path === relative15);
11897
12077
  if (record !== void 0 && (record.reason === "not-selected" || record.reason === "unchanged")) {
11898
12078
  result.included = false;
11899
12079
  result.reason = record.reason;
@@ -11937,7 +12117,7 @@ function renderExplainText(result) {
11937
12117
  return lines.join("\n");
11938
12118
  }
11939
12119
  function workerEntry(directory, isCjs) {
11940
- const entry = path25.join(directory, isCjs ? "index.cjs" : "index.js");
12120
+ const entry = path26.join(directory, isCjs ? "index.cjs" : "index.js");
11941
12121
  return { path: entry, url: pathToFileURL(entry).href };
11942
12122
  }
11943
12123
  var WORKER_SOURCE = `
@@ -11998,7 +12178,7 @@ const { parentPort, workerData } = require("node:worker_threads");
11998
12178
  })();
11999
12179
  `;
12000
12180
  function generateInWorker(cwd, cliOptions, options = {}) {
12001
- return new Promise((resolve14) => {
12181
+ return new Promise((resolve15) => {
12002
12182
  let settled = false;
12003
12183
  let worker = null;
12004
12184
  const finish = (result) => {
@@ -12009,11 +12189,11 @@ function generateInWorker(cwd, cliOptions, options = {}) {
12009
12189
  if (!result.ok && options.runId !== void 0 && options.lockRoots !== void 0) {
12010
12190
  releaseAbandonedRun(options.lockRoots, options.runId);
12011
12191
  }
12012
- resolve14(result);
12192
+ resolve15(result);
12013
12193
  });
12014
12194
  };
12015
12195
  const isCjs = typeof __dirname !== "undefined";
12016
- const directory = isCjs ? __dirname : path25.dirname(fileURLToPath(import.meta.url));
12196
+ const directory = isCjs ? __dirname : path26.dirname(fileURLToPath(import.meta.url));
12017
12197
  try {
12018
12198
  worker = new Worker(WORKER_SOURCE, {
12019
12199
  eval: true,
@@ -12075,43 +12255,99 @@ function windowText(body, fromLine, lineCount) {
12075
12255
  pastEnd
12076
12256
  };
12077
12257
  }
12258
+ function isInside2(parent, child) {
12259
+ const relative15 = path26.relative(parent, child);
12260
+ return relative15 === "" || !relative15.startsWith("..") && !path26.isAbsolute(relative15);
12261
+ }
12262
+ function readConfinedText(baseDir, relativePath) {
12263
+ if (relativePath.length === 0 || relativePath.includes("\0")) {
12264
+ return { ok: false, reason: "not-file", message: "the file name is empty or contains a NUL byte" };
12265
+ }
12266
+ if (path26.isAbsolute(relativePath)) {
12267
+ return { ok: false, reason: "outside", message: "an absolute path is not a snapshot-relative file" };
12268
+ }
12269
+ let baseReal;
12270
+ try {
12271
+ baseReal = fs25.realpathSync(path26.resolve(baseDir));
12272
+ } catch {
12273
+ return { ok: false, reason: "missing", message: "the snapshot directory does not exist" };
12274
+ }
12275
+ const candidate = path26.resolve(baseReal, relativePath);
12276
+ if (!isInside2(baseReal, candidate)) {
12277
+ return { ok: false, reason: "outside", message: "the path resolves outside the snapshot directory" };
12278
+ }
12279
+ let stats;
12280
+ try {
12281
+ stats = fs25.lstatSync(candidate);
12282
+ } catch (error) {
12283
+ const code = error.code;
12284
+ return {
12285
+ ok: false,
12286
+ reason: code === "ENOENT" || code === "ENOTDIR" ? "missing" : "unreadable",
12287
+ message: code === "ENOENT" || code === "ENOTDIR" ? "the file does not exist" : "the file could not be inspected"
12288
+ };
12289
+ }
12290
+ if (stats.isSymbolicLink()) {
12291
+ return { ok: false, reason: "not-file", message: "the file is a symbolic link" };
12292
+ }
12293
+ if (!stats.isFile()) {
12294
+ return { ok: false, reason: "not-file", message: "the path is not a regular file" };
12295
+ }
12296
+ let real;
12297
+ try {
12298
+ real = fs25.realpathSync(candidate);
12299
+ } catch {
12300
+ return { ok: false, reason: "unreadable", message: "the file could not be resolved" };
12301
+ }
12302
+ if (!isInside2(baseReal, real)) {
12303
+ return { ok: false, reason: "outside", message: "the file resolves outside the snapshot directory" };
12304
+ }
12305
+ try {
12306
+ const text2 = fs25.readFileSync(real, "utf8");
12307
+ return { ok: true, text: text2, path: real, stats: fs25.statSync(real) };
12308
+ } catch {
12309
+ return { ok: false, reason: "unreadable", message: "the file could not be read" };
12310
+ }
12311
+ }
12312
+
12313
+ // src/mcp/workspace.ts
12078
12314
  function foldForComparison(value) {
12079
12315
  return process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
12080
12316
  }
12081
12317
  function canonicalPath(value) {
12082
- const absolute = path25.resolve(value);
12318
+ const absolute = path26.resolve(value);
12083
12319
  try {
12084
- return fs24.realpathSync(absolute);
12320
+ return fs25.realpathSync(absolute);
12085
12321
  } catch {
12086
12322
  return absolute;
12087
12323
  }
12088
12324
  }
12089
- function isInside2(parent, child) {
12325
+ function isInside3(parent, child) {
12090
12326
  const foldedParent = foldForComparison(parent);
12091
12327
  const foldedChild = foldForComparison(child);
12092
- return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path25.sep}`);
12328
+ return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path26.sep}`);
12093
12329
  }
12094
12330
  function resolveThroughExistingAncestor(target) {
12095
12331
  let existing = target;
12096
12332
  const missing = [];
12097
- while (!fs24.existsSync(existing)) {
12098
- missing.unshift(path25.basename(existing));
12099
- const parent = path25.dirname(existing);
12333
+ while (!fs25.existsSync(existing)) {
12334
+ missing.unshift(path26.basename(existing));
12335
+ const parent = path26.dirname(existing);
12100
12336
  if (parent === existing) break;
12101
12337
  existing = parent;
12102
12338
  }
12103
12339
  const resolved = canonicalPath(existing);
12104
- return missing.length === 0 ? resolved : path25.join(resolved, ...missing);
12340
+ return missing.length === 0 ? resolved : path26.join(resolved, ...missing);
12105
12341
  }
12106
12342
  function resolveRoot(requested, context) {
12107
12343
  if (requested !== void 0 && (typeof requested !== "string" || requested.trim().length === 0)) {
12108
12344
  return { ok: false, message: '"root" must be a non-empty string when provided.' };
12109
12345
  }
12110
12346
  const wanted = typeof requested === "string" ? requested.trim() : context.cwd;
12111
- const absolute = path25.resolve(context.cwd, wanted);
12347
+ const absolute = path26.resolve(context.cwd, wanted);
12112
12348
  let stats;
12113
12349
  try {
12114
- stats = fs24.statSync(absolute);
12350
+ stats = fs25.statSync(absolute);
12115
12351
  } catch {
12116
12352
  return { ok: false, message: `"${wanted}" does not exist, so it cannot be a repository root.` };
12117
12353
  }
@@ -12120,7 +12356,7 @@ function resolveRoot(requested, context) {
12120
12356
  }
12121
12357
  const resolved = canonicalPath(absolute);
12122
12358
  for (const allowed of context.roots) {
12123
- if (isInside2(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
12359
+ if (isInside3(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
12124
12360
  }
12125
12361
  const shown = context.roots.join(", ");
12126
12362
  return {
@@ -12163,8 +12399,8 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
12163
12399
  }
12164
12400
  const requested = overrides.outDir.trim();
12165
12401
  const permitted = allowedRoots !== void 0 && allowedRoots.length > 0 ? allowedRoots : [root];
12166
- const resolved = resolveThroughExistingAncestor(path25.resolve(root, requested));
12167
- if (!permitted.some((allowed) => isInside2(canonicalPath(allowed), resolved))) {
12402
+ const resolved = resolveThroughExistingAncestor(path26.resolve(root, requested));
12403
+ if (!permitted.some((allowed) => isInside3(canonicalPath(allowed), resolved))) {
12168
12404
  const shown = permitted.map((allowed) => canonicalPath(allowed)).join(", ");
12169
12405
  return {
12170
12406
  ok: false,
@@ -12186,6 +12422,14 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
12186
12422
  if (overrides.sarif === true) cliOptions.sarif = true;
12187
12423
  if (overrides.staged === true) cliOptions.staged = true;
12188
12424
  if (overrides.withDependents === true) cliOptions.withDependents = true;
12425
+ for (const key of ["only", "ignore"]) {
12426
+ const value = overrides[key];
12427
+ if (value === void 0) continue;
12428
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
12429
+ return { ok: false, message: `"${key}" must be an array of glob strings.` };
12430
+ }
12431
+ cliOptions[key] = value;
12432
+ }
12189
12433
  try {
12190
12434
  const config = resolveConfig(loaded.config, cliOptions, root);
12191
12435
  return {
@@ -12205,25 +12449,25 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
12205
12449
  var MANIFEST_CACHE_LIMIT = 8;
12206
12450
  var manifestCache = /* @__PURE__ */ new Map();
12207
12451
  function manifestPathFor(workspace) {
12208
- return path25.resolve(workspace.root, workspace.config.outDir, "manifest.json");
12452
+ return path26.resolve(workspace.root, workspace.config.outDir, "manifest.json");
12209
12453
  }
12210
12454
  function partPathFor(workspace, filename) {
12211
12455
  if (filename.length === 0 || filename.includes("\0")) return null;
12212
- const partsDir = path25.resolve(workspace.root, workspace.config.outDir, "parts");
12213
- const resolved = path25.resolve(partsDir, filename);
12214
- const relative14 = path25.relative(partsDir, resolved);
12215
- if (relative14.length === 0 || relative14.includes(path25.sep) || relative14.includes("/") || relative14.includes("\\") || path25.isAbsolute(relative14)) {
12456
+ const partsDir = path26.resolve(workspace.root, workspace.config.outDir, "parts");
12457
+ const resolved = path26.resolve(partsDir, filename);
12458
+ const relative15 = path26.relative(partsDir, resolved);
12459
+ if (relative15.length === 0 || relative15.includes(path26.sep) || relative15.includes("/") || relative15.includes("\\") || path26.isAbsolute(relative15)) {
12216
12460
  return null;
12217
12461
  }
12218
12462
  let stats;
12219
12463
  try {
12220
- stats = fs24.lstatSync(resolved);
12464
+ stats = fs25.lstatSync(resolved);
12221
12465
  } catch {
12222
12466
  return null;
12223
12467
  }
12224
12468
  if (!stats.isFile()) return null;
12225
12469
  try {
12226
- if (path25.dirname(fs24.realpathSync(resolved)) !== fs24.realpathSync(partsDir)) return null;
12470
+ if (path26.dirname(fs25.realpathSync(resolved)) !== fs25.realpathSync(partsDir)) return null;
12227
12471
  } catch {
12228
12472
  return null;
12229
12473
  }
@@ -12231,31 +12475,28 @@ function partPathFor(workspace, filename) {
12231
12475
  }
12232
12476
  function readManifest3(workspace) {
12233
12477
  const file = manifestPathFor(workspace);
12234
- const shown = path25.relative(workspace.root, file).split(path25.sep).join("/") || file;
12235
- let stats;
12236
- try {
12237
- stats = fs24.statSync(file);
12238
- } catch {
12478
+ const shown = path26.relative(workspace.root, file).split(path26.sep).join("/") || file;
12479
+ const confined = readConfinedText(path26.dirname(file), path26.basename(file));
12480
+ if (!confined.ok) {
12481
+ if (confined.reason === "missing") {
12482
+ return {
12483
+ ok: false,
12484
+ missing: true,
12485
+ message: `There is no snapshot manifest at ${shown}. Call snapshot_plan to preview what would be included, or snapshot_generate to write it.`
12486
+ };
12487
+ }
12239
12488
  return {
12240
12489
  ok: false,
12241
- missing: true,
12242
- message: `There is no snapshot manifest at ${shown}. Call snapshot_plan to preview what would be included, or snapshot_generate to write it.`
12490
+ missing: false,
12491
+ message: `${shown} could not be read as a snapshot manifest: ${confined.message}.`
12243
12492
  };
12244
12493
  }
12494
+ const stats = confined.stats;
12495
+ const raw = confined.text;
12245
12496
  const cached = manifestCache.get(file);
12246
12497
  if (cached && cached.mtimeMs === stats.mtimeMs && cached.ctimeMs === stats.ctimeMs && cached.size === stats.size) {
12247
12498
  return { ok: true, manifest: cached.manifest, file };
12248
12499
  }
12249
- let raw;
12250
- try {
12251
- raw = fs24.readFileSync(file, "utf8");
12252
- } catch (error) {
12253
- return {
12254
- ok: false,
12255
- missing: false,
12256
- message: `${shown} exists but could not be read: ${error instanceof Error ? error.message : String(error)}`
12257
- };
12258
- }
12259
12500
  let parsed;
12260
12501
  try {
12261
12502
  parsed = JSON.parse(raw);
@@ -12285,6 +12526,96 @@ function forgetManifest(file) {
12285
12526
  manifestCache.delete(file);
12286
12527
  }
12287
12528
 
12529
+ // src/security/regex.ts
12530
+ var MAX_PATTERN_LENGTH = 256;
12531
+ var MAX_QUANTIFIER_REPEAT = 1e4;
12532
+ function unsafeRegExpReason(source) {
12533
+ if (source.length === 0) return null;
12534
+ if (source.length > MAX_PATTERN_LENGTH) {
12535
+ return `the pattern is longer than ${MAX_PATTERN_LENGTH} characters`;
12536
+ }
12537
+ let inClass = false;
12538
+ let unbounded = 0;
12539
+ const groups = [];
12540
+ for (let index = 0; index < source.length; index += 1) {
12541
+ const char = source[index];
12542
+ if (char === "\\") {
12543
+ index += 1;
12544
+ continue;
12545
+ }
12546
+ if (inClass) {
12547
+ if (char === "]") inClass = false;
12548
+ continue;
12549
+ }
12550
+ if (char === "[") {
12551
+ inClass = true;
12552
+ continue;
12553
+ }
12554
+ if (char === "(") {
12555
+ groups.push({ quantified: false, alternation: false });
12556
+ continue;
12557
+ }
12558
+ if (char === ")") {
12559
+ const group = groups.pop();
12560
+ if (group === void 0) continue;
12561
+ const next = source[index + 1];
12562
+ if (next === "*" || next === "+" || next === "{" && isUnboundedBrace(source, index + 1)) {
12563
+ if (group.quantified || group.alternation) {
12564
+ return "a quantified group contains another quantifier or an alternation";
12565
+ }
12566
+ }
12567
+ continue;
12568
+ }
12569
+ if (char === "|") {
12570
+ const group = groups[groups.length - 1];
12571
+ if (group !== void 0) group.alternation = true;
12572
+ continue;
12573
+ }
12574
+ if (char === "?") {
12575
+ const previous = source[index - 1];
12576
+ if (previous !== "(" && previous !== "?" && previous !== "*" && previous !== "+" && previous !== "}") {
12577
+ const group = groups[groups.length - 1];
12578
+ if (group !== void 0) group.quantified = true;
12579
+ }
12580
+ continue;
12581
+ }
12582
+ if (char === "*" || char === "+") {
12583
+ unbounded += 1;
12584
+ const group = groups[groups.length - 1];
12585
+ if (group !== void 0) group.quantified = true;
12586
+ continue;
12587
+ }
12588
+ if (char === "{") {
12589
+ const close = source.indexOf("}", index + 1);
12590
+ if (close === -1) continue;
12591
+ const body = source.slice(index + 1, close);
12592
+ const match = /^(\d+)(?:,(\d*))?$/.exec(body);
12593
+ if (match === null) {
12594
+ index = close;
12595
+ continue;
12596
+ }
12597
+ const max = match[2] === void 0 ? Number(match[1]) : match[2] === "" ? Infinity : Number(match[2]);
12598
+ if (max > MAX_QUANTIFIER_REPEAT) {
12599
+ return "a repetition bound is larger than the search budget can evaluate safely";
12600
+ }
12601
+ if (max === Infinity) unbounded += 1;
12602
+ const group = groups[groups.length - 1];
12603
+ if (group !== void 0) group.quantified = true;
12604
+ index = close;
12605
+ }
12606
+ }
12607
+ if (unbounded > 1) {
12608
+ return "the pattern has more than one unbounded repetition";
12609
+ }
12610
+ return null;
12611
+ }
12612
+ function isUnboundedBrace(source, start) {
12613
+ const close = source.indexOf("}", start + 1);
12614
+ if (close === -1) return false;
12615
+ const body = source.slice(start + 1, close);
12616
+ return /^\d+,$/.test(body);
12617
+ }
12618
+
12288
12619
  // src/mcp/tools.ts
12289
12620
  var MAX_SEARCH_BYTES = 4 * 1024 * 1024;
12290
12621
  var READ_ONLY = {
@@ -12316,6 +12647,16 @@ var OUT_DIR_PROPERTY = {
12316
12647
  };
12317
12648
  var outDirOverride = (args) => ({ outDir: args.outDir });
12318
12649
  var SCOPE_PROPERTIES = {
12650
+ only: {
12651
+ type: "array",
12652
+ items: { type: "string" },
12653
+ description: "Globs to include: replaces the config allow-list for this run."
12654
+ },
12655
+ ignore: {
12656
+ type: "array",
12657
+ items: { type: "string" },
12658
+ description: "Globs to exclude, added to the config deny-list for this run."
12659
+ },
12319
12660
  maxPartTokens: {
12320
12661
  type: "string",
12321
12662
  description: 'Token ceiling per part, for example 32000 or "32k". Narrower than maxPartBytes; it converts at four bytes per token.'
@@ -12350,7 +12691,9 @@ function workspaceOverrides(args) {
12350
12691
  sarif: args.sarif,
12351
12692
  changedSince: args.changedSince,
12352
12693
  staged: args.staged,
12353
- withDependents: args.withDependents
12694
+ withDependents: args.withDependents,
12695
+ only: args.only,
12696
+ ignore: args.ignore
12354
12697
  };
12355
12698
  }
12356
12699
  function failure(message) {
@@ -12365,7 +12708,7 @@ function formatBytes2(bytes) {
12365
12708
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
12366
12709
  }
12367
12710
  function relativeFor(workspace, absolute) {
12368
- return path25.relative(workspace.root, absolute).split(path25.sep).join("/");
12711
+ return path26.relative(workspace.root, absolute).split(path26.sep).join("/");
12369
12712
  }
12370
12713
  function capped(values, limit = 20) {
12371
12714
  return { count: values.length, sample: values.slice(0, limit) };
@@ -12384,13 +12727,13 @@ function summarizeDrift(drift) {
12384
12727
  function toRelativePath(root, value) {
12385
12728
  const cleaned = value.trim();
12386
12729
  if (cleaned.length === 0 || cleaned.includes("\0")) return null;
12387
- const resolvedRoot = path25.resolve(root);
12388
- const absolute = path25.resolve(resolvedRoot, cleaned);
12389
- const relative14 = path25.relative(resolvedRoot, absolute);
12390
- if (relative14 === "" || relative14 === ".." || relative14.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative14)) {
12730
+ const resolvedRoot = path26.resolve(root);
12731
+ const absolute = path26.resolve(resolvedRoot, cleaned);
12732
+ const relative15 = path26.relative(resolvedRoot, absolute);
12733
+ if (relative15 === "" || relative15 === ".." || relative15.startsWith(`..${path26.sep}`) || path26.isAbsolute(relative15)) {
12391
12734
  return null;
12392
12735
  }
12393
- return relative14.split(path25.sep).join("/");
12736
+ return relative15.split(path26.sep).join("/");
12394
12737
  }
12395
12738
  function symbolsOf(entry) {
12396
12739
  const summary = entry.summary;
@@ -12483,16 +12826,15 @@ var historyTool = {
12483
12826
  async handler(args, context) {
12484
12827
  const prepared = await prepare(args, context, outDirOverride(args));
12485
12828
  if (!prepared.ok) return prepared.outcome;
12486
- const reportPath = path25.resolve(prepared.workspace.root, prepared.workspace.config.outDir, "reports", "log.md");
12487
- let text2;
12488
- try {
12489
- text2 = fs24.readFileSync(reportPath, "utf8");
12490
- } catch {
12829
+ const snapshotDir = path26.resolve(prepared.workspace.root, prepared.workspace.config.outDir);
12830
+ const reportRead = readConfinedText(snapshotDir, path26.posix.join("reports", "log.md"));
12831
+ if (!reportRead.ok) {
12491
12832
  return {
12492
- 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.",
12833
+ 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.",
12493
12834
  isError: true
12494
12835
  };
12495
12836
  }
12837
+ const text2 = reportRead.text;
12496
12838
  const manifestRead = readManifest3(prepared.workspace);
12497
12839
  const recordedLog = manifestRead.ok ? manifestRead.manifest.artifacts?.log : void 0;
12498
12840
  if (recordedLog !== void 0 && recordedLog !== null) {
@@ -12553,7 +12895,7 @@ var budgetTool = {
12553
12895
  ...args.includeTests === true ? { includeTests: true } : {}
12554
12896
  });
12555
12897
  const paths = new Set(plan.files.map((file) => file.path));
12556
- const gained = [...paths].filter((path26) => !previous.has(path26)).sort();
12898
+ const gained = [...paths].filter((path27) => !previous.has(path27)).sort();
12557
12899
  previous = paths;
12558
12900
  rows.push({
12559
12901
  budget,
@@ -12656,20 +12998,16 @@ var workspaceTool = {
12656
12998
  async handler(args, context) {
12657
12999
  const prepared = await prepare(args, context, outDirOverride(args));
12658
13000
  if (!prepared.ok) return prepared.outcome;
12659
- const index = path25.resolve(
12660
- prepared.workspace.root,
12661
- prepared.workspace.config.outDir,
12662
- "WORKSPACE.json"
12663
- );
12664
- let text2;
12665
- try {
12666
- text2 = fs24.readFileSync(index, "utf8");
12667
- } catch {
13001
+ const snapshotDir = path26.resolve(prepared.workspace.root, prepared.workspace.config.outDir);
13002
+ const index = path26.join(snapshotDir, "WORKSPACE.json");
13003
+ const read = readConfinedText(snapshotDir, "WORKSPACE.json");
13004
+ if (!read.ok) {
12668
13005
  return {
12669
- text: "No workspace index at " + index + ". Generate one with `generate --workspace member-a,member-b`; a single snapshot has no members to list.",
13006
+ 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.",
12670
13007
  isError: true
12671
13008
  };
12672
13009
  }
13010
+ const text2 = read.text;
12673
13011
  const document = JSON.parse(text2);
12674
13012
  const members = document.members ?? [];
12675
13013
  const links = document.links ?? [];
@@ -12810,6 +13148,10 @@ var routesTool = {
12810
13148
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
12811
13149
  let filter = null;
12812
13150
  if (typeof args.pattern === "string") {
13151
+ const unsafe = unsafeRegExpReason(args.pattern);
13152
+ if (unsafe !== null) {
13153
+ return { text: "pattern is refused: " + unsafe + ".", isError: true };
13154
+ }
12813
13155
  try {
12814
13156
  filter = new RegExp(args.pattern, "i");
12815
13157
  } catch (error) {
@@ -12865,7 +13207,7 @@ var cyclesTool = {
12865
13207
  tsconfig: tsconfigPathsFor(prepared.workspace.root)
12866
13208
  });
12867
13209
  const edges = /* @__PURE__ */ new Map();
12868
- for (const path26 of byPath.keys()) edges.set(path26, []);
13210
+ for (const path27 of byPath.keys()) edges.set(path27, []);
12869
13211
  for (const entry of read.manifest.indexes.imports.byFile) {
12870
13212
  const targets = edges.get(entry.path);
12871
13213
  if (targets === void 0) continue;
@@ -12953,6 +13295,12 @@ var searchTool = {
12953
13295
  const cap = Math.max(1, Math.min(500, typeof args.maxMatches === "number" ? args.maxMatches : 50));
12954
13296
  const contextLines = Math.max(0, Math.min(10, typeof args.contextLines === "number" ? args.contextLines : 0));
12955
13297
  let pattern;
13298
+ if (args.regex === true) {
13299
+ const unsafe = unsafeRegExpReason(query);
13300
+ if (unsafe !== null) {
13301
+ return { text: "regex is refused: " + unsafe + ".", isError: true };
13302
+ }
13303
+ }
12956
13304
  try {
12957
13305
  pattern = args.regex === true ? new RegExp(query, "i") : new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i");
12958
13306
  } catch (error) {
@@ -12971,7 +13319,7 @@ var searchTool = {
12971
13319
  if (partPath === null) continue;
12972
13320
  let text2;
12973
13321
  try {
12974
- text2 = fs24.readFileSync(partPath, "utf8");
13322
+ text2 = fs25.readFileSync(partPath, "utf8");
12975
13323
  } catch {
12976
13324
  continue;
12977
13325
  }
@@ -13102,7 +13450,7 @@ var reviewTool = {
13102
13450
  return { text: error.message, isError: true };
13103
13451
  }
13104
13452
  const report2 = auditSnapshot({
13105
- snapshotDir: path25.resolve(workspace.root, workspace.config.outDir),
13453
+ snapshotDir: path26.resolve(workspace.root, workspace.config.outDir),
13106
13454
  repoDir: workspace.root
13107
13455
  });
13108
13456
  const failed = report2.checks.filter((check2) => check2.status === "fail").map((check2) => check2.id + ": " + check2.detail);
@@ -13124,7 +13472,7 @@ var reviewTool = {
13124
13472
  }
13125
13473
  let section = null;
13126
13474
  try {
13127
- section = findSection(parsePartSections(fs24.readFileSync(partPath, "utf8")), file.relativePath);
13475
+ section = findSection(parsePartSections(fs25.readFileSync(partPath, "utf8")), file.relativePath);
13128
13476
  } catch {
13129
13477
  section = null;
13130
13478
  }
@@ -13214,31 +13562,31 @@ var diffContextTool = {
13214
13562
  const changed = [];
13215
13563
  const text2 = [];
13216
13564
  let used = 0;
13217
- for (const path26 of wanted) {
13218
- const file = byPath.get(path26.toLowerCase());
13565
+ for (const path27 of wanted) {
13566
+ const file = byPath.get(path27.toLowerCase());
13219
13567
  if (file === void 0) {
13220
- missing.push(path26);
13568
+ missing.push(path27);
13221
13569
  continue;
13222
13570
  }
13223
13571
  const partPath = partPathFor(workspace, file.part);
13224
13572
  if (partPath === null) {
13225
- missing.push(path26 + " (part missing)");
13573
+ missing.push(path27 + " (part missing)");
13226
13574
  continue;
13227
13575
  }
13228
13576
  let section;
13229
13577
  try {
13230
- section = findSection(parsePartSections(fs24.readFileSync(partPath, "utf8")), file.relativePath);
13578
+ section = findSection(parsePartSections(fs25.readFileSync(partPath, "utf8")), file.relativePath);
13231
13579
  } catch {
13232
13580
  section = null;
13233
13581
  }
13234
13582
  if (section === null) {
13235
- missing.push(path26 + " (section not found)");
13583
+ missing.push(path27 + " (section not found)");
13236
13584
  continue;
13237
13585
  }
13238
13586
  const window = windowText(section.body, 1, linesPerFile);
13239
13587
  const tokens = Math.max(1, Math.ceil(Buffer.byteLength(window.text, "utf8") / 4));
13240
13588
  if (used + tokens > budget) {
13241
- missing.push(path26 + " (budget)");
13589
+ missing.push(path27 + " (budget)");
13242
13590
  continue;
13243
13591
  }
13244
13592
  used += tokens;
@@ -13313,7 +13661,7 @@ var symbolTool = {
13313
13661
  if (partPath === null) continue;
13314
13662
  let partText;
13315
13663
  try {
13316
- partText = fs24.readFileSync(partPath, "utf8");
13664
+ partText = fs25.readFileSync(partPath, "utf8");
13317
13665
  } catch {
13318
13666
  continue;
13319
13667
  }
@@ -13345,28 +13693,39 @@ var symbolTool = {
13345
13693
  };
13346
13694
  }
13347
13695
  const callSites = [];
13696
+ let referencesTruncated = false;
13348
13697
  if (args.references !== false) {
13349
13698
  const limit = Math.max(1, typeof args.maxReferences === "number" ? args.maxReferences : 20);
13350
13699
  const definitionKeys = new Set(matches.map((match) => match.path + ":" + match.line));
13351
13700
  const word = new RegExp("\\b" + name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\b");
13352
- const parts = /* @__PURE__ */ new Map();
13701
+ const sectionsByPart = /* @__PURE__ */ new Map();
13353
13702
  let scanned = 0;
13354
13703
  for (const file of read.manifest.files) {
13355
13704
  if (callSites.length >= limit) break;
13356
13705
  const partPath = partPathFor(workspace, file.part);
13357
13706
  if (partPath === null) continue;
13358
- let partText = parts.get(partPath);
13359
- if (partText === void 0) {
13707
+ let sections = sectionsByPart.get(partPath);
13708
+ if (sections === void 0) {
13709
+ if (scanned >= MAX_SEARCH_BYTES) {
13710
+ referencesTruncated = true;
13711
+ break;
13712
+ }
13713
+ let partText;
13360
13714
  try {
13361
- partText = fs24.readFileSync(partPath, "utf8");
13715
+ partText = fs25.readFileSync(partPath, "utf8");
13362
13716
  } catch {
13363
13717
  continue;
13364
13718
  }
13365
- parts.set(partPath, partText);
13719
+ const bytes = Buffer.byteLength(partText, "utf8");
13720
+ if (scanned + bytes > MAX_SEARCH_BYTES) {
13721
+ referencesTruncated = true;
13722
+ break;
13723
+ }
13724
+ scanned += bytes;
13725
+ sections = parsePartSections(partText);
13726
+ sectionsByPart.set(partPath, sections);
13366
13727
  }
13367
- if (scanned > MAX_SEARCH_BYTES) break;
13368
- scanned += Buffer.byteLength(partText, "utf8");
13369
- const section = findSection(parsePartSections(partText), file.relativePath);
13728
+ const section = findSection(sections, file.relativePath);
13370
13729
  if (section === null) continue;
13371
13730
  const bodyLines = section.body.split("\n");
13372
13731
  for (let index = 0; index < bodyLines.length && callSites.length < limit; index += 1) {
@@ -13380,8 +13739,11 @@ var symbolTool = {
13380
13739
  }
13381
13740
  }
13382
13741
  }
13383
- 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")));
13384
- return { text: text2, structured: { found: matches.length, matches, references: callSites } };
13742
+ 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." : "");
13743
+ return {
13744
+ text: text2,
13745
+ structured: { found: matches.length, matches, references: callSites, truncated: referencesTruncated }
13746
+ };
13385
13747
  }
13386
13748
  };
13387
13749
  var contextTool = {
@@ -13454,7 +13816,7 @@ var contextTool = {
13454
13816
  }
13455
13817
  if (!sectionsByPart.has(file.part)) {
13456
13818
  try {
13457
- sectionsByPart.set(file.part, parsePartSections(fs24.readFileSync(partPath, "utf8")));
13819
+ sectionsByPart.set(file.part, parsePartSections(fs25.readFileSync(partPath, "utf8")));
13458
13820
  } catch {
13459
13821
  sectionsByPart.set(file.part, null);
13460
13822
  }
@@ -13539,6 +13901,10 @@ var queryTool = {
13539
13901
  const maxFiles = typeof args.maxFiles === "number" ? Math.min(200, Math.max(1, args.maxFiles)) : 40;
13540
13902
  let pattern = null;
13541
13903
  if (typeof args.pathPattern === "string") {
13904
+ const unsafe = unsafeRegExpReason(args.pathPattern);
13905
+ if (unsafe !== null) {
13906
+ return { text: "pathPattern is refused: " + unsafe + ".", isError: true };
13907
+ }
13542
13908
  try {
13543
13909
  pattern = new RegExp(args.pathPattern, "i");
13544
13910
  } catch (error) {
@@ -13688,7 +14054,7 @@ var answerTool = {
13688
14054
  let partText = parts.get(partPath);
13689
14055
  if (partText === void 0) {
13690
14056
  try {
13691
- partText = fs24.readFileSync(partPath, "utf8");
14057
+ partText = fs25.readFileSync(partPath, "utf8");
13692
14058
  } catch {
13693
14059
  omitted.push({ path: planned.path, reason: "its part could not be read" });
13694
14060
  continue;
@@ -13785,7 +14151,7 @@ var healthTool = {
13785
14151
  if (!prepared.ok) return prepared.outcome;
13786
14152
  const workspace = prepared.workspace;
13787
14153
  const report2 = auditSnapshot({
13788
- snapshotDir: path25.resolve(workspace.root, workspace.config.outDir),
14154
+ snapshotDir: path26.resolve(workspace.root, workspace.config.outDir),
13789
14155
  repoDir: workspace.root,
13790
14156
  ...typeof args.maxScanBytes === "number" ? { maxScanBytes: args.maxScanBytes } : {},
13791
14157
  ...args.deep === true ? { deep: true } : {}
@@ -14014,16 +14380,6 @@ var generateTool = {
14014
14380
  minimum: 500,
14015
14381
  description: "Fit the snapshot into this token budget, highest value first."
14016
14382
  },
14017
- only: {
14018
- type: "array",
14019
- items: { type: "string" },
14020
- description: "Globs to include: replaces the config allow-list for this run."
14021
- },
14022
- ignore: {
14023
- type: "array",
14024
- items: { type: "string" },
14025
- description: "Globs to exclude, added to the config deny-list for this run."
14026
- },
14027
14383
  ...SCOPE_PROPERTIES
14028
14384
  },
14029
14385
  additionalProperties: false
@@ -14079,7 +14435,7 @@ var generateTool = {
14079
14435
  context.notify?.({ message: "writing the snapshot", progress: 2, total: 2 });
14080
14436
  const summary = result.summary;
14081
14437
  forgetManifest(manifestPathFor(workspace));
14082
- const written = relativeFor(workspace, path25.resolve(workspace.root, workspace.config.outDir));
14438
+ const written = relativeFor(workspace, path26.resolve(workspace.root, workspace.config.outDir));
14083
14439
  const lines = [
14084
14440
  `Wrote ${written}/`,
14085
14441
  `Files: ${summary.totalFiles} included, ${summary.skippedCount} skipped, ${plural(summary.partsCount, "part")}`,
@@ -14524,7 +14880,7 @@ var readTool = {
14524
14880
  }
14525
14881
  let partText;
14526
14882
  try {
14527
- partText = fs24.readFileSync(partPath, "utf8");
14883
+ partText = fs25.readFileSync(partPath, "utf8");
14528
14884
  } catch {
14529
14885
  return failure(
14530
14886
  `${entry.part} could not be read, so the snapshot is damaged. Run snapshot_generate to rebuild it.`
@@ -16202,7 +16558,7 @@ async function workspaceFor(context) {
16202
16558
  }
16203
16559
  function readFileIfPresent(file) {
16204
16560
  try {
16205
- return fs24.readFileSync(file, "utf8");
16561
+ return fs25.readFileSync(file, "utf8");
16206
16562
  } catch {
16207
16563
  return null;
16208
16564
  }
@@ -16241,9 +16597,9 @@ function buildResourceProvider() {
16241
16597
  }
16242
16598
  ];
16243
16599
  const workspace = await workspaceFor(context);
16244
- const reportsDir = "error" in workspace ? null : path25.resolve(workspace.root, workspace.config.outDir, "reports");
16600
+ const reportsDir = "error" in workspace ? null : path26.resolve(workspace.root, workspace.config.outDir, "reports");
16245
16601
  for (const [uri, report2] of REPORT_URIS) {
16246
- const present = reportsDir !== null && fs24.existsSync(path25.join(reportsDir, report2.file));
16602
+ const present = reportsDir !== null && fs25.existsSync(path26.join(reportsDir, report2.file));
16247
16603
  if (!present) continue;
16248
16604
  resources.push({
16249
16605
  uri,
@@ -16305,36 +16661,46 @@ function buildResourceProvider() {
16305
16661
  }
16306
16662
  const workspace = await workspaceFor(context);
16307
16663
  if ("error" in workspace) return null;
16664
+ const snapshotDir = path26.resolve(workspace.root, workspace.config.outDir);
16308
16665
  if (uri === PROMPT_URI) {
16309
- const text2 = readFileIfPresent(
16310
- path25.resolve(workspace.root, workspace.config.outDir, "PROMPT.md")
16311
- );
16312
- if (text2 === null) {
16666
+ const read = readConfinedText(snapshotDir, "PROMPT.md");
16667
+ if (!read.ok) {
16313
16668
  throw new ResourceNotFoundError(
16314
16669
  uri,
16315
- "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."
16670
+ "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."
16316
16671
  );
16317
16672
  }
16318
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, PROMPT_ADVICE) };
16673
+ return {
16674
+ uri,
16675
+ mimeType: "text/markdown",
16676
+ text: ensureSingleRead(uri, read.text, PROMPT_ADVICE)
16677
+ };
16319
16678
  }
16320
16679
  const report2 = REPORT_URIS.get(uri);
16321
16680
  if (report2) {
16322
- const text2 = readFileIfPresent(
16323
- path25.resolve(workspace.root, workspace.config.outDir, "reports", report2.file)
16324
- );
16325
- if (text2 === null) {
16681
+ const read = readConfinedText(snapshotDir, path26.posix.join("reports", report2.file));
16682
+ if (!read.ok) {
16326
16683
  throw new ResourceNotFoundError(
16327
16684
  uri,
16328
- "This snapshot contains no " + report2.file + ": that report was disabled, or nothing has been generated yet. Run snapshot_generate first."
16685
+ "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."
16329
16686
  );
16330
16687
  }
16331
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, REPORT_ADVICE) };
16688
+ return {
16689
+ uri,
16690
+ mimeType: "text/markdown",
16691
+ text: ensureSingleRead(uri, read.text, REPORT_ADVICE)
16692
+ };
16332
16693
  }
16333
16694
  if (uri === "snapshot://manifest") {
16334
16695
  const read = readManifest3(workspace);
16335
16696
  if (!read.ok) return null;
16336
- const text2 = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
16337
- return { uri, mimeType: "application/json", text: ensureSingleRead(uri, text2, MANIFEST_ADVICE) };
16697
+ const confined = readConfinedText(path26.dirname(read.file), path26.basename(read.file));
16698
+ if (!confined.ok) return null;
16699
+ return {
16700
+ uri,
16701
+ mimeType: "application/json",
16702
+ text: ensureSingleRead(uri, confined.text, MANIFEST_ADVICE)
16703
+ };
16338
16704
  }
16339
16705
  const partMatch = PART_URI.exec(uri);
16340
16706
  if (partMatch) {
@@ -16347,7 +16713,7 @@ function buildResourceProvider() {
16347
16713
  if (partPath === null) return null;
16348
16714
  let partBytes;
16349
16715
  try {
16350
- partBytes = fs24.statSync(partPath).size;
16716
+ partBytes = fs25.statSync(partPath).size;
16351
16717
  } catch {
16352
16718
  return null;
16353
16719
  }
@@ -16383,52 +16749,52 @@ function validateArguments(schema, value) {
16383
16749
  }
16384
16750
  return problems;
16385
16751
  }
16386
- function checkValue(path26, schema, value) {
16752
+ function checkValue(path27, schema, value) {
16387
16753
  if (schema.enum && !schema.enum.includes(value)) {
16388
- return [`"${path26}" must be one of: ${schema.enum.join(", ")}`];
16754
+ return [`"${path27}" must be one of: ${schema.enum.join(", ")}`];
16389
16755
  }
16390
16756
  switch (schema.type) {
16391
16757
  case "string": {
16392
- if (typeof value !== "string") return [`"${path26}" must be a string`];
16758
+ if (typeof value !== "string") return [`"${path27}" must be a string`];
16393
16759
  const problems = [];
16394
16760
  if (schema.minLength !== void 0 && value.length < schema.minLength) {
16395
- problems.push(`"${path26}" must be at least ${schema.minLength} character(s)`);
16761
+ problems.push(`"${path27}" must be at least ${schema.minLength} character(s)`);
16396
16762
  }
16397
16763
  if (schema.maxLength !== void 0 && value.length > schema.maxLength) {
16398
- problems.push(`"${path26}" must be at most ${schema.maxLength} character(s)`);
16764
+ problems.push(`"${path27}" must be at most ${schema.maxLength} character(s)`);
16399
16765
  }
16400
16766
  return problems;
16401
16767
  }
16402
16768
  case "number":
16403
16769
  case "integer": {
16404
16770
  if (typeof value !== "number" || Number.isNaN(value)) {
16405
- return [`"${path26}" must be a number`];
16771
+ return [`"${path27}" must be a number`];
16406
16772
  }
16407
16773
  if (schema.type === "integer" && !Number.isInteger(value)) {
16408
- return [`"${path26}" must be an integer`];
16774
+ return [`"${path27}" must be an integer`];
16409
16775
  }
16410
16776
  const problems = [];
16411
16777
  if (schema.minimum !== void 0 && value < schema.minimum) {
16412
- problems.push(`"${path26}" must be >= ${schema.minimum}`);
16778
+ problems.push(`"${path27}" must be >= ${schema.minimum}`);
16413
16779
  }
16414
16780
  if (schema.maximum !== void 0 && value > schema.maximum) {
16415
- problems.push(`"${path26}" must be <= ${schema.maximum}`);
16781
+ problems.push(`"${path27}" must be <= ${schema.maximum}`);
16416
16782
  }
16417
16783
  return problems;
16418
16784
  }
16419
16785
  case "boolean":
16420
- return typeof value === "boolean" ? [] : [`"${path26}" must be a boolean`];
16786
+ return typeof value === "boolean" ? [] : [`"${path27}" must be a boolean`];
16421
16787
  case "array": {
16422
- if (!Array.isArray(value)) return [`"${path26}" must be an array`];
16788
+ if (!Array.isArray(value)) return [`"${path27}" must be an array`];
16423
16789
  if (!schema.items) return [];
16424
16790
  const problems = [];
16425
16791
  value.forEach((item, index) => {
16426
- problems.push(...checkValue(`${path26}[${index}]`, schema.items, item));
16792
+ problems.push(...checkValue(`${path27}[${index}]`, schema.items, item));
16427
16793
  });
16428
16794
  return problems;
16429
16795
  }
16430
16796
  case "object":
16431
- return isJsonObject(value) ? [] : [`"${path26}" must be an object`];
16797
+ return isJsonObject(value) ? [] : [`"${path27}" must be an object`];
16432
16798
  default:
16433
16799
  return [];
16434
16800
  }
@@ -16794,11 +17160,11 @@ var MAX_LINE_BYTES = 32 * 1024 * 1024;
16794
17160
  function createWriter(output) {
16795
17161
  return {
16796
17162
  write(value) {
16797
- return new Promise((resolve14, reject) => {
17163
+ return new Promise((resolve15, reject) => {
16798
17164
  output.write(`${JSON.stringify(value)}
16799
17165
  `, (error) => {
16800
17166
  if (error) reject(error);
16801
- else resolve14();
17167
+ else resolve15();
16802
17168
  });
16803
17169
  });
16804
17170
  }
@@ -16941,8 +17307,8 @@ async function runStdioServer(options) {
16941
17307
  let inFlight = 0;
16942
17308
  let inputEnded = false;
16943
17309
  let resolveDone = () => void 0;
16944
- const finished = new Promise((resolve14) => {
16945
- resolveDone = resolve14;
17310
+ const finished = new Promise((resolve15) => {
17311
+ resolveDone = resolve15;
16946
17312
  });
16947
17313
  const finishIfIdle = () => {
16948
17314
  if (inputEnded && inFlight === 0) resolveDone(0);
@@ -17033,10 +17399,10 @@ function dosDateTime(date) {
17033
17399
  }
17034
17400
  function walkFiles(root, prefix = "") {
17035
17401
  const files = [];
17036
- for (const entry of fs24.readdirSync(path25.join(root, prefix), { withFileTypes: true })) {
17037
- const relative14 = prefix === "" ? entry.name : prefix + "/" + entry.name;
17038
- if (entry.isDirectory()) files.push(...walkFiles(root, relative14));
17039
- else if (entry.isFile()) files.push(relative14);
17402
+ for (const entry of fs25.readdirSync(path26.join(root, prefix), { withFileTypes: true })) {
17403
+ const relative15 = prefix === "" ? entry.name : prefix + "/" + entry.name;
17404
+ if (entry.isDirectory()) files.push(...walkFiles(root, relative15));
17405
+ else if (entry.isFile()) files.push(relative15);
17040
17406
  }
17041
17407
  return files;
17042
17408
  }
@@ -17044,11 +17410,11 @@ function writeZip(options) {
17044
17410
  const entries = [...options.entries ?? []];
17045
17411
  if (options.directory !== void 0) {
17046
17412
  const root = options.directory;
17047
- for (const relative14 of walkFiles(root)) {
17048
- if (options.skip !== void 0 && options.skip(relative14)) continue;
17049
- const full = path25.join(root, relative14);
17050
- const stat = fs24.statSync(full);
17051
- entries.push({ name: relative14, content: fs24.readFileSync(full), mtime: stat.mtime });
17413
+ for (const relative15 of walkFiles(root)) {
17414
+ if (options.skip !== void 0 && options.skip(relative15)) continue;
17415
+ const full = path26.join(root, relative15);
17416
+ const stat = fs25.statSync(full);
17417
+ entries.push({ name: relative15, content: fs25.readFileSync(full), mtime: stat.mtime });
17052
17418
  }
17053
17419
  }
17054
17420
  if (entries.length > 65535) {
@@ -17268,6 +17634,7 @@ var SERVE_PAGE = `<!doctype html>
17268
17634
  var DEFAULT_PORT = 4788;
17269
17635
  var MAX_BODY = 64 * 1024;
17270
17636
  var MAX_PREVIEW = 64 * 1024;
17637
+ var MAX_MCP_IN_FLIGHT = 4;
17271
17638
  function isLoopback(origin) {
17272
17639
  try {
17273
17640
  const url = new URL(origin);
@@ -17295,10 +17662,11 @@ async function startWebServer(options) {
17295
17662
  return server2;
17296
17663
  };
17297
17664
  const temporaryClones = /* @__PURE__ */ new Set();
17298
- const allowedRoots = [path25.resolve(options.cwd)];
17665
+ let mcpInFlight = 0;
17666
+ const allowedRoots = [path26.resolve(options.cwd)];
17299
17667
  const canonical = (candidate) => {
17300
17668
  try {
17301
- return fs24.realpathSync(candidate);
17669
+ return fs25.realpathSync(candidate);
17302
17670
  } catch {
17303
17671
  return null;
17304
17672
  }
@@ -17306,32 +17674,32 @@ async function startWebServer(options) {
17306
17674
  const inside = (resolved) => allowedRoots.some((root) => {
17307
17675
  const canonicalRoot = canonical(root);
17308
17676
  if (canonicalRoot === null) return false;
17309
- const relative14 = path25.relative(canonicalRoot, resolved);
17310
- return relative14 === "" || !relative14.startsWith(`..${path25.sep}`) && relative14 !== ".." && !path25.isAbsolute(relative14);
17677
+ const relative15 = path26.relative(canonicalRoot, resolved);
17678
+ return relative15 === "" || !relative15.startsWith(`..${path26.sep}`) && relative15 !== ".." && !path26.isAbsolute(relative15);
17311
17679
  });
17312
17680
  const insideAllowedRoots = (candidate) => {
17313
17681
  const resolved = canonical(candidate);
17314
17682
  return resolved === null ? false : inside(resolved);
17315
17683
  };
17316
17684
  const lexicallyInside = (candidate) => {
17317
- const resolved = path25.resolve(candidate);
17685
+ const resolved = path26.resolve(candidate);
17318
17686
  return allowedRoots.some((root) => {
17319
- const prefix = path25.resolve(root) + path25.sep;
17320
- return resolved === path25.resolve(root) || resolved.startsWith(prefix);
17687
+ const prefix = path26.resolve(root) + path26.sep;
17688
+ return resolved === path26.resolve(root) || resolved.startsWith(prefix);
17321
17689
  });
17322
17690
  };
17323
17691
  const insideAllowedRootsForWrite = (candidate) => {
17324
- let existing = path25.resolve(candidate);
17692
+ let existing = path26.resolve(candidate);
17325
17693
  const tail = [];
17326
- while (!fs24.existsSync(existing)) {
17327
- tail.unshift(path25.basename(existing));
17328
- const parent = path25.dirname(existing);
17694
+ while (!fs25.existsSync(existing)) {
17695
+ tail.unshift(path26.basename(existing));
17696
+ const parent = path26.dirname(existing);
17329
17697
  if (parent === existing) break;
17330
17698
  existing = parent;
17331
17699
  }
17332
17700
  const resolved = canonical(existing);
17333
17701
  if (resolved === null) return false;
17334
- return inside(tail.length === 0 ? resolved : path25.join(resolved, ...tail));
17702
+ return inside(tail.length === 0 ? resolved : path26.join(resolved, ...tail));
17335
17703
  };
17336
17704
  const authorized = (request) => {
17337
17705
  if (token === null) return true;
@@ -17421,8 +17789,25 @@ async function startWebServer(options) {
17421
17789
  const server2 = mcpFor(request.socket);
17422
17790
  const answers = [];
17423
17791
  for (const item of batch) {
17424
- const answer = await server2.handle(item);
17425
- if (answer !== null) answers.push(answer);
17792
+ const gated = item !== null && typeof item === "object" && item.method === "tools/call";
17793
+ if (gated && mcpInFlight >= MAX_MCP_IN_FLIGHT) {
17794
+ answers.push({
17795
+ jsonrpc: "2.0",
17796
+ id: item.id ?? null,
17797
+ error: {
17798
+ code: -32001,
17799
+ message: "server busy: too many tool calls are already in flight"
17800
+ }
17801
+ });
17802
+ continue;
17803
+ }
17804
+ if (gated) mcpInFlight += 1;
17805
+ try {
17806
+ const answer = await server2.handle(item);
17807
+ if (answer !== null) answers.push(answer);
17808
+ } finally {
17809
+ if (gated) mcpInFlight -= 1;
17810
+ }
17426
17811
  }
17427
17812
  if (answers.length === 0) send(202, "");
17428
17813
  else send(200, Array.isArray(message) ? answers : answers[0]);
@@ -17502,7 +17887,7 @@ async function startWebServer(options) {
17502
17887
  return;
17503
17888
  }
17504
17889
  } else {
17505
- target = path25.resolve(options.cwd, source);
17890
+ target = path26.resolve(options.cwd, source);
17506
17891
  if (!insideAllowedRoots(target)) {
17507
17892
  send(403, { error: "outside the served directory: " + target });
17508
17893
  return;
@@ -17510,7 +17895,7 @@ async function startWebServer(options) {
17510
17895
  }
17511
17896
  let stat;
17512
17897
  try {
17513
- stat = fs24.statSync(target);
17898
+ stat = fs25.statSync(target);
17514
17899
  } catch {
17515
17900
  send(404, { error: "no such path: " + target });
17516
17901
  return;
@@ -17531,11 +17916,17 @@ async function startWebServer(options) {
17531
17916
  hooks: {}
17532
17917
  } : loaded.config ?? {};
17533
17918
  const configuredOutDir = typeof runConfig.outDir === "string" && runConfig.outDir.trim() !== "" ? runConfig.outDir : "snapshot";
17534
- const snapshotDir = path25.resolve(target, configuredOutDir);
17919
+ const snapshotDir = path26.resolve(target, configuredOutDir);
17535
17920
  if (!insideAllowedRootsForWrite(snapshotDir)) {
17536
17921
  send(403, { error: "the configured outDir resolves outside the served directory" });
17537
17922
  return;
17538
17923
  }
17924
+ const configuredTmpDir = typeof runConfig.tmpDir === "string" && runConfig.tmpDir.trim() !== "" ? runConfig.tmpDir : "snapshot.tmp";
17925
+ const stagingDir = path26.resolve(target, configuredTmpDir);
17926
+ if (!insideAllowedRootsForWrite(stagingDir)) {
17927
+ send(403, { error: "the configured tmpDir resolves outside the served directory" });
17928
+ return;
17929
+ }
17539
17930
  const started = Date.now();
17540
17931
  try {
17541
17932
  const manifest = generateSnapshot({ ...runConfig, cwd: target }, {
@@ -17570,12 +17961,12 @@ async function startWebServer(options) {
17570
17961
  return;
17571
17962
  }
17572
17963
  if (request.method === "GET" && request.url?.startsWith("/api/health?") === true) {
17573
- const target = path25.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
17964
+ const target = path26.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
17574
17965
  if (!lexicallyInside(target)) {
17575
17966
  send(403, { error: "outside the served directory: " + target });
17576
17967
  return;
17577
17968
  }
17578
- if (!fs24.existsSync(path25.join(target, "manifest.json"))) {
17969
+ if (!fs25.existsSync(path26.join(target, "manifest.json"))) {
17579
17970
  send(404, { error: "no manifest.json under " + target });
17580
17971
  return;
17581
17972
  }
@@ -17583,17 +17974,17 @@ async function startWebServer(options) {
17583
17974
  send(403, { error: "outside the served directory: " + target });
17584
17975
  return;
17585
17976
  }
17586
- const report2 = auditSnapshot({ snapshotDir: target, repoDir: path25.dirname(target) });
17977
+ const report2 = auditSnapshot({ snapshotDir: target, repoDir: path26.dirname(target) });
17587
17978
  send(200, { score: report2.score, counts: report2.counts, checks: report2.checks });
17588
17979
  return;
17589
17980
  }
17590
17981
  if (request.method === "GET" && (request.url?.startsWith("/api/snapshot?") === true || request.url === "/api/snapshot")) {
17591
- const target = path25.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
17982
+ const target = path26.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
17592
17983
  if (!lexicallyInside(target)) {
17593
17984
  send(403, { error: "outside the served directory: " + target });
17594
17985
  return;
17595
17986
  }
17596
- if (!fs24.existsSync(path25.join(target, "manifest.json"))) {
17987
+ if (!fs25.existsSync(path26.join(target, "manifest.json"))) {
17597
17988
  send(404, { error: "no manifest.json under " + target });
17598
17989
  return;
17599
17990
  }
@@ -17601,10 +17992,18 @@ async function startWebServer(options) {
17601
17992
  send(403, { error: "outside the served directory: " + target });
17602
17993
  return;
17603
17994
  }
17604
- const manifestFile = path25.join(target, "manifest.json");
17995
+ const manifestRead = readConfinedText(target, "manifest.json");
17996
+ if (!manifestRead.ok) {
17997
+ if (manifestRead.reason === "outside") {
17998
+ send(403, { error: "manifest.json resolves outside the snapshot directory" });
17999
+ } else {
18000
+ send(404, { error: "no readable manifest.json under " + target });
18001
+ }
18002
+ return;
18003
+ }
17605
18004
  let manifest;
17606
18005
  try {
17607
- manifest = JSON.parse(fs24.readFileSync(manifestFile, "utf8"));
18006
+ manifest = JSON.parse(manifestRead.text);
17608
18007
  } catch {
17609
18008
  send(404, { error: "no manifest.json under " + target });
17610
18009
  return;
@@ -17614,12 +18013,8 @@ async function startWebServer(options) {
17614
18013
  send(400, { error: "manifest.json is not a snapshot manifest: " + shapeProblem });
17615
18014
  return;
17616
18015
  }
17617
- let prompt = "";
17618
- try {
17619
- prompt = fs24.readFileSync(path25.join(target, "PROMPT.md"), "utf8").slice(0, MAX_PREVIEW);
17620
- } catch {
17621
- prompt = "(this snapshot has no PROMPT.md)";
17622
- }
18016
+ const promptRead = readConfinedText(target, "PROMPT.md");
18017
+ const prompt = promptRead.ok ? promptRead.text.slice(0, MAX_PREVIEW) : "(this snapshot has no readable PROMPT.md)";
17623
18018
  send(200, {
17624
18019
  fingerprint: manifest.fingerprint ?? "",
17625
18020
  generatedAt: manifest.generatedAt ?? "",
@@ -17632,12 +18027,12 @@ async function startWebServer(options) {
17632
18027
  return;
17633
18028
  }
17634
18029
  if (request.method === "GET" && request.url?.startsWith("/api/snapshot.zip") === true) {
17635
- const target = path25.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
18030
+ const target = path26.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
17636
18031
  if (!lexicallyInside(target)) {
17637
18032
  send(403, { error: "outside the served directory: " + target });
17638
18033
  return;
17639
18034
  }
17640
- if (!fs24.existsSync(path25.join(target, "manifest.json")) && !fs24.existsSync(path25.join(target, ".codebase-snapshot"))) {
18035
+ if (!fs25.existsSync(path26.join(target, "manifest.json")) && !fs25.existsSync(path26.join(target, ".codebase-snapshot"))) {
17641
18036
  send(404, { error: "not a snapshot directory: " + target });
17642
18037
  return;
17643
18038
  }
@@ -17661,11 +18056,11 @@ async function startWebServer(options) {
17661
18056
  }
17662
18057
  send(404, { error: "not found" });
17663
18058
  });
17664
- await new Promise((resolve14, reject) => {
18059
+ await new Promise((resolve15, reject) => {
17665
18060
  server.once("error", reject);
17666
18061
  server.listen(port, host, () => {
17667
18062
  server.removeListener("error", reject);
17668
- resolve14();
18063
+ resolve15();
17669
18064
  });
17670
18065
  });
17671
18066
  const address = server.address();
@@ -17677,14 +18072,14 @@ async function startWebServer(options) {
17677
18072
  port: actualPort,
17678
18073
  host,
17679
18074
  token,
17680
- close: () => new Promise((resolve14) => {
18075
+ close: () => new Promise((resolve15) => {
17681
18076
  for (const directory of temporaryClones) {
17682
18077
  try {
17683
- fs24.rmSync(directory, { recursive: true, force: true });
18078
+ fs25.rmSync(directory, { recursive: true, force: true });
17684
18079
  } catch {
17685
18080
  }
17686
18081
  }
17687
- server.close(() => resolve14());
18082
+ server.close(() => resolve15());
17688
18083
  })
17689
18084
  };
17690
18085
  }
@@ -17736,17 +18131,17 @@ function isNewer(candidate, current) {
17736
18131
  }
17737
18132
  function cacheDirectory(env = process.env, platform = process.platform) {
17738
18133
  if (platform === "win32") {
17739
- const base2 = env.LOCALAPPDATA ?? path25.join(os2.homedir(), "AppData", "Local");
17740
- return path25.join(base2, "codebase-snapshot");
18134
+ const base2 = env.LOCALAPPDATA ?? path26.join(os2.homedir(), "AppData", "Local");
18135
+ return path26.join(base2, "codebase-snapshot");
17741
18136
  }
17742
18137
  if (platform === "darwin") {
17743
- return path25.join(os2.homedir(), "Library", "Caches", "codebase-snapshot");
18138
+ return path26.join(os2.homedir(), "Library", "Caches", "codebase-snapshot");
17744
18139
  }
17745
- const base = env.XDG_CACHE_HOME ?? path25.join(os2.homedir(), ".cache");
17746
- return path25.join(base, "codebase-snapshot");
18140
+ const base = env.XDG_CACHE_HOME ?? path26.join(os2.homedir(), ".cache");
18141
+ return path26.join(base, "codebase-snapshot");
17747
18142
  }
17748
18143
  function cacheFilePath(env = process.env) {
17749
- return path25.join(cacheDirectory(env), "update-check.json");
18144
+ return path26.join(cacheDirectory(env), "update-check.json");
17750
18145
  }
17751
18146
  function shouldCheck(argv, env) {
17752
18147
  const disabled = ["1", "true", "yes"].includes(
@@ -17776,7 +18171,7 @@ function shouldCheck(argv, env) {
17776
18171
  function readCache(file) {
17777
18172
  let raw;
17778
18173
  try {
17779
- raw = fs24.readFileSync(file, "utf8");
18174
+ raw = fs25.readFileSync(file, "utf8");
17780
18175
  } catch {
17781
18176
  return null;
17782
18177
  }
@@ -17793,21 +18188,21 @@ function readCache(file) {
17793
18188
  }
17794
18189
  function writeCache(file, entry) {
17795
18190
  try {
17796
- fs24.mkdirSync(path25.dirname(file), { recursive: true });
17797
- fs24.writeFileSync(file, `${JSON.stringify(entry)}
18191
+ fs25.mkdirSync(path26.dirname(file), { recursive: true });
18192
+ fs25.writeFileSync(file, `${JSON.stringify(entry)}
17798
18193
  `, "utf8");
17799
18194
  } catch {
17800
18195
  }
17801
18196
  }
17802
18197
  function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOUT_MS) {
17803
- return new Promise((resolve14) => {
18198
+ return new Promise((resolve15) => {
17804
18199
  let settled = false;
17805
18200
  let request = null;
17806
18201
  const finish = (value) => {
17807
18202
  if (settled) return;
17808
18203
  settled = true;
17809
18204
  clearTimeout(deadline);
17810
- resolve14(value);
18205
+ resolve15(value);
17811
18206
  };
17812
18207
  const deadline = setTimeout(() => {
17813
18208
  request?.destroy();
@@ -18102,14 +18497,14 @@ function compareManifests(before, after, secretRules) {
18102
18497
  function loadManifest(target) {
18103
18498
  let isDirectory;
18104
18499
  try {
18105
- isDirectory = fs24.statSync(target).isDirectory();
18500
+ isDirectory = fs25.statSync(target).isDirectory();
18106
18501
  } catch {
18107
18502
  throw new Error(`No snapshot found at ${target}: the path does not exist.`);
18108
18503
  }
18109
- const manifestPath = isDirectory ? path25.join(target, "manifest.json") : target;
18504
+ const manifestPath = isDirectory ? path26.join(target, "manifest.json") : target;
18110
18505
  let raw;
18111
18506
  try {
18112
- raw = fs24.readFileSync(manifestPath, "utf8");
18507
+ raw = fs25.readFileSync(manifestPath, "utf8");
18113
18508
  } catch {
18114
18509
  throw new Error(`Could not read a manifest at ${manifestPath}.`);
18115
18510
  }
@@ -18211,15 +18606,15 @@ function canonicalIgnorePattern(line) {
18211
18606
  function appendGitignoreEntries(cwd, entries) {
18212
18607
  const wanted = [...new Set(entries)].filter((entry) => entry.trim().length > 0);
18213
18608
  if (wanted.length === 0) return { added: [], note: null };
18214
- const ignorePath = path25.join(cwd, ".gitignore");
18609
+ const ignorePath = path26.join(cwd, ".gitignore");
18215
18610
  const manual = `Add ${wanted.map((entry) => `"${entry}"`).join(" and ")} to your .gitignore yourself.`;
18216
18611
  let decoded = { text: "", bom: Buffer.alloc(0), encoding: "utf8" };
18217
18612
  try {
18218
- if (fs24.existsSync(ignorePath)) {
18219
- if (fs24.statSync(ignorePath).isDirectory()) {
18613
+ if (fs25.existsSync(ignorePath)) {
18614
+ if (fs25.statSync(ignorePath).isDirectory()) {
18220
18615
  return { added: [], note: `${ignorePath} is a directory, so it was not updated. ${manual}` };
18221
18616
  }
18222
- const read = decodeGitignore(fs24.readFileSync(ignorePath));
18617
+ const read = decodeGitignore(fs25.readFileSync(ignorePath));
18223
18618
  if (read === null) {
18224
18619
  return {
18225
18620
  added: [],
@@ -18241,7 +18636,7 @@ function appendGitignoreEntries(cwd, entries) {
18241
18636
  const newline = existing.includes("\r\n") ? "\r\n" : "\n";
18242
18637
  const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : newline;
18243
18638
  try {
18244
- fs24.writeFileSync(
18639
+ fs25.writeFileSync(
18245
18640
  ignorePath,
18246
18641
  encodeGitignore(decoded, `${existing}${prefix}${added.join(newline)}${newline}`)
18247
18642
  );
@@ -18251,7 +18646,7 @@ function appendGitignoreEntries(cwd, entries) {
18251
18646
  return { added, note: null };
18252
18647
  }
18253
18648
  function gitignorePath(cwd, filePath) {
18254
- return path25.relative(cwd, filePath).split(path25.sep).join("/");
18649
+ return path26.relative(cwd, filePath).split(path26.sep).join("/");
18255
18650
  }
18256
18651
 
18257
18652
  // src/wizard/brief-template.ts
@@ -18641,7 +19036,7 @@ function keyReader(input) {
18641
19036
  next() {
18642
19037
  const queued = queue.shift();
18643
19038
  if (queued) return Promise.resolve(queued);
18644
- return new Promise((resolve14) => waiters.push(resolve14));
19039
+ return new Promise((resolve15) => waiters.push(resolve15));
18645
19040
  },
18646
19041
  close() {
18647
19042
  input.off("keypress", onKey);
@@ -18867,7 +19262,7 @@ function parsePackageJson(raw) {
18867
19262
  }
18868
19263
  function readPackageJson(cwd) {
18869
19264
  try {
18870
- return parsePackageJson(fs24.readFileSync(path25.join(cwd, "package.json"), "utf8"));
19265
+ return parsePackageJson(fs25.readFileSync(path26.join(cwd, "package.json"), "utf8"));
18871
19266
  } catch {
18872
19267
  return null;
18873
19268
  }
@@ -18904,7 +19299,7 @@ function artifactAnswers(options) {
18904
19299
  }
18905
19300
  function topLevelDirs(cwd) {
18906
19301
  try {
18907
- return fs24.readdirSync(cwd, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules").map((entry) => entry.name).sort();
19302
+ return fs25.readdirSync(cwd, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules").map((entry) => entry.name).sort();
18908
19303
  } catch {
18909
19304
  return [];
18910
19305
  }
@@ -18919,7 +19314,7 @@ function writeFileOrExplain(target, content) {
18919
19314
  try {
18920
19315
  let stats = null;
18921
19316
  try {
18922
- stats = fs24.lstatSync(target);
19317
+ stats = fs25.lstatSync(target);
18923
19318
  } catch {
18924
19319
  stats = null;
18925
19320
  }
@@ -18934,12 +19329,12 @@ function writeFileOrExplain(target, content) {
18934
19329
  );
18935
19330
  }
18936
19331
  const temporary = `${target}.tmp-${process.pid}-${Date.now()}`;
18937
- fs24.writeFileSync(temporary, content, { encoding: "utf8", flag: "wx" });
19332
+ fs25.writeFileSync(temporary, content, { encoding: "utf8", flag: "wx" });
18938
19333
  try {
18939
- fs24.renameSync(temporary, target);
19334
+ fs25.renameSync(temporary, target);
18940
19335
  } catch (err) {
18941
19336
  try {
18942
- fs24.unlinkSync(temporary);
19337
+ fs25.unlinkSync(temporary);
18943
19338
  } catch {
18944
19339
  }
18945
19340
  throw err;
@@ -18987,19 +19382,19 @@ function serializePackageJson(raw, value) {
18987
19382
  return `${bom}${text2}${raw.endsWith("\n") ? crlf ? "\r\n" : "\n" : ""}`;
18988
19383
  }
18989
19384
  function updatePackageJson(cwd, notes) {
18990
- const packagePath = path25.join(cwd, "package.json");
19385
+ const packagePath = path26.join(cwd, "package.json");
18991
19386
  const unchanged = {
18992
19387
  scripts: [],
18993
19388
  dependency: { name: GENERATOR_NAME, range: null, added: false }
18994
19389
  };
18995
- if (!fs24.existsSync(packagePath)) {
19390
+ if (!fs25.existsSync(packagePath)) {
18996
19391
  notes.push("No package.json found, so npm scripts and the devDependency were not added.");
18997
19392
  return unchanged;
18998
19393
  }
18999
19394
  let raw;
19000
19395
  let parsed;
19001
19396
  try {
19002
- raw = fs24.readFileSync(packagePath, "utf8");
19397
+ raw = fs25.readFileSync(packagePath, "utf8");
19003
19398
  parsed = parsePackageJson(raw);
19004
19399
  } catch {
19005
19400
  notes.push("Could not parse package.json; npm scripts and the devDependency were not added.");
@@ -19074,11 +19469,11 @@ function gitignoreEntriesFor(cwd, outDir, tmpDir) {
19074
19469
  const entries = [];
19075
19470
  for (const directory of [outDir, tmpDir]) {
19076
19471
  if (directory === null) continue;
19077
- const relative14 = path25.relative(cwd, path25.resolve(cwd, directory)).replace(/\\/g, "/");
19078
- if (relative14 === "" || relative14 === "." || relative14.startsWith("..") || path25.isAbsolute(relative14)) {
19472
+ const relative15 = path26.relative(cwd, path26.resolve(cwd, directory)).replace(/\\/g, "/");
19473
+ if (relative15 === "" || relative15 === "." || relative15.startsWith("..") || path26.isAbsolute(relative15)) {
19079
19474
  continue;
19080
19475
  }
19081
- entries.push(`/${relative14}/`);
19476
+ entries.push(`/${relative15}/`);
19082
19477
  }
19083
19478
  return [...new Set(entries)];
19084
19479
  }
@@ -19330,7 +19725,7 @@ async function runInit(options) {
19330
19725
  const configText = renderConfig(answers);
19331
19726
  const preferredName = chooseConfigFileName(options.cwd);
19332
19727
  const presentConfigs = CONFIG_CANDIDATES.filter(
19333
- (name) => fs24.existsSync(path25.join(options.cwd, name))
19728
+ (name) => fs25.existsSync(path26.join(options.cwd, name))
19334
19729
  );
19335
19730
  const present = presentConfigs[0] ?? null;
19336
19731
  if (presentConfigs.length > 1) {
@@ -19339,7 +19734,7 @@ async function runInit(options) {
19339
19734
  );
19340
19735
  }
19341
19736
  const configName = present !== null && options.force ? present : preferredName;
19342
- const configPath = path25.join(options.cwd, configName);
19737
+ const configPath = path26.join(options.cwd, configName);
19343
19738
  const reused = present !== null && options.force !== true && options.reuseConfig === true;
19344
19739
  if (reused) notes.push(`Kept the existing ${present} instead of writing a new one.`);
19345
19740
  if (options.dryRun) {
@@ -19356,7 +19751,7 @@ async function runInit(options) {
19356
19751
  dependency: { name: GENERATOR_NAME, range: `^${GENERATOR_VERSION}`, added: false },
19357
19752
  notes,
19358
19753
  outDir: answers.outDir,
19359
- briefPath: path25.join(options.cwd, BRIEF_SCAFFOLD_FILE),
19754
+ briefPath: path26.join(options.cwd, BRIEF_SCAFFOLD_FILE),
19360
19755
  briefWritten: false
19361
19756
  };
19362
19757
  }
@@ -19375,13 +19770,13 @@ async function runInit(options) {
19375
19770
  '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.'
19376
19771
  );
19377
19772
  }
19378
- if (fs24.existsSync(configPath) && !options.force && !reused) {
19773
+ if (fs25.existsSync(configPath) && !options.force && !reused) {
19379
19774
  throw new Error(`${configName} already exists. Re-run with --force to replace it.`);
19380
19775
  }
19381
19776
  if (!reused) writeFileOrExplain(configPath, configText);
19382
- const briefPath = path25.join(options.cwd, BRIEF_SCAFFOLD_FILE);
19777
+ const briefPath = path26.join(options.cwd, BRIEF_SCAFFOLD_FILE);
19383
19778
  let briefWritten = false;
19384
- if (!fs24.existsSync(briefPath)) {
19779
+ if (!fs25.existsSync(briefPath)) {
19385
19780
  writeFileOrExplain(briefPath, BRIEF_SCAFFOLD);
19386
19781
  briefWritten = true;
19387
19782
  }
@@ -19409,10 +19804,10 @@ async function runInit(options) {
19409
19804
  };
19410
19805
  }
19411
19806
  function describeTarget(cwd) {
19412
- const relative14 = path25.relative(process.cwd(), cwd);
19413
- if (relative14 === "") return "this directory";
19414
- if (relative14.startsWith("..") || path25.isAbsolute(relative14)) return cwd;
19415
- return relative14;
19807
+ const relative15 = path26.relative(process.cwd(), cwd);
19808
+ if (relative15 === "") return "this directory";
19809
+ if (relative15.startsWith("..") || path26.isAbsolute(relative15)) return cwd;
19810
+ return relative15;
19416
19811
  }
19417
19812
  function firstRunMessage(reason, cwd) {
19418
19813
  const where = describeTarget(cwd);
@@ -19435,7 +19830,7 @@ function planFirstRun(facts) {
19435
19830
  var NOT_CONTENT = /* @__PURE__ */ new Set([".git", ".hg", ".svn", ".bzr", ".DS_Store", "Thumbs.db"]);
19436
19831
  function isEffectivelyEmpty(cwd) {
19437
19832
  try {
19438
- return fs24.readdirSync(cwd).every((entry) => NOT_CONTENT.has(entry));
19833
+ return fs25.readdirSync(cwd).every((entry) => NOT_CONTENT.has(entry));
19439
19834
  } catch {
19440
19835
  return false;
19441
19836
  }
@@ -19443,7 +19838,7 @@ function isEffectivelyEmpty(cwd) {
19443
19838
  function hasPriorSnapshot(cwd, outDir) {
19444
19839
  let parsed;
19445
19840
  try {
19446
- parsed = JSON.parse(fs24.readFileSync(path25.join(cwd, outDir, ".codebase-snapshot"), "utf8"));
19841
+ parsed = JSON.parse(fs25.readFileSync(path26.join(cwd, outDir, ".codebase-snapshot"), "utf8"));
19447
19842
  } catch {
19448
19843
  return false;
19449
19844
  }
@@ -19491,36 +19886,52 @@ fi
19491
19886
  `;
19492
19887
  }
19493
19888
  function gitDirectory(cwd) {
19494
- const dotGit = path25.join(cwd, ".git");
19889
+ const dotGit = path26.join(cwd, ".git");
19495
19890
  let stats;
19496
19891
  try {
19497
- stats = fs24.statSync(dotGit);
19892
+ stats = fs25.statSync(dotGit);
19498
19893
  } catch {
19499
19894
  return null;
19500
19895
  }
19501
19896
  if (stats.isDirectory()) return dotGit;
19502
19897
  if (!stats.isFile()) return null;
19503
19898
  try {
19504
- const contents = fs24.readFileSync(dotGit, "utf8");
19899
+ const contents = fs25.readFileSync(dotGit, "utf8");
19505
19900
  const match = /^gitdir:\s*(.+)$/m.exec(contents);
19506
19901
  if (!match) return null;
19507
19902
  const target = match[1];
19508
- const resolved = path25.isAbsolute(target.trim()) ? target.trim() : path25.join(cwd, target.trim());
19509
- if (!fs24.statSync(resolved).isDirectory()) return null;
19510
- if (isInside3(path25.resolve(cwd), path25.resolve(resolved))) return resolved;
19511
- return isRegisteredWorktree(path25.resolve(resolved), cwd) ? resolved : null;
19903
+ const resolved = path26.isAbsolute(target.trim()) ? target.trim() : path26.join(cwd, target.trim());
19904
+ if (!fs25.statSync(resolved).isDirectory()) return null;
19905
+ if (isInside4(path26.resolve(cwd), path26.resolve(resolved))) return resolved;
19906
+ return isRegisteredWorktree(path26.resolve(resolved), cwd) ? resolved : null;
19512
19907
  } catch {
19513
19908
  return null;
19514
19909
  }
19515
19910
  }
19516
- function isInside3(parent, child) {
19517
- const relative14 = path25.relative(parent, child);
19518
- return relative14 === "" || !relative14.startsWith("..") && !path25.isAbsolute(relative14);
19911
+ function isInside4(parent, child) {
19912
+ const relative15 = path26.relative(parent, child);
19913
+ return relative15 === "" || !relative15.startsWith("..") && !path26.isAbsolute(relative15);
19914
+ }
19915
+ function canonicalForWrite(target) {
19916
+ let existing = path26.resolve(target);
19917
+ const tail = [];
19918
+ while (!fs25.existsSync(existing)) {
19919
+ tail.unshift(path26.basename(existing));
19920
+ const parent = path26.dirname(existing);
19921
+ if (parent === existing) break;
19922
+ existing = parent;
19923
+ }
19924
+ try {
19925
+ const real = fs25.realpathSync(existing);
19926
+ return tail.length === 0 ? real : path26.join(real, ...tail);
19927
+ } catch {
19928
+ return null;
19929
+ }
19519
19930
  }
19520
19931
  function isRegisteredWorktree(gitDir, cwd) {
19521
19932
  try {
19522
- const back = fs24.readFileSync(path25.join(gitDir, "gitdir"), "utf8").trim();
19523
- return path25.resolve(gitDir, back) === path25.join(path25.resolve(cwd), ".git");
19933
+ const back = fs25.readFileSync(path26.join(gitDir, "gitdir"), "utf8").trim();
19934
+ return path26.resolve(gitDir, back) === path26.join(path26.resolve(cwd), ".git");
19524
19935
  } catch {
19525
19936
  return false;
19526
19937
  }
@@ -19541,11 +19952,18 @@ function gitOutput(cwd, args) {
19541
19952
  function configuredHooksDirectory(cwd) {
19542
19953
  const hooks = gitOutput(cwd, ["rev-parse", "--git-path", "hooks"]);
19543
19954
  if (hooks === null) return null;
19544
- const resolved = path25.resolve(cwd, hooks);
19955
+ const resolved = path26.resolve(cwd, hooks);
19545
19956
  const common = gitOutput(cwd, ["rev-parse", "--git-common-dir"]);
19546
- const commonDir = common === null ? null : path25.resolve(cwd, common);
19547
- if (isInside3(path25.resolve(cwd), resolved)) return { dir: resolved };
19548
- if (commonDir !== null && isInside3(commonDir, resolved)) return { dir: resolved };
19957
+ const commonDir = common === null ? null : canonicalForWrite(path26.resolve(cwd, common));
19958
+ const cwdReal = canonicalForWrite(cwd);
19959
+ const hooksReal = canonicalForWrite(resolved);
19960
+ if (hooksReal === null || cwdReal === null) {
19961
+ return {
19962
+ refusal: `The hooks directory git reports (${resolved}) could not be resolved, so no hook was written.`
19963
+ };
19964
+ }
19965
+ if (isInside4(cwdReal, hooksReal)) return { dir: hooksReal };
19966
+ if (commonDir !== null && isInside4(commonDir, hooksReal)) return { dir: hooksReal };
19549
19967
  return {
19550
19968
  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.`
19551
19969
  };
@@ -19565,10 +19983,42 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
19565
19983
  ]
19566
19984
  };
19567
19985
  }
19568
- const hooksDir = configured === null ? path25.join(gitDir, "hooks") : configured.dir;
19569
- const hookPath = path25.join(hooksDir, "pre-commit");
19986
+ const hooksDir = configured === null ? path26.join(gitDir, "hooks") : configured.dir;
19987
+ const hookPath = path26.join(hooksDir, "pre-commit");
19988
+ try {
19989
+ const existingStats = fs25.lstatSync(hookPath);
19990
+ if (existingStats.isSymbolicLink()) {
19991
+ return {
19992
+ path: hookPath,
19993
+ written: false,
19994
+ notes: [`Refusing to write ${hookPath}: it is a symbolic link.`]
19995
+ };
19996
+ }
19997
+ if (existingStats.isFile() && existingStats.nlink > 1) {
19998
+ return {
19999
+ path: hookPath,
20000
+ written: false,
20001
+ notes: [`Refusing to write ${hookPath}: it has ${existingStats.nlink} hard links.`]
20002
+ };
20003
+ }
20004
+ if (!existingStats.isFile()) {
20005
+ return {
20006
+ path: hookPath,
20007
+ written: false,
20008
+ notes: [`Refusing to write ${hookPath}: it is not a regular file.`]
20009
+ };
20010
+ }
20011
+ } catch (error) {
20012
+ if (error.code !== "ENOENT") {
20013
+ return {
20014
+ path: hookPath,
20015
+ written: false,
20016
+ notes: [`Refusing to write ${hookPath}: ${error.message}`]
20017
+ };
20018
+ }
20019
+ }
19570
20020
  try {
19571
- fs24.mkdirSync(hooksDir, { recursive: true });
20021
+ fs25.mkdirSync(hooksDir, { recursive: true });
19572
20022
  } catch (err) {
19573
20023
  return {
19574
20024
  path: hookPath,
@@ -19578,7 +20028,7 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
19578
20028
  }
19579
20029
  let existing = null;
19580
20030
  try {
19581
- existing = fs24.readFileSync(hookPath, "utf8");
20031
+ existing = fs25.readFileSync(hookPath, "utf8");
19582
20032
  } catch {
19583
20033
  existing = null;
19584
20034
  }
@@ -19593,8 +20043,8 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
19593
20043
  };
19594
20044
  }
19595
20045
  try {
19596
- fs24.writeFileSync(hookPath, hookScript(outDir), "utf8");
19597
- fs24.chmodSync(hookPath, 493);
20046
+ fs25.writeFileSync(hookPath, hookScript(outDir), "utf8");
20047
+ fs25.chmodSync(hookPath, 493);
19598
20048
  } catch (err) {
19599
20049
  return {
19600
20050
  path: hookPath,
@@ -19616,23 +20066,23 @@ var SUMMARY_MAX_SOURCE_BYTES2 = SUMMARY_MAX_SOURCE_BYTES;
19616
20066
  var FILE_DERIVATIONS = /* @__PURE__ */ new Map();
19617
20067
  var FILE_DERIVATION_LIMIT_BYTES = 64 * 1024 * 1024;
19618
20068
  var fileDerivationBytes = 0;
19619
- function takeDerivation(path26, hash, settings) {
19620
- const cached = FILE_DERIVATIONS.get(path26);
20069
+ function takeDerivation(path27, hash, settings) {
20070
+ const cached = FILE_DERIVATIONS.get(path27);
19621
20071
  if (cached === void 0 || cached.hash !== hash || cached.settings !== settings) return void 0;
19622
- FILE_DERIVATIONS.delete(path26);
19623
- FILE_DERIVATIONS.set(path26, cached);
20072
+ FILE_DERIVATIONS.delete(path27);
20073
+ FILE_DERIVATIONS.set(path27, cached);
19624
20074
  return cached;
19625
20075
  }
19626
- function rememberDerivation(path26, hash, settings, derivation) {
20076
+ function rememberDerivation(path27, hash, settings, derivation) {
19627
20077
  const bodyBytes = derivation.finalContent === derivation.redacted ? derivation.redacted.length : derivation.redacted.length + derivation.finalContent.length;
19628
20078
  const bytes = bodyBytes * 2 + 512;
19629
20079
  if (bytes > FILE_DERIVATION_LIMIT_BYTES / 4) return;
19630
- const previous = FILE_DERIVATIONS.get(path26);
20080
+ const previous = FILE_DERIVATIONS.get(path27);
19631
20081
  if (previous !== void 0) {
19632
- FILE_DERIVATIONS.delete(path26);
20082
+ FILE_DERIVATIONS.delete(path27);
19633
20083
  fileDerivationBytes -= previous.bytes;
19634
20084
  } else {
19635
- FILE_DERIVATIONS.delete(path26);
20085
+ FILE_DERIVATIONS.delete(path27);
19636
20086
  }
19637
20087
  while (fileDerivationBytes + bytes > FILE_DERIVATION_LIMIT_BYTES) {
19638
20088
  const oldest = FILE_DERIVATIONS.keys().next();
@@ -19641,7 +20091,7 @@ function rememberDerivation(path26, hash, settings, derivation) {
19641
20091
  FILE_DERIVATIONS.delete(oldest.value);
19642
20092
  if (evicted !== void 0) fileDerivationBytes -= evicted.bytes;
19643
20093
  }
19644
- FILE_DERIVATIONS.set(path26, { ...derivation, hash, settings, bytes });
20094
+ FILE_DERIVATIONS.set(path27, { ...derivation, hash, settings, bytes });
19645
20095
  fileDerivationBytes += bytes;
19646
20096
  }
19647
20097
  function derivationSettings(config) {
@@ -19921,11 +20371,11 @@ function verifyInMemory(files, parts, unaccounted) {
19921
20371
  return errors;
19922
20372
  }
19923
20373
  function resolveSafeOutputDirs(config) {
19924
- const cwd = path25.resolve(config.cwd);
19925
- const outDir = path25.resolve(cwd, config.outDir);
19926
- const tmpDir = path25.resolve(cwd, config.tmpDir);
19927
- const root = path25.parse(cwd).root;
19928
- const contains = (parent, child) => child === parent || child.startsWith(`${parent}${path25.sep}`);
20374
+ const cwd = path26.resolve(config.cwd);
20375
+ const outDir = path26.resolve(cwd, config.outDir);
20376
+ const tmpDir = path26.resolve(cwd, config.tmpDir);
20377
+ const root = path26.parse(cwd).root;
20378
+ const contains = (parent, child) => child === parent || child.startsWith(`${parent}${path26.sep}`);
19929
20379
  const reject = (reason) => {
19930
20380
  throw new Error(
19931
20381
  `Refusing to generate: ${reason}. outDir=${outDir} tmpDir=${tmpDir} cwd=${cwd}`
@@ -19967,7 +20417,7 @@ function maskPathText(value, secretRules) {
19967
20417
  }
19968
20418
  function maskOwnerBrief(brief, secretRules) {
19969
20419
  if (brief === void 0) return void 0;
19970
- const mask = (value) => scanAndRedactSecrets(value, secretRules ?? [], "owner-brief").redacted;
20420
+ const mask = (value) => maskProse(value, secretRules, "owner-brief");
19971
20421
  return {
19972
20422
  ...brief,
19973
20423
  path: mask(brief.path),
@@ -19977,11 +20427,17 @@ function maskOwnerBrief(brief, secretRules) {
19977
20427
  ...brief.bar === void 0 ? {} : { bar: mask(brief.bar) },
19978
20428
  ...brief.calibration === void 0 ? {} : { calibration: mask(brief.calibration) },
19979
20429
  ...brief.preamble === void 0 ? {} : { preamble: mask(brief.preamble) },
19980
- notes: brief.notes.map((note) => ({ heading: note.heading, body: mask(note.body) }))
20430
+ // The heading is prose too. Masking only the body left `## Incident ghp_…` in PROMPT.md:
20431
+ // ownerNotesSection reproduced the heading as a Markdown title, where no line rule that
20432
+ // expects `key: value` can see it.
20433
+ notes: brief.notes.map((note) => ({ heading: mask(note.heading), body: mask(note.body) }))
19981
20434
  };
19982
20435
  }
20436
+ function maskProse(value, secretRules, scope) {
20437
+ return scanAndRedactSecrets(value, secretRules ?? [], scope).redacted;
20438
+ }
19983
20439
  function maskOverview(overview, secretRules) {
19984
- const mask = (value) => maskPathText(value, secretRules);
20440
+ const mask = (value) => maskProse(value, secretRules, "overview");
19985
20441
  return {
19986
20442
  ...overview.description === void 0 ? {} : { description: mask(overview.description) },
19987
20443
  ...overview.summary === void 0 ? {} : { summary: mask(overview.summary) },
@@ -20008,14 +20464,14 @@ function listEntries(dir) {
20008
20464
  const walk2 = (absolute, prefix) => {
20009
20465
  let children;
20010
20466
  try {
20011
- children = fs24.readdirSync(absolute, { withFileTypes: true });
20467
+ children = fs25.readdirSync(absolute, { withFileTypes: true });
20012
20468
  } catch {
20013
20469
  return;
20014
20470
  }
20015
20471
  for (const child of children) {
20016
- const relative14 = prefix === "" ? child.name : `${prefix}/${child.name}`;
20017
- entries.push(relative14);
20018
- if (child.isDirectory()) walk2(path25.join(absolute, child.name), relative14);
20472
+ const relative15 = prefix === "" ? child.name : `${prefix}/${child.name}`;
20473
+ entries.push(relative15);
20474
+ if (child.isDirectory()) walk2(path26.join(absolute, child.name), relative15);
20019
20475
  }
20020
20476
  };
20021
20477
  walk2(dir, "");
@@ -20027,10 +20483,10 @@ function markerInventory(dir, written) {
20027
20483
  for (const entry of entries) {
20028
20484
  if (entry === OWNERSHIP_MARKER) continue;
20029
20485
  if (isIgnorableEntry(entry)) continue;
20030
- const full = path25.join(dir, ...entry.split("/"));
20486
+ const full = path26.join(dir, ...entry.split("/"));
20031
20487
  let stats;
20032
20488
  try {
20033
- stats = fs24.lstatSync(full);
20489
+ stats = fs25.lstatSync(full);
20034
20490
  } catch {
20035
20491
  continue;
20036
20492
  }
@@ -20042,7 +20498,7 @@ function markerInventory(dir, written) {
20042
20498
  }
20043
20499
  let digest;
20044
20500
  try {
20045
- digest = sha256Hex2(fs24.readFileSync(full));
20501
+ digest = sha256Hex2(fs25.readFileSync(full));
20046
20502
  } catch {
20047
20503
  continue;
20048
20504
  }
@@ -20064,15 +20520,15 @@ function markerPayload(dir, state, id, createdAt, written, runId) {
20064
20520
  entries,
20065
20521
  files
20066
20522
  };
20067
- const manifestPath = path25.join(dir, "manifest.json");
20068
- if (fs24.existsSync(manifestPath)) {
20069
- marker2.manifestSha256 = sha256Hex2(fs24.readFileSync(manifestPath));
20523
+ const manifestPath = path26.join(dir, "manifest.json");
20524
+ if (fs25.existsSync(manifestPath)) {
20525
+ marker2.manifestSha256 = sha256Hex2(fs25.readFileSync(manifestPath));
20070
20526
  }
20071
20527
  return marker2;
20072
20528
  }
20073
20529
  function writeOwnershipMarker(dir, marker2) {
20074
- fs24.writeFileSync(
20075
- path25.join(dir, OWNERSHIP_MARKER),
20530
+ fs25.writeFileSync(
20531
+ path26.join(dir, OWNERSHIP_MARKER),
20076
20532
  `${JSON.stringify(marker2, null, 2)}
20077
20533
  `,
20078
20534
  "utf8"
@@ -20084,13 +20540,13 @@ function markerBelongsTo(dir, id) {
20084
20540
  return evidence.marker.id === id;
20085
20541
  }
20086
20542
  function readOwnershipMarker(dir) {
20087
- const markerPath = path25.join(dir, OWNERSHIP_MARKER);
20088
- if (!fs24.existsSync(markerPath)) {
20543
+ const markerPath = path26.join(dir, OWNERSHIP_MARKER);
20544
+ if (!fs25.existsSync(markerPath)) {
20089
20545
  return { marker: null, problem: "it holds no .codebase-snapshot marker" };
20090
20546
  }
20091
20547
  let raw;
20092
20548
  try {
20093
- raw = fs24.readFileSync(markerPath, "utf8");
20549
+ raw = fs25.readFileSync(markerPath, "utf8");
20094
20550
  } catch {
20095
20551
  return { marker: null, problem: "its .codebase-snapshot marker could not be read" };
20096
20552
  }
@@ -20191,10 +20647,10 @@ function verifyMarkerInventory(dir, entries, files) {
20191
20647
  for (const entry of entries) {
20192
20648
  if (entry === OWNERSHIP_MARKER) continue;
20193
20649
  if (IGNORABLE_ENTRIES.has(entry.slice(entry.lastIndexOf("/") + 1))) continue;
20194
- const full = path25.join(dir, ...entry.split("/"));
20650
+ const full = path26.join(dir, ...entry.split("/"));
20195
20651
  let stats;
20196
20652
  try {
20197
- stats = fs24.lstatSync(full);
20653
+ stats = fs25.lstatSync(full);
20198
20654
  } catch {
20199
20655
  return `its .codebase-snapshot inventory lists ${entry}, which cannot be read`;
20200
20656
  }
@@ -20219,7 +20675,7 @@ function verifyMarkerInventory(dir, entries, files) {
20219
20675
  }
20220
20676
  let digest;
20221
20677
  try {
20222
- digest = sha256Hex2(fs24.readFileSync(full));
20678
+ digest = sha256Hex2(fs25.readFileSync(full));
20223
20679
  } catch {
20224
20680
  return `its .codebase-snapshot inventory cannot verify ${entry}: the file could not be read`;
20225
20681
  }
@@ -20240,12 +20696,12 @@ function assessSnapshotDirectory(dir) {
20240
20696
  marker: marker2
20241
20697
  };
20242
20698
  }
20243
- const manifestPath = path25.join(dir, "manifest.json");
20244
- const hasManifest = fs24.existsSync(manifestPath);
20699
+ const manifestPath = path26.join(dir, "manifest.json");
20700
+ const hasManifest = fs25.existsSync(manifestPath);
20245
20701
  if (hasManifest) {
20246
20702
  let raw;
20247
20703
  try {
20248
- raw = fs24.readFileSync(manifestPath, "utf8");
20704
+ raw = fs25.readFileSync(manifestPath, "utf8");
20249
20705
  } catch {
20250
20706
  return {
20251
20707
  owned: false,
@@ -20346,13 +20802,13 @@ function containsNoFiles(dir) {
20346
20802
  const current = pending.pop();
20347
20803
  let entries;
20348
20804
  try {
20349
- entries = fs24.readdirSync(current, { withFileTypes: true });
20805
+ entries = fs25.readdirSync(current, { withFileTypes: true });
20350
20806
  } catch {
20351
20807
  return false;
20352
20808
  }
20353
20809
  for (const entry of entries) {
20354
20810
  if (entry.isDirectory()) {
20355
- pending.push(path25.join(current, entry.name));
20811
+ pending.push(path26.join(current, entry.name));
20356
20812
  } else if (!IGNORABLE_ENTRIES.has(entry.name)) {
20357
20813
  return false;
20358
20814
  }
@@ -20361,13 +20817,13 @@ function containsNoFiles(dir) {
20361
20817
  return true;
20362
20818
  }
20363
20819
  function assertReplaceable(target, label, secretRules) {
20364
- if (!fs24.existsSync(target)) return;
20365
- if (!fs24.statSync(target).isDirectory()) {
20820
+ if (!fs25.existsSync(target)) return;
20821
+ if (!fs25.statSync(target).isDirectory()) {
20366
20822
  throw new Error(
20367
20823
  `Refusing to write into ${label} ${target}: it exists but is not a directory.`
20368
20824
  );
20369
20825
  }
20370
- const entries = fs24.readdirSync(target);
20826
+ const entries = fs25.readdirSync(target);
20371
20827
  if (entries.length === 0) return;
20372
20828
  if (entries.every((name) => IGNORABLE_ENTRIES.has(name))) return;
20373
20829
  if (containsNoFiles(target)) return;
@@ -20387,18 +20843,18 @@ function assertReplaceable(target, label, secretRules) {
20387
20843
  );
20388
20844
  }
20389
20845
  function assertStagingRootUsable(tmpDir, secretRules) {
20390
- if (!fs24.existsSync(tmpDir)) return;
20391
- if (!fs24.statSync(tmpDir).isDirectory()) {
20846
+ if (!fs25.existsSync(tmpDir)) return;
20847
+ if (!fs25.statSync(tmpDir).isDirectory()) {
20392
20848
  throw new Error(`Refusing to write into tmpDir ${tmpDir}: it exists but is not a directory.`);
20393
20849
  }
20394
- const entries = fs24.readdirSync(tmpDir);
20850
+ const entries = fs25.readdirSync(tmpDir);
20395
20851
  if (entries.length === 0) return;
20396
20852
  const foreign = entries.filter((name) => {
20397
- const full = path25.join(tmpDir, name);
20853
+ const full = path26.join(tmpDir, name);
20398
20854
  if (!name.startsWith(RUN_DIR_PREFIX)) return true;
20399
20855
  let stats;
20400
20856
  try {
20401
- stats = fs24.statSync(full);
20857
+ stats = fs25.statSync(full);
20402
20858
  } catch {
20403
20859
  return true;
20404
20860
  }
@@ -20406,7 +20862,7 @@ function assertStagingRootUsable(tmpDir, secretRules) {
20406
20862
  const { marker: marker2 } = readOwnershipMarker(full);
20407
20863
  if (marker2) return false;
20408
20864
  try {
20409
- return fs24.readdirSync(full).length > 0;
20865
+ return fs25.readdirSync(full).length > 0;
20410
20866
  } catch {
20411
20867
  return true;
20412
20868
  }
@@ -20421,13 +20877,13 @@ function assertStagingRootUsable(tmpDir, secretRules) {
20421
20877
  function cleanStaleRunDirs(tmpDir) {
20422
20878
  let entries;
20423
20879
  try {
20424
- entries = fs24.readdirSync(tmpDir);
20880
+ entries = fs25.readdirSync(tmpDir);
20425
20881
  } catch {
20426
20882
  return;
20427
20883
  }
20428
20884
  for (const name of entries) {
20429
20885
  if (!name.startsWith(RUN_DIR_PREFIX)) continue;
20430
- const full = path25.join(tmpDir, name);
20886
+ const full = path26.join(tmpDir, name);
20431
20887
  const { marker: marker2 } = readOwnershipMarker(full);
20432
20888
  if (marker2) {
20433
20889
  const created = Date.parse(marker2.createdAt);
@@ -20435,33 +20891,33 @@ function cleanStaleRunDirs(tmpDir) {
20435
20891
  const abandoned = typeof marker2.pid === "number" && !isProcessAlive(marker2.pid);
20436
20892
  if (aged || abandoned) {
20437
20893
  try {
20438
- fs24.rmSync(full, { recursive: true, force: true });
20894
+ fs25.rmSync(full, { recursive: true, force: true });
20439
20895
  } catch {
20440
20896
  }
20441
20897
  }
20442
20898
  continue;
20443
20899
  }
20444
20900
  try {
20445
- if (fs24.readdirSync(full).length === 0) fs24.rmSync(full, { recursive: true, force: true });
20901
+ if (fs25.readdirSync(full).length === 0) fs25.rmSync(full, { recursive: true, force: true });
20446
20902
  } catch {
20447
20903
  }
20448
20904
  }
20449
20905
  }
20450
20906
  function removeIfEmpty(dir) {
20451
20907
  try {
20452
- if (fs24.readdirSync(dir).length === 0) fs24.rmSync(dir, { recursive: true, force: true });
20908
+ if (fs25.readdirSync(dir).length === 0) fs25.rmSync(dir, { recursive: true, force: true });
20453
20909
  } catch {
20454
20910
  }
20455
20911
  }
20456
20912
  function ensureParentDirectory(target, label) {
20457
- const parent = path25.dirname(target);
20458
- if (fs24.existsSync(parent) && !fs24.statSync(parent).isDirectory()) {
20913
+ const parent = path26.dirname(target);
20914
+ if (fs25.existsSync(parent) && !fs25.statSync(parent).isDirectory()) {
20459
20915
  throw new Error(
20460
20916
  `Refusing to create ${label} ${target}: ${parent} exists but is not a directory.`
20461
20917
  );
20462
20918
  }
20463
20919
  try {
20464
- fs24.mkdirSync(parent, { recursive: true });
20920
+ fs25.mkdirSync(parent, { recursive: true });
20465
20921
  } catch (err) {
20466
20922
  throw new Error(
20467
20923
  `Refusing to create ${label} ${target}: its parent ${parent} could not be created (${err.message}).`
@@ -20470,6 +20926,7 @@ function ensureParentDirectory(target, label) {
20470
20926
  }
20471
20927
  var LOCK_HEARTBEAT_MS = 5e3;
20472
20928
  var LOCK_STALE_HEARTBEAT_MS = 12e4;
20929
+ var LOCK_EMPTY_GRACE_MS = 5e3;
20473
20930
  var LOCK_HEARTBEAT_SOURCE = `
20474
20931
  const { parentPort, workerData } = require("node:worker_threads");
20475
20932
  const fs = require("node:fs");
@@ -20519,17 +20976,17 @@ function acquireRunLock(stagingRoot, runId) {
20519
20976
  `;
20520
20977
  for (let attempt = 0; attempt < 2; attempt += 1) {
20521
20978
  try {
20522
- const handle = fs24.openSync(lockPath, "wx");
20979
+ const handle = fs25.openSync(lockPath, "wx");
20523
20980
  try {
20524
- fs24.writeSync(handle, payload);
20981
+ fs25.writeSync(handle, payload);
20525
20982
  } finally {
20526
- fs24.closeSync(handle);
20983
+ fs25.closeSync(handle);
20527
20984
  }
20528
20985
  const stopHeartbeat = startLockHeartbeat(lockPath);
20529
20986
  return () => {
20530
20987
  stopHeartbeat();
20531
20988
  try {
20532
- fs24.rmSync(lockPath, { force: true });
20989
+ fs25.rmSync(lockPath, { force: true });
20533
20990
  } catch {
20534
20991
  }
20535
20992
  };
@@ -20549,45 +21006,45 @@ function lockKeyFor(stagingRoot) {
20549
21006
  return sha256Hex2(key).slice(0, 16);
20550
21007
  }
20551
21008
  function canonicalLockTarget(targetPath) {
20552
- const resolved = path25.resolve(targetPath);
21009
+ const resolved = path26.resolve(targetPath);
20553
21010
  let existing = resolved;
20554
21011
  const tail = [];
20555
21012
  for (; ; ) {
20556
21013
  try {
20557
- return path25.join(fs24.realpathSync(existing), ...tail);
21014
+ return path26.join(fs25.realpathSync(existing), ...tail);
20558
21015
  } catch {
20559
- const parent = path25.dirname(existing);
21016
+ const parent = path26.dirname(existing);
20560
21017
  if (parent === existing) return resolved;
20561
- tail.unshift(path25.basename(existing));
21018
+ tail.unshift(path26.basename(existing));
20562
21019
  existing = parent;
20563
21020
  }
20564
21021
  }
20565
21022
  }
20566
21023
  function lockPathFor(stagingRoot) {
20567
- return path25.join(os2.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
21024
+ return path26.join(os2.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
20568
21025
  }
20569
21026
  function releaseAbandonedRun(stagingRoots, runId) {
20570
21027
  if (runId.length === 0) return;
20571
21028
  for (const root of new Set(stagingRoots)) {
20572
21029
  const lockPath = lockPathFor(root);
20573
21030
  try {
20574
- const payload = JSON.parse(fs24.readFileSync(lockPath, "utf8"));
20575
- if (payload.runId === runId) fs24.rmSync(lockPath, { force: true });
21031
+ const payload = JSON.parse(fs25.readFileSync(lockPath, "utf8"));
21032
+ if (payload.runId === runId) fs25.rmSync(lockPath, { force: true });
20576
21033
  } catch {
20577
21034
  }
20578
21035
  let entries;
20579
21036
  try {
20580
- entries = fs24.readdirSync(root);
21037
+ entries = fs25.readdirSync(root);
20581
21038
  } catch {
20582
21039
  continue;
20583
21040
  }
20584
21041
  for (const name of entries) {
20585
21042
  if (!name.startsWith(RUN_DIR_PREFIX)) continue;
20586
- const directory = path25.join(root, name);
21043
+ const directory = path26.join(root, name);
20587
21044
  const { marker: marker2 } = readOwnershipMarker(directory);
20588
21045
  if (marker2?.runId !== runId) continue;
20589
21046
  try {
20590
- fs24.rmSync(directory, { recursive: true, force: true });
21047
+ fs25.rmSync(directory, { recursive: true, force: true });
20591
21048
  } catch {
20592
21049
  }
20593
21050
  }
@@ -20595,7 +21052,7 @@ function releaseAbandonedRun(stagingRoots, runId) {
20595
21052
  }
20596
21053
  function lockHeartbeatAgeMs(lockPath) {
20597
21054
  try {
20598
- return Date.now() - fs24.statSync(lockPath).mtimeMs;
21055
+ return Date.now() - fs25.statSync(lockPath).mtimeMs;
20599
21056
  } catch {
20600
21057
  return Number.POSITIVE_INFINITY;
20601
21058
  }
@@ -20603,7 +21060,7 @@ function lockHeartbeatAgeMs(lockPath) {
20603
21060
  function lockOwnerIsGone(lockPath) {
20604
21061
  let raw;
20605
21062
  try {
20606
- raw = fs24.readFileSync(lockPath, "utf8");
21063
+ raw = fs25.readFileSync(lockPath, "utf8");
20607
21064
  } catch {
20608
21065
  return false;
20609
21066
  }
@@ -20611,9 +21068,11 @@ function lockOwnerIsGone(lockPath) {
20611
21068
  try {
20612
21069
  pid = JSON.parse(raw).pid;
20613
21070
  } catch {
20614
- return lockFileIsAncient(lockPath);
21071
+ return lockFileIsAncient(lockPath, LOCK_EMPTY_GRACE_MS);
21072
+ }
21073
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) {
21074
+ return lockFileIsAncient(lockPath, LOCK_EMPTY_GRACE_MS);
20615
21075
  }
20616
- if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return lockFileIsAncient(lockPath);
20617
21076
  try {
20618
21077
  process.kill(pid, 0);
20619
21078
  return lockFileIsAncient(lockPath);
@@ -20625,44 +21084,44 @@ function lockOwnerIsGone(lockPath) {
20625
21084
  function reclaimStaleLock(lockPath) {
20626
21085
  let before;
20627
21086
  try {
20628
- before = fs24.statSync(lockPath);
21087
+ before = fs25.statSync(lockPath);
20629
21088
  } catch {
20630
21089
  return true;
20631
21090
  }
20632
21091
  if (!lockOwnerIsGone(lockPath)) return false;
20633
21092
  try {
20634
- const current = fs24.statSync(lockPath);
21093
+ const current = fs25.statSync(lockPath);
20635
21094
  const sameFile = current.ino === before.ino && current.birthtimeMs === before.birthtimeMs && current.mtimeMs === before.mtimeMs;
20636
21095
  if (!sameFile) return false;
20637
- fs24.rmSync(lockPath, { force: true });
21096
+ fs25.rmSync(lockPath, { force: true });
20638
21097
  return true;
20639
21098
  } catch {
20640
21099
  return false;
20641
21100
  }
20642
21101
  }
20643
- function lockFileIsAncient(lockPath) {
20644
- return lockHeartbeatAgeMs(lockPath) > LOCK_STALE_HEARTBEAT_MS;
21102
+ function lockFileIsAncient(lockPath, thresholdMs = LOCK_STALE_HEARTBEAT_MS) {
21103
+ return lockHeartbeatAgeMs(lockPath) > thresholdMs;
20645
21104
  }
20646
21105
  function writeManifestAtomically(manifestPath, manifest) {
20647
21106
  const tempPath = `${manifestPath}.${process.pid}.tmp`;
20648
- fs24.writeFileSync(tempPath, JSON.stringify(manifest, null, 2), "utf8");
21107
+ fs25.writeFileSync(tempPath, JSON.stringify(manifest, null, 2), "utf8");
20649
21108
  try {
20650
- fs24.renameSync(tempPath, manifestPath);
21109
+ fs25.renameSync(tempPath, manifestPath);
20651
21110
  } catch (err) {
20652
21111
  try {
20653
- fs24.rmSync(tempPath, { force: true });
21112
+ fs25.rmSync(tempPath, { force: true });
20654
21113
  } catch {
20655
21114
  }
20656
21115
  throw err;
20657
21116
  }
20658
21117
  }
20659
- function swapIntoPlace(stagingDir, outDir, beforeSwap) {
21118
+ function swapIntoPlace(stagingDir, outDir, beforeSwap, onStagingPreserved) {
20660
21119
  ensureParentDirectory(outDir, "outDir");
20661
21120
  const deadline = Date.now() + 3e3;
20662
21121
  let delay = 25;
20663
21122
  for (; ; ) {
20664
21123
  try {
20665
- swapOnce(stagingDir, outDir, beforeSwap);
21124
+ swapOnce(stagingDir, outDir, beforeSwap, onStagingPreserved);
20666
21125
  return;
20667
21126
  } catch (err) {
20668
21127
  const code = err.code;
@@ -20675,21 +21134,21 @@ function swapIntoPlace(stagingDir, outDir, beforeSwap) {
20675
21134
  }
20676
21135
  }
20677
21136
  function recoverInterruptedPublish(outDir) {
20678
- if (fs24.existsSync(outDir)) return;
20679
- const parent = path25.dirname(outDir);
20680
- const base = path25.basename(outDir);
21137
+ if (fs25.existsSync(outDir)) return;
21138
+ const parent = path26.dirname(outDir);
21139
+ const base = path26.basename(outDir);
20681
21140
  let backups;
20682
21141
  try {
20683
- backups = fs24.readdirSync(parent).filter((name) => name.startsWith(`${base}.backup-`));
21142
+ backups = fs25.readdirSync(parent).filter((name) => name.startsWith(`${base}.backup-`));
20684
21143
  } catch {
20685
21144
  return;
20686
21145
  }
20687
21146
  if (backups.length !== 1) return;
20688
- const backupDir = path25.join(parent, backups[0]);
21147
+ const backupDir = path26.join(parent, backups[0]);
20689
21148
  const { marker: marker2, problem } = readOwnershipMarker(backupDir);
20690
21149
  if (problem !== null || marker2 === null || marker2.state !== "complete") return;
20691
21150
  try {
20692
- fs24.renameSync(backupDir, outDir);
21151
+ fs25.renameSync(backupDir, outDir);
20693
21152
  process.stderr.write(
20694
21153
  `\u26A0 Recovered ${outDir} from ${backupDir}, left by an interrupted run. That snapshot is the one from before the interrupted run.
20695
21154
  `
@@ -20697,18 +21156,19 @@ function recoverInterruptedPublish(outDir) {
20697
21156
  } catch {
20698
21157
  }
20699
21158
  }
20700
- function swapOnce(stagingDir, outDir, beforeSwap) {
21159
+ function swapOnce(stagingDir, outDir, beforeSwap, onStagingPreserved) {
20701
21160
  const backupDir = `${outDir}.backup-${process.pid}-${Date.now()}`;
20702
- const hadPrevious = fs24.existsSync(outDir);
21161
+ const hadPrevious = fs25.existsSync(outDir);
20703
21162
  if (hadPrevious) beforeSwap?.();
20704
21163
  let movedAside = false;
20705
21164
  if (hadPrevious) {
20706
21165
  try {
20707
- fs24.renameSync(outDir, backupDir);
21166
+ fs25.renameSync(outDir, backupDir);
20708
21167
  movedAside = true;
20709
21168
  } catch (err) {
20710
21169
  if (!isLockError(err)) throw err;
20711
- fs24.rmSync(outDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
21170
+ onStagingPreserved?.();
21171
+ fs25.rmSync(outDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
20712
21172
  process.stderr.write(
20713
21173
  `\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.
20714
21174
  `
@@ -20717,27 +21177,28 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
20717
21177
  }
20718
21178
  try {
20719
21179
  try {
20720
- fs24.renameSync(stagingDir, outDir);
21180
+ fs25.renameSync(stagingDir, outDir);
20721
21181
  } catch (err) {
20722
21182
  if (err.code !== "EXDEV") throw err;
20723
21183
  const partialDir = `${outDir}.partial-${process.pid}-${Date.now()}`;
20724
21184
  try {
20725
- fs24.cpSync(stagingDir, partialDir, { recursive: true });
20726
- fs24.renameSync(partialDir, outDir);
20727
- fs24.rmSync(stagingDir, { recursive: true, force: true });
21185
+ fs25.cpSync(stagingDir, partialDir, { recursive: true });
21186
+ fs25.renameSync(partialDir, outDir);
21187
+ fs25.rmSync(stagingDir, { recursive: true, force: true });
20728
21188
  } catch (copyErr) {
20729
21189
  try {
20730
- fs24.rmSync(partialDir, { recursive: true, force: true });
21190
+ fs25.rmSync(partialDir, { recursive: true, force: true });
20731
21191
  } catch {
20732
21192
  }
20733
21193
  throw copyErr;
20734
21194
  }
20735
21195
  }
20736
21196
  } catch (err) {
20737
- if (hadPrevious && movedAside && fs24.existsSync(backupDir)) {
20738
- if (fs24.existsSync(outDir)) fs24.rmSync(outDir, { recursive: true, force: true });
20739
- fs24.renameSync(backupDir, outDir);
21197
+ if (hadPrevious && movedAside && fs25.existsSync(backupDir)) {
21198
+ if (fs25.existsSync(outDir)) fs25.rmSync(outDir, { recursive: true, force: true });
21199
+ fs25.renameSync(backupDir, outDir);
20740
21200
  } else if (hadPrevious && !movedAside) {
21201
+ onStagingPreserved?.();
20741
21202
  process.stderr.write(
20742
21203
  `\u26A0 The previous snapshot at ${outDir} was removed and the new one could not be moved into place. It is complete at ${stagingDir}.
20743
21204
  `
@@ -20747,7 +21208,7 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
20747
21208
  }
20748
21209
  if (hadPrevious) {
20749
21210
  try {
20750
- fs24.rmSync(backupDir, { recursive: true, force: true });
21211
+ fs25.rmSync(backupDir, { recursive: true, force: true });
20751
21212
  } catch (err) {
20752
21213
  process.stderr.write(
20753
21214
  `\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.
@@ -20926,8 +21387,8 @@ function generateSnapshot(configInput, options) {
20926
21387
  // first run cannot have marked them yet, so the name alone keeps a run from recording its own
20927
21388
  // output — but only at these exact paths, not at every directory that shares the name.
20928
21389
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
20929
- (directory) => path25.relative(config.cwd, path25.resolve(config.cwd, directory)).replace(/\\/g, "/")
20930
- ).filter((relative14) => relative14.length > 0 && !relative14.startsWith("..")),
21390
+ (directory) => path26.relative(config.cwd, path26.resolve(config.cwd, directory)).replace(/\\/g, "/")
21391
+ ).filter((relative15) => relative15.length > 0 && !relative15.startsWith("..")),
20931
21392
  // A staged path can be absent from the working tree while its index blob exists. Discovery
20932
21393
  // lists the working tree, so those paths would never reach the scan at all.
20933
21394
  ...stagedPaths.size > 0 ? { extraPaths: [...stagedPaths] } : {}
@@ -20955,7 +21416,7 @@ function generateSnapshot(configInput, options) {
20955
21416
  let totalSizeBytes = 0;
20956
21417
  let largeFileCount = 0;
20957
21418
  for (const relativePath of candidateFiles) {
20958
- const absolutePath = path25.join(config.cwd, relativePath);
21419
+ const absolutePath = path26.join(config.cwd, relativePath);
20959
21420
  const fromIndex = stagedPaths.has(relativePath);
20960
21421
  let buffer;
20961
21422
  let sizeBytes;
@@ -20986,9 +21447,9 @@ function generateSnapshot(configInput, options) {
20986
21447
  } else {
20987
21448
  let stats;
20988
21449
  try {
20989
- stats = fs24.statSync(absolutePath);
21450
+ stats = fs25.statSync(absolutePath);
20990
21451
  if (!stats.isFile()) {
20991
- const nestedRepository = stats.isDirectory() && fs24.existsSync(path25.join(absolutePath, ".git"));
21452
+ const nestedRepository = stats.isDirectory() && fs25.existsSync(path26.join(absolutePath, ".git"));
20992
21453
  skipped.push(
20993
21454
  nestedRepository ? {
20994
21455
  path: relativePath,
@@ -21024,7 +21485,7 @@ function generateSnapshot(configInput, options) {
21024
21485
  continue;
21025
21486
  }
21026
21487
  try {
21027
- buffer = fs24.readFileSync(absolutePath);
21488
+ buffer = fs25.readFileSync(absolutePath);
21028
21489
  } catch (err) {
21029
21490
  const code = err.code;
21030
21491
  skipped.push({
@@ -21139,14 +21600,14 @@ function generateSnapshot(configInput, options) {
21139
21600
  }
21140
21601
  retain(secretFindings, (finding) => finding.path === void 0 || keep.has(finding.path));
21141
21602
  retain(encodingNotes, (note) => keep.has(note.path));
21142
- retain(oversizeSummaryPaths, (path26) => keep.has(path26));
21143
- retain(previewSummaryPaths, (path26) => keep.has(path26));
21603
+ retain(oversizeSummaryPaths, (path27) => keep.has(path27));
21604
+ retain(previewSummaryPaths, (path27) => keep.has(path27));
21144
21605
  retain(fileWarnings, (warning) => keep.has(warning.path));
21145
- for (const path26 of [...monolithBodies.keys()]) {
21146
- if (!keep.has(path26)) monolithBodies.delete(path26);
21606
+ for (const path27 of [...monolithBodies.keys()]) {
21607
+ if (!keep.has(path27)) monolithBodies.delete(path27);
21147
21608
  }
21148
- for (const path26 of [...skippedSummaryImports.keys()]) {
21149
- if (!keep.has(path26)) skippedSummaryImports.delete(path26);
21609
+ for (const path27 of [...skippedSummaryImports.keys()]) {
21610
+ if (!keep.has(path27)) skippedSummaryImports.delete(path27);
21150
21611
  }
21151
21612
  };
21152
21613
  if (changedScope !== null && changedPaths !== null && config.withDependents === true) {
@@ -21617,7 +22078,7 @@ function generateSnapshot(configInput, options) {
21617
22078
  const reportExcludes = [...config.excludePatterns, ...config.presetExclude];
21618
22079
  const diffReport = artifacts.diff ? generateDiffReport(config.cwd, {
21619
22080
  secretRules: config.secretRules,
21620
- excluded: (relativePath) => reportExcludes.some((pattern) => matchesExclude(relativePath, pattern))
22081
+ excluded: (relativePath) => isSensitivePath(relativePath) || defaultIgnoreReason(relativePath) !== null || config.include.length > 0 && !config.include.some((pattern) => matchesExclude(relativePath, pattern)) || reportExcludes.some((pattern) => matchesExclude(relativePath, pattern))
21621
22082
  }) : null;
21622
22083
  if (diffReport !== null) manifest.artifacts.diff = artifactRecord(diffReport.text);
21623
22084
  const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount, secretRules: config.secretRules }) : null;
@@ -21643,8 +22104,8 @@ function generateSnapshot(configInput, options) {
21643
22104
  task: config.promptTask,
21644
22105
  brief: maskOwnerBrief(config.brief, config.secretRules),
21645
22106
  history: recentCommits(config.cwd).map((commit) => ({
21646
- subject: maskPathText(commit.subject, config.secretRules),
21647
- body: maskPathText(commit.body, config.secretRules)
22107
+ subject: maskProse(commit.subject, config.secretRules, "git-log"),
22108
+ body: maskProse(commit.body, config.secretRules, "git-log")
21648
22109
  })),
21649
22110
  overview: maskOverview(readProjectOverview(config.cwd), config.secretRules)
21650
22111
  }) : null;
@@ -21744,15 +22205,16 @@ function generateSnapshot(configInput, options) {
21744
22205
  recoverInterruptedPublish(outDir);
21745
22206
  assertReplaceable(outDir, "outDir", config.secretRules);
21746
22207
  let stagingDir = null;
22208
+ let stagingPreserved = false;
21747
22209
  let releaseDeferred = false;
21748
22210
  try {
21749
22211
  ensureParentDirectory(outDir, "outDir");
21750
- fs24.mkdirSync(tmpDir, { recursive: true });
22212
+ fs25.mkdirSync(tmpDir, { recursive: true });
21751
22213
  cleanStaleRunDirs(tmpDir);
21752
22214
  const snapshotId = crypto.randomUUID();
21753
22215
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
21754
- stagingDir = path25.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
21755
- fs24.mkdirSync(stagingDir);
22216
+ stagingDir = path26.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
22217
+ fs25.mkdirSync(stagingDir);
21756
22218
  writeOwnershipMarker(stagingDir, {
21757
22219
  generator: GENERATOR_NAME,
21758
22220
  version: GENERATOR_VERSION,
@@ -21763,30 +22225,30 @@ function generateSnapshot(configInput, options) {
21763
22225
  runId,
21764
22226
  pid: process.pid
21765
22227
  });
21766
- const partsDir = path25.join(stagingDir, "parts");
21767
- const reportsDir = path25.join(stagingDir, "reports");
21768
- if (artifacts.parts) fs24.mkdirSync(partsDir, { recursive: true });
22228
+ const partsDir = path26.join(stagingDir, "parts");
22229
+ const reportsDir = path26.join(stagingDir, "reports");
22230
+ if (artifacts.parts) fs25.mkdirSync(partsDir, { recursive: true });
21769
22231
  if (artifacts.navigation || artifacts.projectTree || artifacts.audit || artifacts.diff || artifacts.log || artifacts.tokenTree || config.sarif === true) {
21770
- fs24.mkdirSync(reportsDir, { recursive: true });
22232
+ fs25.mkdirSync(reportsDir, { recursive: true });
21771
22233
  }
21772
22234
  const writtenArtifacts = /* @__PURE__ */ new Map();
21773
22235
  const writeArtifact = (targetDir, relativeEntry, data) => {
21774
- const full = path25.join(targetDir, ...relativeEntry.split("/"));
21775
- fs24.writeFileSync(full, data, "utf8");
21776
- const stats = fs24.statSync(full);
22236
+ const full = path26.join(targetDir, ...relativeEntry.split("/"));
22237
+ fs25.writeFileSync(full, data, "utf8");
22238
+ const stats = fs25.statSync(full);
21777
22239
  writtenArtifacts.set(relativeEntry, {
21778
22240
  digest: { path: relativeEntry, bytes: stats.size, sha256: sha256Hex2(data) },
21779
22241
  mtimeMs: stats.mtimeMs
21780
22242
  });
21781
22243
  };
21782
22244
  const recordArtifact = (targetDir, relativeEntry) => {
21783
- const full = path25.join(targetDir, ...relativeEntry.split("/"));
21784
- const stats = fs24.statSync(full);
22245
+ const full = path26.join(targetDir, ...relativeEntry.split("/"));
22246
+ const stats = fs25.statSync(full);
21785
22247
  writtenArtifacts.set(relativeEntry, {
21786
22248
  digest: {
21787
22249
  path: relativeEntry,
21788
22250
  bytes: stats.size,
21789
- sha256: sha256Hex2(fs24.readFileSync(full))
22251
+ sha256: sha256Hex2(fs25.readFileSync(full))
21790
22252
  },
21791
22253
  mtimeMs: stats.mtimeMs
21792
22254
  });
@@ -21835,7 +22297,7 @@ function generateSnapshot(configInput, options) {
21835
22297
  "Refusing to sign: manifest.json is disabled for this run. Signing covers the manifest, so enable the manifest artifact or drop --sign."
21836
22298
  );
21837
22299
  }
21838
- const record = signManifest(path25.join(stagingDir, "manifest.json"), {
22300
+ const record = signManifest(path26.join(stagingDir, "manifest.json"), {
21839
22301
  key: options.sign.key ?? null
21840
22302
  });
21841
22303
  writeArtifact(stagingDir, SIGNATURE_FILE, JSON.stringify(record, null, 2) + "\n");
@@ -21853,17 +22315,24 @@ function generateSnapshot(configInput, options) {
21853
22315
  stagingDir,
21854
22316
  markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts, runId)
21855
22317
  );
21856
- swapIntoPlace(stagingDir, outDir, () => assertReplaceable(outDir, "outDir", config.secretRules));
22318
+ swapIntoPlace(
22319
+ stagingDir,
22320
+ outDir,
22321
+ () => assertReplaceable(outDir, "outDir", config.secretRules),
22322
+ () => {
22323
+ stagingPreserved = true;
22324
+ }
22325
+ );
21857
22326
  stagingDir = null;
21858
22327
  const warningsBeforeHook = manifest.warnings.length;
21859
22328
  const pendingHook = runAfterGenerate(config, manifest);
21860
22329
  const shipHookState = () => {
21861
22330
  if (!markerBelongsTo(outDir, snapshotId)) return;
21862
22331
  if (artifacts.manifest && manifest.warnings.length !== warningsBeforeHook) {
21863
- writeManifestAtomically(path25.join(outDir, "manifest.json"), manifest);
22332
+ writeManifestAtomically(path26.join(outDir, "manifest.json"), manifest);
21864
22333
  recordArtifact(outDir, "manifest.json");
21865
22334
  if (options?.sign !== void 0) {
21866
- const record = signManifest(path25.join(outDir, "manifest.json"), {
22335
+ const record = signManifest(path26.join(outDir, "manifest.json"), {
21867
22336
  key: options.sign.key ?? null
21868
22337
  });
21869
22338
  writeArtifact(outDir, SIGNATURE_FILE, JSON.stringify(record, null, 2) + "\n");
@@ -21907,9 +22376,9 @@ function generateSnapshot(configInput, options) {
21907
22376
  }
21908
22377
  return manifest;
21909
22378
  } catch (err) {
21910
- if (stagingDir !== null) {
22379
+ if (stagingDir !== null && !stagingPreserved) {
21911
22380
  try {
21912
- fs24.rmSync(stagingDir, { recursive: true, force: true });
22381
+ fs25.rmSync(stagingDir, { recursive: true, force: true });
21913
22382
  } catch {
21914
22383
  }
21915
22384
  }