codebase-snapshot 0.20.5 → 0.20.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 fs25 from 'fs';
5
+ import * as fs24 from 'fs';
6
6
  import * as os2 from 'os';
7
- import * as path26 from 'path';
7
+ import * as path25 from 'path';
8
8
  import ts from 'typescript';
9
9
  import { createRequire } from 'module';
10
10
  import { fileURLToPath, pathToFileURL } from 'url';
@@ -116,7 +116,7 @@ function finalizeSummary(summary) {
116
116
  }
117
117
  function eachLine(content, visit) {
118
118
  const text2 = content.length > MAX_SUMMARY_CHARS ? content.slice(0, MAX_SUMMARY_CHARS) : content;
119
- for (const line of text2.split(/\r?\n/)) visit(line);
119
+ for (const line of text2.split(/\r\n|\n|\r/)) visit(line);
120
120
  }
121
121
  function isTopLevel(line) {
122
122
  return !/^[\s]/.test(line);
@@ -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(path27, content) {
399
+ summarize(path26, content) {
400
400
  const summary = emptySummary();
401
- const lower = path27.toLowerCase();
401
+ const lower = path26.toLowerCase();
402
402
  const isJava = lower.endsWith(".java");
403
403
  const isKotlin = lower.endsWith(".kt") || lower.endsWith(".kts");
404
404
  eachLine(content, (line) => {
@@ -807,7 +807,7 @@ function summarizeTypeScriptSource(relativePath, content) {
807
807
  routeHandlers: []
808
808
  };
809
809
  const lowerPath = relativePath.toLowerCase();
810
- const scriptKind2 = /.tsx$/.test(lowerPath) ? ts.ScriptKind.TSX : /.jsx$/.test(lowerPath) ? ts.ScriptKind.JSX : /.(?:js|mjs|cjs)$/.test(lowerPath) ? ts.ScriptKind.JS : ts.ScriptKind.TS;
810
+ const scriptKind2 = /\.tsx$/.test(lowerPath) ? ts.ScriptKind.TSX : /\.jsx$/.test(lowerPath) ? ts.ScriptKind.JSX : /.(?:js|mjs|cjs)$/.test(lowerPath) ? ts.ScriptKind.JS : ts.ScriptKind.TS;
811
811
  const sourceFile = ts.createSourceFile(
812
812
  relativePath,
813
813
  content,
@@ -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(path27) {
1010
- const base = path27.split("/").pop() ?? path27;
1009
+ function componentName(path26) {
1010
+ const base = path26.split("/").pop() ?? path26;
1011
1011
  return base.replace(/\.[^.]+$/, "");
1012
1012
  }
1013
1013
  var sfcProfile = {
1014
1014
  id: "sfc",
1015
1015
  extensions: [".vue", ".svelte", ".astro"],
1016
- summarize(path27, content) {
1016
+ summarize(path26, content) {
1017
1017
  let script = "";
1018
- let usesJsx = path27.toLowerCase().endsWith(".astro");
1019
- if (path27.toLowerCase().endsWith(".astro")) {
1018
+ let usesJsx = path26.toLowerCase().endsWith(".astro");
1019
+ if (path26.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(path27);
1029
+ const name = componentName(path26);
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(path27) {
1221
- const lower = path27.toLowerCase();
1220
+ function profileForPath(path26) {
1221
+ const lower = path26.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(path27, content) {
1227
- const profile = profileForPath(path27);
1228
- return profile ? profile.summarize(path27, content) : null;
1226
+ function summarizeWithProfile(path26, content) {
1227
+ const profile = profileForPath(path26);
1228
+ return profile ? profile.summarize(path26, 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 = path26.extname(filePath).toLowerCase();
1273
+ const ext = path25.extname(filePath).toLowerCase();
1274
1274
  return BINARY_EXTENSIONS.has(ext);
1275
1275
  }
1276
1276
  function isBinaryBuffer(buffer) {
@@ -1399,17 +1399,17 @@ function decodeText(buffer) {
1399
1399
  };
1400
1400
  }
1401
1401
  const invalidBytes = countInvalidUtf8Bytes(buffer);
1402
+ const controlBytes = countControlBytes(buffer);
1403
+ if (controlBytes > CONTROL_BYTES_FLOOR && controlBytes * 100 > buffer.length) {
1404
+ return {
1405
+ text: "",
1406
+ encoding: "utf-8",
1407
+ invalidBytes,
1408
+ binary: true,
1409
+ binaryReason: `${controlBytes} control byte(s) in ${buffer.length} B; not text`
1410
+ };
1411
+ }
1402
1412
  if (invalidBytes === 0) {
1403
- const controlBytes = countControlBytes(buffer);
1404
- if (controlBytes > CONTROL_BYTES_FLOOR && controlBytes * 100 > buffer.length) {
1405
- return {
1406
- text: "",
1407
- encoding: "utf-8",
1408
- invalidBytes: 0,
1409
- binary: true,
1410
- binaryReason: `${controlBytes} control byte(s) in ${buffer.length} B; valid UTF-8 but not text`
1411
- };
1412
- }
1413
1413
  return {
1414
1414
  text: new TextDecoder("utf-8").decode(buffer),
1415
1415
  encoding: "utf-8",
@@ -1440,13 +1440,13 @@ function isBinaryFile(absolutePath) {
1440
1440
  if (isBinaryExtension(absolutePath)) return true;
1441
1441
  let fd;
1442
1442
  try {
1443
- fd = fs25.openSync(absolutePath, "r");
1443
+ fd = fs24.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 = fs25.readSync(fd, buffer, 0, wanted, position);
1449
+ const bytesRead = fs24.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
- fs25.closeSync(fd);
1467
+ fs24.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 = fs25.statSync(absolutePath);
1489
+ const stats = fs24.statSync(absolutePath);
1490
1490
  if (!stats.isFile() || stats.size > SUMMARY_MAX_SOURCE_BYTES) return [];
1491
- buffer = fs25.readFileSync(absolutePath);
1491
+ buffer = fs24.readFileSync(absolutePath);
1492
1492
  } catch {
1493
1493
  return [];
1494
1494
  }
@@ -1708,9 +1708,15 @@ function skeletonizeTypeScript(source, fileName = "file.ts") {
1708
1708
  if (end > start) spans.push({ start, end });
1709
1709
  }
1710
1710
  }
1711
- ts.forEachChild(node, visit);
1712
1711
  };
1713
- visit(sourceFile);
1712
+ const stack = [sourceFile];
1713
+ while (stack.length > 0) {
1714
+ const node = stack.pop();
1715
+ visit(node);
1716
+ ts.forEachChild(node, (child) => {
1717
+ stack.push(child);
1718
+ });
1719
+ }
1714
1720
  if (spans.length === 0) return { text: source, collapsed: 0 };
1715
1721
  const outermost = [];
1716
1722
  for (const span of spans.sort((a, b) => a.start - b.start || b.end - a.end)) {
@@ -1867,20 +1873,20 @@ var SKIPPED_WALK_DIRS = /* @__PURE__ */ new Set([
1867
1873
  ]);
1868
1874
  function readSmallFile(fullPath) {
1869
1875
  try {
1870
- const stats = fs25.statSync(fullPath);
1876
+ const stats = fs24.statSync(fullPath);
1871
1877
  if (!stats.isFile() || stats.size > MANIFEST_MAX_BYTES) return null;
1872
- return fs25.readFileSync(fullPath, "utf8");
1878
+ return fs24.readFileSync(fullPath, "utf8");
1873
1879
  } catch {
1874
1880
  return null;
1875
1881
  }
1876
1882
  }
1877
1883
  function readManifest(cwd, name) {
1878
- return readSmallFile(path26.join(cwd, name));
1884
+ return readSmallFile(path25.join(cwd, name));
1879
1885
  }
1880
1886
  function dependenciesFromPackageJson(raw) {
1881
1887
  const names = /* @__PURE__ */ new Set();
1882
1888
  try {
1883
- const parsed = JSON.parse(raw);
1889
+ const parsed = JSON.parse(stripJsonComments(raw.replace(/^\uFEFF/, "")));
1884
1890
  for (const section of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
1885
1891
  const block = parsed[section];
1886
1892
  if (block && typeof block === "object") {
@@ -1935,7 +1941,7 @@ function pnpmWorkspacePatterns(raw) {
1935
1941
  function childDirectories(cwd, parent) {
1936
1942
  let entries;
1937
1943
  try {
1938
- entries = fs25.readdirSync(path26.join(cwd, parent), { withFileTypes: true });
1944
+ entries = fs24.readdirSync(path25.join(cwd, parent), { withFileTypes: true });
1939
1945
  } catch {
1940
1946
  return [];
1941
1947
  }
@@ -1971,12 +1977,12 @@ function scanWorkspacePackages(cwd, patterns) {
1971
1977
  const files = /* @__PURE__ */ new Set();
1972
1978
  const dependencies = /* @__PURE__ */ new Set();
1973
1979
  for (const relative15 of workspacePackageDirs(cwd, patterns)) {
1974
- const full = path26.join(cwd, relative15);
1980
+ const full = path25.join(cwd, relative15);
1975
1981
  try {
1976
- for (const entry of fs25.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
1982
+ for (const entry of fs24.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
1977
1983
  } catch {
1978
1984
  }
1979
- const raw = readSmallFile(path26.join(full, "package.json"));
1985
+ const raw = readSmallFile(path25.join(full, "package.json"));
1980
1986
  if (raw !== null) {
1981
1987
  for (const name of dependenciesFromPackageJson(raw)) dependencies.add(name);
1982
1988
  }
@@ -1986,7 +1992,7 @@ function scanWorkspacePackages(cwd, patterns) {
1986
1992
  var SNAPSHOT_MARKER = ".codebase-snapshot";
1987
1993
  function isToolOwnedDirectory(dir) {
1988
1994
  try {
1989
- return fs25.statSync(dir).isDirectory() && fs25.existsSync(path26.join(dir, SNAPSHOT_MARKER));
1995
+ return fs24.statSync(dir).isDirectory() && fs24.existsSync(path25.join(dir, SNAPSHOT_MARKER));
1990
1996
  } catch {
1991
1997
  return false;
1992
1998
  }
@@ -2001,7 +2007,7 @@ function countMarkdownFiles(cwd) {
2001
2007
  directoriesSeen += 1;
2002
2008
  let entries;
2003
2009
  try {
2004
- entries = fs25.readdirSync(current.dir, { withFileTypes: true });
2010
+ entries = fs24.readdirSync(current.dir, { withFileTypes: true });
2005
2011
  } catch {
2006
2012
  continue;
2007
2013
  }
@@ -2012,7 +2018,7 @@ function countMarkdownFiles(cwd) {
2012
2018
  }
2013
2019
  if (!entry.isDirectory() || current.depth >= 2) continue;
2014
2020
  if (entry.name.startsWith(".") || SKIPPED_WALK_DIRS.has(entry.name)) continue;
2015
- const child = path26.join(current.dir, entry.name);
2021
+ const child = path25.join(current.dir, entry.name);
2016
2022
  if (isToolOwnedDirectory(child)) continue;
2017
2023
  queue.push({ dir: child, depth: current.depth + 1 });
2018
2024
  }
@@ -2023,7 +2029,7 @@ function buildPresetContext(cwd) {
2023
2029
  const files = /* @__PURE__ */ new Set();
2024
2030
  const dirs = /* @__PURE__ */ new Set();
2025
2031
  try {
2026
- for (const entry of fs25.readdirSync(cwd, { withFileTypes: true })) {
2032
+ for (const entry of fs24.readdirSync(cwd, { withFileTypes: true })) {
2027
2033
  if (entry.isDirectory()) dirs.add(entry.name);
2028
2034
  else if (entry.isFile()) files.add(entry.name);
2029
2035
  }
@@ -2040,7 +2046,7 @@ function buildPresetContext(cwd) {
2040
2046
  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
2047
  let workspace = { files: /* @__PURE__ */ new Set(), dependencies: /* @__PURE__ */ new Set() };
2042
2048
  if (isWorkspace) {
2043
- const pnpmRaw = files.has("pnpm-workspace.yaml") ? readSmallFile(path26.join(cwd, "pnpm-workspace.yaml")) : null;
2049
+ const pnpmRaw = files.has("pnpm-workspace.yaml") ? readSmallFile(path25.join(cwd, "pnpm-workspace.yaml")) : null;
2044
2050
  const declared = pnpmRaw === null ? [] : pnpmWorkspacePatterns(pnpmRaw);
2045
2051
  const patterns = declared.length > 0 ? declared : declaredWorkspaces.length > 0 ? declaredWorkspaces : DEFAULT_WORKSPACE_PATTERNS;
2046
2052
  workspace = scanWorkspacePackages(cwd, patterns);
@@ -3779,7 +3785,7 @@ function redactStructuredValues(text2, filePath, recordFinding) {
3779
3785
  }
3780
3786
  return segments.join("");
3781
3787
  }
3782
- var DOCKERFILE_ENV = /^([ \t]*ENV[ \t]+)([A-Za-z_][A-Za-z0-9_]*)([ \t]+)(\S.*)$/;
3788
+ var DOCKERFILE_ENV = /^([ \t]*)(ENV|ARG)([ \t]+)([A-Za-z_][A-Za-z0-9_]*)([ \t]*=[ \t]*|[ \t]+)(\S.*)$/i;
3783
3789
  function redactDockerfileEnv(text2, filePath, recordFinding) {
3784
3790
  if (!isDockerfile(filePath)) return text2;
3785
3791
  const segments = text2.split(LINE_BREAK);
@@ -3788,10 +3794,9 @@ function redactDockerfileEnv(text2, filePath, recordFinding) {
3788
3794
  if (line === void 0) continue;
3789
3795
  const match = DOCKERFILE_ENV.exec(line);
3790
3796
  if (match === null) continue;
3791
- if (!CREDENTIAL_KEY_TAIL.test(match[2] ?? "")) continue;
3792
- const value = match[4] ?? "";
3793
- if (value.startsWith("=")) continue;
3794
- segments[index] = `${match[1]}${match[2]}${match[3]}${REDACTION_MARKER}`;
3797
+ if (!CREDENTIAL_KEY_TAIL.test(match[4] ?? "")) continue;
3798
+ const separator = match[5] ?? "";
3799
+ segments[index] = `${match[1]}${match[2]}${match[3]}${match[4]}${separator}${REDACTION_MARKER}`;
3795
3800
  recordFinding(index / 2 + 1, ["dockerfile-env-secret"]);
3796
3801
  }
3797
3802
  return segments.join("");
@@ -3876,6 +3881,7 @@ function isSourceCodeFile(filePath) {
3876
3881
  var PLACEHOLDER_PATTERNS = [
3877
3882
  /^<[^>]*>?$/,
3878
3883
  /^\.{3,}$/,
3884
+ /^(?:[A-Za-z0-9_-]{1,8}-)?\.{3,}$/,
3879
3885
  /^(?:x{4,}|X{4,}|\*{3,})$/,
3880
3886
  /^(?:replace|change)[-_ ]?me(?:[-_ ].*)?$/i,
3881
3887
  /^your[-_ ].*$/i,
@@ -3889,7 +3895,7 @@ function isPlaceholderValue(value) {
3889
3895
  if (trimmed.length === 0) return false;
3890
3896
  if (PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(trimmed))) return true;
3891
3897
  if (trimmed.includes(REDACTION_MARKER) || trimmed.includes(PEM_REDACTION_MARKER)) return true;
3892
- return trimmed.includes("...") || /^<[^>]*$/.test(trimmed);
3898
+ return false;
3893
3899
  }
3894
3900
  function quotesAreBalanced(text2) {
3895
3901
  let single = 0;
@@ -3941,6 +3947,7 @@ var ASSIGNMENT_FILE = /\.(?:sh|bash|zsh|ksh|fish|env|ya?ml|toml|ini|conf|cfg|pro
3941
3947
  var ASSIGNMENT_BASENAME = /^(?:\.env(?:\.[^/]*)?|\.envrc|\.profile|\.bashrc|\.zshrc|\.bash_profile)$/i;
3942
3948
  function isAssignmentFile(filePath) {
3943
3949
  if (filePath === void 0) return false;
3950
+ if (isDockerfile(filePath)) return true;
3944
3951
  const normalised = filePath.replace(/\\/g, "/");
3945
3952
  if (ASSIGNMENT_FILE.test(normalised)) return true;
3946
3953
  const base = normalised.slice(normalised.lastIndexOf("/") + 1);
@@ -4007,7 +4014,7 @@ function loadSigningKey(environment = process.env) {
4007
4014
  return crypto.createPrivateKey({ key: pem, format: "pem" });
4008
4015
  }
4009
4016
  function signManifest(manifestPath, options = {}) {
4010
- const bytes = fs25.readFileSync(manifestPath);
4017
+ const bytes = fs24.readFileSync(manifestPath);
4011
4018
  const manifest = JSON.parse(bytes.toString("utf8"));
4012
4019
  if (typeof manifest.fingerprint !== "string" || !/^[0-9a-f]{64}$/.test(manifest.fingerprint)) {
4013
4020
  throw new Error("refusing to sign: the manifest has no valid fingerprint");
@@ -4027,12 +4034,12 @@ function signManifest(manifestPath, options = {}) {
4027
4034
  };
4028
4035
  }
4029
4036
  function verifySnapshotSignature(snapshotDir) {
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" };
4037
+ const signaturePath = path25.join(snapshotDir, SIGNATURE_FILE);
4038
+ const manifestPath = path25.join(snapshotDir, "manifest.json");
4039
+ if (!fs24.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
4033
4040
  let record;
4034
4041
  try {
4035
- record = JSON.parse(fs25.readFileSync(signaturePath, "utf8"));
4042
+ record = JSON.parse(fs24.readFileSync(signaturePath, "utf8"));
4036
4043
  } catch (error) {
4037
4044
  return { ok: false, reason: "signature.json is not JSON: " + error.message };
4038
4045
  }
@@ -4041,7 +4048,7 @@ function verifySnapshotSignature(snapshotDir) {
4041
4048
  }
4042
4049
  let bytes;
4043
4050
  try {
4044
- bytes = fs25.readFileSync(manifestPath);
4051
+ bytes = fs24.readFileSync(manifestPath);
4045
4052
  } catch {
4046
4053
  return { ok: false, reason: "the signed manifest is missing" };
4047
4054
  }
@@ -4049,6 +4056,15 @@ function verifySnapshotSignature(snapshotDir) {
4049
4056
  if (sha2562 !== record.manifestSha256) {
4050
4057
  return { ok: false, reason: "manifest.json changed after it was signed" };
4051
4058
  }
4059
+ let signedFingerprint;
4060
+ try {
4061
+ signedFingerprint = JSON.parse(bytes.toString("utf8")).fingerprint;
4062
+ } catch {
4063
+ return { ok: false, reason: "the signed manifest is not JSON" };
4064
+ }
4065
+ if (typeof record.fingerprint !== "string" || record.fingerprint !== signedFingerprint) {
4066
+ return { ok: false, reason: "signature.json names a different fingerprint than the manifest" };
4067
+ }
4052
4068
  let verified = false;
4053
4069
  try {
4054
4070
  const key = crypto.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
@@ -4061,7 +4077,7 @@ function verifySnapshotSignature(snapshotDir) {
4061
4077
 
4062
4078
  // src/version.ts
4063
4079
  var GENERATOR_NAME = "codebase-snapshot";
4064
- var GENERATOR_VERSION = "0.20.5";
4080
+ var GENERATOR_VERSION = "0.20.7";
4065
4081
  var SCHEMA_VERSION = "3.0.0";
4066
4082
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
4067
4083
  function isOurGeneratorName(name) {
@@ -4078,14 +4094,14 @@ var PRESET_IGNORES = new Set(
4078
4094
  );
4079
4095
  function readLinkTarget(linkPath, fallback) {
4080
4096
  try {
4081
- return fs25.readlinkSync(linkPath);
4097
+ return fs24.readlinkSync(linkPath);
4082
4098
  } catch {
4083
4099
  return fallback;
4084
4100
  }
4085
4101
  }
4086
4102
  function brokenLinkRecord(linkPath, relativePath, rootReal) {
4087
4103
  const rawTarget = readLinkTarget(linkPath, linkPath);
4088
- const resolvedFallback = path26.resolve(path26.dirname(linkPath), rawTarget);
4104
+ const resolvedFallback = path25.resolve(path25.dirname(linkPath), rawTarget);
4089
4105
  return isInside(rootReal, resolvedFallback) ? { path: relativePath, reason: "read-error", detail: "broken symlink" } : {
4090
4106
  path: relativePath,
4091
4107
  reason: "outside-root",
@@ -4093,8 +4109,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
4093
4109
  };
4094
4110
  }
4095
4111
  function isInside(root, candidate) {
4096
- const relative15 = path26.relative(root, candidate);
4097
- return relative15 === "" || !relative15.startsWith(`..${path26.sep}`) && relative15 !== ".." && !path26.isAbsolute(relative15);
4112
+ const relative15 = path25.relative(root, candidate);
4113
+ return relative15 === "" || !relative15.startsWith(`..${path25.sep}`) && relative15 !== ".." && !path25.isAbsolute(relative15);
4098
4114
  }
4099
4115
  var GIT_OUTPUT_LIMIT = 68157440;
4100
4116
  function getGitInfo(cwd, fallbackBranch = "main") {
@@ -4160,7 +4176,7 @@ var DEFAULT_IGNORED_FILES = [
4160
4176
  var SENSITIVE_BASENAME = /^(?:\.env(?:[._-][A-Za-z0-9_-]*)*|\.env(?:backup|bak|old|orig|copy|save)|\.envrc|\.npmrc(?:\.[A-Za-z0-9_-]+)?|\.yarnrc(?:\.yml)?|\.netrc(?:\.[A-Za-z0-9_-]+)?|\.git-credentials|\.htpasswd|\.pgpass|\.pypirc|\.vault-token|vault[-_]agent[-_]token|\.composer-auth\.json|auth\.json|application_default_credentials\.json|id_[a-z0-9_]+(?:\.[A-Za-z0-9_-]+)?|credentials(?:\.(?:json|ya?ml|toml))?|service[-_]?account(?:\.[a-z0-9_-]+)*\.json|secrets?\.(?:json|ya?ml|toml)|env|[A-Za-z0-9_-]{1,64}\.env)$/i;
4161
4177
  var SENSITIVE_PATH = /(?:^|\/)\.(?:aws|ssh|gnupg)\/|(?:^|\/)\.docker\/config\.json$|(?:^|\/)\.kube\/config$|(?:^|\/)\.config\/gcloud\/|(?:^|\/)\.composer\/|(?:^|\/)\.terraform\/credentials\.tfrc\.json$/i;
4162
4178
  var SENSITIVE_EXT = /\.(?:pem|key|p12|pfx|jks|keystore|ppk|asc|kdbx|tfstate|tfvars)$/i;
4163
- var TEMPLATE_SUFFIX = /^(.*)\.(?:example|sample|template|dist)(\.[A-Za-z0-9_-]+)?$/i;
4179
+ var TEMPLATE_SUFFIX = /^(.*)\.(?:example|sample|template|dist)(\.(?:json|ya?ml|toml|ini|txt|md|properties|conf|cfg))?$/i;
4164
4180
  var BACKUP_SUFFIX = /(?:~|\.(?:bak|backup|old|orig|save|copy|swp|swo|tmp|part))$/i;
4165
4181
  function normaliseName(name) {
4166
4182
  let normalised = name.trim().replace(/[. ]+$/, "");
@@ -4354,10 +4370,10 @@ function trimUnescapedTrailingSpaces(line) {
4354
4370
  return line.slice(0, end);
4355
4371
  }
4356
4372
  function readGitignoreRules(dir) {
4357
- const gitignorePath2 = path26.join(dir, ".gitignore");
4373
+ const gitignorePath2 = path25.join(dir, ".gitignore");
4358
4374
  let raw;
4359
4375
  try {
4360
- raw = fs25.readFileSync(gitignorePath2, "utf8");
4376
+ raw = fs24.readFileSync(gitignorePath2, "utf8");
4361
4377
  } catch {
4362
4378
  return [];
4363
4379
  }
@@ -4568,7 +4584,7 @@ function listIgnoredPaths(cwd) {
4568
4584
  }
4569
4585
  function hasSnapshotMarker(target) {
4570
4586
  try {
4571
- return fs25.statSync(target).isDirectory() && isToolOwnedDirectory2(target);
4587
+ return fs24.statSync(target).isDirectory() && isToolOwnedDirectory2(target);
4572
4588
  } catch {
4573
4589
  return false;
4574
4590
  }
@@ -4577,7 +4593,7 @@ var IGNORABLE_DIRECTORY_ENTRIES = /* @__PURE__ */ new Set([".DS_Store"]);
4577
4593
  function isToolOwnedDirectory2(dir) {
4578
4594
  let raw;
4579
4595
  try {
4580
- raw = fs25.readFileSync(path26.join(dir, ".codebase-snapshot"), "utf8");
4596
+ raw = fs24.readFileSync(path25.join(dir, ".codebase-snapshot"), "utf8");
4581
4597
  } catch {
4582
4598
  return false;
4583
4599
  }
@@ -4589,30 +4605,67 @@ function isToolOwnedDirectory2(dir) {
4589
4605
  }
4590
4606
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
4591
4607
  const marker2 = parsed;
4592
- if (marker2.generator !== GENERATOR_NAME || marker2.state !== "complete" || typeof marker2.id !== "string" || !Array.isArray(marker2.files)) {
4608
+ if (marker2.generator !== GENERATOR_NAME || marker2.state !== "complete" || marker2.schemaVersion !== SCHEMA_VERSION || typeof marker2.id !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(marker2.id) || typeof marker2.manifestSha256 !== "string" || !Array.isArray(marker2.files)) {
4593
4609
  return false;
4594
4610
  }
4595
- const accounted = /* @__PURE__ */ new Set();
4611
+ let manifestBytes;
4612
+ try {
4613
+ manifestBytes = fs24.readFileSync(path25.join(dir, "manifest.json"));
4614
+ } catch {
4615
+ return false;
4616
+ }
4617
+ if (createHash("sha256").update(manifestBytes).digest("hex") !== marker2.manifestSha256) {
4618
+ return false;
4619
+ }
4620
+ const recordedFiles = /* @__PURE__ */ new Set();
4596
4621
  for (const item of marker2.files) {
4597
4622
  if (!item || typeof item !== "object" || Array.isArray(item)) return false;
4598
- const entry = item.path;
4599
- if (typeof entry !== "string" || entry.length === 0) return false;
4600
- const parts = entry.split("/");
4601
- for (let depth = 1; depth <= parts.length; depth += 1) {
4602
- accounted.add(parts.slice(0, depth).join("/"));
4623
+ const record = item;
4624
+ const entry = record.path;
4625
+ if (typeof entry !== "string" || entry.length === 0 || entry.includes(String.fromCharCode(92)) || entry.includes("\0") || path25.isAbsolute(entry) || entry.split("/").includes("..") || typeof record.bytes !== "number" || !Number.isSafeInteger(record.bytes) || record.bytes < 0 || typeof record.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(record.sha256)) {
4626
+ return false;
4627
+ }
4628
+ const full = path25.join(dir, ...entry.split("/"));
4629
+ let stats;
4630
+ try {
4631
+ stats = fs24.lstatSync(full);
4632
+ } catch {
4633
+ return false;
4634
+ }
4635
+ if (!stats.isFile() || stats.size !== record.bytes) return false;
4636
+ let digest;
4637
+ try {
4638
+ digest = createHash("sha256").update(fs24.readFileSync(full)).digest("hex");
4639
+ } catch {
4640
+ return false;
4603
4641
  }
4642
+ if (digest !== record.sha256) return false;
4643
+ recordedFiles.add(entry);
4604
4644
  }
4605
- let entries;
4606
- try {
4607
- entries = fs25.readdirSync(dir);
4608
- } catch {
4609
- return false;
4645
+ const stack = [""];
4646
+ while (stack.length > 0) {
4647
+ const current = stack.pop();
4648
+ let entries;
4649
+ try {
4650
+ entries = fs24.readdirSync(path25.join(dir, current), { withFileTypes: true });
4651
+ } catch {
4652
+ return false;
4653
+ }
4654
+ for (const entry of entries) {
4655
+ const relative15 = current === "" ? entry.name : current + "/" + entry.name;
4656
+ if (relative15 === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry.name)) continue;
4657
+ if (entry.isDirectory()) {
4658
+ stack.push(relative15);
4659
+ continue;
4660
+ }
4661
+ if (!entry.isFile()) return false;
4662
+ if (relative15 === "signature.json" && !recordedFiles.has(relative15) && verifySnapshotSignature(dir).ok) {
4663
+ continue;
4664
+ }
4665
+ if (!recordedFiles.has(relative15)) return false;
4666
+ }
4610
4667
  }
4611
- return entries.every(
4612
- (entry) => entry === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry) || // A snapshot signed before signing moved into staging has a valid signature.json the old
4613
- // marker could not record. It is our artifact when the signature verifies.
4614
- entry === "signature.json" && verifySnapshotSignature(dir).ok || accounted.has(entry)
4615
- );
4668
+ return true;
4616
4669
  }
4617
4670
  function makeToolOwnedDecider(cwd, toolOwnedPaths) {
4618
4671
  const markers = /* @__PURE__ */ new Map();
@@ -4623,7 +4676,7 @@ function makeToolOwnedDecider(cwd, toolOwnedPaths) {
4623
4676
  const prefix = parts.slice(0, depth).join("/");
4624
4677
  let hasMarker = markers.get(prefix);
4625
4678
  if (hasMarker === void 0) {
4626
- hasMarker = isToolOwnedDirectory2(path26.join(cwd, prefix));
4679
+ hasMarker = isToolOwnedDirectory2(path25.join(cwd, prefix));
4627
4680
  markers.set(prefix, hasMarker);
4628
4681
  }
4629
4682
  if (hasMarker) return true;
@@ -4638,7 +4691,7 @@ function makeLinkProbe() {
4638
4691
  let known = cache.get(absolutePath);
4639
4692
  if (known === void 0) {
4640
4693
  try {
4641
- known = fs25.lstatSync(absolutePath).isSymbolicLink();
4694
+ known = fs24.lstatSync(absolutePath).isSymbolicLink();
4642
4695
  } catch {
4643
4696
  known = false;
4644
4697
  }
@@ -4651,7 +4704,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
4651
4704
  const isLink = makeLinkProbe();
4652
4705
  let rootReal = cwd;
4653
4706
  try {
4654
- rootReal = fs25.realpathSync(cwd);
4707
+ rootReal = fs24.realpathSync(cwd);
4655
4708
  } catch {
4656
4709
  }
4657
4710
  const reported = /* @__PURE__ */ new Set();
@@ -4666,7 +4719,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
4666
4719
  let linkedPath = null;
4667
4720
  for (let depth = 1; depth <= parts.length; depth += 1) {
4668
4721
  const prefix = parts.slice(0, depth).join("/");
4669
- if (isLink(path26.join(cwd, prefix))) {
4722
+ if (isLink(path25.join(cwd, prefix))) {
4670
4723
  linkedPath = prefix;
4671
4724
  break;
4672
4725
  }
@@ -4675,11 +4728,11 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
4675
4728
  kept.push(candidate);
4676
4729
  continue;
4677
4730
  }
4678
- const absolute = path26.join(cwd, linkedPath);
4731
+ const absolute = path25.join(cwd, linkedPath);
4679
4732
  const rawTarget = readLinkTarget(absolute, absolute);
4680
4733
  let targetReal = null;
4681
4734
  try {
4682
- targetReal = fs25.realpathSync(absolute);
4735
+ targetReal = fs24.realpathSync(absolute);
4683
4736
  } catch {
4684
4737
  targetReal = null;
4685
4738
  }
@@ -4697,7 +4750,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
4697
4750
  }
4698
4751
  let stats = null;
4699
4752
  try {
4700
- stats = fs25.statSync(absolute);
4753
+ stats = fs24.statSync(absolute);
4701
4754
  } catch {
4702
4755
  stats = null;
4703
4756
  }
@@ -4721,7 +4774,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
4721
4774
  });
4722
4775
  continue;
4723
4776
  }
4724
- const targetRelative = path26.relative(rootReal, targetReal).split(path26.sep).join("/");
4777
+ const targetRelative = path25.relative(rootReal, targetReal).split(path25.sep).join("/");
4725
4778
  if (isSensitivePath(targetRelative)) {
4726
4779
  report2(linkedPath, {
4727
4780
  path: linkedPath,
@@ -4794,7 +4847,7 @@ function collectFiles(cwd, options = {}) {
4794
4847
  "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."
4795
4848
  );
4796
4849
  }
4797
- if (fs25.existsSync(path26.join(cwd, ".git"))) {
4850
+ if (fs24.existsSync(path25.join(cwd, ".git"))) {
4798
4851
  throw new Error(
4799
4852
  "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."
4800
4853
  );
@@ -4865,15 +4918,16 @@ function dropSymlinksToUnincludedTargets(cwd, files, skipped) {
4865
4918
  const aliases = /* @__PURE__ */ new Set();
4866
4919
  for (const file of files) {
4867
4920
  try {
4868
- if (fs25.lstatSync(path26.join(cwd, file)).isSymbolicLink()) aliases.add(file);
4921
+ if (fs24.lstatSync(path25.join(cwd, file)).isSymbolicLink()) aliases.add(file);
4869
4922
  } catch {
4870
4923
  }
4871
4924
  }
4872
4925
  if (aliases.size === 0) return [...files];
4873
4926
  const includedTargets = /* @__PURE__ */ new Set();
4874
4927
  for (const file of files) {
4928
+ if (aliases.has(file)) continue;
4875
4929
  try {
4876
- includedTargets.add(fs25.realpathSync(path26.join(cwd, file)));
4930
+ includedTargets.add(fs24.realpathSync(path25.join(cwd, file)));
4877
4931
  } catch {
4878
4932
  }
4879
4933
  }
@@ -4885,7 +4939,7 @@ function dropSymlinksToUnincludedTargets(cwd, files, skipped) {
4885
4939
  }
4886
4940
  let target;
4887
4941
  try {
4888
- target = fs25.realpathSync(path26.join(cwd, file));
4942
+ target = fs24.realpathSync(path25.join(cwd, file));
4889
4943
  } catch {
4890
4944
  skipped.push({ path: file, reason: "read-error", detail: "symlink target could not be resolved" });
4891
4945
  continue;
@@ -4904,7 +4958,7 @@ function dropSymlinksToUnincludedTargets(cwd, files, skipped) {
4904
4958
  }
4905
4959
  function rootRealFor(root) {
4906
4960
  try {
4907
- return fs25.realpathSync(root);
4961
+ return fs24.realpathSync(root);
4908
4962
  } catch {
4909
4963
  return root;
4910
4964
  }
@@ -4913,18 +4967,18 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
4913
4967
  const results = { files: [], skipped: [] };
4914
4968
  const stack = [];
4915
4969
  const toolDirNames = toolDirNamesFor(reservedPaths);
4916
- const relativeToBase = (target) => path26.relative(baseDir, target).replace(/\\/g, "/") || ".";
4970
+ const relativeToBase = (target) => path25.relative(baseDir, target).replace(/\\/g, "/") || ".";
4917
4971
  const enter = (current, layers) => {
4918
4972
  if (visited.has(current)) return false;
4919
4973
  visited.add(current);
4920
4974
  const localRules = readGitignoreRules(current);
4921
4975
  const gitignoreLayers = localRules.length === 0 ? layers : [
4922
4976
  ...layers,
4923
- { prefix: path26.relative(baseDir, current).replace(/\\/g, "/"), rules: localRules }
4977
+ { prefix: path25.relative(baseDir, current).replace(/\\/g, "/"), rules: localRules }
4924
4978
  ];
4925
4979
  let entries;
4926
4980
  try {
4927
- entries = fs25.readdirSync(current, { withFileTypes: true });
4981
+ entries = fs24.readdirSync(current, { withFileTypes: true });
4928
4982
  } catch {
4929
4983
  results.skipped.push({
4930
4984
  path: relativeToBase(current),
@@ -4946,8 +5000,8 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
4946
5000
  }
4947
5001
  const entry = frame.entries[frame.index];
4948
5002
  frame.index += 1;
4949
- const fullPath = path26.join(frame.dir, entry.name);
4950
- const relPath = path26.relative(baseDir, fullPath).replace(/\\/g, "/");
5003
+ const fullPath = path25.join(frame.dir, entry.name);
5004
+ const relPath = path25.relative(baseDir, fullPath).replace(/\\/g, "/");
4951
5005
  if (reservedPaths.has(relPath)) continue;
4952
5006
  if (entry.isDirectory() && DEFAULT_IGNORED_DIRS.includes(entry.name)) {
4953
5007
  results.skipped.push({
@@ -4980,14 +5034,14 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
4980
5034
  if (entry.isSymbolicLink()) {
4981
5035
  let targetReal;
4982
5036
  try {
4983
- targetReal = fs25.realpathSync(fullPath);
5037
+ targetReal = fs24.realpathSync(fullPath);
4984
5038
  } catch {
4985
5039
  results.skipped.push(brokenLinkRecord(fullPath, relPath, rootReal));
4986
5040
  continue;
4987
5041
  }
4988
5042
  let stats;
4989
5043
  try {
4990
- stats = fs25.statSync(fullPath);
5044
+ stats = fs24.statSync(fullPath);
4991
5045
  } catch {
4992
5046
  results.skipped.push({ path: relPath, reason: "read-error", detail: "unreadable symlink" });
4993
5047
  continue;
@@ -5017,7 +5071,7 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
5017
5071
  });
5018
5072
  continue;
5019
5073
  }
5020
- const targetRelative = path26.relative(rootReal, targetReal).split(path26.sep).join("/");
5074
+ const targetRelative = path25.relative(rootReal, targetReal).split(path25.sep).join("/");
5021
5075
  if (isSensitivePath(targetRelative)) {
5022
5076
  results.skipped.push({
5023
5077
  path: relPath,
@@ -5073,20 +5127,20 @@ var CONFIG_FILENAMES = [
5073
5127
  ];
5074
5128
  function findConfigFile(cwd) {
5075
5129
  for (const filename of CONFIG_FILENAMES) {
5076
- const fullPath = path26.join(cwd, filename);
5130
+ const fullPath = path25.join(cwd, filename);
5077
5131
  let stats = null;
5078
5132
  try {
5079
- stats = fs25.statSync(fullPath);
5133
+ stats = fs24.statSync(fullPath);
5080
5134
  } catch {
5081
- if (fs25.existsSync(fullPath)) return fullPath;
5135
+ if (fs24.existsSync(fullPath)) return fullPath;
5082
5136
  continue;
5083
5137
  }
5084
5138
  if (stats.isFile()) return fullPath;
5085
5139
  }
5086
- const pkgJsonPath = path26.join(cwd, "package.json");
5087
- if (!fs25.existsSync(pkgJsonPath)) return null;
5140
+ const pkgJsonPath = path25.join(cwd, "package.json");
5141
+ if (!fs24.existsSync(pkgJsonPath)) return null;
5088
5142
  try {
5089
- const parsed = JSON.parse(stripJsonComments(fs25.readFileSync(pkgJsonPath, "utf8")));
5143
+ const parsed = JSON.parse(stripJsonComments(fs24.readFileSync(pkgJsonPath, "utf8")));
5090
5144
  const snapshot = parsed?.snapshot;
5091
5145
  return typeof snapshot === "object" && snapshot !== null && !Array.isArray(snapshot) ? pkgJsonPath : null;
5092
5146
  } catch {
@@ -5145,8 +5199,25 @@ function normalizeResolvedConfig(config) {
5145
5199
  monolithWanted,
5146
5200
  monolithWanted
5147
5201
  );
5202
+ if (!Number.isSafeInteger(config.maxPartBytes) || config.maxPartBytes < MIN_MAX_PART_BYTES) {
5203
+ throw new Error(
5204
+ `maxPartBytes must be at least ${MIN_MAX_PART_BYTES} bytes (received ${String(config.maxPartBytes)}).`
5205
+ );
5206
+ }
5207
+ if (!Number.isSafeInteger(config.largeFileBytes) || config.largeFileBytes < 0) {
5208
+ throw new Error(
5209
+ `largeFileBytes must be a non-negative integer; received ${String(config.largeFileBytes)}.`
5210
+ );
5211
+ }
5212
+ const maxPartTokens = config.maxPartTokens ?? Math.floor(config.maxPartBytes / 4);
5213
+ if (!Number.isSafeInteger(maxPartTokens) || maxPartTokens < MIN_MAX_PART_TOKENS) {
5214
+ throw new Error(
5215
+ `maxPartTokens must be at least ${MIN_MAX_PART_TOKENS} tokens; received ${String(maxPartTokens)}.`
5216
+ );
5217
+ }
5148
5218
  return markResolvedConfig({
5149
5219
  ...config,
5220
+ maxPartTokens,
5150
5221
  discovery,
5151
5222
  // A spread copy built before the field existed carries no value; the default applies, and it
5152
5223
  // is re-validated because the number reaches a rendered artifact.
@@ -5301,10 +5372,10 @@ function readConfigExport(exported, file) {
5301
5372
  var lastModuleConfig = null;
5302
5373
  function moduleConfigKey(fullPath) {
5303
5374
  try {
5304
- return createHash("sha256").update(fs25.readFileSync(fullPath)).digest("hex").slice(0, 24);
5375
+ return createHash("sha256").update(fs24.readFileSync(fullPath)).digest("hex").slice(0, 24);
5305
5376
  } catch {
5306
5377
  try {
5307
- const stats = fs25.statSync(fullPath);
5378
+ const stats = fs24.statSync(fullPath);
5308
5379
  return `stat-${stats.mtimeMs}-${stats.size}`;
5309
5380
  } catch {
5310
5381
  return "unreadable";
@@ -5330,7 +5401,7 @@ async function importConfigModule(fullPath) {
5330
5401
  function attachConfigDir(config, filePath) {
5331
5402
  if (typeof config === "object" && config !== null) {
5332
5403
  Object.defineProperty(config, CONFIG_DIR_SYMBOL, {
5333
- value: path26.dirname(filePath),
5404
+ value: path25.dirname(filePath),
5334
5405
  enumerable: false,
5335
5406
  configurable: true
5336
5407
  });
@@ -5342,12 +5413,12 @@ async function loadConfigFileDetailed(cwd, options = {}) {
5342
5413
  const errors = [];
5343
5414
  const configDirectories = [];
5344
5415
  for (const filename of CONFIG_FILENAMES) {
5345
- const fullPath = path26.join(cwd, filename);
5416
+ const fullPath = path25.join(cwd, filename);
5346
5417
  let candidateStats = null;
5347
5418
  try {
5348
- candidateStats = fs25.statSync(fullPath);
5419
+ candidateStats = fs24.statSync(fullPath);
5349
5420
  } catch {
5350
- if (!fs25.existsSync(fullPath)) continue;
5421
+ if (!fs24.existsSync(fullPath)) continue;
5351
5422
  }
5352
5423
  if (candidateStats !== null && !candidateStats.isFile()) {
5353
5424
  configDirectories.push(fullPath);
@@ -5355,7 +5426,7 @@ async function loadConfigFileDetailed(cwd, options = {}) {
5355
5426
  }
5356
5427
  if (filename.endsWith(".json") || filename === ".snapshotrc") {
5357
5428
  try {
5358
- const config = parseJsonish(fs25.readFileSync(fullPath, "utf8"), fullPath);
5429
+ const config = parseJsonish(fs24.readFileSync(fullPath, "utf8"), fullPath);
5359
5430
  if (config === null || typeof config !== "object" || Array.isArray(config)) {
5360
5431
  throw new Error(
5361
5432
  `${fullPath} does not hold a configuration object (received ${describeValue2(config)}).`
@@ -5395,10 +5466,10 @@ async function loadConfigFileDetailed(cwd, options = {}) {
5395
5466
  continue;
5396
5467
  }
5397
5468
  }
5398
- const pkgJsonPath = path26.join(cwd, "package.json");
5399
- if (fs25.existsSync(pkgJsonPath)) {
5469
+ const pkgJsonPath = path25.join(cwd, "package.json");
5470
+ if (fs24.existsSync(pkgJsonPath)) {
5400
5471
  try {
5401
- const parsed = parseJsonish(fs25.readFileSync(pkgJsonPath, "utf8"), pkgJsonPath);
5472
+ const parsed = parseJsonish(fs24.readFileSync(pkgJsonPath, "utf8"), pkgJsonPath);
5402
5473
  const snapshotKey = parsed.snapshot;
5403
5474
  if (snapshotKey && typeof snapshotKey === "object" && !Array.isArray(snapshotKey)) {
5404
5475
  assertKnownConfigKeys(
@@ -5573,27 +5644,27 @@ function readConfiguredBrief(cwd, value) {
5573
5644
  }
5574
5645
  const rootReal = (() => {
5575
5646
  try {
5576
- return fs25.realpathSync(cwd);
5647
+ return fs24.realpathSync(cwd);
5577
5648
  } catch {
5578
- return path26.resolve(cwd);
5649
+ return path25.resolve(cwd);
5579
5650
  }
5580
5651
  })();
5581
- const requested = path26.resolve(cwd, value);
5652
+ const requested = path25.resolve(cwd, value);
5582
5653
  let filePath;
5583
5654
  try {
5584
- filePath = fs25.realpathSync(requested);
5655
+ filePath = fs24.realpathSync(requested);
5585
5656
  } catch {
5586
5657
  throw new Error(
5587
5658
  'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
5588
5659
  );
5589
5660
  }
5590
- const relative15 = path26.relative(rootReal, filePath);
5591
- if (relative15.length === 0 || relative15 === ".." || relative15.startsWith(`..${path26.sep}`) || path26.isAbsolute(relative15)) {
5661
+ const relative15 = path25.relative(rootReal, filePath);
5662
+ if (relative15.length === 0 || relative15 === ".." || relative15.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative15)) {
5592
5663
  throw new Error(
5593
5664
  'brief "' + value + '" resolves outside the repository. A brief must be a file inside the repository being described; an absolute or parent path is refused.'
5594
5665
  );
5595
5666
  }
5596
- const posixRelative = relative15.split(path26.sep).join("/");
5667
+ const posixRelative = relative15.split(path25.sep).join("/");
5597
5668
  if (isSensitivePath(posixRelative) || isSensitivePath(value)) {
5598
5669
  throw new Error(
5599
5670
  'brief "' + value + '" is a credential-bearing file. A snapshot must not reproduce secrets, so it cannot be used as the owner brief.'
@@ -5601,9 +5672,16 @@ function readConfiguredBrief(cwd, value) {
5601
5672
  }
5602
5673
  let text2;
5603
5674
  try {
5604
- if (!fs25.statSync(filePath).isFile()) throw new Error("not a file");
5605
- text2 = fs25.readFileSync(filePath, "utf8");
5606
- } catch {
5675
+ const stats = fs24.statSync(filePath);
5676
+ if (!stats.isFile()) throw new Error("not a file");
5677
+ if (stats.size > MAX_BRIEF_BYTES) {
5678
+ throw new Error(
5679
+ 'brief "' + value + '" is ' + stats.size + " bytes; the limit is " + MAX_BRIEF_BYTES + ". Keep it to what a reader can act on, or move the detail into a document the snapshot carries."
5680
+ );
5681
+ }
5682
+ text2 = fs24.readFileSync(filePath, "utf8");
5683
+ } catch (error) {
5684
+ if (error instanceof Error && error.message.startsWith('brief "')) throw error;
5607
5685
  throw new Error(
5608
5686
  'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
5609
5687
  );
@@ -5714,9 +5792,9 @@ function resolveKindRules(value) {
5714
5792
  function outputExcludePatterns(cwd, outDir, tmpDir) {
5715
5793
  const patterns = [];
5716
5794
  for (const dir of [outDir, tmpDir]) {
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)) {
5795
+ const absolute = path25.resolve(cwd, dir);
5796
+ const relative15 = path25.relative(cwd, absolute);
5797
+ if (!relative15 || relative15 === ".." || relative15.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative15)) {
5720
5798
  continue;
5721
5799
  }
5722
5800
  patterns.push(`${relative15.replace(/\\/g, "/")}/**`);
@@ -5849,11 +5927,11 @@ function resolveCandidateCwd(userConfig, cliOptions, baseDir) {
5849
5927
  );
5850
5928
  }
5851
5929
  const candidate = cliOptions?.cwd || userConfig?.cwd || baseDir || process.cwd();
5852
- const resolved = path26.resolve(candidate);
5853
- if (!fs25.existsSync(resolved)) {
5930
+ const resolved = path25.resolve(candidate);
5931
+ if (!fs24.existsSync(resolved)) {
5854
5932
  throw new Error(`Working directory does not exist: ${resolved}`);
5855
5933
  }
5856
- if (!fs25.statSync(resolved).isDirectory()) {
5934
+ if (!fs24.statSync(resolved).isDirectory()) {
5857
5935
  throw new Error(`Working directory is not a directory: ${resolved}`);
5858
5936
  }
5859
5937
  return resolved;
@@ -6006,7 +6084,10 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
6006
6084
  outDir,
6007
6085
  tmpDir,
6008
6086
  maxPartBytes: resolvedMaxPartBytes,
6009
- ...maxPartTokens === void 0 ? {} : { maxPartTokens },
6087
+ // Record the effective value even when the user did not set it. normalizeResolvedConfig
6088
+ // derives it for the manifest; leaving validate's fresh resolution unset made a clean
6089
+ // snapshot report a configuration mismatch.
6090
+ maxPartTokens: maxPartTokens ?? Math.floor(resolvedMaxPartBytes / 4),
6010
6091
  largeFileBytes: largeFileBytesFor(resolvedMaxPartBytes, cliOptions, userConfig),
6011
6092
  previewHeadLines: strictPositiveInteger(userConfig?.previewHeadLines, 80, "`previewHeadLines`"),
6012
6093
  previewTailLines: strictPositiveInteger(userConfig?.previewTailLines, 40, "`previewTailLines`"),
@@ -6408,7 +6489,8 @@ function generateSarifReport(manifest, findings, rules, toolVersion) {
6408
6489
  const results = findings.filter((finding) => typeof finding.path === "string" && finding.path.length > 0).map((finding) => {
6409
6490
  const primary = finding.rules[0] ?? "unknown";
6410
6491
  const line = Math.max(1, finding.line);
6411
- const findingPath = String(finding.path).replace(/\\/g, "/");
6492
+ const rawPath = findSecretInPath(String(finding.path), rules)?.masked ?? String(finding.path);
6493
+ const findingPath = rawPath.replace(/\\/g, "/").split("/").map((segment) => encodeURIComponent(segment)).join("/");
6412
6494
  return {
6413
6495
  ruleId: ruleIdFor(primary),
6414
6496
  ruleIndex: ruleIndex.get(primary) ?? 0,
@@ -6833,7 +6915,9 @@ function fenceIsOpen(text2, fence) {
6833
6915
  }
6834
6916
  var OMISSION_NOTICE_LINE = /^\.\.\. \[\d+ lines omitted: [^\]]*\] \.\.\.$/;
6835
6917
  function applyTruncatedContent(file, content, reason) {
6836
- const keptLines = content.split("\n").filter((line) => !OMISSION_NOTICE_LINE.test(line)).length;
6918
+ const keptLines = content.split("\n").filter(
6919
+ (line) => !OMISSION_NOTICE_LINE.test(line) && line.trim() !== SECTION_TRUNCATION_NOTICE
6920
+ ).length;
6837
6921
  file.content = content;
6838
6922
  file.isPreviewTruncated = true;
6839
6923
  file.inclusionMode = "preview";
@@ -6853,7 +6937,8 @@ function rehashPart(part, markdown) {
6853
6937
  byteSize: Buffer.byteLength(redistributed, "utf8"),
6854
6938
  sha256: crypto.createHash("sha256").update(redistributed).digest("hex"),
6855
6939
  lines: countLines(redistributed),
6856
- estimatedTokens
6940
+ estimatedTokens,
6941
+ hardClipped: true
6857
6942
  }
6858
6943
  };
6859
6944
  }
@@ -7029,11 +7114,14 @@ function generateMonolithJson(manifest, filesWithContent) {
7029
7114
  );
7030
7115
  return JSON.stringify({ manifest: embedded, files }, null, 2);
7031
7116
  }
7117
+ function xmlSafe(value) {
7118
+ return value.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]/g, "\uFFFD");
7119
+ }
7032
7120
  function xmlAttribute(value) {
7033
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
7121
+ return xmlSafe(value).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
7034
7122
  }
7035
7123
  function cdata(value) {
7036
- return "<![CDATA[" + value.replace(/\]\]>/g, "]]]]><![CDATA[>") + "]]>";
7124
+ return "<![CDATA[" + xmlSafe(value).replace(/\]\]>/g, "]]]]><![CDATA[>") + "]]>";
7037
7125
  }
7038
7126
  function generateMonolithXml(manifest, filesWithContent) {
7039
7127
  const files = filesWithContent.map((file) => {
@@ -7134,14 +7222,19 @@ function generateNavigation(manifest) {
7134
7222
  }
7135
7223
 
7136
7224
  // src/generator/selection.ts
7225
+ function cell(value) {
7226
+ return escapeControls(value).replace(/\r?\n/g, " ").replace(/\|/g, "\\|");
7227
+ }
7137
7228
  function generateSelectionReport(manifest, selection) {
7138
7229
  const lines = [];
7139
7230
  lines.push("# Selection");
7140
7231
  lines.push("");
7141
7232
  lines.push("**Kind:** `" + selection.kind + "` ");
7142
- for (const detailLine of selection.detail.split("\n")) {
7143
- lines.push("**" + detailLine.slice(0, detailLine.indexOf(":")) + ":**" + detailLine.slice(detailLine.indexOf(":") + 1) + " ");
7144
- }
7233
+ const detail = selection.detail.replace(/\r?\n/g, " ");
7234
+ const colon = detail.indexOf(":");
7235
+ lines.push(
7236
+ "**" + (colon === -1 ? "Selection" : detail.slice(0, colon)) + ":**" + (colon === -1 ? " " + detail : detail.slice(colon + 1)) + " "
7237
+ );
7145
7238
  lines.push("**Selected files:** " + selection.files.length + " ");
7146
7239
  const spent = manifest.budget?.usedTokens ?? manifest.slice?.usedTokens ?? 0;
7147
7240
  lines.push("**Tokens spent:** " + spent.toLocaleString("en-US"));
@@ -7151,7 +7244,7 @@ function generateSelectionReport(manifest, selection) {
7151
7244
  lines.push("| File | Tokens | Reason |");
7152
7245
  lines.push("| :-- | --: | :-- |");
7153
7246
  for (const file of selection.files) {
7154
- lines.push("| `" + file.path + "` | " + file.tokens.toLocaleString("en-US") + " | " + file.why + " |");
7247
+ lines.push("| `" + cell(file.path) + "` | " + file.tokens.toLocaleString("en-US") + " | " + cell(file.why) + " |");
7155
7248
  }
7156
7249
  lines.push("");
7157
7250
  const dropped = selection.kind === "slice" ? manifest.slice?.dropped : manifest.budget?.dropped;
@@ -7171,7 +7264,7 @@ function generateSelectionReport(manifest, selection) {
7171
7264
  lines.push("| File | Tokens |");
7172
7265
  lines.push("| :-- | --: |");
7173
7266
  for (const item of next) {
7174
- lines.push("| `" + item.path + "` | " + item.tokens.toLocaleString("en-US") + " |");
7267
+ lines.push("| `" + cell(item.path) + "` | " + item.tokens.toLocaleString("en-US") + " |");
7175
7268
  }
7176
7269
  lines.push("");
7177
7270
  }
@@ -7270,10 +7363,10 @@ function resolveImport(from, specifier, byPath) {
7270
7363
  if (segment === "..") parts.pop();
7271
7364
  else parts.push(segment);
7272
7365
  }
7273
- const path27 = parts.join("/");
7274
- const withoutExtension = path27.replace(/\.[cm]?[jt]sx?$/, "");
7366
+ const path26 = parts.join("/");
7367
+ const withoutExtension = path26.replace(/\.[cm]?[jt]sx?$/, "");
7275
7368
  const candidates = [
7276
- path27,
7369
+ path26,
7277
7370
  withoutExtension + ".ts",
7278
7371
  withoutExtension + ".tsx",
7279
7372
  withoutExtension + ".js",
@@ -7282,18 +7375,18 @@ function resolveImport(from, specifier, byPath) {
7282
7375
  withoutExtension + ".go",
7283
7376
  withoutExtension + ".rs",
7284
7377
  withoutExtension + "/index.ts",
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"
7378
+ path26 + ".ts",
7379
+ path26 + ".tsx",
7380
+ path26 + ".js",
7381
+ path26 + ".jsx",
7382
+ path26 + ".mjs",
7383
+ path26 + ".cjs",
7384
+ path26 + ".py",
7385
+ path26 + ".go",
7386
+ path26 + ".rs",
7387
+ path26 + ".java",
7388
+ path26 + "/index.ts",
7389
+ path26 + "/index.js"
7297
7390
  ];
7298
7391
  for (const candidate of candidates) {
7299
7392
  const found = byPath.get(candidate);
@@ -7322,12 +7415,12 @@ function planForQuestion(manifest, question, options = {}) {
7322
7415
  const scored = [];
7323
7416
  for (const file of manifest.files) {
7324
7417
  if (isTest(file) && !wantsTests) continue;
7325
- const path27 = file.relativePath.toLowerCase();
7326
- const words = path27.split(/[^a-z0-9_]+/).filter((word) => word.length >= 3);
7418
+ const path26 = file.relativePath.toLowerCase();
7419
+ const words = path26.split(/[^a-z0-9_]+/).filter((word) => word.length >= 3);
7327
7420
  let score = 0;
7328
7421
  const reasons = [];
7329
7422
  for (const term of terms) {
7330
- if (path27.includes(term)) {
7423
+ if (path26.includes(term)) {
7331
7424
  score += 8;
7332
7425
  reasons.push("path:" + term);
7333
7426
  continue;
@@ -7378,7 +7471,9 @@ function planForQuestion(manifest, question, options = {}) {
7378
7471
  notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
7379
7472
  }
7380
7473
  }
7381
- scored.sort((left, right) => right.score - left.score || left.file.relativePath.localeCompare(right.file.relativePath));
7474
+ scored.sort(
7475
+ (left, right) => right.score - left.score || (left.file.relativePath < right.file.relativePath ? -1 : left.file.relativePath > right.file.relativePath ? 1 : 0)
7476
+ );
7382
7477
  const chosen = /* @__PURE__ */ new Map();
7383
7478
  const skipped = [];
7384
7479
  let used = 0;
@@ -7486,12 +7581,15 @@ function stripComments2(text2, relativePath) {
7486
7581
  if (ranges_ === void 0) return;
7487
7582
  for (const range of ranges_) ranges.push([range.pos, range.end]);
7488
7583
  };
7489
- const visit = (node) => {
7584
+ const stack = [source];
7585
+ while (stack.length > 0) {
7586
+ const node = stack.pop();
7490
7587
  collect(ts.getLeadingCommentRanges(text2, node.getFullStart()));
7491
7588
  collect(ts.getTrailingCommentRanges(text2, node.getEnd()));
7492
- ts.forEachChild(node, visit);
7493
- };
7494
- visit(source);
7589
+ ts.forEachChild(node, (child) => {
7590
+ stack.push(child);
7591
+ });
7592
+ }
7495
7593
  collect(ts.getLeadingCommentRanges(text2, source.endOfFileToken.getFullStart()));
7496
7594
  if (ranges.length === 0) return { text: text2, removed: 0 };
7497
7595
  ranges.sort((left, right) => left[0] - right[0]);
@@ -7516,7 +7614,15 @@ function stripComments2(text2, relativePath) {
7516
7614
  function runGit(cwd, args) {
7517
7615
  const result = spawnSync(
7518
7616
  "git",
7519
- ["-c", "core.quotepath=false", "-c", "diff.noprefix=false", ...args],
7617
+ [
7618
+ "-c",
7619
+ "core.quotepath=false",
7620
+ "-c",
7621
+ "diff.noprefix=false",
7622
+ "-c",
7623
+ "diff.mnemonicPrefix=false",
7624
+ ...args
7625
+ ],
7520
7626
  { cwd, encoding: "utf8", windowsHide: true, maxBuffer: 64 * 1024 * 1024 }
7521
7627
  );
7522
7628
  if (result.status !== 0) return { ok: false, out: (result.stderr ?? "").trim() };
@@ -7575,60 +7681,44 @@ function unquoteGitPath(value) {
7575
7681
  flushBytes();
7576
7682
  return out;
7577
7683
  }
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);
7684
+ function wholeLinePath(value, prefix) {
7685
+ const withoutTimestamp = value.endsWith(" ") ? value.slice(0, -1) : value;
7686
+ const unquoted = unquoteGitPath(withoutTimestamp);
7600
7687
  if (unquoted === "/dev/null") return null;
7601
7688
  if (!unquoted.startsWith(prefix)) return null;
7602
7689
  return unquoted.slice(prefix.length);
7603
7690
  }
7691
+ function headerPaths(value) {
7692
+ const separator = value.lastIndexOf(" b/");
7693
+ if (separator <= 0) return [];
7694
+ const left = unquoteGitPath(value.slice(0, separator));
7695
+ const right = unquoteGitPath(value.slice(separator + 1));
7696
+ const paths = [];
7697
+ if (left.startsWith("a/")) paths.push(left.slice(2));
7698
+ if (right.startsWith("b/")) paths.push(right.slice(2));
7699
+ return paths;
7700
+ }
7604
7701
  function diffSectionPaths(body) {
7605
7702
  const paths = /* @__PURE__ */ new Set();
7703
+ let header = null;
7606
7704
  for (const line of body.split("\n")) {
7607
7705
  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);
7706
+ header = line.slice("diff --git ".length);
7616
7707
  continue;
7617
7708
  }
7618
7709
  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);
7710
+ const path26 = wholeLinePath(line.slice(4), "b/");
7711
+ if (path26 !== null) paths.add(path26);
7623
7712
  continue;
7624
7713
  }
7625
7714
  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);
7715
+ const path26 = wholeLinePath(line.slice(4), "a/");
7716
+ if (path26 !== null) paths.add(path26);
7630
7717
  }
7631
7718
  }
7719
+ if (paths.size === 0 && header !== null) {
7720
+ for (const path26 of headerPaths(header)) paths.add(path26);
7721
+ }
7632
7722
  return [...paths];
7633
7723
  }
7634
7724
  function generateDiffReport(cwd, options = {}) {
@@ -7652,7 +7742,7 @@ function generateDiffReport(cwd, options = {}) {
7652
7742
  omittedUnparseable += 1;
7653
7743
  continue;
7654
7744
  }
7655
- const blocked = paths2.some((path27) => isSensitivePath(path27) || options.excluded?.(path27) === true);
7745
+ const blocked = paths2.some((path26) => isSensitivePath(path26) || options.excluded?.(path26) === true);
7656
7746
  if (blocked) {
7657
7747
  omittedSensitive += 1;
7658
7748
  continue;
@@ -7679,7 +7769,7 @@ function generateDiffReport(cwd, options = {}) {
7679
7769
  }
7680
7770
  if (sections.length === 0) return null;
7681
7771
  const paths = /* @__PURE__ */ new Set();
7682
- for (const section of sections) for (const path27 of diffSectionPaths(section)) paths.add(path27);
7772
+ for (const section of sections) for (const path26 of diffSectionPaths(section)) paths.add(path26);
7683
7773
  const joined = [
7684
7774
  "# Uncommitted changes",
7685
7775
  "",
@@ -7729,28 +7819,39 @@ function generateLogReport(cwd, options = {}) {
7729
7819
  }
7730
7820
 
7731
7821
  // src/generator/tokens.ts
7822
+ function cell2(value) {
7823
+ return escapeControls(value).replace(/\r?\n/g, " ").replace(/\|/g, "\\|");
7824
+ }
7825
+ function byCodeUnit(left, right) {
7826
+ return left < right ? -1 : left > right ? 1 : 0;
7827
+ }
7732
7828
  function tokensOf2(bytes) {
7733
7829
  return Math.max(1, Math.ceil(bytes * 0.25));
7734
7830
  }
7735
7831
  function generateTokenTree(manifest) {
7736
7832
  if (manifest.files.length === 0) return null;
7737
- const rows = manifest.files.map((file) => ({ path: file.relativePath, layer: file.layer, part: file.part, tokens: tokensOf2(file.includedBytes) })).sort((left, right) => right.tokens - left.tokens || left.path.localeCompare(right.path));
7833
+ const rows = manifest.files.map((file) => ({ path: file.relativePath, layer: file.layer, part: file.part, tokens: tokensOf2(file.includedBytes) })).sort((left, right) => right.tokens - left.tokens || byCodeUnit(left.path, right.path));
7738
7834
  const byDirectory = /* @__PURE__ */ new Map();
7739
7835
  for (const row of rows) {
7740
7836
  const directory = row.path.includes("/") ? row.path.slice(0, row.path.lastIndexOf("/")) : ".";
7741
7837
  byDirectory.set(directory, (byDirectory.get(directory) ?? 0) + row.tokens);
7742
7838
  }
7743
- const directories = [...byDirectory.entries()].sort((left, right) => right[1] - left[1]);
7839
+ const directories = [...byDirectory.entries()].sort(
7840
+ (left, right) => right[1] - left[1] || byCodeUnit(left[0], right[0])
7841
+ );
7744
7842
  const total = rows.reduce((sum, row) => sum + row.tokens, 0);
7745
- const rowsTable = rows.map((row) => "| " + row.path + " | " + row.layer + " | " + row.part + " | " + row.tokens + " |");
7843
+ const rowsTable = rows.map(
7844
+ (row) => "| " + cell2(row.path) + " | " + cell2(row.layer) + " | " + cell2(row.part) + " | " + row.tokens + " |"
7845
+ );
7746
7846
  const directoryTable = directories.map(
7747
- (entry) => "| " + entry[0] + " | " + entry[1] + " | " + (entry[1] / total * 100).toFixed(1) + "% |"
7847
+ (entry) => "| " + cell2(entry[0]) + " | " + entry[1] + " | " + (entry[1] / total * 100).toFixed(1) + "% |"
7748
7848
  );
7749
7849
  const text2 = [
7750
7850
  "# Token tree",
7751
7851
  "",
7752
- "Estimated tokens per file (one token per four bytes of emitted body), sorted by cost. The total",
7753
- "is the same estimate the manifest carries: an estimate, not a count.",
7852
+ "Estimated tokens per file (one token per four bytes of emitted body), sorted by cost. Each",
7853
+ "row is an estimate; the manifest total is estimated from the assembled parts, so the two can",
7854
+ "differ slightly and neither is a tokenizer count.",
7754
7855
  "",
7755
7856
  "## Directories",
7756
7857
  "",
@@ -7952,7 +8053,9 @@ function systemSection(manifest, code, brief, escape, sawManifest) {
7952
8053
  if (brief?.system !== void 0) {
7953
8054
  out.push(...ownerBlock(brief.system, brief.path, code, escape), "", "What the index records:", "");
7954
8055
  }
7955
- const layers = Object.entries(manifest.layers).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
8056
+ const layers = Object.entries(manifest.layers).sort(
8057
+ (a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)
8058
+ );
7956
8059
  if (layers.length > 0) {
7957
8060
  const shown = layers.slice(0, MAX_LAYER_ROWS).map(([name, count]) => code(name) + " " + formatNumber(count));
7958
8061
  const rest = layers.length > MAX_LAYER_ROWS ? ", and " + formatNumber(layers.length - MAX_LAYER_ROWS) + " more" : "";
@@ -7966,7 +8069,7 @@ function systemSection(manifest, code, brief, escape, sawManifest) {
7966
8069
  " A change here reaches the most call sites; read it before judging anything that uses it."
7967
8070
  );
7968
8071
  }
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);
8072
+ 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);
7970
8073
  out.push(
7971
8074
  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"
7972
8075
  );
@@ -8070,7 +8173,7 @@ function coverageSection(manifest, code, auditWritten, partsWritten, sawManifest
8070
8173
  for (const record of manifest.skipped) {
8071
8174
  reasons.set(record.reason, (reasons.get(record.reason) ?? 0) + 1);
8072
8175
  }
8073
- const tally = [...reasons.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([reason, count]) => code(reason) + " " + formatNumber(count)).join(", ");
8176
+ const tally = [...reasons.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([reason, count]) => code(reason) + " " + formatNumber(count)).join(", ");
8074
8177
  const found = manifest.totals.candidateFiles;
8075
8178
  const included = manifest.totals.includedFiles;
8076
8179
  const skipped = manifest.counts.skippedCount;
@@ -8201,8 +8304,8 @@ function ownerNotesSection(brief, code, text2) {
8201
8304
  }
8202
8305
  return out;
8203
8306
  }
8204
- function ownerBlock(body, path27, code, escape) {
8205
- return ["> Written by the project owner in " + code(path27) + ", not generated.", "", escape(body)];
8307
+ function ownerBlock(body, path26, code, escape) {
8308
+ return ["> Written by the project owner in " + code(path26) + ", not generated.", "", escape(body)];
8206
8309
  }
8207
8310
  function snapshotSection(manifest, code, partsWritten) {
8208
8311
  const out = ["## This snapshot", ""];
@@ -8572,7 +8675,7 @@ function resolveChangedScope(cwd, request) {
8572
8675
  const descriptions = [];
8573
8676
  if (request.changedSince !== void 0) {
8574
8677
  assertUsableRef(request.changedSince);
8575
- for (const path27 of gitPaths(cwd, [
8678
+ for (const path26 of gitPaths(cwd, [
8576
8679
  "diff",
8577
8680
  "--name-only",
8578
8681
  "-z",
@@ -8580,9 +8683,9 @@ function resolveChangedScope(cwd, request) {
8580
8683
  `${request.changedSince}...HEAD`,
8581
8684
  "--"
8582
8685
  ])) {
8583
- paths.add(path27);
8686
+ paths.add(path26);
8584
8687
  }
8585
- for (const path27 of gitPaths(cwd, [
8688
+ for (const path26 of gitPaths(cwd, [
8586
8689
  "diff",
8587
8690
  "--name-only",
8588
8691
  "-z",
@@ -8590,15 +8693,15 @@ function resolveChangedScope(cwd, request) {
8590
8693
  "HEAD",
8591
8694
  "--"
8592
8695
  ])) {
8593
- paths.add(path27);
8696
+ paths.add(path26);
8594
8697
  }
8595
- for (const path27 of gitPaths(cwd, ["ls-files", "--others", "--exclude-standard", "-z", "--"])) {
8596
- paths.add(path27);
8698
+ for (const path26 of gitPaths(cwd, ["ls-files", "--others", "--exclude-standard", "-z", "--"])) {
8699
+ paths.add(path26);
8597
8700
  }
8598
8701
  descriptions.push(`changed since ${request.changedSince}`);
8599
8702
  }
8600
8703
  if (request.staged === true) {
8601
- for (const path27 of gitPaths(cwd, [
8704
+ for (const path26 of gitPaths(cwd, [
8602
8705
  "diff",
8603
8706
  "--cached",
8604
8707
  "--name-only",
@@ -8606,10 +8709,10 @@ function resolveChangedScope(cwd, request) {
8606
8709
  "--relative",
8607
8710
  "--"
8608
8711
  ])) {
8609
- paths.add(path27);
8610
- stagedPaths.add(path27);
8712
+ paths.add(path26);
8713
+ stagedPaths.add(path26);
8611
8714
  }
8612
- for (const path27 of gitPaths(cwd, [
8715
+ for (const path26 of gitPaths(cwd, [
8613
8716
  "diff",
8614
8717
  "--cached",
8615
8718
  "--name-only",
@@ -8618,7 +8721,7 @@ function resolveChangedScope(cwd, request) {
8618
8721
  "--diff-filter=D",
8619
8722
  "--"
8620
8723
  ])) {
8621
- deletedPaths.add(path27);
8724
+ deletedPaths.add(path26);
8622
8725
  }
8623
8726
  descriptions.push("staged");
8624
8727
  }
@@ -8656,15 +8759,19 @@ var PYTHON_SUFFIXES = [".py", ".pyi", "/__init__.py", "/__init__.pyi"];
8656
8759
  var CASE_INSENSITIVE_FILESYSTEM = process.platform === "win32" || process.platform === "darwin";
8657
8760
  var TSCONFIG_CACHE = /* @__PURE__ */ new Map();
8658
8761
  function tsconfigPathsFor(cwd) {
8659
- const configPath = path26.join(cwd, "tsconfig.json");
8762
+ const configPath = path25.join(cwd, "tsconfig.json");
8660
8763
  let stats;
8661
8764
  try {
8662
- stats = fs25.statSync(configPath);
8765
+ stats = fs24.statSync(configPath);
8663
8766
  } catch (err) {
8664
8767
  if (err.code === "ENOENT") return null;
8665
8768
  return null;
8666
8769
  }
8667
8770
  const key = `${stats.mtimeMs}:${stats.size}`;
8771
+ if (!TSCONFIG_CACHE.has(configPath) && TSCONFIG_CACHE.size >= 64) {
8772
+ const oldest = TSCONFIG_CACHE.keys().next().value;
8773
+ if (oldest !== void 0) TSCONFIG_CACHE.delete(oldest);
8774
+ }
8668
8775
  const cached = TSCONFIG_CACHE.get(configPath);
8669
8776
  if (cached !== void 0 && cached.key === key) return cached.value;
8670
8777
  let value = null;
@@ -8693,8 +8800,8 @@ function tsconfigPathsFor(cwd) {
8693
8800
  return value;
8694
8801
  }
8695
8802
  function repositoryRelative(cwd, target) {
8696
- const relative15 = path26.relative(cwd, target).replace(/\\/g, "/");
8697
- return relative15.length === 0 || !relative15.startsWith("..") && !path26.isAbsolute(relative15) ? relative15 : null;
8803
+ const relative15 = path25.relative(cwd, target).replace(/\\/g, "/");
8804
+ return relative15.length === 0 || !relative15.startsWith("..") && !path25.isAbsolute(relative15) ? relative15 : null;
8698
8805
  }
8699
8806
  function rememberFirst(map, key, value) {
8700
8807
  if (!map.has(key)) map.set(key, value);
@@ -8709,15 +8816,15 @@ function buildImportResolver(files, options = {}) {
8709
8816
  if (CASE_INSENSITIVE_FILESYSTEM) {
8710
8817
  rememberFirst(byPathFolded, relativePath.toLowerCase(), relativePath);
8711
8818
  }
8712
- const extension = path26.posix.extname(relativePath);
8819
+ const extension = path25.posix.extname(relativePath);
8713
8820
  if (!SOURCE_EXTENSIONS.has(extension)) return;
8714
8821
  const stem = relativePath.slice(0, -extension.length);
8715
8822
  rememberFirst(byStem, stem, relativePath);
8716
8823
  if (CASE_INSENSITIVE_FILESYSTEM) {
8717
8824
  rememberFirst(byStemFolded, stem.toLowerCase(), relativePath);
8718
8825
  }
8719
- if (path26.posix.basename(stem) === "index") {
8720
- const directory = path26.posix.dirname(stem);
8826
+ if (path25.posix.basename(stem) === "index") {
8827
+ const directory = path25.posix.dirname(stem);
8721
8828
  rememberFirst(byStem, directory, relativePath);
8722
8829
  if (CASE_INSENSITIVE_FILESYSTEM) {
8723
8830
  rememberFirst(byStemFolded, directory.toLowerCase(), relativePath);
@@ -8733,7 +8840,7 @@ function buildImportResolver(files, options = {}) {
8733
8840
  return { byPath, byPathFolded, byStem, byStemFolded, tsconfig: options.tsconfig ?? null };
8734
8841
  }
8735
8842
  function resolveSpecifier(fromFile, specifier, resolver) {
8736
- const extension = path26.posix.extname(fromFile).toLowerCase();
8843
+ const extension = path25.posix.extname(fromFile).toLowerCase();
8737
8844
  const exact = (key) => resolver.byPath.get(key) ?? (CASE_INSENSITIVE_FILESYSTEM ? resolver.byPathFolded.get(key.toLowerCase()) : void 0) ?? null;
8738
8845
  const firstOf = (candidates) => {
8739
8846
  for (const candidate of candidates) {
@@ -8756,34 +8863,34 @@ function resolveSpecifier(fromFile, specifier, resolver) {
8756
8863
  if (PYTHON_EXTENSIONS.has(extension) && specifier.startsWith(".")) {
8757
8864
  const dots = /^\.+/.exec(specifier)?.[0].length ?? 0;
8758
8865
  const rest = specifier.slice(dots).replace(/\./g, "/");
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;
8866
+ let base = path25.posix.dirname(fromFile);
8867
+ for (let up = 1; up < dots; up += 1) base = path25.posix.dirname(base);
8868
+ const joined2 = rest ? path25.posix.normalize(path25.posix.join(base, rest)) : base;
8762
8869
  return firstOf([joined2, ...PYTHON_SUFFIXES.map((suffix) => `${joined2}${suffix}`)]);
8763
8870
  }
8764
8871
  if (RUBY_EXTENSIONS.has(extension) && specifier.startsWith("./")) {
8765
- const joined2 = path26.posix.normalize(
8766
- path26.posix.join(path26.posix.dirname(fromFile), specifier)
8872
+ const joined2 = path25.posix.normalize(
8873
+ path25.posix.join(path25.posix.dirname(fromFile), specifier)
8767
8874
  );
8768
8875
  return firstOf([`${joined2}.rb`, joined2]);
8769
8876
  }
8770
8877
  if (C_EXTENSIONS.has(extension) && specifier.startsWith("./")) {
8771
- const joined2 = path26.posix.normalize(
8772
- path26.posix.join(path26.posix.dirname(fromFile), specifier)
8878
+ const joined2 = path25.posix.normalize(
8879
+ path25.posix.join(path25.posix.dirname(fromFile), specifier)
8773
8880
  );
8774
8881
  return exact(joined2);
8775
8882
  }
8776
8883
  if (extension === ".dart" && !specifier.includes(":")) {
8777
- const joined2 = path26.posix.normalize(
8778
- path26.posix.join(path26.posix.dirname(fromFile), specifier)
8884
+ const joined2 = path25.posix.normalize(
8885
+ path25.posix.join(path25.posix.dirname(fromFile), specifier)
8779
8886
  );
8780
8887
  return firstOf([joined2, `${joined2}.dart`]);
8781
8888
  }
8782
8889
  if (!RELATIVE_SPECIFIER.test(specifier)) {
8783
8890
  return resolveTsconfigSpecifier(specifier, resolver, lookupPath);
8784
8891
  }
8785
- const joined = path26.posix.normalize(
8786
- path26.posix.join(path26.posix.dirname(fromFile), specifier)
8892
+ const joined = path25.posix.normalize(
8893
+ path25.posix.join(path25.posix.dirname(fromFile), specifier)
8787
8894
  );
8788
8895
  return lookupPath(joined);
8789
8896
  }
@@ -8807,13 +8914,13 @@ function resolveTsconfigSpecifier(specifier, resolver, lookupPath) {
8807
8914
  if (captured === null) continue;
8808
8915
  for (const target of rule.targets) {
8809
8916
  const substituted = target.split("*").join(captured);
8810
- const base = config.baseUrl === null ? substituted : path26.posix.join(config.baseUrl, substituted);
8811
- const hit = lookupPath(path26.posix.normalize(base));
8917
+ const base = config.baseUrl === null ? substituted : path25.posix.join(config.baseUrl, substituted);
8918
+ const hit = lookupPath(path25.posix.normalize(base));
8812
8919
  if (hit) return hit;
8813
8920
  }
8814
8921
  }
8815
8922
  if (config.baseUrl !== null) {
8816
- return lookupPath(path26.posix.normalize(path26.posix.join(config.baseUrl, specifier)));
8923
+ return lookupPath(path25.posix.normalize(path25.posix.join(config.baseUrl, specifier)));
8817
8924
  }
8818
8925
  return null;
8819
8926
  }
@@ -8824,6 +8931,77 @@ function importsChangedFile(importerPath, imports, changedPaths, resolver) {
8824
8931
  }
8825
8932
  return false;
8826
8933
  }
8934
+ function isInside2(parent, child) {
8935
+ const relative15 = path25.relative(parent, child);
8936
+ return relative15 === "" || !relative15.startsWith("..") && !path25.isAbsolute(relative15);
8937
+ }
8938
+ function resolveConfined(baseDir, relativePath) {
8939
+ if (relativePath.length === 0 || relativePath.includes("\0")) {
8940
+ return { ok: false, reason: "not-file", message: "the file name is empty or contains a NUL byte" };
8941
+ }
8942
+ if (path25.isAbsolute(relativePath)) {
8943
+ return { ok: false, reason: "outside", message: "an absolute path is not a snapshot-relative file" };
8944
+ }
8945
+ let baseReal;
8946
+ try {
8947
+ baseReal = fs24.realpathSync(path25.resolve(baseDir));
8948
+ } catch {
8949
+ return { ok: false, reason: "missing", message: "the snapshot directory does not exist" };
8950
+ }
8951
+ const candidate = path25.resolve(baseReal, relativePath);
8952
+ if (!isInside2(baseReal, candidate)) {
8953
+ return { ok: false, reason: "outside", message: "the path resolves outside the snapshot directory" };
8954
+ }
8955
+ let stats;
8956
+ try {
8957
+ stats = fs24.lstatSync(candidate);
8958
+ } catch (error) {
8959
+ const code = error.code;
8960
+ return {
8961
+ ok: false,
8962
+ reason: code === "ENOENT" || code === "ENOTDIR" ? "missing" : "unreadable",
8963
+ message: code === "ENOENT" || code === "ENOTDIR" ? "the file does not exist" : "the file could not be inspected"
8964
+ };
8965
+ }
8966
+ if (stats.isSymbolicLink()) {
8967
+ return { ok: false, reason: "not-file", message: "the file is a symbolic link" };
8968
+ }
8969
+ if (!stats.isFile()) {
8970
+ return { ok: false, reason: "not-file", message: "the path is not a regular file" };
8971
+ }
8972
+ let real;
8973
+ try {
8974
+ real = fs24.realpathSync(candidate);
8975
+ } catch {
8976
+ return { ok: false, reason: "unreadable", message: "the file could not be resolved" };
8977
+ }
8978
+ if (!isInside2(baseReal, real)) {
8979
+ return { ok: false, reason: "outside", message: "the file resolves outside the snapshot directory" };
8980
+ }
8981
+ return { ok: true, path: real, stats };
8982
+ }
8983
+ function readConfinedBytes(baseDir, relativePath) {
8984
+ const resolved = resolveConfined(baseDir, relativePath);
8985
+ if (!resolved.ok) return resolved;
8986
+ try {
8987
+ const bytes = fs24.readFileSync(resolved.path);
8988
+ return { ok: true, bytes, path: resolved.path, stats: fs24.statSync(resolved.path) };
8989
+ } catch {
8990
+ return { ok: false, reason: "unreadable", message: "the file could not be read" };
8991
+ }
8992
+ }
8993
+ function readConfinedText(baseDir, relativePath) {
8994
+ const resolved = resolveConfined(baseDir, relativePath);
8995
+ if (!resolved.ok) return resolved;
8996
+ try {
8997
+ const text2 = fs24.readFileSync(resolved.path, "utf8");
8998
+ return { ok: true, text: text2, path: resolved.path, stats: fs24.statSync(resolved.path) };
8999
+ } catch {
9000
+ return { ok: false, reason: "unreadable", message: "the file could not be read" };
9001
+ }
9002
+ }
9003
+
9004
+ // src/generator/overview.ts
8827
9005
  var SUMMARY_LIMIT = 400;
8828
9006
  var MAX_RELEASES = 2;
8829
9007
  function readProjectOverview(cwd) {
@@ -8833,15 +9011,12 @@ function readProjectOverview(cwd) {
8833
9011
  releases: readReleases(cwd)
8834
9012
  };
8835
9013
  }
8836
- function readText(file) {
8837
- try {
8838
- return fs25.readFileSync(file, "utf8");
8839
- } catch {
8840
- return null;
8841
- }
9014
+ function readText(cwd, relative15) {
9015
+ const read = readConfinedText(cwd, relative15);
9016
+ return read.ok ? read.text : null;
8842
9017
  }
8843
9018
  function readDescription(cwd) {
8844
- const raw = readText(path26.join(cwd, "package.json"));
9019
+ const raw = readText(cwd, "package.json");
8845
9020
  if (raw === null) return {};
8846
9021
  try {
8847
9022
  const parsed = JSON.parse(stripJsonComments(raw));
@@ -8851,7 +9026,7 @@ function readDescription(cwd) {
8851
9026
  }
8852
9027
  }
8853
9028
  function readSummary(cwd) {
8854
- const raw = readText(path26.join(cwd, "README.md"));
9029
+ const raw = readText(cwd, "README.md");
8855
9030
  if (raw === null) return {};
8856
9031
  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, "'");
8857
9032
  const paragraph = [];
@@ -8877,7 +9052,7 @@ function truncate(text2, limit) {
8877
9052
  return (space > limit / 2 ? window.slice(0, space) : window).trim() + "\u2026";
8878
9053
  }
8879
9054
  function readReleases(cwd) {
8880
- const raw = readText(path26.join(cwd, "CHANGELOG.md"));
9055
+ const raw = readText(cwd, "CHANGELOG.md");
8881
9056
  if (raw === null) return [];
8882
9057
  const headings = raw.split(/\r?\n/).map((line) => /^##\s+(.+?)\s*$/.exec(line)?.[1]?.trim()).filter((heading) => heading !== void 0 && /^v?\d+\.\d+/.test(heading));
8883
9058
  return headings.slice(0, MAX_RELEASES);
@@ -8939,10 +9114,10 @@ var LANGUAGE_BY_BASENAME = {
8939
9114
  };
8940
9115
  function detectLanguage(filePath) {
8941
9116
  const normalized = filePath.replace(/\\/g, "/");
8942
- const base = path26.posix.basename(normalized);
9117
+ const base = path25.posix.basename(normalized);
8943
9118
  if (LANGUAGE_BY_BASENAME[base]) return LANGUAGE_BY_BASENAME[base];
8944
9119
  if (base === ".env" || base.startsWith(".env.")) return "dotenv";
8945
- const ext = path26.posix.extname(base).toLowerCase();
9120
+ const ext = path25.posix.extname(base).toLowerCase();
8946
9121
  return LANGUAGE_BY_EXTENSION[ext] ?? "text";
8947
9122
  }
8948
9123
  function maskedPath(value, secretRules) {
@@ -8950,33 +9125,33 @@ function maskedPath(value, secretRules) {
8950
9125
  }
8951
9126
  function confineToDirectory(directory, filename) {
8952
9127
  if (filename.includes("\0")) return null;
8953
- if (path26.isAbsolute(filename)) return null;
8954
- const base = path26.resolve(directory);
8955
- const resolved = path26.resolve(base, filename);
9128
+ if (path25.isAbsolute(filename)) return null;
9129
+ const base = path25.resolve(directory);
9130
+ const resolved = path25.resolve(base, filename);
8956
9131
  const caseInsensitive = process.platform === "win32" || process.platform === "darwin";
8957
- const prefix = caseInsensitive ? `${base}${path26.sep}`.toLowerCase() : `${base}${path26.sep}`;
9132
+ const prefix = caseInsensitive ? `${base}${path25.sep}`.toLowerCase() : `${base}${path25.sep}`;
8958
9133
  const candidate = caseInsensitive ? resolved.toLowerCase() : resolved;
8959
9134
  return candidate.startsWith(prefix) ? resolved : null;
8960
9135
  }
8961
9136
  function findStagingDirectory(config) {
8962
- const tmpDir = path26.resolve(config.cwd, config.tmpDir);
9137
+ const tmpDir = path25.resolve(config.cwd, config.tmpDir);
8963
9138
  let entries;
8964
9139
  try {
8965
- entries = fs25.readdirSync(tmpDir);
9140
+ entries = fs24.readdirSync(tmpDir);
8966
9141
  } catch {
8967
9142
  return null;
8968
9143
  }
8969
9144
  const runs = entries.filter((name) => name.startsWith("run-")).sort();
8970
9145
  const newest = runs[runs.length - 1];
8971
- return newest ? path26.join(tmpDir, newest) : null;
9146
+ return newest ? path25.join(tmpDir, newest) : null;
8972
9147
  }
8973
9148
  function describeMissingManifest(config, manifestPath) {
8974
- const outDir = path26.resolve(config.cwd, config.outDir);
8975
- const markerPath = path26.join(outDir, ".codebase-snapshot");
9149
+ const outDir = path25.resolve(config.cwd, config.outDir);
9150
+ const markerPath = path25.join(outDir, ".codebase-snapshot");
8976
9151
  let marker2 = null;
8977
9152
  try {
8978
- if (fs25.existsSync(markerPath)) {
8979
- const parsed = JSON.parse(fs25.readFileSync(markerPath, "utf8"));
9153
+ if (fs24.existsSync(markerPath)) {
9154
+ const parsed = JSON.parse(fs24.readFileSync(markerPath, "utf8"));
8980
9155
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
8981
9156
  marker2 = parsed;
8982
9157
  }
@@ -9011,13 +9186,13 @@ function sha256Hex(buffer) {
9011
9186
  return crypto.createHash("sha256").update(buffer).digest("hex");
9012
9187
  }
9013
9188
  function wouldNowBeIncluded(cwd, relativePath) {
9014
- const absolutePath = path26.join(cwd, relativePath);
9189
+ const absolutePath = path25.join(cwd, relativePath);
9015
9190
  try {
9016
- const stats = fs25.statSync(absolutePath);
9191
+ const stats = fs24.statSync(absolutePath);
9017
9192
  if (!stats.isFile()) return false;
9018
9193
  if (isBinaryExtension(absolutePath)) return false;
9019
9194
  if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) return false;
9020
- return !decodeText(fs25.readFileSync(absolutePath)).binary;
9195
+ return !decodeText(fs24.readFileSync(absolutePath)).binary;
9021
9196
  } catch {
9022
9197
  return false;
9023
9198
  }
@@ -9029,7 +9204,7 @@ var TRUNCATION_REASONS = /* @__PURE__ */ new Set([
9029
9204
  ]);
9030
9205
  function isConfinedRelative(value) {
9031
9206
  if (value.length === 0 || value.includes("\0") || value.includes("\\")) return false;
9032
- if (path26.isAbsolute(value)) return false;
9207
+ if (path25.isAbsolute(value)) return false;
9033
9208
  return !value.split("/").includes("..");
9034
9209
  }
9035
9210
  function describeManifestShapeProblem(value) {
@@ -9195,6 +9370,9 @@ function describeManifestShapeProblem(value) {
9195
9370
  if (typeof fields.relativePath !== "string") {
9196
9371
  return 'a "files" entry has no "relativePath"';
9197
9372
  }
9373
+ if (!isConfinedRelative(fields.relativePath)) {
9374
+ return 'a "files" entry "relativePath" resolves outside the repository and was not inspected';
9375
+ }
9198
9376
  if (!currentSchema) continue;
9199
9377
  if (typeof fields.part !== "string" || fields.part.length === 0) {
9200
9378
  return 'a "files" entry records no "part"';
@@ -9213,6 +9391,18 @@ function describeManifestShapeProblem(value) {
9213
9391
  }
9214
9392
  }
9215
9393
  if (!Array.isArray(candidate.skipped)) return 'missing "skipped" array';
9394
+ for (const entry of candidate.skipped) {
9395
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
9396
+ return 'a "skipped" entry is not an object';
9397
+ }
9398
+ const fields = entry;
9399
+ if (typeof fields.path !== "string" || !isConfinedRelative(fields.path)) {
9400
+ return 'a "skipped" entry "path" resolves outside the repository and was not inspected';
9401
+ }
9402
+ if (typeof fields.reason !== "string" || fields.reason.length === 0) {
9403
+ return 'a "skipped" entry has no "reason"';
9404
+ }
9405
+ }
9216
9406
  if (!Array.isArray(candidate.parts)) return 'missing "parts" array';
9217
9407
  for (const entry of candidate.parts) {
9218
9408
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
@@ -9223,7 +9413,7 @@ function describeManifestShapeProblem(value) {
9223
9413
  if (typeof filename !== "string" || filename.trim() === "") {
9224
9414
  return 'a "parts" entry has no "filename"';
9225
9415
  }
9226
- if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path26.isAbsolute(filename)) {
9416
+ if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path25.isAbsolute(filename)) {
9227
9417
  return 'a "parts" entry "filename" must be a bare filename inside parts/';
9228
9418
  }
9229
9419
  if (currentSchema) {
@@ -9249,8 +9439,8 @@ function describeManifestShapeProblem(value) {
9249
9439
  function validateSnapshot(configInput) {
9250
9440
  assertUsableConfigInput(configInput);
9251
9441
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput);
9252
- const manifestPath = path26.resolve(config.cwd, config.outDir, "manifest.json");
9253
- if (!fs25.existsSync(manifestPath)) {
9442
+ const manifestPath = path25.resolve(config.cwd, config.outDir, "manifest.json");
9443
+ if (!fs24.existsSync(manifestPath)) {
9254
9444
  return {
9255
9445
  valid: false,
9256
9446
  manifestPresent: false,
@@ -9261,7 +9451,7 @@ function validateSnapshot(configInput) {
9261
9451
  }
9262
9452
  let manifest;
9263
9453
  try {
9264
- manifest = JSON.parse(fs25.readFileSync(manifestPath, "utf8"));
9454
+ manifest = JSON.parse(fs24.readFileSync(manifestPath, "utf8"));
9265
9455
  } catch (err) {
9266
9456
  return {
9267
9457
  valid: false,
@@ -9273,17 +9463,19 @@ function validateSnapshot(configInput) {
9273
9463
  }
9274
9464
  const shapeProblem = describeManifestShapeProblem(manifest);
9275
9465
  if (shapeProblem) {
9466
+ const drift2 = emptyDrift();
9467
+ drift2.partIssues.push({ part: "manifest.json", issue: shapeProblem });
9276
9468
  return {
9277
9469
  valid: false,
9278
9470
  manifestPresent: true,
9279
- drift: emptyDrift(),
9471
+ drift: drift2,
9280
9472
  errors: [`${manifestPath} is not a snapshot manifest: ${shapeProblem}`],
9281
9473
  warnings: []
9282
9474
  };
9283
9475
  }
9284
9476
  const drift = emptyDrift();
9285
9477
  const warnings = [];
9286
- const snapshotDir = path26.resolve(config.cwd, config.outDir);
9478
+ const snapshotDir = path25.resolve(config.cwd, config.outDir);
9287
9479
  const unreadableSkips = manifest.skipped.filter(
9288
9480
  (entry) => entry.reason === "missing" || entry.reason === "read-error"
9289
9481
  );
@@ -9391,7 +9583,7 @@ function validateSnapshot(configInput) {
9391
9583
  );
9392
9584
  return importsChangedFile(
9393
9585
  diskFile,
9394
- importsOfFile(diskFile, path26.join(config.cwd, diskFile)),
9586
+ importsOfFile(diskFile, path25.join(config.cwd, diskFile)),
9395
9587
  unchangedScope,
9396
9588
  dependentResolver
9397
9589
  );
@@ -9413,7 +9605,7 @@ function validateSnapshot(configInput) {
9413
9605
  // own output directory as a set of files missing from the snapshot, so a correct
9414
9606
  // snapshot was reported as drifting.
9415
9607
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
9416
- (directory) => path26.relative(config.cwd, path26.resolve(config.cwd, directory)).replace(/\\/g, "/")
9608
+ (directory) => path25.relative(config.cwd, path25.resolve(config.cwd, directory)).replace(/\\/g, "/")
9417
9609
  ).filter((relative15) => relative15.length > 0 && !relative15.startsWith(".."))
9418
9610
  });
9419
9611
  for (const diskFile of collection.files) {
@@ -9441,7 +9633,7 @@ function validateSnapshot(configInput) {
9441
9633
  let diskHash;
9442
9634
  try {
9443
9635
  const stagedBlob = recordedStaged && stagedScope?.has(diskFile) === true ? readStagedBlob(config.cwd, diskFile) : null;
9444
- diskHash = sha256Hex(stagedBlob ?? fs25.readFileSync(path26.join(config.cwd, diskFile)));
9636
+ diskHash = sha256Hex(stagedBlob ?? fs24.readFileSync(path25.join(config.cwd, diskFile)));
9445
9637
  } catch (err) {
9446
9638
  if (err.code === "ENOENT") {
9447
9639
  drift.missingOnDisk.push(diskFile);
@@ -9471,7 +9663,7 @@ function validateSnapshot(configInput) {
9471
9663
  }
9472
9664
  let statFailure = null;
9473
9665
  try {
9474
- fs25.statSync(confined);
9666
+ fs24.statSync(confined);
9475
9667
  } catch (err) {
9476
9668
  statFailure = err;
9477
9669
  }
@@ -9491,7 +9683,7 @@ function validateSnapshot(configInput) {
9491
9683
  ...Object.values(config.budgets.byLayer)
9492
9684
  );
9493
9685
  const partNames = /* @__PURE__ */ new Set();
9494
- const partsDir = path26.join(snapshotDir, "parts");
9686
+ const partsDir = path25.join(snapshotDir, "parts");
9495
9687
  for (const part of manifest.parts) {
9496
9688
  if (!part || typeof part.filename !== "string") continue;
9497
9689
  partNames.add(part.filename);
@@ -9504,13 +9696,15 @@ function validateSnapshot(configInput) {
9504
9696
  });
9505
9697
  continue;
9506
9698
  }
9507
- let buffer;
9508
- try {
9509
- buffer = fs25.readFileSync(partPath);
9510
- } catch {
9511
- drift.partIssues.push({ part: part.filename, issue: "missing from snapshot/parts" });
9699
+ const partRead = readConfinedBytes(partsDir, part.filename);
9700
+ if (!partRead.ok) {
9701
+ drift.partIssues.push({
9702
+ part: part.filename,
9703
+ issue: `missing or not a regular file in snapshot/parts (${partRead.reason})`
9704
+ });
9512
9705
  continue;
9513
9706
  }
9707
+ const buffer = partRead.bytes;
9514
9708
  if (buffer.length !== part.byteSize) {
9515
9709
  drift.partIssues.push({
9516
9710
  part: part.filename,
@@ -9883,15 +10077,15 @@ function validateSnapshot(configInput) {
9883
10077
  ];
9884
10078
  for (const [key, artifact] of declaredArtifacts) {
9885
10079
  if (!artifact) continue;
9886
- const artifactPath = path26.join(snapshotDir, ...key.split("/"));
9887
- let buffer;
9888
- try {
9889
- if (!fs25.statSync(artifactPath).isFile()) throw new Error("not a regular file");
9890
- buffer = fs25.readFileSync(artifactPath);
9891
- } catch {
9892
- drift.partIssues.push({ part: key, issue: "declared artifact is missing" });
10080
+ const artifactRead = readConfinedBytes(snapshotDir, key);
10081
+ if (!artifactRead.ok) {
10082
+ drift.partIssues.push({
10083
+ part: key,
10084
+ issue: `declared artifact is missing or not a regular file (${artifactRead.reason})`
10085
+ });
9893
10086
  continue;
9894
10087
  }
10088
+ const buffer = artifactRead.bytes;
9895
10089
  if (sha256Hex(buffer) !== artifact.sha256 || buffer.length !== artifact.byteSize) {
9896
10090
  drift.partIssues.push({ part: key, issue: "artifact does not match its recorded digest" });
9897
10091
  continue;
@@ -9900,9 +10094,9 @@ function validateSnapshot(configInput) {
9900
10094
  for (const match of buffer.toString("utf8").matchAll(/\]\(([^)\s]+)\)/g)) {
9901
10095
  const target = match[1].split("#")[0];
9902
10096
  if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
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)) {
10097
+ const resolved = path25.resolve(snapshotDir, "reports", target);
10098
+ const relative15 = path25.relative(snapshotDir, resolved);
10099
+ if (relative15.startsWith("..") || path25.isAbsolute(relative15) || !fs24.existsSync(resolved)) {
9906
10100
  drift.partIssues.push({
9907
10101
  part: key,
9908
10102
  issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
@@ -9914,13 +10108,11 @@ function validateSnapshot(configInput) {
9914
10108
  const sarifArtifact = manifest.artifacts?.sarif;
9915
10109
  if (sarifArtifact) {
9916
10110
  const sarifKey = "reports/audit.sarif";
9917
- try {
9918
- const buffer = fs25.readFileSync(path26.join(snapshotDir, "reports", "audit.sarif"));
9919
- if (sha256Hex(buffer) !== sarifArtifact.sha256 || buffer.length !== sarifArtifact.byteSize) {
9920
- drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
9921
- }
9922
- } catch {
9923
- drift.partIssues.push({ part: sarifKey, issue: "declared artifact is missing" });
10111
+ const sarifRead = readConfinedBytes(snapshotDir, "reports/audit.sarif");
10112
+ if (!sarifRead.ok) {
10113
+ drift.partIssues.push({ part: sarifKey, issue: "declared artifact is missing or not a regular file" });
10114
+ } else if (sha256Hex(sarifRead.bytes) !== sarifArtifact.sha256 || sarifRead.bytes.length !== sarifArtifact.byteSize) {
10115
+ drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
9924
10116
  }
9925
10117
  }
9926
10118
  if (manifest.git && manifest.git.branch && manifest.git.branch !== config.branch) {
@@ -9961,9 +10153,9 @@ function validateSnapshot(configInput) {
9961
10153
  `${drift.configMismatches.length} configuration mismatch(es) between the manifest and this run.`
9962
10154
  );
9963
10155
  }
9964
- const signaturePath = path26.join(path26.dirname(manifestPath), "signature.json");
9965
- if (fs25.existsSync(signaturePath)) {
9966
- const outcome = verifySnapshotSignature(path26.dirname(manifestPath));
10156
+ const signaturePath = path25.join(path25.dirname(manifestPath), "signature.json");
10157
+ if (fs24.existsSync(signaturePath)) {
10158
+ const outcome = verifySnapshotSignature(path25.dirname(manifestPath));
9967
10159
  if (!outcome.ok) errors.push("signature: " + outcome.reason + ".");
9968
10160
  }
9969
10161
  if (manifest.slice !== void 0 || manifest.budget !== void 0) {
@@ -10106,7 +10298,7 @@ function parseRemoteSource(input, options = {}) {
10106
10298
  const directory = fileURLToPath(url2);
10107
10299
  return {
10108
10300
  ok: true,
10109
- source: { kind: "file", url: trimmed, host: "file", owner: "", repo: path26.basename(directory), ref: null }
10301
+ source: { kind: "file", url: trimmed, host: "file", owner: "", repo: path25.basename(directory), ref: null }
10110
10302
  };
10111
10303
  }
10112
10304
  let url;
@@ -10184,9 +10376,9 @@ function gitEnvironment(token, host) {
10184
10376
  async function cloneRepository(source, options) {
10185
10377
  const log = options.log ?? (() => {
10186
10378
  });
10187
- const dest = path26.resolve(options.dest);
10188
- fs25.rmSync(dest, { recursive: true, force: true });
10189
- fs25.mkdirSync(dest, { recursive: true });
10379
+ const dest = path25.resolve(options.dest);
10380
+ fs24.rmSync(dest, { recursive: true, force: true });
10381
+ fs24.mkdirSync(dest, { recursive: true });
10190
10382
  try {
10191
10383
  const ref = options.ref ?? source.ref;
10192
10384
  const args = [
@@ -10245,7 +10437,7 @@ async function cloneRepository(source, options) {
10245
10437
  };
10246
10438
  } catch (error) {
10247
10439
  try {
10248
- fs25.rmSync(dest, { recursive: true, force: true });
10440
+ fs24.rmSync(dest, { recursive: true, force: true });
10249
10441
  } catch {
10250
10442
  }
10251
10443
  throw error;
@@ -10258,16 +10450,16 @@ function directorySize(root) {
10258
10450
  const current = stack.pop();
10259
10451
  let entries;
10260
10452
  try {
10261
- entries = fs25.readdirSync(current, { withFileTypes: true });
10453
+ entries = fs24.readdirSync(current, { withFileTypes: true });
10262
10454
  } catch {
10263
10455
  continue;
10264
10456
  }
10265
10457
  for (const entry of entries) {
10266
- const full = path26.join(current, entry.name);
10458
+ const full = path25.join(current, entry.name);
10267
10459
  if (entry.isDirectory()) stack.push(full);
10268
10460
  else if (entry.isFile()) {
10269
10461
  try {
10270
- total += fs25.statSync(full).size;
10462
+ total += fs24.statSync(full).size;
10271
10463
  } catch {
10272
10464
  }
10273
10465
  }
@@ -10276,7 +10468,7 @@ function directorySize(root) {
10276
10468
  return total;
10277
10469
  }
10278
10470
  function makeCloneDirectory() {
10279
- return fs25.mkdtempSync(path26.join(os2.tmpdir(), "codebase-snapshot-clone-"));
10471
+ return fs24.mkdtempSync(path25.join(os2.tmpdir(), "codebase-snapshot-clone-"));
10280
10472
  }
10281
10473
 
10282
10474
  // src/mcp/instructions.ts
@@ -10484,7 +10676,7 @@ var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
10484
10676
  var META_PREFIX = "- Meta: ";
10485
10677
  var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
10486
10678
  var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
10487
- var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
10679
+ var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures", "comments-stripped"]);
10488
10680
  var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
10489
10681
  function readIncludedLines(fields) {
10490
10682
  const last = fields[fields.length - 1];
@@ -10557,8 +10749,8 @@ function findSection(sections, relativePath) {
10557
10749
  if (exact) return exact;
10558
10750
  const foldedPath = rendered.toLowerCase();
10559
10751
  const folded = sections.filter((section) => {
10560
- const path27 = section.path.toLowerCase();
10561
- return path27 === relativePath.toLowerCase() || path27 === foldedPath;
10752
+ const path26 = section.path.toLowerCase();
10753
+ return path26 === relativePath.toLowerCase() || path26 === foldedPath;
10562
10754
  });
10563
10755
  return folded.length === 1 ? folded[0] : null;
10564
10756
  }
@@ -10579,26 +10771,28 @@ var ARTIFACT_FILES = {
10579
10771
  fullXml: "full-codebase.xml",
10580
10772
  sarif: "reports/audit.sarif"
10581
10773
  };
10582
- var TEXT_ARTIFACT = /\.(md|json|txt|sarif)$/i;
10774
+ var TEXT_ARTIFACT = /\.(md|json|txt|sarif|xml)$/i;
10583
10775
  function sha256(buffer) {
10584
10776
  return createHash("sha256").update(buffer).digest("hex");
10585
10777
  }
10586
- function readBytes(file) {
10587
- try {
10588
- return fs25.readFileSync(file);
10589
- } catch {
10590
- return null;
10591
- }
10592
- }
10593
10778
  function readText2(file) {
10594
10779
  try {
10595
- return fs25.readFileSync(file, "utf8");
10780
+ return fs24.readFileSync(file, "utf8");
10596
10781
  } catch {
10597
10782
  return null;
10598
10783
  }
10599
10784
  }
10785
+ function snapshotText(snapshotDir, relative15) {
10786
+ const read = readConfinedText(snapshotDir, relative15);
10787
+ return read.ok ? read.text : null;
10788
+ }
10789
+ function snapshotBytes(snapshotDir, relative15) {
10790
+ const read = readConfinedBytes(snapshotDir, relative15);
10791
+ return read.ok ? read.bytes : null;
10792
+ }
10600
10793
  function readJson(file) {
10601
- const text2 = readText2(file);
10794
+ const confined = readConfinedText(path25.dirname(file), path25.basename(file));
10795
+ const text2 = confined.ok ? confined.text : null;
10602
10796
  if (text2 === null) return null;
10603
10797
  try {
10604
10798
  return JSON.parse(text2);
@@ -10609,14 +10803,14 @@ function readJson(file) {
10609
10803
  function walk(dir, prefix = "") {
10610
10804
  let entries;
10611
10805
  try {
10612
- entries = fs25.readdirSync(dir, { withFileTypes: true });
10806
+ entries = fs24.readdirSync(dir, { withFileTypes: true });
10613
10807
  } catch {
10614
10808
  return [];
10615
10809
  }
10616
10810
  const files = [];
10617
10811
  for (const entry of entries) {
10618
10812
  const relative15 = prefix === "" ? entry.name : prefix + "/" + entry.name;
10619
- if (entry.isDirectory()) files.push(...walk(path26.join(dir, entry.name), relative15));
10813
+ if (entry.isDirectory()) files.push(...walk(path25.join(dir, entry.name), relative15));
10620
10814
  else if (entry.isFile()) files.push(relative15);
10621
10815
  }
10622
10816
  return files;
@@ -10655,16 +10849,28 @@ function secretTokens(text2) {
10655
10849
  }
10656
10850
  return [...tokens];
10657
10851
  }
10658
- function readArtifactTexts(snapshotDir) {
10852
+ function readArtifactTexts(snapshotDir, maxBytes = 32 * 1024 * 1024) {
10659
10853
  const texts = [];
10854
+ let bytes = 0;
10660
10855
  for (const relative15 of walk(snapshotDir)) {
10661
10856
  if (!TEXT_ARTIFACT.test(relative15)) continue;
10662
- const text2 = readText2(path26.join(snapshotDir, relative15));
10663
- if (text2 !== null) texts.push(text2);
10857
+ const full = path25.join(snapshotDir, relative15);
10858
+ let size2;
10859
+ try {
10860
+ size2 = fs24.statSync(full).size;
10861
+ } catch {
10862
+ continue;
10863
+ }
10864
+ if (bytes + size2 > maxBytes) break;
10865
+ const text2 = snapshotText(snapshotDir, relative15);
10866
+ if (text2 !== null) {
10867
+ texts.push(text2);
10868
+ bytes += Buffer.byteLength(text2, "utf8");
10869
+ }
10664
10870
  }
10665
10871
  return texts;
10666
10872
  }
10667
- function findHostPaths(snapshotDir, repoDir) {
10873
+ function findHostPaths(snapshotDir, repoDir, maxBytes = 32 * 1024 * 1024) {
10668
10874
  const patterns = [
10669
10875
  /\/home\/[A-Za-z0-9._-]+/g,
10670
10876
  /\/Users\/[A-Za-z0-9._-]+/g,
@@ -10675,10 +10881,19 @@ function findHostPaths(snapshotDir, repoDir) {
10675
10881
  ];
10676
10882
  const repoPattern = new RegExp(escapeRegExp(repoDir), "g");
10677
10883
  const hits = /* @__PURE__ */ new Set();
10884
+ let scanned = 0;
10678
10885
  for (const relative15 of walk(snapshotDir)) {
10679
10886
  if (!TEXT_ARTIFACT.test(relative15)) continue;
10680
- const text2 = readText2(path26.join(snapshotDir, relative15));
10887
+ let size2;
10888
+ try {
10889
+ size2 = fs24.statSync(path25.join(snapshotDir, relative15)).size;
10890
+ } catch {
10891
+ continue;
10892
+ }
10893
+ if (scanned + size2 > maxBytes) break;
10894
+ const text2 = snapshotText(snapshotDir, relative15);
10681
10895
  if (text2 === null) continue;
10896
+ scanned += Buffer.byteLength(text2, "utf8");
10682
10897
  for (const pattern of patterns) {
10683
10898
  for (const match of text2.match(pattern) ?? []) hits.add(relative15 + ": " + match);
10684
10899
  }
@@ -10833,10 +11048,10 @@ function markdownPackBodies(text2) {
10833
11048
  return bodies.size === 0 ? null : bodies;
10834
11049
  }
10835
11050
  function auditSnapshot(options) {
10836
- const snapshotDir = path26.resolve(options.snapshotDir);
10837
- const repoDir = path26.resolve(options.repoDir);
11051
+ const snapshotDir = path25.resolve(options.snapshotDir);
11052
+ const repoDir = path25.resolve(options.repoDir);
10838
11053
  const checks = [];
10839
- const manifestFile = path26.join(snapshotDir, "manifest.json");
11054
+ const manifestFile = path25.join(snapshotDir, "manifest.json");
10840
11055
  const raw = readJson(manifestFile);
10841
11056
  const problem = raw === null ? "the file is missing or is not valid JSON" : describeManifestShapeProblem(raw);
10842
11057
  if (raw === null || problem !== null) {
@@ -10865,7 +11080,7 @@ function auditSnapshot(options) {
10865
11080
  const missingParts = [];
10866
11081
  const mismatched = [];
10867
11082
  for (const part of manifest.parts) {
10868
- const bytes = readBytes(path26.join(snapshotDir, "parts", part.filename));
11083
+ const bytes = snapshotBytes(snapshotDir, "parts/" + part.filename);
10869
11084
  if (bytes === null) {
10870
11085
  missingParts.push(part.filename);
10871
11086
  continue;
@@ -10933,7 +11148,7 @@ function auditSnapshot(options) {
10933
11148
  const relative15 = ARTIFACT_FILES[key];
10934
11149
  if (relative15 === void 0) continue;
10935
11150
  artifactCount += 1;
10936
- const bytes = readBytes(path26.join(snapshotDir, relative15));
11151
+ const bytes = snapshotBytes(snapshotDir, relative15);
10937
11152
  if (bytes === null) artifactProblems.push(relative15 + " is missing");
10938
11153
  else if (typeof value.sha256 === "string" && sha256(bytes) !== value.sha256) {
10939
11154
  artifactProblems.push(relative15 + " changed");
@@ -10980,8 +11195,8 @@ function auditSnapshot(options) {
10980
11195
  unexpected.length + " unexpected path(s): " + sample(unexpected)
10981
11196
  )
10982
11197
  );
10983
- const signaturePath = path26.join(snapshotDir, "signature.json");
10984
- if (fs25.existsSync(signaturePath)) {
11198
+ const signaturePath = path25.join(snapshotDir, "signature.json");
11199
+ if (fs24.existsSync(signaturePath)) {
10985
11200
  const outcome = verifySnapshotSignature(snapshotDir);
10986
11201
  checks.push(
10987
11202
  outcome.ok ? check(
@@ -11046,7 +11261,7 @@ function auditSnapshot(options) {
11046
11261
  manifest.files.map((file) => [anchorForPath(file.relativePath), file.relativePath])
11047
11262
  );
11048
11263
  for (const part of manifest.parts) {
11049
- const partText = readText2(path26.join(snapshotDir, "parts", part.filename));
11264
+ const partText = snapshotText(snapshotDir, "parts/" + part.filename);
11050
11265
  if (partText === null) continue;
11051
11266
  const sections = parsePartSections(partText);
11052
11267
  partTexts.set(part.filename, partText);
@@ -11113,7 +11328,7 @@ function auditSnapshot(options) {
11113
11328
  }
11114
11329
  };
11115
11330
  if (manifest.artifacts?.readme != null) {
11116
- const text2 = readText2(path26.join(snapshotDir, "README.md"));
11331
+ const text2 = snapshotText(snapshotDir, "README.md");
11117
11332
  if (text2 === null) {
11118
11333
  reportProblems.push("README.md is recorded but unreadable");
11119
11334
  } else {
@@ -11153,7 +11368,7 @@ function auditSnapshot(options) {
11153
11368
  }
11154
11369
  }
11155
11370
  if (manifest.artifacts?.prompt != null) {
11156
- const text2 = readText2(path26.join(snapshotDir, "PROMPT.md"));
11371
+ const text2 = snapshotText(snapshotDir, "PROMPT.md");
11157
11372
  if (text2 === null) {
11158
11373
  reportProblems.push("PROMPT.md is recorded but unreadable");
11159
11374
  } else {
@@ -11342,7 +11557,7 @@ function auditSnapshot(options) {
11342
11557
  ];
11343
11558
  for (const reader of packReaders) {
11344
11559
  if (manifest.artifacts?.[reader.key] == null) continue;
11345
- const packText = readText2(path26.join(snapshotDir, reader.file));
11560
+ const packText = snapshotText(snapshotDir, reader.file);
11346
11561
  const problems = [];
11347
11562
  if (packText === null) {
11348
11563
  problems.push(reader.file + " is recorded but unreadable");
@@ -11355,8 +11570,8 @@ function auditSnapshot(options) {
11355
11570
  for (const file of manifest.files) {
11356
11571
  if (!packed.has(file.relativePath)) problems.push(file.relativePath + " is in the manifest but not the pack");
11357
11572
  }
11358
- for (const path27 of packed) {
11359
- if (!known2.has(path27)) problems.push(path27 + " is in the pack but not the manifest");
11573
+ for (const path26 of packed) {
11574
+ if (!known2.has(path26)) problems.push(path26 + " is in the pack but not the manifest");
11360
11575
  }
11361
11576
  }
11362
11577
  }
@@ -11505,7 +11720,7 @@ function auditSnapshot(options) {
11505
11720
  let packBodies = 0;
11506
11721
  let packSkipped = 0;
11507
11722
  for (const pack of packsWanted) {
11508
- const text2 = readText2(path26.join(snapshotDir, pack.file));
11723
+ const text2 = snapshotText(snapshotDir, pack.file);
11509
11724
  if (text2 === null) continue;
11510
11725
  const bodies = pack.read(text2);
11511
11726
  if (bodies === null) {
@@ -11569,7 +11784,8 @@ function auditSnapshot(options) {
11569
11784
  unreplayable += 1;
11570
11785
  continue;
11571
11786
  }
11572
- const bytes = readBytes(path26.join(repoDir, file.relativePath));
11787
+ const repoBytes = readConfinedBytes(repoDir, file.relativePath);
11788
+ const bytes = repoBytes.ok ? repoBytes.bytes : null;
11573
11789
  if (bytes === null || sha256(bytes) !== file.hashSha256) {
11574
11790
  unreplayable += 1;
11575
11791
  continue;
@@ -11607,9 +11823,9 @@ function auditSnapshot(options) {
11607
11823
  )
11608
11824
  );
11609
11825
  }
11610
- const indexParent = path26.dirname(snapshotDir);
11611
- const indexPath = path26.join(indexParent, "WORKSPACE.json");
11612
- if (fs25.existsSync(indexPath)) {
11826
+ const indexParent = path25.dirname(snapshotDir);
11827
+ const indexPath = path25.join(indexParent, "WORKSPACE.json");
11828
+ if (fs24.existsSync(indexPath)) {
11613
11829
  const indexText = readText2(indexPath);
11614
11830
  let members = [];
11615
11831
  let problem2 = null;
@@ -11620,7 +11836,7 @@ function auditSnapshot(options) {
11620
11836
  } catch (error) {
11621
11837
  problem2 = error.message;
11622
11838
  }
11623
- const memberName = path26.basename(snapshotDir);
11839
+ const memberName = path25.basename(snapshotDir);
11624
11840
  const member = members.find((entry) => entry.name === memberName);
11625
11841
  if (problem2 !== null) {
11626
11842
  checks.push(check(
@@ -11644,7 +11860,7 @@ function auditSnapshot(options) {
11644
11860
  if (typeof member.files === "number" && member.files !== manifest.counts.totalFiles) {
11645
11861
  disagreements.push("file count");
11646
11862
  }
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;
11863
+ 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;
11648
11864
  checks.push(
11649
11865
  sourceGone !== null ? check("workspace.index", "The workspace index agrees with this member", "warning", "warn", sourceGone) : disagreements.length === 0 ? check(
11650
11866
  "workspace.index",
@@ -11669,7 +11885,14 @@ function auditSnapshot(options) {
11669
11885
  for (const relative15 of walk(snapshotDir)) {
11670
11886
  if (!TEXT_ARTIFACT.test(relative15) || scannedBytes > scanBudget) continue;
11671
11887
  if (relative15 === SIGNATURE_FILE) continue;
11672
- const text2 = readText2(path26.join(snapshotDir, relative15));
11888
+ let size2;
11889
+ try {
11890
+ size2 = fs24.statSync(path25.join(snapshotDir, relative15)).size;
11891
+ } catch {
11892
+ continue;
11893
+ }
11894
+ if (scannedBytes + size2 > scanBudget) break;
11895
+ const text2 = snapshotText(snapshotDir, relative15);
11673
11896
  if (text2 === null) continue;
11674
11897
  scannedBytes += Buffer.byteLength(text2, "utf8");
11675
11898
  let findingCount = 0;
@@ -11687,9 +11910,9 @@ function auditSnapshot(options) {
11687
11910
  leakHits.push(relative15 + " (" + findingCount + " line(s))");
11688
11911
  }
11689
11912
  }
11690
- const signatureRecordPath = path26.join(snapshotDir, SIGNATURE_FILE);
11691
- if (fs25.existsSync(signatureRecordPath)) {
11692
- const recordText = readText2(signatureRecordPath);
11913
+ const signatureRecordPath = path25.join(snapshotDir, SIGNATURE_FILE);
11914
+ if (fs24.existsSync(signatureRecordPath)) {
11915
+ const recordText = snapshotText(snapshotDir, SIGNATURE_FILE);
11693
11916
  if (recordText !== null) {
11694
11917
  scannedBytes += Buffer.byteLength(recordText, "utf8");
11695
11918
  let scanText = recordText;
@@ -11729,11 +11952,17 @@ function auditSnapshot(options) {
11729
11952
  );
11730
11953
  const leakedFrom = [];
11731
11954
  let compared = 0;
11732
- const artifactTexts = readArtifactTexts(snapshotDir);
11955
+ const artifactTexts = readArtifactTexts(snapshotDir, scanBudget);
11733
11956
  const artifactContains = (token) => artifactTexts.some((text2) => text2.includes(token));
11734
11957
  for (const record of skippedSensitive.slice(0, 40)) {
11735
11958
  if (record.path.includes("[REDACTED") || compared > 400) continue;
11736
- const text2 = readText2(path26.join(repoDir, record.path));
11959
+ try {
11960
+ if (fs24.statSync(path25.join(repoDir, record.path)).size > scanBudget) continue;
11961
+ } catch {
11962
+ continue;
11963
+ }
11964
+ const repoRead = readConfinedText(repoDir, record.path);
11965
+ const text2 = repoRead.ok ? repoRead.text : null;
11737
11966
  if (text2 === null) continue;
11738
11967
  for (const token of secretTokens(text2)) {
11739
11968
  compared += 1;
@@ -11755,7 +11984,7 @@ function auditSnapshot(options) {
11755
11984
  "A value from " + sample([...new Set(leakedFrom)]) + " appears in the snapshot."
11756
11985
  )
11757
11986
  );
11758
- const pii = findHostPaths(snapshotDir, repoDir);
11987
+ const pii = findHostPaths(snapshotDir, repoDir, scanBudget);
11759
11988
  checks.push(
11760
11989
  pii.length === 0 ? check(
11761
11990
  "pii.paths",
@@ -11876,6 +12105,17 @@ function report(snapshotDir, repoDir, checks) {
11876
12105
  counts
11877
12106
  };
11878
12107
  }
12108
+ function safeRegularFile(cwd, absolute) {
12109
+ try {
12110
+ if (!fs24.lstatSync(absolute).isFile()) return false;
12111
+ const root = fs24.realpathSync(cwd);
12112
+ const real = fs24.realpathSync(absolute);
12113
+ const relative15 = path25.relative(root, real);
12114
+ return relative15 !== ".." && !relative15.startsWith(".." + path25.sep) && !path25.isAbsolute(relative15);
12115
+ } catch {
12116
+ return false;
12117
+ }
12118
+ }
11879
12119
  function describeMatcher(matcher) {
11880
12120
  if (typeof matcher === "string") return matcher;
11881
12121
  if (matcher instanceof RegExp) return String(matcher);
@@ -11885,13 +12125,13 @@ function describeMatcher(matcher) {
11885
12125
  return String(matcher);
11886
12126
  }
11887
12127
  function normalizeTarget(cwd, target) {
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)) {
12128
+ const resolvedCwd = path25.resolve(cwd);
12129
+ const absolute = path25.resolve(resolvedCwd, target);
12130
+ const relative15 = path25.relative(resolvedCwd, absolute);
12131
+ if (relative15 === "" || relative15 === ".." || relative15.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative15)) {
11892
12132
  return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
11893
12133
  }
11894
- return { relative: relative15.split(path26.sep).join("/"), outsideRoot: false };
12134
+ return { relative: relative15.split(path25.sep).join("/"), outsideRoot: false };
11895
12135
  }
11896
12136
  function findRuleMatch(rules, relativePath) {
11897
12137
  return rules.find(
@@ -11910,9 +12150,9 @@ function findRecordedAncestor(skipped, relative15, maskedPath2) {
11910
12150
  return nearest;
11911
12151
  }
11912
12152
  function readManifest2(config) {
11913
- const manifestPath = path26.resolve(config.cwd, config.outDir, "manifest.json");
12153
+ const manifestPath = path25.resolve(config.cwd, config.outDir, "manifest.json");
11914
12154
  try {
11915
- return JSON.parse(fs25.readFileSync(manifestPath, "utf8"));
12155
+ return JSON.parse(fs24.readFileSync(manifestPath, "utf8"));
11916
12156
  } catch {
11917
12157
  return null;
11918
12158
  }
@@ -11930,10 +12170,14 @@ function explainPath(config, target) {
11930
12170
  detail: "path resolves outside the configured repository root and was not inspected"
11931
12171
  };
11932
12172
  }
11933
- const absolute = path26.join(config.cwd, relative15);
12173
+ const absolute = path25.join(config.cwd, relative15);
12174
+ const stagedBlob = config.staged === true ? readStagedBlob(config.cwd, relative15) : null;
11934
12175
  const result = {
11935
12176
  path: maskedPath2,
11936
- exists: fs25.existsSync(absolute),
12177
+ // `existsSync` follows a symlink, so an in-repo link to /etc/passwd answered "exists" for a
12178
+ // file the scanner refuses. `lstat` plus a canonical containment check keeps the answer about
12179
+ // a regular file the repository actually contains; a staged blob is the index's answer.
12180
+ exists: stagedBlob !== null || safeRegularFile(config.cwd, absolute),
11937
12181
  included: false
11938
12182
  };
11939
12183
  const collection = collectFiles(config.cwd, {
@@ -11947,7 +12191,7 @@ function explainPath(config, target) {
11947
12191
  // Same exclusion `generate` applies, so `explain` never says "not-discovered" about a file
11948
12192
  // that is only missing because the walker dropped the tool's own output directory.
11949
12193
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
11950
- (directory) => path26.relative(config.cwd, path26.resolve(config.cwd, directory)).replace(/\\/g, "/")
12194
+ (directory) => path25.relative(config.cwd, path25.resolve(config.cwd, directory)).replace(/\\/g, "/")
11951
12195
  ).filter((relative16) => relative16.length > 0 && !relative16.startsWith(".."))
11952
12196
  });
11953
12197
  if (!collection.files.includes(relative15)) {
@@ -12012,11 +12256,13 @@ function explainPath(config, target) {
12012
12256
  result.detail = "binary extension; generate skips it without reading and records `binary` in manifest.skipped[]";
12013
12257
  return result;
12014
12258
  }
12015
- let sizeOnDisk = null;
12016
- try {
12017
- sizeOnDisk = fs25.statSync(absolute).size;
12018
- } catch {
12019
- sizeOnDisk = null;
12259
+ let sizeOnDisk = stagedBlob?.length ?? null;
12260
+ if (sizeOnDisk === null) {
12261
+ try {
12262
+ sizeOnDisk = fs24.statSync(absolute).size;
12263
+ } catch {
12264
+ sizeOnDisk = null;
12265
+ }
12020
12266
  }
12021
12267
  if (sizeOnDisk !== null && sizeOnDisk > BINARY_SCAN_BYTES && isBinaryFile(absolute)) {
12022
12268
  result.included = false;
@@ -12024,10 +12270,10 @@ function explainPath(config, target) {
12024
12270
  result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
12025
12271
  return result;
12026
12272
  }
12027
- if (fs25.existsSync(absolute) && fs25.statSync(absolute).isFile()) {
12273
+ if (stagedBlob !== null || safeRegularFile(config.cwd, absolute)) {
12028
12274
  let buffer;
12029
12275
  try {
12030
- buffer = fs25.readFileSync(absolute);
12276
+ buffer = stagedBlob ?? fs24.readFileSync(absolute);
12031
12277
  } catch (err) {
12032
12278
  result.included = false;
12033
12279
  result.reason = "read-error";
@@ -12076,6 +12322,22 @@ function explainPath(config, target) {
12076
12322
  const record = manifest?.skipped?.find((skip) => skip.path === relative15);
12077
12323
  if (record !== void 0 && (record.reason === "not-selected" || record.reason === "unchanged")) {
12078
12324
  result.included = false;
12325
+ for (const key of [
12326
+ "layer",
12327
+ "layerMatch",
12328
+ "kind",
12329
+ "kindMatch",
12330
+ "language",
12331
+ "inclusionMode",
12332
+ "lines",
12333
+ "bytes",
12334
+ "encoding",
12335
+ "secretCount",
12336
+ "secrets"
12337
+ ]) {
12338
+ delete result[key];
12339
+ }
12340
+ result.part = null;
12079
12341
  result.reason = record.reason;
12080
12342
  result.detail = record.detail ?? (record.reason === "not-selected" ? "the snapshot was generated for a selection (--slice or --budget-tokens) that did not include this path" : "the snapshot was generated with a changed-files scope that did not include this path");
12081
12343
  }
@@ -12117,7 +12379,7 @@ function renderExplainText(result) {
12117
12379
  return lines.join("\n");
12118
12380
  }
12119
12381
  function workerEntry(directory, isCjs) {
12120
- const entry = path26.join(directory, isCjs ? "index.cjs" : "index.js");
12382
+ const entry = path25.join(directory, isCjs ? "index.cjs" : "index.js");
12121
12383
  return { path: entry, url: pathToFileURL(entry).href };
12122
12384
  }
12123
12385
  var WORKER_SOURCE = `
@@ -12126,7 +12388,10 @@ const { parentPort, workerData } = require("node:worker_threads");
12126
12388
  (async () => {
12127
12389
  try {
12128
12390
  const mod = await import(workerData.entryUrl);
12129
- const loaded = await mod.loadConfigFileDetailed(workerData.cwd);
12391
+ const loaded =
12392
+ workerData.config === null || workerData.config === undefined
12393
+ ? await mod.loadConfigFileDetailed(workerData.cwd, { allowExecutableConfig: false })
12394
+ : { config: workerData.config, errors: [] };
12130
12395
  if (loaded.errors.length > 0) {
12131
12396
  parentPort.postMessage({ ok: false, message: loaded.errors.join("; ") });
12132
12397
  return;
@@ -12138,6 +12403,7 @@ const { parentPort, workerData } = require("node:worker_threads");
12138
12403
  const manifest = mod.generateSnapshot(config, {
12139
12404
  dryRun: workerData.dryRun === true,
12140
12405
  ...(workerData.narrow ?? {}),
12406
+ ...(workerData.source === undefined ? {} : { source: workerData.source }),
12141
12407
  ...(workerData.runId === undefined ? {} : { runId: workerData.runId }),
12142
12408
  });
12143
12409
  const skipCounts = new Map();
@@ -12193,7 +12459,7 @@ function generateInWorker(cwd, cliOptions, options = {}) {
12193
12459
  });
12194
12460
  };
12195
12461
  const isCjs = typeof __dirname !== "undefined";
12196
- const directory = isCjs ? __dirname : path26.dirname(fileURLToPath(import.meta.url));
12462
+ const directory = isCjs ? __dirname : path25.dirname(fileURLToPath(import.meta.url));
12197
12463
  try {
12198
12464
  worker = new Worker(WORKER_SOURCE, {
12199
12465
  eval: true,
@@ -12203,6 +12469,8 @@ function generateInWorker(cwd, cliOptions, options = {}) {
12203
12469
  cliOptions,
12204
12470
  dryRun: options.dryRun === true,
12205
12471
  narrow: options.narrow ?? {},
12472
+ ...options.config === void 0 ? {} : { config: options.config },
12473
+ ...options.source === void 0 ? {} : { source: options.source },
12206
12474
  ...options.runId === void 0 ? {} : { runId: options.runId }
12207
12475
  }
12208
12476
  });
@@ -12255,69 +12523,13 @@ function windowText(body, fromLine, lineCount) {
12255
12523
  pastEnd
12256
12524
  };
12257
12525
  }
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
12314
12526
  function foldForComparison(value) {
12315
12527
  return process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
12316
12528
  }
12317
12529
  function canonicalPath(value) {
12318
- const absolute = path26.resolve(value);
12530
+ const absolute = path25.resolve(value);
12319
12531
  try {
12320
- return fs25.realpathSync(absolute);
12532
+ return fs24.realpathSync(absolute);
12321
12533
  } catch {
12322
12534
  return absolute;
12323
12535
  }
@@ -12325,29 +12537,29 @@ function canonicalPath(value) {
12325
12537
  function isInside3(parent, child) {
12326
12538
  const foldedParent = foldForComparison(parent);
12327
12539
  const foldedChild = foldForComparison(child);
12328
- return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path26.sep}`);
12540
+ return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path25.sep}`);
12329
12541
  }
12330
12542
  function resolveThroughExistingAncestor(target) {
12331
12543
  let existing = target;
12332
12544
  const missing = [];
12333
- while (!fs25.existsSync(existing)) {
12334
- missing.unshift(path26.basename(existing));
12335
- const parent = path26.dirname(existing);
12545
+ while (!fs24.existsSync(existing)) {
12546
+ missing.unshift(path25.basename(existing));
12547
+ const parent = path25.dirname(existing);
12336
12548
  if (parent === existing) break;
12337
12549
  existing = parent;
12338
12550
  }
12339
12551
  const resolved = canonicalPath(existing);
12340
- return missing.length === 0 ? resolved : path26.join(resolved, ...missing);
12552
+ return missing.length === 0 ? resolved : path25.join(resolved, ...missing);
12341
12553
  }
12342
12554
  function resolveRoot(requested, context) {
12343
12555
  if (requested !== void 0 && (typeof requested !== "string" || requested.trim().length === 0)) {
12344
12556
  return { ok: false, message: '"root" must be a non-empty string when provided.' };
12345
12557
  }
12346
12558
  const wanted = typeof requested === "string" ? requested.trim() : context.cwd;
12347
- const absolute = path26.resolve(context.cwd, wanted);
12559
+ const absolute = path25.resolve(context.cwd, wanted);
12348
12560
  let stats;
12349
12561
  try {
12350
- stats = fs25.statSync(absolute);
12562
+ stats = fs24.statSync(absolute);
12351
12563
  } catch {
12352
12564
  return { ok: false, message: `"${wanted}" does not exist, so it cannot be a repository root.` };
12353
12565
  }
@@ -12399,7 +12611,7 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
12399
12611
  }
12400
12612
  const requested = overrides.outDir.trim();
12401
12613
  const permitted = allowedRoots !== void 0 && allowedRoots.length > 0 ? allowedRoots : [root];
12402
- const resolved = resolveThroughExistingAncestor(path26.resolve(root, requested));
12614
+ const resolved = resolveThroughExistingAncestor(path25.resolve(root, requested));
12403
12615
  if (!permitted.some((allowed) => isInside3(canonicalPath(allowed), resolved))) {
12404
12616
  const shown = permitted.map((allowed) => canonicalPath(allowed)).join(", ");
12405
12617
  return {
@@ -12449,25 +12661,25 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
12449
12661
  var MANIFEST_CACHE_LIMIT = 8;
12450
12662
  var manifestCache = /* @__PURE__ */ new Map();
12451
12663
  function manifestPathFor(workspace) {
12452
- return path26.resolve(workspace.root, workspace.config.outDir, "manifest.json");
12664
+ return path25.resolve(workspace.root, workspace.config.outDir, "manifest.json");
12453
12665
  }
12454
12666
  function partPathFor(workspace, filename) {
12455
12667
  if (filename.length === 0 || filename.includes("\0")) return null;
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)) {
12668
+ const partsDir = path25.resolve(workspace.root, workspace.config.outDir, "parts");
12669
+ const resolved = path25.resolve(partsDir, filename);
12670
+ const relative15 = path25.relative(partsDir, resolved);
12671
+ if (relative15.length === 0 || relative15.includes(path25.sep) || relative15.includes("/") || relative15.includes("\\") || path25.isAbsolute(relative15)) {
12460
12672
  return null;
12461
12673
  }
12462
12674
  let stats;
12463
12675
  try {
12464
- stats = fs25.lstatSync(resolved);
12676
+ stats = fs24.lstatSync(resolved);
12465
12677
  } catch {
12466
12678
  return null;
12467
12679
  }
12468
12680
  if (!stats.isFile()) return null;
12469
12681
  try {
12470
- if (path26.dirname(fs25.realpathSync(resolved)) !== fs25.realpathSync(partsDir)) return null;
12682
+ if (path25.dirname(fs24.realpathSync(resolved)) !== fs24.realpathSync(partsDir)) return null;
12471
12683
  } catch {
12472
12684
  return null;
12473
12685
  }
@@ -12475,8 +12687,8 @@ function partPathFor(workspace, filename) {
12475
12687
  }
12476
12688
  function readManifest3(workspace) {
12477
12689
  const file = manifestPathFor(workspace);
12478
- const shown = path26.relative(workspace.root, file).split(path26.sep).join("/") || file;
12479
- const confined = readConfinedText(path26.dirname(file), path26.basename(file));
12690
+ const shown = path25.relative(workspace.root, file).split(path25.sep).join("/") || file;
12691
+ const confined = readConfinedText(path25.dirname(file), path25.basename(file));
12480
12692
  if (!confined.ok) {
12481
12693
  if (confined.reason === "missing") {
12482
12694
  return {
@@ -12558,11 +12770,18 @@ function unsafeRegExpReason(source) {
12558
12770
  if (char === ")") {
12559
12771
  const group = groups.pop();
12560
12772
  if (group === void 0) continue;
12561
- const next = source[index + 1];
12562
- if (next === "*" || next === "+" || next === "{" && isUnboundedBrace(source, index + 1)) {
12773
+ if (isQuantifiedAt(source, index + 1)) {
12563
12774
  if (group.quantified || group.alternation) {
12564
12775
  return "a quantified group contains another quantifier or an alternation";
12565
12776
  }
12777
+ group.quantified = true;
12778
+ } else if (isOptionalQuantifierAt(source, index + 1)) {
12779
+ group.quantified = true;
12780
+ }
12781
+ const parent = groups[groups.length - 1];
12782
+ if (parent !== void 0) {
12783
+ parent.quantified = parent.quantified || group.quantified;
12784
+ parent.alternation = parent.alternation || group.alternation;
12566
12785
  }
12567
12786
  continue;
12568
12787
  }
@@ -12609,11 +12828,31 @@ function unsafeRegExpReason(source) {
12609
12828
  }
12610
12829
  return null;
12611
12830
  }
12612
- function isUnboundedBrace(source, start) {
12831
+ function isOptionalQuantifierAt(source, start) {
12832
+ if (source[start] === "?") return true;
12833
+ if (source[start] !== "{") return false;
12613
12834
  const close = source.indexOf("}", start + 1);
12614
12835
  if (close === -1) return false;
12615
12836
  const body = source.slice(start + 1, close);
12616
- return /^\d+,$/.test(body);
12837
+ const match = /^(\d+)(?:,(\d*))?$/.exec(body);
12838
+ if (match === null) return false;
12839
+ const minimum = Number(match[1]);
12840
+ if (match[2] === void 0) return minimum <= 1;
12841
+ const maximum = match[2] === "" ? Infinity : Number(match[2]);
12842
+ return maximum <= 1;
12843
+ }
12844
+ function isQuantifiedAt(source, start) {
12845
+ const char = source[start];
12846
+ if (char === "*" || char === "+") return true;
12847
+ if (char !== "{") return false;
12848
+ const close = source.indexOf("}", start + 1);
12849
+ if (close === -1) return false;
12850
+ const body = source.slice(start + 1, close);
12851
+ const match = /^(\d+)(?:,(\d*))?$/.exec(body);
12852
+ if (match === null) return false;
12853
+ if (match[2] === void 0) return Number(match[1]) > 1;
12854
+ if (match[2] === "") return true;
12855
+ return Number(match[2]) > 1;
12617
12856
  }
12618
12857
 
12619
12858
  // src/mcp/tools.ts
@@ -12708,7 +12947,7 @@ function formatBytes2(bytes) {
12708
12947
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
12709
12948
  }
12710
12949
  function relativeFor(workspace, absolute) {
12711
- return path26.relative(workspace.root, absolute).split(path26.sep).join("/");
12950
+ return path25.relative(workspace.root, absolute).split(path25.sep).join("/");
12712
12951
  }
12713
12952
  function capped(values, limit = 20) {
12714
12953
  return { count: values.length, sample: values.slice(0, limit) };
@@ -12727,13 +12966,13 @@ function summarizeDrift(drift) {
12727
12966
  function toRelativePath(root, value) {
12728
12967
  const cleaned = value.trim();
12729
12968
  if (cleaned.length === 0 || cleaned.includes("\0")) return null;
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)) {
12969
+ const resolvedRoot = path25.resolve(root);
12970
+ const absolute = path25.resolve(resolvedRoot, cleaned);
12971
+ const relative15 = path25.relative(resolvedRoot, absolute);
12972
+ if (relative15 === "" || relative15 === ".." || relative15.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative15)) {
12734
12973
  return null;
12735
12974
  }
12736
- return relative15.split(path26.sep).join("/");
12975
+ return relative15.split(path25.sep).join("/");
12737
12976
  }
12738
12977
  function symbolsOf(entry) {
12739
12978
  const summary = entry.summary;
@@ -12826,8 +13065,8 @@ var historyTool = {
12826
13065
  async handler(args, context) {
12827
13066
  const prepared = await prepare(args, context, outDirOverride(args));
12828
13067
  if (!prepared.ok) return prepared.outcome;
12829
- const snapshotDir = path26.resolve(prepared.workspace.root, prepared.workspace.config.outDir);
12830
- const reportRead = readConfinedText(snapshotDir, path26.posix.join("reports", "log.md"));
13068
+ const snapshotDir = path25.resolve(prepared.workspace.root, prepared.workspace.config.outDir);
13069
+ const reportRead = readConfinedText(snapshotDir, path25.posix.join("reports", "log.md"));
12831
13070
  if (!reportRead.ok) {
12832
13071
  return {
12833
13072
  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.",
@@ -12895,7 +13134,7 @@ var budgetTool = {
12895
13134
  ...args.includeTests === true ? { includeTests: true } : {}
12896
13135
  });
12897
13136
  const paths = new Set(plan.files.map((file) => file.path));
12898
- const gained = [...paths].filter((path27) => !previous.has(path27)).sort();
13137
+ const gained = [...paths].filter((path26) => !previous.has(path26)).sort();
12899
13138
  previous = paths;
12900
13139
  rows.push({
12901
13140
  budget,
@@ -12998,8 +13237,8 @@ var workspaceTool = {
12998
13237
  async handler(args, context) {
12999
13238
  const prepared = await prepare(args, context, outDirOverride(args));
13000
13239
  if (!prepared.ok) return prepared.outcome;
13001
- const snapshotDir = path26.resolve(prepared.workspace.root, prepared.workspace.config.outDir);
13002
- const index = path26.join(snapshotDir, "WORKSPACE.json");
13240
+ const snapshotDir = path25.resolve(prepared.workspace.root, prepared.workspace.config.outDir);
13241
+ const index = path25.join(snapshotDir, "WORKSPACE.json");
13003
13242
  const read = readConfinedText(snapshotDir, "WORKSPACE.json");
13004
13243
  if (!read.ok) {
13005
13244
  return {
@@ -13008,7 +13247,12 @@ var workspaceTool = {
13008
13247
  };
13009
13248
  }
13010
13249
  const text2 = read.text;
13011
- const document = JSON.parse(text2);
13250
+ let document;
13251
+ try {
13252
+ document = JSON.parse(text2);
13253
+ } catch (error) {
13254
+ return { text: "WORKSPACE.json is not valid JSON: " + error.message, isError: true };
13255
+ }
13012
13256
  const members = document.members ?? [];
13013
13257
  const links = document.links ?? [];
13014
13258
  const lines = [
@@ -13207,7 +13451,7 @@ var cyclesTool = {
13207
13451
  tsconfig: tsconfigPathsFor(prepared.workspace.root)
13208
13452
  });
13209
13453
  const edges = /* @__PURE__ */ new Map();
13210
- for (const path27 of byPath.keys()) edges.set(path27, []);
13454
+ for (const path26 of byPath.keys()) edges.set(path26, []);
13211
13455
  for (const entry of read.manifest.indexes.imports.byFile) {
13212
13456
  const targets = edges.get(entry.path);
13213
13457
  if (targets === void 0) continue;
@@ -13319,15 +13563,21 @@ var searchTool = {
13319
13563
  if (partPath === null) continue;
13320
13564
  let text2;
13321
13565
  try {
13322
- text2 = fs25.readFileSync(partPath, "utf8");
13566
+ text2 = fs24.readFileSync(partPath, "utf8");
13323
13567
  } catch {
13324
13568
  continue;
13325
13569
  }
13326
- if (Buffer.byteLength(text2, "utf8") > MAX_SEARCH_BYTES) {
13570
+ const partBytes = Buffer.byteLength(text2, "utf8");
13571
+ if (partBytes > MAX_SEARCH_BYTES) {
13327
13572
  skippedOversize.push(part.filename);
13573
+ truncated = true;
13328
13574
  continue;
13329
13575
  }
13330
- scanned += text2.length;
13576
+ if (scanned + partBytes > MAX_SEARCH_BYTES) {
13577
+ truncated = true;
13578
+ break;
13579
+ }
13580
+ scanned += partBytes;
13331
13581
  for (const section of parsePartSections(text2)) {
13332
13582
  if (matches.length >= cap) {
13333
13583
  truncated = true;
@@ -13450,7 +13700,7 @@ var reviewTool = {
13450
13700
  return { text: error.message, isError: true };
13451
13701
  }
13452
13702
  const report2 = auditSnapshot({
13453
- snapshotDir: path26.resolve(workspace.root, workspace.config.outDir),
13703
+ snapshotDir: path25.resolve(workspace.root, workspace.config.outDir),
13454
13704
  repoDir: workspace.root
13455
13705
  });
13456
13706
  const failed = report2.checks.filter((check2) => check2.status === "fail").map((check2) => check2.id + ": " + check2.detail);
@@ -13472,7 +13722,7 @@ var reviewTool = {
13472
13722
  }
13473
13723
  let section = null;
13474
13724
  try {
13475
- section = findSection(parsePartSections(fs25.readFileSync(partPath, "utf8")), file.relativePath);
13725
+ section = findSection(parsePartSections(fs24.readFileSync(partPath, "utf8")), file.relativePath);
13476
13726
  } catch {
13477
13727
  section = null;
13478
13728
  }
@@ -13562,31 +13812,31 @@ var diffContextTool = {
13562
13812
  const changed = [];
13563
13813
  const text2 = [];
13564
13814
  let used = 0;
13565
- for (const path27 of wanted) {
13566
- const file = byPath.get(path27.toLowerCase());
13815
+ for (const path26 of wanted) {
13816
+ const file = byPath.get(path26.toLowerCase());
13567
13817
  if (file === void 0) {
13568
- missing.push(path27);
13818
+ missing.push(path26);
13569
13819
  continue;
13570
13820
  }
13571
13821
  const partPath = partPathFor(workspace, file.part);
13572
13822
  if (partPath === null) {
13573
- missing.push(path27 + " (part missing)");
13823
+ missing.push(path26 + " (part missing)");
13574
13824
  continue;
13575
13825
  }
13576
13826
  let section;
13577
13827
  try {
13578
- section = findSection(parsePartSections(fs25.readFileSync(partPath, "utf8")), file.relativePath);
13828
+ section = findSection(parsePartSections(fs24.readFileSync(partPath, "utf8")), file.relativePath);
13579
13829
  } catch {
13580
13830
  section = null;
13581
13831
  }
13582
13832
  if (section === null) {
13583
- missing.push(path27 + " (section not found)");
13833
+ missing.push(path26 + " (section not found)");
13584
13834
  continue;
13585
13835
  }
13586
13836
  const window = windowText(section.body, 1, linesPerFile);
13587
13837
  const tokens = Math.max(1, Math.ceil(Buffer.byteLength(window.text, "utf8") / 4));
13588
13838
  if (used + tokens > budget) {
13589
- missing.push(path27 + " (budget)");
13839
+ missing.push(path26 + " (budget)");
13590
13840
  continue;
13591
13841
  }
13592
13842
  used += tokens;
@@ -13661,7 +13911,7 @@ var symbolTool = {
13661
13911
  if (partPath === null) continue;
13662
13912
  let partText;
13663
13913
  try {
13664
- partText = fs25.readFileSync(partPath, "utf8");
13914
+ partText = fs24.readFileSync(partPath, "utf8");
13665
13915
  } catch {
13666
13916
  continue;
13667
13917
  }
@@ -13712,7 +13962,7 @@ var symbolTool = {
13712
13962
  }
13713
13963
  let partText;
13714
13964
  try {
13715
- partText = fs25.readFileSync(partPath, "utf8");
13965
+ partText = fs24.readFileSync(partPath, "utf8");
13716
13966
  } catch {
13717
13967
  continue;
13718
13968
  }
@@ -13816,7 +14066,7 @@ var contextTool = {
13816
14066
  }
13817
14067
  if (!sectionsByPart.has(file.part)) {
13818
14068
  try {
13819
- sectionsByPart.set(file.part, parsePartSections(fs25.readFileSync(partPath, "utf8")));
14069
+ sectionsByPart.set(file.part, parsePartSections(fs24.readFileSync(partPath, "utf8")));
13820
14070
  } catch {
13821
14071
  sectionsByPart.set(file.part, null);
13822
14072
  }
@@ -14054,7 +14304,7 @@ var answerTool = {
14054
14304
  let partText = parts.get(partPath);
14055
14305
  if (partText === void 0) {
14056
14306
  try {
14057
- partText = fs25.readFileSync(partPath, "utf8");
14307
+ partText = fs24.readFileSync(partPath, "utf8");
14058
14308
  } catch {
14059
14309
  omitted.push({ path: planned.path, reason: "its part could not be read" });
14060
14310
  continue;
@@ -14151,7 +14401,7 @@ var healthTool = {
14151
14401
  if (!prepared.ok) return prepared.outcome;
14152
14402
  const workspace = prepared.workspace;
14153
14403
  const report2 = auditSnapshot({
14154
- snapshotDir: path26.resolve(workspace.root, workspace.config.outDir),
14404
+ snapshotDir: path25.resolve(workspace.root, workspace.config.outDir),
14155
14405
  repoDir: workspace.root,
14156
14406
  ...typeof args.maxScanBytes === "number" ? { maxScanBytes: args.maxScanBytes } : {},
14157
14407
  ...args.deep === true ? { deep: true } : {}
@@ -14290,7 +14540,12 @@ var planTool = {
14290
14540
  const prepared = await prepare(args, context, workspaceOverrides(args));
14291
14541
  if (!prepared.ok) return prepared.outcome;
14292
14542
  const workspace = prepared.workspace;
14293
- const result = await generateInWorker(workspace.root, workspace.cliOptions, { dryRun: true });
14543
+ const controller = new AbortController();
14544
+ context.onCancel?.(() => controller.abort());
14545
+ const result = await generateInWorker(workspace.root, workspace.cliOptions, {
14546
+ dryRun: true,
14547
+ signal: controller.signal
14548
+ });
14294
14549
  if (!result.ok) return failure(result.message);
14295
14550
  const summary = result.summary;
14296
14551
  const topReasons = summary.skipReasons;
@@ -14435,7 +14690,7 @@ var generateTool = {
14435
14690
  context.notify?.({ message: "writing the snapshot", progress: 2, total: 2 });
14436
14691
  const summary = result.summary;
14437
14692
  forgetManifest(manifestPathFor(workspace));
14438
- const written = relativeFor(workspace, path26.resolve(workspace.root, workspace.config.outDir));
14693
+ const written = relativeFor(workspace, path25.resolve(workspace.root, workspace.config.outDir));
14439
14694
  const lines = [
14440
14695
  `Wrote ${written}/`,
14441
14696
  `Files: ${summary.totalFiles} included, ${summary.skippedCount} skipped, ${plural(summary.partsCount, "part")}`,
@@ -14498,7 +14753,12 @@ function configAsGenerated(workspace, manifest) {
14498
14753
  ...cli.includeLogs !== void 0 || configured("logCount") || recorded?.logCount !== void 0 ? { logCount: choose("logCount", recorded?.logCount, workspace.config.logCount, cli.includeLogs) } : {},
14499
14754
  ...cli.skeleton === true || configured("skeleton") || recorded?.skeleton !== void 0 ? { skeleton: choose("skeleton", recorded?.skeleton, workspace.config.skeleton, cli.skeleton === true ? true : void 0) } : {},
14500
14755
  ...cli.sarif === true || configured("sarif") || recorded?.sarif !== void 0 ? { sarif: choose("sarif", recorded?.sarif, workspace.config.sarif, cli.sarif === true ? true : void 0) } : {},
14501
- ...configured("maxParts") || recorded?.maxParts !== void 0 ? { maxParts: choose("maxParts", recorded?.maxParts, workspace.config.maxParts) } : {}
14756
+ ...configured("maxParts") || recorded?.maxParts !== void 0 ? { maxParts: choose("maxParts", recorded?.maxParts, workspace.config.maxParts) } : {},
14757
+ ...cli.maxPartTokens !== void 0 || configured("maxPartTokens") || recorded?.maxPartTokens !== void 0 ? { maxPartTokens: choose("maxPartTokens", recorded?.maxPartTokens, workspace.config.maxPartTokens, cli.maxPartTokens) } : {},
14758
+ ...cli.changedSince !== void 0 || configured("changedSince") || recorded?.changedSince !== void 0 ? { changedSince: choose("changedSince", recorded?.changedSince, workspace.config.changedSince, cli.changedSince) } : {},
14759
+ ...cli.staged === true || configured("staged") || recorded?.staged !== void 0 ? { staged: choose("staged", recorded?.staged, workspace.config.staged, cli.staged === true ? true : void 0) } : {},
14760
+ ...cli.withDependents === true || configured("withDependents") || recorded?.withDependents !== void 0 ? { withDependents: choose("withDependents", recorded?.withDependents, workspace.config.withDependents, cli.withDependents === true ? true : void 0) } : {},
14761
+ ...configured("promptTask") || recorded?.promptTask !== void 0 ? { promptTask: choose("promptTask", recorded?.promptTask, workspace.config.promptTask) } : {}
14502
14762
  };
14503
14763
  }
14504
14764
  var validateTool = {
@@ -14880,7 +15140,7 @@ var readTool = {
14880
15140
  }
14881
15141
  let partText;
14882
15142
  try {
14883
- partText = fs25.readFileSync(partPath, "utf8");
15143
+ partText = fs24.readFileSync(partPath, "utf8");
14884
15144
  } catch {
14885
15145
  return failure(
14886
15146
  `${entry.part} could not be read, so the snapshot is damaged. Run snapshot_generate to rebuild it.`
@@ -15389,7 +15649,7 @@ var COMMAND_OPTION_SCOPE = {
15389
15649
  "version"
15390
15650
  ],
15391
15651
  diff: ["format", "mode", "no-config", "no-update-check", "help", "version"],
15392
- describe: ["format", "mode", "help", "version"],
15652
+ describe: ["format", "mode", "no-update-check", "help", "version"],
15393
15653
  init: [
15394
15654
  "install-hook",
15395
15655
  "cwd",
@@ -15410,7 +15670,7 @@ var COMMAND_OPTION_SCOPE = {
15410
15670
  "help",
15411
15671
  "version"
15412
15672
  ],
15413
- skill: ["cwd", "format", "mode", "install", "target", "help", "version"],
15673
+ skill: ["cwd", "format", "mode", "install", "target", "no-update-check", "help", "version"],
15414
15674
  // `mcp` reads the repository, so it takes --cwd. It has no --format: stdout carries JSON-RPC
15415
15675
  // messages, and there is no second shape to choose, so offering the flag would be a lie.
15416
15676
  serve: ["port", "host", "token", "no-auth", "allow-private", "cwd", "no-update-check", "help"],
@@ -15469,6 +15729,7 @@ var COMMAND_ORDER = [
15469
15729
  "health",
15470
15730
  "report",
15471
15731
  "explain",
15732
+ "update",
15472
15733
  "init",
15473
15734
  "setup",
15474
15735
  "diff",
@@ -15930,24 +16191,28 @@ function buildAgentContract() {
15930
16191
  {
15931
16192
  flag: "--only",
15932
16193
  type: "string",
16194
+ default: "unset",
15933
16195
  summary: "Comma-separated globs to include: overrides the config include list for this run.",
15934
16196
  appliesTo: optionAppliesTo("only")
15935
16197
  },
15936
16198
  {
15937
16199
  flag: "--ignore",
15938
16200
  type: "string",
16201
+ default: "unset",
15939
16202
  summary: "Comma-separated globs to exclude, added to the config exclude list for this run.",
15940
16203
  appliesTo: optionAppliesTo("ignore")
15941
16204
  },
15942
16205
  {
15943
16206
  flag: "--remove-empty-lines",
15944
16207
  type: "boolean",
16208
+ default: false,
15945
16209
  summary: "Drop blank and whitespace-only lines from emitted bodies; line numbers no longer match the source.",
15946
16210
  appliesTo: optionAppliesTo("remove-empty-lines")
15947
16211
  },
15948
16212
  {
15949
16213
  flag: "--all-members",
15950
16214
  type: "boolean",
16215
+ default: false,
15951
16216
  summary: "Audit every snapshot a --workspace run wrote, not only the one at outDir.",
15952
16217
  appliesTo: optionAppliesTo("all-members")
15953
16218
  },
@@ -16558,7 +16823,7 @@ async function workspaceFor(context) {
16558
16823
  }
16559
16824
  function readFileIfPresent(file) {
16560
16825
  try {
16561
- return fs25.readFileSync(file, "utf8");
16826
+ return fs24.readFileSync(file, "utf8");
16562
16827
  } catch {
16563
16828
  return null;
16564
16829
  }
@@ -16597,9 +16862,9 @@ function buildResourceProvider() {
16597
16862
  }
16598
16863
  ];
16599
16864
  const workspace = await workspaceFor(context);
16600
- const reportsDir = "error" in workspace ? null : path26.resolve(workspace.root, workspace.config.outDir, "reports");
16865
+ const reportsDir = "error" in workspace ? null : path25.resolve(workspace.root, workspace.config.outDir, "reports");
16601
16866
  for (const [uri, report2] of REPORT_URIS) {
16602
- const present = reportsDir !== null && fs25.existsSync(path26.join(reportsDir, report2.file));
16867
+ const present = reportsDir !== null && fs24.existsSync(path25.join(reportsDir, report2.file));
16603
16868
  if (!present) continue;
16604
16869
  resources.push({
16605
16870
  uri,
@@ -16661,7 +16926,7 @@ function buildResourceProvider() {
16661
16926
  }
16662
16927
  const workspace = await workspaceFor(context);
16663
16928
  if ("error" in workspace) return null;
16664
- const snapshotDir = path26.resolve(workspace.root, workspace.config.outDir);
16929
+ const snapshotDir = path25.resolve(workspace.root, workspace.config.outDir);
16665
16930
  if (uri === PROMPT_URI) {
16666
16931
  const read = readConfinedText(snapshotDir, "PROMPT.md");
16667
16932
  if (!read.ok) {
@@ -16678,7 +16943,7 @@ function buildResourceProvider() {
16678
16943
  }
16679
16944
  const report2 = REPORT_URIS.get(uri);
16680
16945
  if (report2) {
16681
- const read = readConfinedText(snapshotDir, path26.posix.join("reports", report2.file));
16946
+ const read = readConfinedText(snapshotDir, path25.posix.join("reports", report2.file));
16682
16947
  if (!read.ok) {
16683
16948
  throw new ResourceNotFoundError(
16684
16949
  uri,
@@ -16694,7 +16959,7 @@ function buildResourceProvider() {
16694
16959
  if (uri === "snapshot://manifest") {
16695
16960
  const read = readManifest3(workspace);
16696
16961
  if (!read.ok) return null;
16697
- const confined = readConfinedText(path26.dirname(read.file), path26.basename(read.file));
16962
+ const confined = readConfinedText(path25.dirname(read.file), path25.basename(read.file));
16698
16963
  if (!confined.ok) return null;
16699
16964
  return {
16700
16965
  uri,
@@ -16713,7 +16978,7 @@ function buildResourceProvider() {
16713
16978
  if (partPath === null) return null;
16714
16979
  let partBytes;
16715
16980
  try {
16716
- partBytes = fs25.statSync(partPath).size;
16981
+ partBytes = fs24.statSync(partPath).size;
16717
16982
  } catch {
16718
16983
  return null;
16719
16984
  }
@@ -16749,52 +17014,52 @@ function validateArguments(schema, value) {
16749
17014
  }
16750
17015
  return problems;
16751
17016
  }
16752
- function checkValue(path27, schema, value) {
17017
+ function checkValue(path26, schema, value) {
16753
17018
  if (schema.enum && !schema.enum.includes(value)) {
16754
- return [`"${path27}" must be one of: ${schema.enum.join(", ")}`];
17019
+ return [`"${path26}" must be one of: ${schema.enum.join(", ")}`];
16755
17020
  }
16756
17021
  switch (schema.type) {
16757
17022
  case "string": {
16758
- if (typeof value !== "string") return [`"${path27}" must be a string`];
17023
+ if (typeof value !== "string") return [`"${path26}" must be a string`];
16759
17024
  const problems = [];
16760
17025
  if (schema.minLength !== void 0 && value.length < schema.minLength) {
16761
- problems.push(`"${path27}" must be at least ${schema.minLength} character(s)`);
17026
+ problems.push(`"${path26}" must be at least ${schema.minLength} character(s)`);
16762
17027
  }
16763
17028
  if (schema.maxLength !== void 0 && value.length > schema.maxLength) {
16764
- problems.push(`"${path27}" must be at most ${schema.maxLength} character(s)`);
17029
+ problems.push(`"${path26}" must be at most ${schema.maxLength} character(s)`);
16765
17030
  }
16766
17031
  return problems;
16767
17032
  }
16768
17033
  case "number":
16769
17034
  case "integer": {
16770
17035
  if (typeof value !== "number" || Number.isNaN(value)) {
16771
- return [`"${path27}" must be a number`];
17036
+ return [`"${path26}" must be a number`];
16772
17037
  }
16773
17038
  if (schema.type === "integer" && !Number.isInteger(value)) {
16774
- return [`"${path27}" must be an integer`];
17039
+ return [`"${path26}" must be an integer`];
16775
17040
  }
16776
17041
  const problems = [];
16777
17042
  if (schema.minimum !== void 0 && value < schema.minimum) {
16778
- problems.push(`"${path27}" must be >= ${schema.minimum}`);
17043
+ problems.push(`"${path26}" must be >= ${schema.minimum}`);
16779
17044
  }
16780
17045
  if (schema.maximum !== void 0 && value > schema.maximum) {
16781
- problems.push(`"${path27}" must be <= ${schema.maximum}`);
17046
+ problems.push(`"${path26}" must be <= ${schema.maximum}`);
16782
17047
  }
16783
17048
  return problems;
16784
17049
  }
16785
17050
  case "boolean":
16786
- return typeof value === "boolean" ? [] : [`"${path27}" must be a boolean`];
17051
+ return typeof value === "boolean" ? [] : [`"${path26}" must be a boolean`];
16787
17052
  case "array": {
16788
- if (!Array.isArray(value)) return [`"${path27}" must be an array`];
17053
+ if (!Array.isArray(value)) return [`"${path26}" must be an array`];
16789
17054
  if (!schema.items) return [];
16790
17055
  const problems = [];
16791
17056
  value.forEach((item, index) => {
16792
- problems.push(...checkValue(`${path27}[${index}]`, schema.items, item));
17057
+ problems.push(...checkValue(`${path26}[${index}]`, schema.items, item));
16793
17058
  });
16794
17059
  return problems;
16795
17060
  }
16796
17061
  case "object":
16797
- return isJsonObject(value) ? [] : [`"${path27}" must be an object`];
17062
+ return isJsonObject(value) ? [] : [`"${path26}" must be an object`];
16798
17063
  default:
16799
17064
  return [];
16800
17065
  }
@@ -17342,10 +17607,22 @@ async function runStdioServer(options) {
17342
17607
  )
17343
17608
  );
17344
17609
  };
17610
+ const isCancellation = (line) => {
17611
+ try {
17612
+ const parsed = JSON.parse(line);
17613
+ return parsed !== null && typeof parsed === "object" && parsed.method === "notifications/cancelled";
17614
+ } catch {
17615
+ return false;
17616
+ }
17617
+ };
17345
17618
  const stopReading = createLineReader(process.stdin, {
17346
17619
  onOverflow: (bytes) => log(`mcp: discarded an oversized message (${bytes} bytes)`),
17347
17620
  onLine: (line) => {
17348
17621
  if (inFlight >= MAX_IN_FLIGHT) {
17622
+ if (isCancellation(line)) {
17623
+ void handleLine(line);
17624
+ return;
17625
+ }
17349
17626
  rejectOverloaded(line);
17350
17627
  return;
17351
17628
  }
@@ -17391,30 +17668,44 @@ function crc32(data) {
17391
17668
  return (crc ^ 4294967295) >>> 0;
17392
17669
  }
17393
17670
  function dosDateTime(date) {
17394
- const year = Math.max(1980, date.getFullYear());
17671
+ const year = Math.max(1980, date.getUTCFullYear());
17395
17672
  return {
17396
- time: date.getHours() << 11 | date.getMinutes() << 5 | Math.floor(date.getSeconds() / 2),
17397
- date: year - 1980 << 9 | date.getMonth() + 1 << 5 | date.getDate()
17673
+ time: date.getUTCHours() << 11 | date.getUTCMinutes() << 5 | Math.floor(date.getUTCSeconds() / 2),
17674
+ date: year - 1980 << 9 | date.getUTCMonth() + 1 << 5 | date.getUTCDate()
17398
17675
  };
17399
17676
  }
17400
17677
  function walkFiles(root, prefix = "") {
17401
17678
  const files = [];
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);
17679
+ const stack = [prefix];
17680
+ while (stack.length > 0) {
17681
+ const current = stack.pop();
17682
+ for (const entry of fs24.readdirSync(path25.join(root, current), { withFileTypes: true })) {
17683
+ const relative15 = current === "" ? entry.name : current + "/" + entry.name;
17684
+ if (entry.isDirectory()) stack.push(relative15);
17685
+ else if (entry.isFile()) files.push(relative15);
17686
+ }
17406
17687
  }
17407
17688
  return files;
17408
17689
  }
17409
17690
  function writeZip(options) {
17410
17691
  const entries = [...options.entries ?? []];
17692
+ const maxTotalBytes = options.maxTotalBytes ?? 256 * 1024 * 1024;
17693
+ let totalBytes = entries.reduce((total, entry) => total + entry.content.length, 0);
17694
+ if (totalBytes > maxTotalBytes) {
17695
+ throw new Error("zip: uncompressed content exceeds " + maxTotalBytes + " bytes");
17696
+ }
17411
17697
  if (options.directory !== void 0) {
17412
17698
  const root = options.directory;
17413
17699
  for (const relative15 of walkFiles(root)) {
17414
17700
  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 });
17701
+ const full = path25.join(root, relative15);
17702
+ const stat = fs24.statSync(full);
17703
+ if (totalBytes + stat.size > maxTotalBytes) {
17704
+ throw new Error("zip: uncompressed content exceeds " + maxTotalBytes + " bytes");
17705
+ }
17706
+ const content = fs24.readFileSync(full);
17707
+ totalBytes += content.length;
17708
+ entries.push({ name: relative15, content, mtime: stat.mtime });
17418
17709
  }
17419
17710
  }
17420
17711
  if (entries.length > 65535) {
@@ -17652,6 +17943,23 @@ async function startWebServer(options) {
17652
17943
  throw new Error("Refusing to serve " + host + " without a token.");
17653
17944
  }
17654
17945
  const createMcp = () => createServer({ cwd: options.cwd, log });
17946
+ const toolCount = buildTools().length;
17947
+ const rateWindows = /* @__PURE__ */ new Map();
17948
+ const rateLimited = (request) => {
17949
+ const remote = request.socket.remoteAddress ?? "unknown";
17950
+ const now = Date.now();
17951
+ const window = rateWindows.get(remote);
17952
+ if (window === void 0 || window.resetAt <= now) {
17953
+ if (!rateWindows.has(remote) && rateWindows.size >= 1024) {
17954
+ for (const [key, value] of rateWindows) if (value.resetAt <= now) rateWindows.delete(key);
17955
+ }
17956
+ rateWindows.set(remote, { count: 1, resetAt: now + 1e4 });
17957
+ return false;
17958
+ }
17959
+ if (window.count >= 120) return true;
17960
+ window.count += 1;
17961
+ return false;
17962
+ };
17655
17963
  const mcpPerSocket = /* @__PURE__ */ new WeakMap();
17656
17964
  const mcpFor = (socket) => {
17657
17965
  let server2 = mcpPerSocket.get(socket);
@@ -17663,43 +17971,44 @@ async function startWebServer(options) {
17663
17971
  };
17664
17972
  const temporaryClones = /* @__PURE__ */ new Set();
17665
17973
  let mcpInFlight = 0;
17666
- const allowedRoots = [path26.resolve(options.cwd)];
17974
+ const allowedRoots = [path25.resolve(options.cwd)];
17667
17975
  const canonical = (candidate) => {
17668
17976
  try {
17669
- return fs25.realpathSync(candidate);
17977
+ return fs24.realpathSync(candidate);
17670
17978
  } catch {
17671
17979
  return null;
17672
17980
  }
17673
17981
  };
17982
+ const fold = (value) => process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
17674
17983
  const inside = (resolved) => allowedRoots.some((root) => {
17675
17984
  const canonicalRoot = canonical(root);
17676
17985
  if (canonicalRoot === null) return false;
17677
- const relative15 = path26.relative(canonicalRoot, resolved);
17678
- return relative15 === "" || !relative15.startsWith(`..${path26.sep}`) && relative15 !== ".." && !path26.isAbsolute(relative15);
17986
+ const relative15 = path25.relative(fold(canonicalRoot), fold(resolved));
17987
+ return relative15 === "" || !relative15.startsWith(`..${path25.sep}`) && relative15 !== ".." && !path25.isAbsolute(relative15);
17679
17988
  });
17680
17989
  const insideAllowedRoots = (candidate) => {
17681
17990
  const resolved = canonical(candidate);
17682
17991
  return resolved === null ? false : inside(resolved);
17683
17992
  };
17684
17993
  const lexicallyInside = (candidate) => {
17685
- const resolved = path26.resolve(candidate);
17994
+ const resolved = fold(path25.resolve(candidate));
17686
17995
  return allowedRoots.some((root) => {
17687
- const prefix = path26.resolve(root) + path26.sep;
17688
- return resolved === path26.resolve(root) || resolved.startsWith(prefix);
17996
+ const resolvedRoot = fold(path25.resolve(root));
17997
+ return resolved === resolvedRoot || resolved.startsWith(resolvedRoot + path25.sep);
17689
17998
  });
17690
17999
  };
17691
18000
  const insideAllowedRootsForWrite = (candidate) => {
17692
- let existing = path26.resolve(candidate);
18001
+ let existing = path25.resolve(candidate);
17693
18002
  const tail = [];
17694
- while (!fs25.existsSync(existing)) {
17695
- tail.unshift(path26.basename(existing));
17696
- const parent = path26.dirname(existing);
18003
+ while (!fs24.existsSync(existing)) {
18004
+ tail.unshift(path25.basename(existing));
18005
+ const parent = path25.dirname(existing);
17697
18006
  if (parent === existing) break;
17698
18007
  existing = parent;
17699
18008
  }
17700
18009
  const resolved = canonical(existing);
17701
18010
  if (resolved === null) return false;
17702
- return inside(tail.length === 0 ? resolved : path26.join(resolved, ...tail));
18011
+ return inside(tail.length === 0 ? resolved : path25.join(resolved, ...tail));
17703
18012
  };
17704
18013
  const authorized = (request) => {
17705
18014
  if (token === null) return true;
@@ -17743,8 +18052,12 @@ async function startWebServer(options) {
17743
18052
  response.end();
17744
18053
  return;
17745
18054
  }
18055
+ if (rateLimited(request)) {
18056
+ send(429, { error: "too many requests" }, { "retry-after": "10" });
18057
+ return;
18058
+ }
17746
18059
  if (request.method === "GET" && request.url === "/healthz") {
17747
- send(200, { ok: true, name: "codebase-snapshot", tools: 12 });
18060
+ send(200, { ok: true, name: "codebase-snapshot", tools: toolCount });
17748
18061
  return;
17749
18062
  }
17750
18063
  if (request.method === "GET" && (request.url === "/" || request.url === "/index.html")) {
@@ -17811,7 +18124,13 @@ async function startWebServer(options) {
17811
18124
  }
17812
18125
  if (answers.length === 0) send(202, "");
17813
18126
  else send(200, Array.isArray(message) ? answers : answers[0]);
17814
- })();
18127
+ })().catch((error) => {
18128
+ log("serve: " + error.message);
18129
+ try {
18130
+ send(500, { error: "internal error" });
18131
+ } catch {
18132
+ }
18133
+ });
17815
18134
  });
17816
18135
  return;
17817
18136
  }
@@ -17887,7 +18206,7 @@ async function startWebServer(options) {
17887
18206
  return;
17888
18207
  }
17889
18208
  } else {
17890
- target = path26.resolve(options.cwd, source);
18209
+ target = path25.resolve(options.cwd, source);
17891
18210
  if (!insideAllowedRoots(target)) {
17892
18211
  send(403, { error: "outside the served directory: " + target });
17893
18212
  return;
@@ -17895,7 +18214,7 @@ async function startWebServer(options) {
17895
18214
  }
17896
18215
  let stat;
17897
18216
  try {
17898
- stat = fs25.statSync(target);
18217
+ stat = fs24.statSync(target);
17899
18218
  } catch {
17900
18219
  send(404, { error: "no such path: " + target });
17901
18220
  return;
@@ -17904,36 +18223,55 @@ async function startWebServer(options) {
17904
18223
  send(400, { error: "not a directory: " + target });
17905
18224
  return;
17906
18225
  }
17907
- const loaded = await loadConfigFileDetailed(target, { allowExecutableConfig: false });
18226
+ const loaded = isRemote ? { config: null, errors: [] } : await loadConfigFileDetailed(target, { allowExecutableConfig: false });
17908
18227
  if (loaded.errors.length > 0) {
17909
18228
  send(400, { error: loaded.errors.join("; ") });
17910
18229
  return;
17911
18230
  }
17912
18231
  const runConfig = isRemote ? {
17913
- ...loaded.config ?? {},
17914
18232
  outDir: "snapshot",
17915
18233
  tmpDir: "snapshot.tmp",
17916
18234
  hooks: {}
17917
18235
  } : loaded.config ?? {};
17918
18236
  const configuredOutDir = typeof runConfig.outDir === "string" && runConfig.outDir.trim() !== "" ? runConfig.outDir : "snapshot";
17919
- const snapshotDir = path26.resolve(target, configuredOutDir);
18237
+ const snapshotDir = path25.resolve(target, configuredOutDir);
17920
18238
  if (!insideAllowedRootsForWrite(snapshotDir)) {
17921
18239
  send(403, { error: "the configured outDir resolves outside the served directory" });
17922
18240
  return;
17923
18241
  }
17924
18242
  const configuredTmpDir = typeof runConfig.tmpDir === "string" && runConfig.tmpDir.trim() !== "" ? runConfig.tmpDir : "snapshot.tmp";
17925
- const stagingDir = path26.resolve(target, configuredTmpDir);
18243
+ const stagingDir = path25.resolve(target, configuredTmpDir);
17926
18244
  if (!insideAllowedRootsForWrite(stagingDir)) {
17927
18245
  send(403, { error: "the configured tmpDir resolves outside the served directory" });
17928
18246
  return;
17929
18247
  }
17930
18248
  const started = Date.now();
17931
18249
  try {
17932
- const manifest = generateSnapshot({ ...runConfig, cwd: target }, {
17933
- ...provenance === void 0 ? {} : { source: provenance },
17934
- ...mode === "slice" ? { slice: { question } } : {},
17935
- ...mode === "budget" && budgetTokens !== void 0 ? { budgetTokens } : {}
17936
- });
18250
+ const generated = await generateInWorker(
18251
+ target,
18252
+ { cwd: target },
18253
+ {
18254
+ config: runConfig,
18255
+ ...provenance === void 0 ? {} : { source: provenance },
18256
+ ...mode === "slice" && question.length >= 3 ? { narrow: { slice: { question } } } : {},
18257
+ ...mode === "budget" && budgetTokens !== void 0 ? { narrow: { budgetTokens } } : {}
18258
+ }
18259
+ );
18260
+ if (!generated.ok) {
18261
+ send(500, { error: generated.message });
18262
+ return;
18263
+ }
18264
+ const manifestRead = readConfinedText(snapshotDir, "manifest.json");
18265
+ if (!manifestRead.ok) {
18266
+ send(500, { error: "the generate worker did not write manifest.json" });
18267
+ return;
18268
+ }
18269
+ const manifest = JSON.parse(manifestRead.text);
18270
+ const shape = describeManifestShapeProblem(manifest);
18271
+ if (shape !== null) {
18272
+ send(500, { error: "the generated manifest is not a snapshot manifest: " + shape });
18273
+ return;
18274
+ }
17937
18275
  const seconds = ((Date.now() - started) / 1e3).toFixed(2);
17938
18276
  const health = auditSnapshot({ snapshotDir, repoDir: target });
17939
18277
  send(200, {
@@ -17956,35 +18294,50 @@ async function startWebServer(options) {
17956
18294
  } catch (error) {
17957
18295
  send(500, { error: error.message });
17958
18296
  }
17959
- })();
18297
+ })().catch((error) => {
18298
+ log("serve: " + error.message);
18299
+ try {
18300
+ send(500, { error: "internal error" });
18301
+ } catch {
18302
+ }
18303
+ });
17960
18304
  });
17961
18305
  return;
17962
18306
  }
17963
18307
  if (request.method === "GET" && request.url?.startsWith("/api/health?") === true) {
17964
- const target = path26.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
18308
+ const target = path25.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
17965
18309
  if (!lexicallyInside(target)) {
17966
18310
  send(403, { error: "outside the served directory: " + target });
17967
18311
  return;
17968
18312
  }
17969
- if (!fs25.existsSync(path26.join(target, "manifest.json"))) {
17970
- send(404, { error: "no manifest.json under " + target });
18313
+ if (!fs24.existsSync(target)) {
18314
+ send(404, { error: "no snapshot directory at " + target });
17971
18315
  return;
17972
18316
  }
17973
18317
  if (!insideAllowedRoots(target)) {
17974
18318
  send(403, { error: "outside the served directory: " + target });
17975
18319
  return;
17976
18320
  }
17977
- const report2 = auditSnapshot({ snapshotDir: target, repoDir: path26.dirname(target) });
18321
+ const repoDir = path25.dirname(target);
18322
+ if (!insideAllowedRoots(repoDir)) {
18323
+ send(403, { error: "the repository root for this snapshot is outside the served directory" });
18324
+ return;
18325
+ }
18326
+ if (!fs24.existsSync(path25.join(target, "manifest.json"))) {
18327
+ send(404, { error: "no manifest.json under " + target });
18328
+ return;
18329
+ }
18330
+ const report2 = auditSnapshot({ snapshotDir: target, repoDir });
17978
18331
  send(200, { score: report2.score, counts: report2.counts, checks: report2.checks });
17979
18332
  return;
17980
18333
  }
17981
18334
  if (request.method === "GET" && (request.url?.startsWith("/api/snapshot?") === true || request.url === "/api/snapshot")) {
17982
- const target = path26.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
18335
+ const target = path25.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
17983
18336
  if (!lexicallyInside(target)) {
17984
18337
  send(403, { error: "outside the served directory: " + target });
17985
18338
  return;
17986
18339
  }
17987
- if (!fs25.existsSync(path26.join(target, "manifest.json"))) {
18340
+ if (!fs24.existsSync(target)) {
17988
18341
  send(404, { error: "no manifest.json under " + target });
17989
18342
  return;
17990
18343
  }
@@ -18027,12 +18380,12 @@ async function startWebServer(options) {
18027
18380
  return;
18028
18381
  }
18029
18382
  if (request.method === "GET" && request.url?.startsWith("/api/snapshot.zip") === true) {
18030
- const target = path26.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
18383
+ const target = path25.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
18031
18384
  if (!lexicallyInside(target)) {
18032
18385
  send(403, { error: "outside the served directory: " + target });
18033
18386
  return;
18034
18387
  }
18035
- if (!fs25.existsSync(path26.join(target, "manifest.json")) && !fs25.existsSync(path26.join(target, ".codebase-snapshot"))) {
18388
+ if (!fs24.existsSync(target)) {
18036
18389
  send(404, { error: "not a snapshot directory: " + target });
18037
18390
  return;
18038
18391
  }
@@ -18040,6 +18393,10 @@ async function startWebServer(options) {
18040
18393
  send(403, { error: "outside the served directory: " + target });
18041
18394
  return;
18042
18395
  }
18396
+ if (!fs24.existsSync(path25.join(target, "manifest.json")) && !fs24.existsSync(path25.join(target, ".codebase-snapshot"))) {
18397
+ send(404, { error: "not a snapshot directory: " + target });
18398
+ return;
18399
+ }
18043
18400
  try {
18044
18401
  const zip = writeZip({ directory: target });
18045
18402
  response.writeHead(200, {
@@ -18075,7 +18432,7 @@ async function startWebServer(options) {
18075
18432
  close: () => new Promise((resolve15) => {
18076
18433
  for (const directory of temporaryClones) {
18077
18434
  try {
18078
- fs25.rmSync(directory, { recursive: true, force: true });
18435
+ fs24.rmSync(directory, { recursive: true, force: true });
18079
18436
  } catch {
18080
18437
  }
18081
18438
  }
@@ -18131,17 +18488,17 @@ function isNewer(candidate, current) {
18131
18488
  }
18132
18489
  function cacheDirectory(env = process.env, platform = process.platform) {
18133
18490
  if (platform === "win32") {
18134
- const base2 = env.LOCALAPPDATA ?? path26.join(os2.homedir(), "AppData", "Local");
18135
- return path26.join(base2, "codebase-snapshot");
18491
+ const base2 = env.LOCALAPPDATA ?? path25.join(os2.homedir(), "AppData", "Local");
18492
+ return path25.join(base2, "codebase-snapshot");
18136
18493
  }
18137
18494
  if (platform === "darwin") {
18138
- return path26.join(os2.homedir(), "Library", "Caches", "codebase-snapshot");
18495
+ return path25.join(os2.homedir(), "Library", "Caches", "codebase-snapshot");
18139
18496
  }
18140
- const base = env.XDG_CACHE_HOME ?? path26.join(os2.homedir(), ".cache");
18141
- return path26.join(base, "codebase-snapshot");
18497
+ const base = env.XDG_CACHE_HOME ?? path25.join(os2.homedir(), ".cache");
18498
+ return path25.join(base, "codebase-snapshot");
18142
18499
  }
18143
18500
  function cacheFilePath(env = process.env) {
18144
- return path26.join(cacheDirectory(env), "update-check.json");
18501
+ return path25.join(cacheDirectory(env), "update-check.json");
18145
18502
  }
18146
18503
  function shouldCheck(argv, env) {
18147
18504
  const disabled = ["1", "true", "yes"].includes(
@@ -18171,7 +18528,7 @@ function shouldCheck(argv, env) {
18171
18528
  function readCache(file) {
18172
18529
  let raw;
18173
18530
  try {
18174
- raw = fs25.readFileSync(file, "utf8");
18531
+ raw = fs24.readFileSync(file, "utf8");
18175
18532
  } catch {
18176
18533
  return null;
18177
18534
  }
@@ -18188,8 +18545,8 @@ function readCache(file) {
18188
18545
  }
18189
18546
  function writeCache(file, entry) {
18190
18547
  try {
18191
- fs25.mkdirSync(path26.dirname(file), { recursive: true });
18192
- fs25.writeFileSync(file, `${JSON.stringify(entry)}
18548
+ fs24.mkdirSync(path25.dirname(file), { recursive: true });
18549
+ fs24.writeFileSync(file, `${JSON.stringify(entry)}
18193
18550
  `, "utf8");
18194
18551
  } catch {
18195
18552
  }
@@ -18497,14 +18854,14 @@ function compareManifests(before, after, secretRules) {
18497
18854
  function loadManifest(target) {
18498
18855
  let isDirectory;
18499
18856
  try {
18500
- isDirectory = fs25.statSync(target).isDirectory();
18857
+ isDirectory = fs24.statSync(target).isDirectory();
18501
18858
  } catch {
18502
18859
  throw new Error(`No snapshot found at ${target}: the path does not exist.`);
18503
18860
  }
18504
- const manifestPath = isDirectory ? path26.join(target, "manifest.json") : target;
18861
+ const manifestPath = isDirectory ? path25.join(target, "manifest.json") : target;
18505
18862
  let raw;
18506
18863
  try {
18507
- raw = fs25.readFileSync(manifestPath, "utf8");
18864
+ raw = fs24.readFileSync(manifestPath, "utf8");
18508
18865
  } catch {
18509
18866
  throw new Error(`Could not read a manifest at ${manifestPath}.`);
18510
18867
  }
@@ -18606,15 +18963,31 @@ function canonicalIgnorePattern(line) {
18606
18963
  function appendGitignoreEntries(cwd, entries) {
18607
18964
  const wanted = [...new Set(entries)].filter((entry) => entry.trim().length > 0);
18608
18965
  if (wanted.length === 0) return { added: [], note: null };
18609
- const ignorePath = path26.join(cwd, ".gitignore");
18966
+ const ignorePath = path25.join(cwd, ".gitignore");
18610
18967
  const manual = `Add ${wanted.map((entry) => `"${entry}"`).join(" and ")} to your .gitignore yourself.`;
18611
18968
  let decoded = { text: "", bom: Buffer.alloc(0), encoding: "utf8" };
18612
18969
  try {
18613
- if (fs25.existsSync(ignorePath)) {
18614
- if (fs25.statSync(ignorePath).isDirectory()) {
18970
+ if (fs24.existsSync(ignorePath)) {
18971
+ const stats = fs24.lstatSync(ignorePath);
18972
+ if (stats.isDirectory()) {
18615
18973
  return { added: [], note: `${ignorePath} is a directory, so it was not updated. ${manual}` };
18616
18974
  }
18617
- const read = decodeGitignore(fs25.readFileSync(ignorePath));
18975
+ if (stats.isSymbolicLink() || !stats.isFile() || stats.nlink > 1) {
18976
+ return {
18977
+ added: [],
18978
+ note: `${ignorePath} is a symbolic link, a hard link, or not a regular file, so it was not updated. ` + manual
18979
+ };
18980
+ }
18981
+ const rootReal = fs24.realpathSync(cwd);
18982
+ const fileReal = fs24.realpathSync(ignorePath);
18983
+ const relative15 = path25.relative(rootReal, fileReal);
18984
+ if (relative15 === ".." || relative15.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative15)) {
18985
+ return {
18986
+ added: [],
18987
+ note: `${ignorePath} resolves outside the repository, so it was not updated. ${manual}`
18988
+ };
18989
+ }
18990
+ const read = decodeGitignore(fs24.readFileSync(ignorePath));
18618
18991
  if (read === null) {
18619
18992
  return {
18620
18993
  added: [],
@@ -18635,18 +19008,25 @@ function appendGitignoreEntries(cwd, entries) {
18635
19008
  if (added.length === 0) return { added: [], note: null };
18636
19009
  const newline = existing.includes("\r\n") ? "\r\n" : "\n";
18637
19010
  const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : newline;
19011
+ const tempPath = `${ignorePath}.${process.pid}.${Date.now()}.tmp`;
18638
19012
  try {
18639
- fs25.writeFileSync(
18640
- ignorePath,
18641
- encodeGitignore(decoded, `${existing}${prefix}${added.join(newline)}${newline}`)
19013
+ fs24.writeFileSync(
19014
+ tempPath,
19015
+ encodeGitignore(decoded, `${existing}${prefix}${added.join(newline)}${newline}`),
19016
+ { flag: "wx" }
18642
19017
  );
19018
+ fs24.renameSync(tempPath, ignorePath);
18643
19019
  } catch (err) {
19020
+ try {
19021
+ fs24.rmSync(tempPath, { force: true });
19022
+ } catch {
19023
+ }
18644
19024
  return { added: [], note: `${err.message}. ${manual}` };
18645
19025
  }
18646
19026
  return { added, note: null };
18647
19027
  }
18648
19028
  function gitignorePath(cwd, filePath) {
18649
- return path26.relative(cwd, filePath).split(path26.sep).join("/");
19029
+ return path25.relative(cwd, filePath).split(path25.sep).join("/");
18650
19030
  }
18651
19031
 
18652
19032
  // src/wizard/brief-template.ts
@@ -19262,7 +19642,7 @@ function parsePackageJson(raw) {
19262
19642
  }
19263
19643
  function readPackageJson(cwd) {
19264
19644
  try {
19265
- return parsePackageJson(fs25.readFileSync(path26.join(cwd, "package.json"), "utf8"));
19645
+ return parsePackageJson(fs24.readFileSync(path25.join(cwd, "package.json"), "utf8"));
19266
19646
  } catch {
19267
19647
  return null;
19268
19648
  }
@@ -19299,7 +19679,7 @@ function artifactAnswers(options) {
19299
19679
  }
19300
19680
  function topLevelDirs(cwd) {
19301
19681
  try {
19302
- return fs25.readdirSync(cwd, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules").map((entry) => entry.name).sort();
19682
+ return fs24.readdirSync(cwd, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules").map((entry) => entry.name).sort();
19303
19683
  } catch {
19304
19684
  return [];
19305
19685
  }
@@ -19314,7 +19694,7 @@ function writeFileOrExplain(target, content) {
19314
19694
  try {
19315
19695
  let stats = null;
19316
19696
  try {
19317
- stats = fs25.lstatSync(target);
19697
+ stats = fs24.lstatSync(target);
19318
19698
  } catch {
19319
19699
  stats = null;
19320
19700
  }
@@ -19329,12 +19709,12 @@ function writeFileOrExplain(target, content) {
19329
19709
  );
19330
19710
  }
19331
19711
  const temporary = `${target}.tmp-${process.pid}-${Date.now()}`;
19332
- fs25.writeFileSync(temporary, content, { encoding: "utf8", flag: "wx" });
19712
+ fs24.writeFileSync(temporary, content, { encoding: "utf8", flag: "wx" });
19333
19713
  try {
19334
- fs25.renameSync(temporary, target);
19714
+ fs24.renameSync(temporary, target);
19335
19715
  } catch (err) {
19336
19716
  try {
19337
- fs25.unlinkSync(temporary);
19717
+ fs24.unlinkSync(temporary);
19338
19718
  } catch {
19339
19719
  }
19340
19720
  throw err;
@@ -19382,19 +19762,19 @@ function serializePackageJson(raw, value) {
19382
19762
  return `${bom}${text2}${raw.endsWith("\n") ? crlf ? "\r\n" : "\n" : ""}`;
19383
19763
  }
19384
19764
  function updatePackageJson(cwd, notes) {
19385
- const packagePath = path26.join(cwd, "package.json");
19765
+ const packagePath = path25.join(cwd, "package.json");
19386
19766
  const unchanged = {
19387
19767
  scripts: [],
19388
19768
  dependency: { name: GENERATOR_NAME, range: null, added: false }
19389
19769
  };
19390
- if (!fs25.existsSync(packagePath)) {
19770
+ if (!fs24.existsSync(packagePath)) {
19391
19771
  notes.push("No package.json found, so npm scripts and the devDependency were not added.");
19392
19772
  return unchanged;
19393
19773
  }
19394
19774
  let raw;
19395
19775
  let parsed;
19396
19776
  try {
19397
- raw = fs25.readFileSync(packagePath, "utf8");
19777
+ raw = fs24.readFileSync(packagePath, "utf8");
19398
19778
  parsed = parsePackageJson(raw);
19399
19779
  } catch {
19400
19780
  notes.push("Could not parse package.json; npm scripts and the devDependency were not added.");
@@ -19469,8 +19849,8 @@ function gitignoreEntriesFor(cwd, outDir, tmpDir) {
19469
19849
  const entries = [];
19470
19850
  for (const directory of [outDir, tmpDir]) {
19471
19851
  if (directory === null) continue;
19472
- const relative15 = path26.relative(cwd, path26.resolve(cwd, directory)).replace(/\\/g, "/");
19473
- if (relative15 === "" || relative15 === "." || relative15.startsWith("..") || path26.isAbsolute(relative15)) {
19852
+ const relative15 = path25.relative(cwd, path25.resolve(cwd, directory)).replace(/\\/g, "/");
19853
+ if (relative15 === "" || relative15 === "." || relative15.startsWith("..") || path25.isAbsolute(relative15)) {
19474
19854
  continue;
19475
19855
  }
19476
19856
  entries.push(`/${relative15}/`);
@@ -19629,7 +20009,14 @@ async function runInit(options) {
19629
20009
  try {
19630
20010
  const raw = await text(io, "Part size (e.g. 150k, 1.5mb, 900000)", {
19631
20011
  defaultValue: currentBudget,
19632
- validate: (value) => parseByteSize(value) === void 0 ? "Not a valid size." : null,
20012
+ validate: (value) => {
20013
+ const parsed = parseByteSize(value);
20014
+ if (parsed === void 0) return "Not a valid size.";
20015
+ if (parsed < MIN_MAX_PART_BYTES) {
20016
+ return `A part budget below ${MIN_MAX_PART_BYTES} bytes cannot hold the truncation notice.`;
20017
+ }
20018
+ return null;
20019
+ },
19633
20020
  allowBack: true
19634
20021
  });
19635
20022
  answers.maxPartBytes = parseByteSize(raw) ?? answers.maxPartBytes;
@@ -19725,7 +20112,7 @@ async function runInit(options) {
19725
20112
  const configText = renderConfig(answers);
19726
20113
  const preferredName = chooseConfigFileName(options.cwd);
19727
20114
  const presentConfigs = CONFIG_CANDIDATES.filter(
19728
- (name) => fs25.existsSync(path26.join(options.cwd, name))
20115
+ (name) => fs24.existsSync(path25.join(options.cwd, name))
19729
20116
  );
19730
20117
  const present = presentConfigs[0] ?? null;
19731
20118
  if (presentConfigs.length > 1) {
@@ -19734,7 +20121,7 @@ async function runInit(options) {
19734
20121
  );
19735
20122
  }
19736
20123
  const configName = present !== null && options.force ? present : preferredName;
19737
- const configPath = path26.join(options.cwd, configName);
20124
+ const configPath = path25.join(options.cwd, configName);
19738
20125
  const reused = present !== null && options.force !== true && options.reuseConfig === true;
19739
20126
  if (reused) notes.push(`Kept the existing ${present} instead of writing a new one.`);
19740
20127
  if (options.dryRun) {
@@ -19751,7 +20138,7 @@ async function runInit(options) {
19751
20138
  dependency: { name: GENERATOR_NAME, range: `^${GENERATOR_VERSION}`, added: false },
19752
20139
  notes,
19753
20140
  outDir: answers.outDir,
19754
- briefPath: path26.join(options.cwd, BRIEF_SCAFFOLD_FILE),
20141
+ briefPath: path25.join(options.cwd, BRIEF_SCAFFOLD_FILE),
19755
20142
  briefWritten: false
19756
20143
  };
19757
20144
  }
@@ -19770,13 +20157,13 @@ async function runInit(options) {
19770
20157
  '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.'
19771
20158
  );
19772
20159
  }
19773
- if (fs25.existsSync(configPath) && !options.force && !reused) {
20160
+ if (fs24.existsSync(configPath) && !options.force && !reused) {
19774
20161
  throw new Error(`${configName} already exists. Re-run with --force to replace it.`);
19775
20162
  }
19776
20163
  if (!reused) writeFileOrExplain(configPath, configText);
19777
- const briefPath = path26.join(options.cwd, BRIEF_SCAFFOLD_FILE);
20164
+ const briefPath = path25.join(options.cwd, BRIEF_SCAFFOLD_FILE);
19778
20165
  let briefWritten = false;
19779
- if (!fs25.existsSync(briefPath)) {
20166
+ if (!fs24.existsSync(briefPath)) {
19780
20167
  writeFileOrExplain(briefPath, BRIEF_SCAFFOLD);
19781
20168
  briefWritten = true;
19782
20169
  }
@@ -19804,9 +20191,9 @@ async function runInit(options) {
19804
20191
  };
19805
20192
  }
19806
20193
  function describeTarget(cwd) {
19807
- const relative15 = path26.relative(process.cwd(), cwd);
20194
+ const relative15 = path25.relative(process.cwd(), cwd);
19808
20195
  if (relative15 === "") return "this directory";
19809
- if (relative15.startsWith("..") || path26.isAbsolute(relative15)) return cwd;
20196
+ if (relative15.startsWith("..") || path25.isAbsolute(relative15)) return cwd;
19810
20197
  return relative15;
19811
20198
  }
19812
20199
  function firstRunMessage(reason, cwd) {
@@ -19830,7 +20217,7 @@ function planFirstRun(facts) {
19830
20217
  var NOT_CONTENT = /* @__PURE__ */ new Set([".git", ".hg", ".svn", ".bzr", ".DS_Store", "Thumbs.db"]);
19831
20218
  function isEffectivelyEmpty(cwd) {
19832
20219
  try {
19833
- return fs25.readdirSync(cwd).every((entry) => NOT_CONTENT.has(entry));
20220
+ return fs24.readdirSync(cwd).every((entry) => NOT_CONTENT.has(entry));
19834
20221
  } catch {
19835
20222
  return false;
19836
20223
  }
@@ -19838,7 +20225,7 @@ function isEffectivelyEmpty(cwd) {
19838
20225
  function hasPriorSnapshot(cwd, outDir) {
19839
20226
  let parsed;
19840
20227
  try {
19841
- parsed = JSON.parse(fs25.readFileSync(path26.join(cwd, outDir, ".codebase-snapshot"), "utf8"));
20228
+ parsed = JSON.parse(fs24.readFileSync(path25.join(cwd, outDir, ".codebase-snapshot"), "utf8"));
19842
20229
  } catch {
19843
20230
  return false;
19844
20231
  }
@@ -19877,7 +20264,7 @@ if [ ! -f "$SNAPSHOT_DIR/manifest.json" ]; then
19877
20264
  exit 1
19878
20265
  fi
19879
20266
 
19880
- if ! npx --no-install ${GENERATOR_NAME} validate >/dev/null 2>&1; then
20267
+ if ! npx --no-install ${GENERATOR_NAME} validate --out-dir "$SNAPSHOT_DIR" >/dev/null 2>&1; then
19881
20268
  echo "${GENERATOR_NAME}: the snapshot is out of date." >&2
19882
20269
  echo " Run \\"npx ${GENERATOR_NAME} generate\\", stage the change, and commit again." >&2
19883
20270
  echo " (npx --no-install is used on purpose: this hook must not install anything)" >&2
@@ -19886,52 +20273,56 @@ fi
19886
20273
  `;
19887
20274
  }
19888
20275
  function gitDirectory(cwd) {
19889
- const dotGit = path26.join(cwd, ".git");
20276
+ const dotGit = path25.join(cwd, ".git");
19890
20277
  let stats;
19891
20278
  try {
19892
- stats = fs25.statSync(dotGit);
20279
+ stats = fs24.statSync(dotGit);
19893
20280
  } catch {
19894
20281
  return null;
19895
20282
  }
19896
20283
  if (stats.isDirectory()) return dotGit;
19897
20284
  if (!stats.isFile()) return null;
19898
20285
  try {
19899
- const contents = fs25.readFileSync(dotGit, "utf8");
20286
+ const contents = fs24.readFileSync(dotGit, "utf8");
19900
20287
  const match = /^gitdir:\s*(.+)$/m.exec(contents);
19901
20288
  if (!match) return null;
19902
20289
  const target = match[1];
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;
20290
+ const resolved = path25.isAbsolute(target.trim()) ? target.trim() : path25.join(cwd, target.trim());
20291
+ const cwdReal = canonicalForWrite(cwd);
20292
+ const resolvedReal = canonicalForWrite(resolved);
20293
+ if (cwdReal === null || resolvedReal === null || !fs24.statSync(resolvedReal).isDirectory()) {
20294
+ return null;
20295
+ }
20296
+ if (isInside4(cwdReal, resolvedReal)) return resolvedReal;
20297
+ return isRegisteredWorktree(path25.resolve(resolved), cwd) ? resolvedReal : null;
19907
20298
  } catch {
19908
20299
  return null;
19909
20300
  }
19910
20301
  }
19911
20302
  function isInside4(parent, child) {
19912
- const relative15 = path26.relative(parent, child);
19913
- return relative15 === "" || !relative15.startsWith("..") && !path26.isAbsolute(relative15);
20303
+ const relative15 = path25.relative(parent, child);
20304
+ return relative15 === "" || !relative15.startsWith("..") && !path25.isAbsolute(relative15);
19914
20305
  }
19915
20306
  function canonicalForWrite(target) {
19916
- let existing = path26.resolve(target);
20307
+ let existing = path25.resolve(target);
19917
20308
  const tail = [];
19918
- while (!fs25.existsSync(existing)) {
19919
- tail.unshift(path26.basename(existing));
19920
- const parent = path26.dirname(existing);
20309
+ while (!fs24.existsSync(existing)) {
20310
+ tail.unshift(path25.basename(existing));
20311
+ const parent = path25.dirname(existing);
19921
20312
  if (parent === existing) break;
19922
20313
  existing = parent;
19923
20314
  }
19924
20315
  try {
19925
- const real = fs25.realpathSync(existing);
19926
- return tail.length === 0 ? real : path26.join(real, ...tail);
20316
+ const real = fs24.realpathSync(existing);
20317
+ return tail.length === 0 ? real : path25.join(real, ...tail);
19927
20318
  } catch {
19928
20319
  return null;
19929
20320
  }
19930
20321
  }
19931
20322
  function isRegisteredWorktree(gitDir, cwd) {
19932
20323
  try {
19933
- const back = fs25.readFileSync(path26.join(gitDir, "gitdir"), "utf8").trim();
19934
- return path26.resolve(gitDir, back) === path26.join(path26.resolve(cwd), ".git");
20324
+ const back = fs24.readFileSync(path25.join(gitDir, "gitdir"), "utf8").trim();
20325
+ return path25.resolve(gitDir, back) === path25.join(path25.resolve(cwd), ".git");
19935
20326
  } catch {
19936
20327
  return false;
19937
20328
  }
@@ -19952,9 +20343,9 @@ function gitOutput(cwd, args) {
19952
20343
  function configuredHooksDirectory(cwd) {
19953
20344
  const hooks = gitOutput(cwd, ["rev-parse", "--git-path", "hooks"]);
19954
20345
  if (hooks === null) return null;
19955
- const resolved = path26.resolve(cwd, hooks);
20346
+ const resolved = path25.resolve(cwd, hooks);
19956
20347
  const common = gitOutput(cwd, ["rev-parse", "--git-common-dir"]);
19957
- const commonDir = common === null ? null : canonicalForWrite(path26.resolve(cwd, common));
20348
+ const commonDir = common === null ? null : canonicalForWrite(path25.resolve(cwd, common));
19958
20349
  const cwdReal = canonicalForWrite(cwd);
19959
20350
  const hooksReal = canonicalForWrite(resolved);
19960
20351
  if (hooksReal === null || cwdReal === null) {
@@ -19983,10 +20374,18 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
19983
20374
  ]
19984
20375
  };
19985
20376
  }
19986
- const hooksDir = configured === null ? path26.join(gitDir, "hooks") : configured.dir;
19987
- const hookPath = path26.join(hooksDir, "pre-commit");
20377
+ const hooksDirRaw = configured === null ? path25.join(gitDir, "hooks") : configured.dir;
20378
+ const hooksDir = canonicalForWrite(hooksDirRaw);
20379
+ if (hooksDir === null) {
20380
+ return {
20381
+ path: null,
20382
+ written: false,
20383
+ notes: [`Refusing to write the hooks directory: ${hooksDirRaw} could not be resolved.`]
20384
+ };
20385
+ }
20386
+ const hookPath = path25.join(hooksDir, "pre-commit");
19988
20387
  try {
19989
- const existingStats = fs25.lstatSync(hookPath);
20388
+ const existingStats = fs24.lstatSync(hookPath);
19990
20389
  if (existingStats.isSymbolicLink()) {
19991
20390
  return {
19992
20391
  path: hookPath,
@@ -20018,7 +20417,7 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
20018
20417
  }
20019
20418
  }
20020
20419
  try {
20021
- fs25.mkdirSync(hooksDir, { recursive: true });
20420
+ fs24.mkdirSync(hooksDir, { recursive: true });
20022
20421
  } catch (err) {
20023
20422
  return {
20024
20423
  path: hookPath,
@@ -20028,7 +20427,7 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
20028
20427
  }
20029
20428
  let existing = null;
20030
20429
  try {
20031
- existing = fs25.readFileSync(hookPath, "utf8");
20430
+ existing = fs24.readFileSync(hookPath, "utf8");
20032
20431
  } catch {
20033
20432
  existing = null;
20034
20433
  }
@@ -20043,8 +20442,8 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
20043
20442
  };
20044
20443
  }
20045
20444
  try {
20046
- fs25.writeFileSync(hookPath, hookScript(outDir), "utf8");
20047
- fs25.chmodSync(hookPath, 493);
20445
+ fs24.writeFileSync(hookPath, hookScript(outDir), "utf8");
20446
+ fs24.chmodSync(hookPath, 493);
20048
20447
  } catch (err) {
20049
20448
  return {
20050
20449
  path: hookPath,
@@ -20066,23 +20465,23 @@ var SUMMARY_MAX_SOURCE_BYTES2 = SUMMARY_MAX_SOURCE_BYTES;
20066
20465
  var FILE_DERIVATIONS = /* @__PURE__ */ new Map();
20067
20466
  var FILE_DERIVATION_LIMIT_BYTES = 64 * 1024 * 1024;
20068
20467
  var fileDerivationBytes = 0;
20069
- function takeDerivation(path27, hash, settings) {
20070
- const cached = FILE_DERIVATIONS.get(path27);
20468
+ function takeDerivation(path26, relativePath, hash, settings) {
20469
+ const key = path26 + "\0" + relativePath;
20470
+ const cached = FILE_DERIVATIONS.get(key);
20071
20471
  if (cached === void 0 || cached.hash !== hash || cached.settings !== settings) return void 0;
20072
- FILE_DERIVATIONS.delete(path27);
20073
- FILE_DERIVATIONS.set(path27, cached);
20472
+ FILE_DERIVATIONS.delete(key);
20473
+ FILE_DERIVATIONS.set(key, cached);
20074
20474
  return cached;
20075
20475
  }
20076
- function rememberDerivation(path27, hash, settings, derivation) {
20476
+ function rememberDerivation(path26, relativePath, hash, settings, derivation) {
20477
+ const key = path26 + "\0" + relativePath;
20077
20478
  const bodyBytes = derivation.finalContent === derivation.redacted ? derivation.redacted.length : derivation.redacted.length + derivation.finalContent.length;
20078
20479
  const bytes = bodyBytes * 2 + 512;
20079
20480
  if (bytes > FILE_DERIVATION_LIMIT_BYTES / 4) return;
20080
- const previous = FILE_DERIVATIONS.get(path27);
20481
+ const previous = FILE_DERIVATIONS.get(key);
20081
20482
  if (previous !== void 0) {
20082
- FILE_DERIVATIONS.delete(path27);
20483
+ FILE_DERIVATIONS.delete(key);
20083
20484
  fileDerivationBytes -= previous.bytes;
20084
- } else {
20085
- FILE_DERIVATIONS.delete(path27);
20086
20485
  }
20087
20486
  while (fileDerivationBytes + bytes > FILE_DERIVATION_LIMIT_BYTES) {
20088
20487
  const oldest = FILE_DERIVATIONS.keys().next();
@@ -20091,7 +20490,7 @@ function rememberDerivation(path27, hash, settings, derivation) {
20091
20490
  FILE_DERIVATIONS.delete(oldest.value);
20092
20491
  if (evicted !== void 0) fileDerivationBytes -= evicted.bytes;
20093
20492
  }
20094
- FILE_DERIVATIONS.set(path27, { ...derivation, hash, settings, bytes });
20493
+ FILE_DERIVATIONS.set(key, { ...derivation, hash, settings, bytes });
20095
20494
  fileDerivationBytes += bytes;
20096
20495
  }
20097
20496
  function derivationSettings(config) {
@@ -20347,6 +20746,11 @@ function verifyInMemory(files, parts, unaccounted) {
20347
20746
  }
20348
20747
  }
20349
20748
  for (const part of parts) {
20749
+ if (part.metadata.hardClipped === true) {
20750
+ errors.push(
20751
+ `${part.filename} was hard-clipped by the part budget; its manifest entries cannot describe the surviving sections. Increase the budget or split the file instead of shipping a lie.`
20752
+ );
20753
+ }
20350
20754
  if (sha256Hex2(part.markdown) !== part.metadata.sha256) {
20351
20755
  errors.push(`${part.filename} content does not match its recorded sha256.`);
20352
20756
  }
@@ -20371,11 +20775,16 @@ function verifyInMemory(files, parts, unaccounted) {
20371
20775
  return errors;
20372
20776
  }
20373
20777
  function resolveSafeOutputDirs(config) {
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}`);
20778
+ const cwd = path25.resolve(config.cwd);
20779
+ const outDir = path25.resolve(cwd, config.outDir);
20780
+ const tmpDir = path25.resolve(cwd, config.tmpDir);
20781
+ const root = path25.parse(cwd).root;
20782
+ const fold = (value) => process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
20783
+ const contains = (parent, child) => {
20784
+ const foldedParent = fold(parent);
20785
+ const foldedChild = fold(child);
20786
+ return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path25.sep}`);
20787
+ };
20379
20788
  const reject = (reason) => {
20380
20789
  throw new Error(
20381
20790
  `Refusing to generate: ${reason}. outDir=${outDir} tmpDir=${tmpDir} cwd=${cwd}`
@@ -20464,14 +20873,14 @@ function listEntries(dir) {
20464
20873
  const walk2 = (absolute, prefix) => {
20465
20874
  let children;
20466
20875
  try {
20467
- children = fs25.readdirSync(absolute, { withFileTypes: true });
20876
+ children = fs24.readdirSync(absolute, { withFileTypes: true });
20468
20877
  } catch {
20469
20878
  return;
20470
20879
  }
20471
20880
  for (const child of children) {
20472
20881
  const relative15 = prefix === "" ? child.name : `${prefix}/${child.name}`;
20473
20882
  entries.push(relative15);
20474
- if (child.isDirectory()) walk2(path26.join(absolute, child.name), relative15);
20883
+ if (child.isDirectory()) walk2(path25.join(absolute, child.name), relative15);
20475
20884
  }
20476
20885
  };
20477
20886
  walk2(dir, "");
@@ -20483,10 +20892,10 @@ function markerInventory(dir, written) {
20483
20892
  for (const entry of entries) {
20484
20893
  if (entry === OWNERSHIP_MARKER) continue;
20485
20894
  if (isIgnorableEntry(entry)) continue;
20486
- const full = path26.join(dir, ...entry.split("/"));
20895
+ const full = path25.join(dir, ...entry.split("/"));
20487
20896
  let stats;
20488
20897
  try {
20489
- stats = fs25.lstatSync(full);
20898
+ stats = fs24.lstatSync(full);
20490
20899
  } catch {
20491
20900
  continue;
20492
20901
  }
@@ -20498,7 +20907,7 @@ function markerInventory(dir, written) {
20498
20907
  }
20499
20908
  let digest;
20500
20909
  try {
20501
- digest = sha256Hex2(fs25.readFileSync(full));
20910
+ digest = sha256Hex2(fs24.readFileSync(full));
20502
20911
  } catch {
20503
20912
  continue;
20504
20913
  }
@@ -20520,15 +20929,15 @@ function markerPayload(dir, state, id, createdAt, written, runId) {
20520
20929
  entries,
20521
20930
  files
20522
20931
  };
20523
- const manifestPath = path26.join(dir, "manifest.json");
20524
- if (fs25.existsSync(manifestPath)) {
20525
- marker2.manifestSha256 = sha256Hex2(fs25.readFileSync(manifestPath));
20932
+ const manifestPath = path25.join(dir, "manifest.json");
20933
+ if (fs24.existsSync(manifestPath)) {
20934
+ marker2.manifestSha256 = sha256Hex2(fs24.readFileSync(manifestPath));
20526
20935
  }
20527
20936
  return marker2;
20528
20937
  }
20529
20938
  function writeOwnershipMarker(dir, marker2) {
20530
- fs25.writeFileSync(
20531
- path26.join(dir, OWNERSHIP_MARKER),
20939
+ fs24.writeFileSync(
20940
+ path25.join(dir, OWNERSHIP_MARKER),
20532
20941
  `${JSON.stringify(marker2, null, 2)}
20533
20942
  `,
20534
20943
  "utf8"
@@ -20540,13 +20949,13 @@ function markerBelongsTo(dir, id) {
20540
20949
  return evidence.marker.id === id;
20541
20950
  }
20542
20951
  function readOwnershipMarker(dir) {
20543
- const markerPath = path26.join(dir, OWNERSHIP_MARKER);
20544
- if (!fs25.existsSync(markerPath)) {
20952
+ const markerPath = path25.join(dir, OWNERSHIP_MARKER);
20953
+ if (!fs24.existsSync(markerPath)) {
20545
20954
  return { marker: null, problem: "it holds no .codebase-snapshot marker" };
20546
20955
  }
20547
20956
  let raw;
20548
20957
  try {
20549
- raw = fs25.readFileSync(markerPath, "utf8");
20958
+ raw = fs24.readFileSync(markerPath, "utf8");
20550
20959
  } catch {
20551
20960
  return { marker: null, problem: "its .codebase-snapshot marker could not be read" };
20552
20961
  }
@@ -20647,10 +21056,10 @@ function verifyMarkerInventory(dir, entries, files) {
20647
21056
  for (const entry of entries) {
20648
21057
  if (entry === OWNERSHIP_MARKER) continue;
20649
21058
  if (IGNORABLE_ENTRIES.has(entry.slice(entry.lastIndexOf("/") + 1))) continue;
20650
- const full = path26.join(dir, ...entry.split("/"));
21059
+ const full = path25.join(dir, ...entry.split("/"));
20651
21060
  let stats;
20652
21061
  try {
20653
- stats = fs25.lstatSync(full);
21062
+ stats = fs24.lstatSync(full);
20654
21063
  } catch {
20655
21064
  return `its .codebase-snapshot inventory lists ${entry}, which cannot be read`;
20656
21065
  }
@@ -20675,7 +21084,7 @@ function verifyMarkerInventory(dir, entries, files) {
20675
21084
  }
20676
21085
  let digest;
20677
21086
  try {
20678
- digest = sha256Hex2(fs25.readFileSync(full));
21087
+ digest = sha256Hex2(fs24.readFileSync(full));
20679
21088
  } catch {
20680
21089
  return `its .codebase-snapshot inventory cannot verify ${entry}: the file could not be read`;
20681
21090
  }
@@ -20696,12 +21105,12 @@ function assessSnapshotDirectory(dir) {
20696
21105
  marker: marker2
20697
21106
  };
20698
21107
  }
20699
- const manifestPath = path26.join(dir, "manifest.json");
20700
- const hasManifest = fs25.existsSync(manifestPath);
21108
+ const manifestPath = path25.join(dir, "manifest.json");
21109
+ const hasManifest = fs24.existsSync(manifestPath);
20701
21110
  if (hasManifest) {
20702
21111
  let raw;
20703
21112
  try {
20704
- raw = fs25.readFileSync(manifestPath, "utf8");
21113
+ raw = fs24.readFileSync(manifestPath, "utf8");
20705
21114
  } catch {
20706
21115
  return {
20707
21116
  owned: false,
@@ -20802,13 +21211,13 @@ function containsNoFiles(dir) {
20802
21211
  const current = pending.pop();
20803
21212
  let entries;
20804
21213
  try {
20805
- entries = fs25.readdirSync(current, { withFileTypes: true });
21214
+ entries = fs24.readdirSync(current, { withFileTypes: true });
20806
21215
  } catch {
20807
21216
  return false;
20808
21217
  }
20809
21218
  for (const entry of entries) {
20810
21219
  if (entry.isDirectory()) {
20811
- pending.push(path26.join(current, entry.name));
21220
+ pending.push(path25.join(current, entry.name));
20812
21221
  } else if (!IGNORABLE_ENTRIES.has(entry.name)) {
20813
21222
  return false;
20814
21223
  }
@@ -20817,13 +21226,13 @@ function containsNoFiles(dir) {
20817
21226
  return true;
20818
21227
  }
20819
21228
  function assertReplaceable(target, label, secretRules) {
20820
- if (!fs25.existsSync(target)) return;
20821
- if (!fs25.statSync(target).isDirectory()) {
21229
+ if (!fs24.existsSync(target)) return;
21230
+ if (!fs24.statSync(target).isDirectory()) {
20822
21231
  throw new Error(
20823
21232
  `Refusing to write into ${label} ${target}: it exists but is not a directory.`
20824
21233
  );
20825
21234
  }
20826
- const entries = fs25.readdirSync(target);
21235
+ const entries = fs24.readdirSync(target);
20827
21236
  if (entries.length === 0) return;
20828
21237
  if (entries.every((name) => IGNORABLE_ENTRIES.has(name))) return;
20829
21238
  if (containsNoFiles(target)) return;
@@ -20843,18 +21252,18 @@ function assertReplaceable(target, label, secretRules) {
20843
21252
  );
20844
21253
  }
20845
21254
  function assertStagingRootUsable(tmpDir, secretRules) {
20846
- if (!fs25.existsSync(tmpDir)) return;
20847
- if (!fs25.statSync(tmpDir).isDirectory()) {
21255
+ if (!fs24.existsSync(tmpDir)) return;
21256
+ if (!fs24.statSync(tmpDir).isDirectory()) {
20848
21257
  throw new Error(`Refusing to write into tmpDir ${tmpDir}: it exists but is not a directory.`);
20849
21258
  }
20850
- const entries = fs25.readdirSync(tmpDir);
21259
+ const entries = fs24.readdirSync(tmpDir);
20851
21260
  if (entries.length === 0) return;
20852
21261
  const foreign = entries.filter((name) => {
20853
- const full = path26.join(tmpDir, name);
21262
+ const full = path25.join(tmpDir, name);
20854
21263
  if (!name.startsWith(RUN_DIR_PREFIX)) return true;
20855
21264
  let stats;
20856
21265
  try {
20857
- stats = fs25.statSync(full);
21266
+ stats = fs24.statSync(full);
20858
21267
  } catch {
20859
21268
  return true;
20860
21269
  }
@@ -20862,7 +21271,7 @@ function assertStagingRootUsable(tmpDir, secretRules) {
20862
21271
  const { marker: marker2 } = readOwnershipMarker(full);
20863
21272
  if (marker2) return false;
20864
21273
  try {
20865
- return fs25.readdirSync(full).length > 0;
21274
+ return fs24.readdirSync(full).length > 0;
20866
21275
  } catch {
20867
21276
  return true;
20868
21277
  }
@@ -20877,13 +21286,13 @@ function assertStagingRootUsable(tmpDir, secretRules) {
20877
21286
  function cleanStaleRunDirs(tmpDir) {
20878
21287
  let entries;
20879
21288
  try {
20880
- entries = fs25.readdirSync(tmpDir);
21289
+ entries = fs24.readdirSync(tmpDir);
20881
21290
  } catch {
20882
21291
  return;
20883
21292
  }
20884
21293
  for (const name of entries) {
20885
21294
  if (!name.startsWith(RUN_DIR_PREFIX)) continue;
20886
- const full = path26.join(tmpDir, name);
21295
+ const full = path25.join(tmpDir, name);
20887
21296
  const { marker: marker2 } = readOwnershipMarker(full);
20888
21297
  if (marker2) {
20889
21298
  const created = Date.parse(marker2.createdAt);
@@ -20891,33 +21300,33 @@ function cleanStaleRunDirs(tmpDir) {
20891
21300
  const abandoned = typeof marker2.pid === "number" && !isProcessAlive(marker2.pid);
20892
21301
  if (aged || abandoned) {
20893
21302
  try {
20894
- fs25.rmSync(full, { recursive: true, force: true });
21303
+ fs24.rmSync(full, { recursive: true, force: true });
20895
21304
  } catch {
20896
21305
  }
20897
21306
  }
20898
21307
  continue;
20899
21308
  }
20900
21309
  try {
20901
- if (fs25.readdirSync(full).length === 0) fs25.rmSync(full, { recursive: true, force: true });
21310
+ if (fs24.readdirSync(full).length === 0) fs24.rmSync(full, { recursive: true, force: true });
20902
21311
  } catch {
20903
21312
  }
20904
21313
  }
20905
21314
  }
20906
21315
  function removeIfEmpty(dir) {
20907
21316
  try {
20908
- if (fs25.readdirSync(dir).length === 0) fs25.rmSync(dir, { recursive: true, force: true });
21317
+ if (fs24.readdirSync(dir).length === 0) fs24.rmSync(dir, { recursive: true, force: true });
20909
21318
  } catch {
20910
21319
  }
20911
21320
  }
20912
21321
  function ensureParentDirectory(target, label) {
20913
- const parent = path26.dirname(target);
20914
- if (fs25.existsSync(parent) && !fs25.statSync(parent).isDirectory()) {
21322
+ const parent = path25.dirname(target);
21323
+ if (fs24.existsSync(parent) && !fs24.statSync(parent).isDirectory()) {
20915
21324
  throw new Error(
20916
21325
  `Refusing to create ${label} ${target}: ${parent} exists but is not a directory.`
20917
21326
  );
20918
21327
  }
20919
21328
  try {
20920
- fs25.mkdirSync(parent, { recursive: true });
21329
+ fs24.mkdirSync(parent, { recursive: true });
20921
21330
  } catch (err) {
20922
21331
  throw new Error(
20923
21332
  `Refusing to create ${label} ${target}: its parent ${parent} could not be created (${err.message}).`
@@ -20976,17 +21385,17 @@ function acquireRunLock(stagingRoot, runId) {
20976
21385
  `;
20977
21386
  for (let attempt = 0; attempt < 2; attempt += 1) {
20978
21387
  try {
20979
- const handle = fs25.openSync(lockPath, "wx");
21388
+ const handle = fs24.openSync(lockPath, "wx");
20980
21389
  try {
20981
- fs25.writeSync(handle, payload);
21390
+ fs24.writeSync(handle, payload);
20982
21391
  } finally {
20983
- fs25.closeSync(handle);
21392
+ fs24.closeSync(handle);
20984
21393
  }
20985
21394
  const stopHeartbeat = startLockHeartbeat(lockPath);
20986
21395
  return () => {
20987
21396
  stopHeartbeat();
20988
21397
  try {
20989
- fs25.rmSync(lockPath, { force: true });
21398
+ fs24.rmSync(lockPath, { force: true });
20990
21399
  } catch {
20991
21400
  }
20992
21401
  };
@@ -21006,45 +21415,45 @@ function lockKeyFor(stagingRoot) {
21006
21415
  return sha256Hex2(key).slice(0, 16);
21007
21416
  }
21008
21417
  function canonicalLockTarget(targetPath) {
21009
- const resolved = path26.resolve(targetPath);
21418
+ const resolved = path25.resolve(targetPath);
21010
21419
  let existing = resolved;
21011
21420
  const tail = [];
21012
21421
  for (; ; ) {
21013
21422
  try {
21014
- return path26.join(fs25.realpathSync(existing), ...tail);
21423
+ return path25.join(fs24.realpathSync(existing), ...tail);
21015
21424
  } catch {
21016
- const parent = path26.dirname(existing);
21425
+ const parent = path25.dirname(existing);
21017
21426
  if (parent === existing) return resolved;
21018
- tail.unshift(path26.basename(existing));
21427
+ tail.unshift(path25.basename(existing));
21019
21428
  existing = parent;
21020
21429
  }
21021
21430
  }
21022
21431
  }
21023
21432
  function lockPathFor(stagingRoot) {
21024
- return path26.join(os2.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
21433
+ return path25.join(os2.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
21025
21434
  }
21026
21435
  function releaseAbandonedRun(stagingRoots, runId) {
21027
21436
  if (runId.length === 0) return;
21028
21437
  for (const root of new Set(stagingRoots)) {
21029
21438
  const lockPath = lockPathFor(root);
21030
21439
  try {
21031
- const payload = JSON.parse(fs25.readFileSync(lockPath, "utf8"));
21032
- if (payload.runId === runId) fs25.rmSync(lockPath, { force: true });
21440
+ const payload = JSON.parse(fs24.readFileSync(lockPath, "utf8"));
21441
+ if (payload.runId === runId) fs24.rmSync(lockPath, { force: true });
21033
21442
  } catch {
21034
21443
  }
21035
21444
  let entries;
21036
21445
  try {
21037
- entries = fs25.readdirSync(root);
21446
+ entries = fs24.readdirSync(root);
21038
21447
  } catch {
21039
21448
  continue;
21040
21449
  }
21041
21450
  for (const name of entries) {
21042
21451
  if (!name.startsWith(RUN_DIR_PREFIX)) continue;
21043
- const directory = path26.join(root, name);
21452
+ const directory = path25.join(root, name);
21044
21453
  const { marker: marker2 } = readOwnershipMarker(directory);
21045
21454
  if (marker2?.runId !== runId) continue;
21046
21455
  try {
21047
- fs25.rmSync(directory, { recursive: true, force: true });
21456
+ fs24.rmSync(directory, { recursive: true, force: true });
21048
21457
  } catch {
21049
21458
  }
21050
21459
  }
@@ -21052,7 +21461,7 @@ function releaseAbandonedRun(stagingRoots, runId) {
21052
21461
  }
21053
21462
  function lockHeartbeatAgeMs(lockPath) {
21054
21463
  try {
21055
- return Date.now() - fs25.statSync(lockPath).mtimeMs;
21464
+ return Date.now() - fs24.statSync(lockPath).mtimeMs;
21056
21465
  } catch {
21057
21466
  return Number.POSITIVE_INFINITY;
21058
21467
  }
@@ -21060,7 +21469,7 @@ function lockHeartbeatAgeMs(lockPath) {
21060
21469
  function lockOwnerIsGone(lockPath) {
21061
21470
  let raw;
21062
21471
  try {
21063
- raw = fs25.readFileSync(lockPath, "utf8");
21472
+ raw = fs24.readFileSync(lockPath, "utf8");
21064
21473
  } catch {
21065
21474
  return false;
21066
21475
  }
@@ -21084,16 +21493,16 @@ function lockOwnerIsGone(lockPath) {
21084
21493
  function reclaimStaleLock(lockPath) {
21085
21494
  let before;
21086
21495
  try {
21087
- before = fs25.statSync(lockPath);
21496
+ before = fs24.statSync(lockPath);
21088
21497
  } catch {
21089
21498
  return true;
21090
21499
  }
21091
21500
  if (!lockOwnerIsGone(lockPath)) return false;
21092
21501
  try {
21093
- const current = fs25.statSync(lockPath);
21502
+ const current = fs24.statSync(lockPath);
21094
21503
  const sameFile = current.ino === before.ino && current.birthtimeMs === before.birthtimeMs && current.mtimeMs === before.mtimeMs;
21095
21504
  if (!sameFile) return false;
21096
- fs25.rmSync(lockPath, { force: true });
21505
+ fs24.rmSync(lockPath, { force: true });
21097
21506
  return true;
21098
21507
  } catch {
21099
21508
  return false;
@@ -21104,12 +21513,12 @@ function lockFileIsAncient(lockPath, thresholdMs = LOCK_STALE_HEARTBEAT_MS) {
21104
21513
  }
21105
21514
  function writeManifestAtomically(manifestPath, manifest) {
21106
21515
  const tempPath = `${manifestPath}.${process.pid}.tmp`;
21107
- fs25.writeFileSync(tempPath, JSON.stringify(manifest, null, 2), "utf8");
21516
+ fs24.writeFileSync(tempPath, JSON.stringify(manifest, null, 2), "utf8");
21108
21517
  try {
21109
- fs25.renameSync(tempPath, manifestPath);
21518
+ fs24.renameSync(tempPath, manifestPath);
21110
21519
  } catch (err) {
21111
21520
  try {
21112
- fs25.rmSync(tempPath, { force: true });
21521
+ fs24.rmSync(tempPath, { force: true });
21113
21522
  } catch {
21114
21523
  }
21115
21524
  throw err;
@@ -21134,21 +21543,21 @@ function swapIntoPlace(stagingDir, outDir, beforeSwap, onStagingPreserved) {
21134
21543
  }
21135
21544
  }
21136
21545
  function recoverInterruptedPublish(outDir) {
21137
- if (fs25.existsSync(outDir)) return;
21138
- const parent = path26.dirname(outDir);
21139
- const base = path26.basename(outDir);
21546
+ if (fs24.existsSync(outDir)) return;
21547
+ const parent = path25.dirname(outDir);
21548
+ const base = path25.basename(outDir);
21140
21549
  let backups;
21141
21550
  try {
21142
- backups = fs25.readdirSync(parent).filter((name) => name.startsWith(`${base}.backup-`));
21551
+ backups = fs24.readdirSync(parent).filter((name) => name.startsWith(`${base}.backup-`));
21143
21552
  } catch {
21144
21553
  return;
21145
21554
  }
21146
21555
  if (backups.length !== 1) return;
21147
- const backupDir = path26.join(parent, backups[0]);
21556
+ const backupDir = path25.join(parent, backups[0]);
21148
21557
  const { marker: marker2, problem } = readOwnershipMarker(backupDir);
21149
21558
  if (problem !== null || marker2 === null || marker2.state !== "complete") return;
21150
21559
  try {
21151
- fs25.renameSync(backupDir, outDir);
21560
+ fs24.renameSync(backupDir, outDir);
21152
21561
  process.stderr.write(
21153
21562
  `\u26A0 Recovered ${outDir} from ${backupDir}, left by an interrupted run. That snapshot is the one from before the interrupted run.
21154
21563
  `
@@ -21158,17 +21567,17 @@ function recoverInterruptedPublish(outDir) {
21158
21567
  }
21159
21568
  function swapOnce(stagingDir, outDir, beforeSwap, onStagingPreserved) {
21160
21569
  const backupDir = `${outDir}.backup-${process.pid}-${Date.now()}`;
21161
- const hadPrevious = fs25.existsSync(outDir);
21570
+ const hadPrevious = fs24.existsSync(outDir);
21162
21571
  if (hadPrevious) beforeSwap?.();
21163
21572
  let movedAside = false;
21164
21573
  if (hadPrevious) {
21165
21574
  try {
21166
- fs25.renameSync(outDir, backupDir);
21575
+ fs24.renameSync(outDir, backupDir);
21167
21576
  movedAside = true;
21168
21577
  } catch (err) {
21169
21578
  if (!isLockError(err)) throw err;
21170
21579
  onStagingPreserved?.();
21171
- fs25.rmSync(outDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
21580
+ fs24.rmSync(outDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
21172
21581
  process.stderr.write(
21173
21582
  `\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.
21174
21583
  `
@@ -21177,26 +21586,26 @@ function swapOnce(stagingDir, outDir, beforeSwap, onStagingPreserved) {
21177
21586
  }
21178
21587
  try {
21179
21588
  try {
21180
- fs25.renameSync(stagingDir, outDir);
21589
+ fs24.renameSync(stagingDir, outDir);
21181
21590
  } catch (err) {
21182
21591
  if (err.code !== "EXDEV") throw err;
21183
21592
  const partialDir = `${outDir}.partial-${process.pid}-${Date.now()}`;
21184
21593
  try {
21185
- fs25.cpSync(stagingDir, partialDir, { recursive: true });
21186
- fs25.renameSync(partialDir, outDir);
21187
- fs25.rmSync(stagingDir, { recursive: true, force: true });
21594
+ fs24.cpSync(stagingDir, partialDir, { recursive: true });
21595
+ fs24.renameSync(partialDir, outDir);
21596
+ fs24.rmSync(stagingDir, { recursive: true, force: true });
21188
21597
  } catch (copyErr) {
21189
21598
  try {
21190
- fs25.rmSync(partialDir, { recursive: true, force: true });
21599
+ fs24.rmSync(partialDir, { recursive: true, force: true });
21191
21600
  } catch {
21192
21601
  }
21193
21602
  throw copyErr;
21194
21603
  }
21195
21604
  }
21196
21605
  } catch (err) {
21197
- if (hadPrevious && movedAside && fs25.existsSync(backupDir)) {
21198
- if (fs25.existsSync(outDir)) fs25.rmSync(outDir, { recursive: true, force: true });
21199
- fs25.renameSync(backupDir, outDir);
21606
+ if (hadPrevious && movedAside && fs24.existsSync(backupDir)) {
21607
+ if (fs24.existsSync(outDir)) fs24.rmSync(outDir, { recursive: true, force: true });
21608
+ fs24.renameSync(backupDir, outDir);
21200
21609
  } else if (hadPrevious && !movedAside) {
21201
21610
  onStagingPreserved?.();
21202
21611
  process.stderr.write(
@@ -21208,7 +21617,7 @@ function swapOnce(stagingDir, outDir, beforeSwap, onStagingPreserved) {
21208
21617
  }
21209
21618
  if (hadPrevious) {
21210
21619
  try {
21211
- fs25.rmSync(backupDir, { recursive: true, force: true });
21620
+ fs24.rmSync(backupDir, { recursive: true, force: true });
21212
21621
  } catch (err) {
21213
21622
  process.stderr.write(
21214
21623
  `\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.
@@ -21387,7 +21796,7 @@ function generateSnapshot(configInput, options) {
21387
21796
  // first run cannot have marked them yet, so the name alone keeps a run from recording its own
21388
21797
  // output — but only at these exact paths, not at every directory that shares the name.
21389
21798
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
21390
- (directory) => path26.relative(config.cwd, path26.resolve(config.cwd, directory)).replace(/\\/g, "/")
21799
+ (directory) => path25.relative(config.cwd, path25.resolve(config.cwd, directory)).replace(/\\/g, "/")
21391
21800
  ).filter((relative15) => relative15.length > 0 && !relative15.startsWith("..")),
21392
21801
  // A staged path can be absent from the working tree while its index blob exists. Discovery
21393
21802
  // lists the working tree, so those paths would never reach the scan at all.
@@ -21416,7 +21825,7 @@ function generateSnapshot(configInput, options) {
21416
21825
  let totalSizeBytes = 0;
21417
21826
  let largeFileCount = 0;
21418
21827
  for (const relativePath of candidateFiles) {
21419
- const absolutePath = path26.join(config.cwd, relativePath);
21828
+ const absolutePath = path25.join(config.cwd, relativePath);
21420
21829
  const fromIndex = stagedPaths.has(relativePath);
21421
21830
  let buffer;
21422
21831
  let sizeBytes;
@@ -21447,9 +21856,9 @@ function generateSnapshot(configInput, options) {
21447
21856
  } else {
21448
21857
  let stats;
21449
21858
  try {
21450
- stats = fs25.statSync(absolutePath);
21859
+ stats = fs24.statSync(absolutePath);
21451
21860
  if (!stats.isFile()) {
21452
- const nestedRepository = stats.isDirectory() && fs25.existsSync(path26.join(absolutePath, ".git"));
21861
+ const nestedRepository = stats.isDirectory() && fs24.existsSync(path25.join(absolutePath, ".git"));
21453
21862
  skipped.push(
21454
21863
  nestedRepository ? {
21455
21864
  path: relativePath,
@@ -21485,7 +21894,7 @@ function generateSnapshot(configInput, options) {
21485
21894
  continue;
21486
21895
  }
21487
21896
  try {
21488
- buffer = fs25.readFileSync(absolutePath);
21897
+ buffer = fs24.readFileSync(absolutePath);
21489
21898
  } catch (err) {
21490
21899
  const code = err.code;
21491
21900
  skipped.push({
@@ -21534,9 +21943,9 @@ function generateSnapshot(configInput, options) {
21534
21943
  const language = detectLanguage(relativePath);
21535
21944
  bump(layerCounts, layer2);
21536
21945
  bump(kindCounts, kind);
21537
- const derivation = takeDerivation(absolutePath, hashSha256, derivationKey) ?? (() => {
21946
+ const derivation = takeDerivation(absolutePath, relativePath, hashSha256, derivationKey) ?? (() => {
21538
21947
  const fresh = deriveFile(relativePath, rawContent, sizeBytes, config);
21539
- rememberDerivation(absolutePath, hashSha256, derivationKey, fresh);
21948
+ rememberDerivation(absolutePath, relativePath, hashSha256, derivationKey, fresh);
21540
21949
  return fresh;
21541
21950
  })();
21542
21951
  const { lineCount } = derivation;
@@ -21600,14 +22009,14 @@ function generateSnapshot(configInput, options) {
21600
22009
  }
21601
22010
  retain(secretFindings, (finding) => finding.path === void 0 || keep.has(finding.path));
21602
22011
  retain(encodingNotes, (note) => keep.has(note.path));
21603
- retain(oversizeSummaryPaths, (path27) => keep.has(path27));
21604
- retain(previewSummaryPaths, (path27) => keep.has(path27));
22012
+ retain(oversizeSummaryPaths, (path26) => keep.has(path26));
22013
+ retain(previewSummaryPaths, (path26) => keep.has(path26));
21605
22014
  retain(fileWarnings, (warning) => keep.has(warning.path));
21606
- for (const path27 of [...monolithBodies.keys()]) {
21607
- if (!keep.has(path27)) monolithBodies.delete(path27);
22015
+ for (const path26 of [...monolithBodies.keys()]) {
22016
+ if (!keep.has(path26)) monolithBodies.delete(path26);
21608
22017
  }
21609
- for (const path27 of [...skippedSummaryImports.keys()]) {
21610
- if (!keep.has(path27)) skippedSummaryImports.delete(path27);
22018
+ for (const path26 of [...skippedSummaryImports.keys()]) {
22019
+ if (!keep.has(path26)) skippedSummaryImports.delete(path26);
21611
22020
  }
21612
22021
  };
21613
22022
  if (changedScope !== null && changedPaths !== null && config.withDependents === true) {
@@ -21716,7 +22125,9 @@ function generateSnapshot(configInput, options) {
21716
22125
  const tokens = Math.max(1, Math.ceil(file.includedBytes / 4));
21717
22126
  const value = (entry(file.relativePath) ? 100 : 0) + layerWeight(file.layer) + Math.min(60, (importers.get(file.relativePath) ?? 0) * 6) - Math.min(40, tokens / 250);
21718
22127
  return { file, tokens, value };
21719
- }).sort((left, right) => right.value - left.value || left.tokens - right.tokens || left.file.relativePath.localeCompare(right.file.relativePath));
22128
+ }).sort(
22129
+ (left, right) => right.value - left.value || left.tokens - right.tokens || (left.file.relativePath < right.file.relativePath ? -1 : left.file.relativePath > right.file.relativePath ? 1 : 0)
22130
+ );
21720
22131
  const keep = /* @__PURE__ */ new Set();
21721
22132
  let used = 0;
21722
22133
  const selected = [];
@@ -22125,8 +22536,11 @@ function generateSnapshot(configInput, options) {
22125
22536
  const entry = {
22126
22537
  ...file,
22127
22538
  content,
22128
- inclusionMode: file.inclusionMode === "comments-stripped" ? "comments-stripped" : "full",
22129
- ...file.emptyLinesRemoved === true ? { emptyLinesRemoved: true } : {},
22539
+ // `fullContents` is the pre-preview body but still carries comments and blank lines: the
22540
+ // monolith is the whole source, not the comments-stripped variant. Calling it
22541
+ // `comments-stripped` (or copying `emptyLinesRemoved`) described a transformation this
22542
+ // artifact did not perform.
22543
+ inclusionMode: "full",
22130
22544
  isPreviewTruncated: false,
22131
22545
  includedBytes: Buffer.byteLength(content, "utf8"),
22132
22546
  includedLines: countLines(content)
@@ -22209,12 +22623,12 @@ function generateSnapshot(configInput, options) {
22209
22623
  let releaseDeferred = false;
22210
22624
  try {
22211
22625
  ensureParentDirectory(outDir, "outDir");
22212
- fs25.mkdirSync(tmpDir, { recursive: true });
22626
+ fs24.mkdirSync(tmpDir, { recursive: true });
22213
22627
  cleanStaleRunDirs(tmpDir);
22214
22628
  const snapshotId = crypto.randomUUID();
22215
22629
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
22216
- stagingDir = path26.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
22217
- fs25.mkdirSync(stagingDir);
22630
+ stagingDir = path25.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
22631
+ fs24.mkdirSync(stagingDir);
22218
22632
  writeOwnershipMarker(stagingDir, {
22219
22633
  generator: GENERATOR_NAME,
22220
22634
  version: GENERATOR_VERSION,
@@ -22225,30 +22639,34 @@ function generateSnapshot(configInput, options) {
22225
22639
  runId,
22226
22640
  pid: process.pid
22227
22641
  });
22228
- const partsDir = path26.join(stagingDir, "parts");
22229
- const reportsDir = path26.join(stagingDir, "reports");
22230
- if (artifacts.parts) fs25.mkdirSync(partsDir, { recursive: true });
22642
+ const partsDir = path25.join(stagingDir, "parts");
22643
+ const reportsDir = path25.join(stagingDir, "reports");
22644
+ if (artifacts.parts) fs24.mkdirSync(partsDir, { recursive: true });
22231
22645
  if (artifacts.navigation || artifacts.projectTree || artifacts.audit || artifacts.diff || artifacts.log || artifacts.tokenTree || config.sarif === true) {
22232
- fs25.mkdirSync(reportsDir, { recursive: true });
22646
+ fs24.mkdirSync(reportsDir, { recursive: true });
22233
22647
  }
22234
22648
  const writtenArtifacts = /* @__PURE__ */ new Map();
22649
+ const ledgerRoot = (targetDir) => stagingDir !== null && (targetDir === stagingDir || targetDir.startsWith(stagingDir + path25.sep)) ? stagingDir : outDir;
22650
+ const ledgerEntry = (targetDir, relativeEntry) => path25.relative(ledgerRoot(targetDir), path25.join(targetDir, ...relativeEntry.split("/"))).split(path25.sep).join("/");
22235
22651
  const writeArtifact = (targetDir, relativeEntry, data) => {
22236
- const full = path26.join(targetDir, ...relativeEntry.split("/"));
22237
- fs25.writeFileSync(full, data, "utf8");
22238
- const stats = fs25.statSync(full);
22239
- writtenArtifacts.set(relativeEntry, {
22240
- digest: { path: relativeEntry, bytes: stats.size, sha256: sha256Hex2(data) },
22652
+ const full = path25.join(targetDir, ...relativeEntry.split("/"));
22653
+ fs24.writeFileSync(full, data, "utf8");
22654
+ const stats = fs24.statSync(full);
22655
+ const entry = ledgerEntry(targetDir, relativeEntry);
22656
+ writtenArtifacts.set(entry, {
22657
+ digest: { path: entry, bytes: stats.size, sha256: sha256Hex2(data) },
22241
22658
  mtimeMs: stats.mtimeMs
22242
22659
  });
22243
22660
  };
22244
22661
  const recordArtifact = (targetDir, relativeEntry) => {
22245
- const full = path26.join(targetDir, ...relativeEntry.split("/"));
22246
- const stats = fs25.statSync(full);
22247
- writtenArtifacts.set(relativeEntry, {
22662
+ const full = path25.join(targetDir, ...relativeEntry.split("/"));
22663
+ const stats = fs24.statSync(full);
22664
+ const entry = ledgerEntry(targetDir, relativeEntry);
22665
+ writtenArtifacts.set(entry, {
22248
22666
  digest: {
22249
- path: relativeEntry,
22667
+ path: entry,
22250
22668
  bytes: stats.size,
22251
- sha256: sha256Hex2(fs25.readFileSync(full))
22669
+ sha256: sha256Hex2(fs24.readFileSync(full))
22252
22670
  },
22253
22671
  mtimeMs: stats.mtimeMs
22254
22672
  });
@@ -22297,7 +22715,7 @@ function generateSnapshot(configInput, options) {
22297
22715
  "Refusing to sign: manifest.json is disabled for this run. Signing covers the manifest, so enable the manifest artifact or drop --sign."
22298
22716
  );
22299
22717
  }
22300
- const record = signManifest(path26.join(stagingDir, "manifest.json"), {
22718
+ const record = signManifest(path25.join(stagingDir, "manifest.json"), {
22301
22719
  key: options.sign.key ?? null
22302
22720
  });
22303
22721
  writeArtifact(stagingDir, SIGNATURE_FILE, JSON.stringify(record, null, 2) + "\n");
@@ -22329,10 +22747,10 @@ function generateSnapshot(configInput, options) {
22329
22747
  const shipHookState = () => {
22330
22748
  if (!markerBelongsTo(outDir, snapshotId)) return;
22331
22749
  if (artifacts.manifest && manifest.warnings.length !== warningsBeforeHook) {
22332
- writeManifestAtomically(path26.join(outDir, "manifest.json"), manifest);
22750
+ writeManifestAtomically(path25.join(outDir, "manifest.json"), manifest);
22333
22751
  recordArtifact(outDir, "manifest.json");
22334
22752
  if (options?.sign !== void 0) {
22335
- const record = signManifest(path26.join(outDir, "manifest.json"), {
22753
+ const record = signManifest(path25.join(outDir, "manifest.json"), {
22336
22754
  key: options.sign.key ?? null
22337
22755
  });
22338
22756
  writeArtifact(outDir, SIGNATURE_FILE, JSON.stringify(record, null, 2) + "\n");
@@ -22378,7 +22796,7 @@ function generateSnapshot(configInput, options) {
22378
22796
  } catch (err) {
22379
22797
  if (stagingDir !== null && !stagingPreserved) {
22380
22798
  try {
22381
- fs25.rmSync(stagingDir, { recursive: true, force: true });
22799
+ fs24.rmSync(stagingDir, { recursive: true, force: true });
22382
22800
  } catch {
22383
22801
  }
22384
22802
  }