codebase-snapshot 0.20.4 → 0.20.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -134,7 +134,7 @@ function finalizeSummary(summary) {
134
134
  }
135
135
  function eachLine(content, visit) {
136
136
  const text2 = content.length > MAX_SUMMARY_CHARS ? content.slice(0, MAX_SUMMARY_CHARS) : content;
137
- for (const line of text2.split(/\r?\n/)) visit(line);
137
+ for (const line of text2.split(/\r\n|\n|\r/)) visit(line);
138
138
  }
139
139
  function isTopLevel(line) {
140
140
  return !/^[\s]/.test(line);
@@ -639,9 +639,9 @@ var rubyProfile = {
639
639
  eachLine(content, (line) => {
640
640
  const trimmed = line.trim();
641
641
  if (!trimmed || trimmed.startsWith("#")) return;
642
- const relative14 = REQUIRE_RELATIVE.exec(trimmed);
643
- if (relative14) {
644
- summary.imports.push(`./${relative14[1]}`);
642
+ const relative15 = REQUIRE_RELATIVE.exec(trimmed);
643
+ if (relative15) {
644
+ summary.imports.push(`./${relative15[1]}`);
645
645
  return;
646
646
  }
647
647
  const required = REQUIRE.exec(trimmed);
@@ -825,7 +825,7 @@ function summarizeTypeScriptSource(relativePath, content) {
825
825
  routeHandlers: []
826
826
  };
827
827
  const lowerPath = relativePath.toLowerCase();
828
- const scriptKind2 = /.tsx$/.test(lowerPath) ? ts__default.default.ScriptKind.TSX : /.jsx$/.test(lowerPath) ? ts__default.default.ScriptKind.JSX : /.(?:js|mjs|cjs)$/.test(lowerPath) ? ts__default.default.ScriptKind.JS : ts__default.default.ScriptKind.TS;
828
+ const scriptKind2 = /\.tsx$/.test(lowerPath) ? ts__default.default.ScriptKind.TSX : /\.jsx$/.test(lowerPath) ? ts__default.default.ScriptKind.JSX : /.(?:js|mjs|cjs)$/.test(lowerPath) ? ts__default.default.ScriptKind.JS : ts__default.default.ScriptKind.TS;
829
829
  const sourceFile = ts__default.default.createSourceFile(
830
830
  relativePath,
831
831
  content,
@@ -1417,17 +1417,17 @@ function decodeText(buffer) {
1417
1417
  };
1418
1418
  }
1419
1419
  const invalidBytes = countInvalidUtf8Bytes(buffer);
1420
+ const controlBytes = countControlBytes(buffer);
1421
+ if (controlBytes > CONTROL_BYTES_FLOOR && controlBytes * 100 > buffer.length) {
1422
+ return {
1423
+ text: "",
1424
+ encoding: "utf-8",
1425
+ invalidBytes,
1426
+ binary: true,
1427
+ binaryReason: `${controlBytes} control byte(s) in ${buffer.length} B; not text`
1428
+ };
1429
+ }
1420
1430
  if (invalidBytes === 0) {
1421
- const controlBytes = countControlBytes(buffer);
1422
- if (controlBytes > CONTROL_BYTES_FLOOR && controlBytes * 100 > buffer.length) {
1423
- return {
1424
- text: "",
1425
- encoding: "utf-8",
1426
- invalidBytes: 0,
1427
- binary: true,
1428
- binaryReason: `${controlBytes} control byte(s) in ${buffer.length} B; valid UTF-8 but not text`
1429
- };
1430
- }
1431
1431
  return {
1432
1432
  text: new TextDecoder("utf-8").decode(buffer),
1433
1433
  encoding: "utf-8",
@@ -1726,9 +1726,15 @@ function skeletonizeTypeScript(source, fileName = "file.ts") {
1726
1726
  if (end > start) spans.push({ start, end });
1727
1727
  }
1728
1728
  }
1729
- ts__default.default.forEachChild(node, visit);
1730
1729
  };
1731
- visit(sourceFile);
1730
+ const stack = [sourceFile];
1731
+ while (stack.length > 0) {
1732
+ const node = stack.pop();
1733
+ visit(node);
1734
+ ts__default.default.forEachChild(node, (child) => {
1735
+ stack.push(child);
1736
+ });
1737
+ }
1732
1738
  if (spans.length === 0) return { text: source, collapsed: 0 };
1733
1739
  const outermost = [];
1734
1740
  for (const span of spans.sort((a, b) => a.start - b.start || b.end - a.end)) {
@@ -1898,7 +1904,7 @@ function readManifest(cwd, name) {
1898
1904
  function dependenciesFromPackageJson(raw) {
1899
1905
  const names = /* @__PURE__ */ new Set();
1900
1906
  try {
1901
- const parsed = JSON.parse(raw);
1907
+ const parsed = JSON.parse(stripJsonComments(raw.replace(/^\uFEFF/, "")));
1902
1908
  for (const section of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
1903
1909
  const block = parsed[section];
1904
1910
  if (block && typeof block === "object") {
@@ -1988,8 +1994,8 @@ function workspacePackageDirs(cwd, patterns) {
1988
1994
  function scanWorkspacePackages(cwd, patterns) {
1989
1995
  const files = /* @__PURE__ */ new Set();
1990
1996
  const dependencies = /* @__PURE__ */ new Set();
1991
- for (const relative14 of workspacePackageDirs(cwd, patterns)) {
1992
- const full = path25__namespace.join(cwd, relative14);
1997
+ for (const relative15 of workspacePackageDirs(cwd, patterns)) {
1998
+ const full = path25__namespace.join(cwd, relative15);
1993
1999
  try {
1994
2000
  for (const entry of fs24__namespace.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
1995
2001
  } catch {
@@ -3203,7 +3209,7 @@ var DEFAULT_SECRET_PATTERNS = [
3203
3209
  // rendering of textual userinfo mixes cases, while the prose the earlier rules were
3204
3210
  // protecting (`Bearer authentication`) is a lowercase word.
3205
3211
  rule: "authorization-header",
3206
- pattern: /(?<=[Aa]uthorization["']?\s*[:=]\s*["']?[A-Za-z][A-Za-z0-9._~+/-]{0,31}\s{1,8})(?:[A-Za-z0-9_.+/-]{0,31}[0-9][A-Za-z0-9_.+/-]{0,1024}|[A-Za-z0-9_.+/-]{32,1024}|[A-Za-z0-9_.+/-]{8,1024}={1,2}|(?=[A-Za-z0-9_.+/-]{0,1023}[A-Z])(?=[A-Za-z0-9_.+/-]{0,1023}[a-z])[A-Za-z0-9_.+/-]{12,1024})(?![A-Za-z0-9_.+/=-])/
3212
+ pattern: /(?<=[Aa][Uu][Tt][Hh][Oo][Rr][Ii][Zz][Aa][Tt][Ii][Oo][Nn]["']?\s*[:=]\s*["']?[A-Za-z][A-Za-z0-9._~+/-]{0,31}\s{1,8})(?:[A-Za-z0-9_.+/-]{0,31}[0-9][A-Za-z0-9_.+/-]{0,1024}|[A-Za-z0-9_.+/-]{32,1024}|[A-Za-z0-9_.+/-]{8,1024}={1,2}|(?=[A-Za-z0-9_.+/-]{0,1023}[A-Z])(?=[A-Za-z0-9_.+/-]{0,1023}[a-z])[A-Za-z0-9_.+/-]{12,1024})(?![A-Za-z0-9_.+/=-])/
3207
3213
  },
3208
3214
  {
3209
3215
  // Broader names than before (`apiKey`, `clientSecret`, `privateKey` were
@@ -3781,6 +3787,7 @@ function redactStructuredValues(text2, filePath, recordFinding) {
3781
3787
  if (firstValue === void 0) continue;
3782
3788
  const valueIndent = (/^[ \t]*/.exec(firstValue)?.[0] ?? "").length;
3783
3789
  if (valueIndent <= baseIndent) continue;
3790
+ if (STRUCTURED_KEY.test(firstValue) || /^[ \t]*-[ \t]/.test(firstValue)) continue;
3784
3791
  let masked = false;
3785
3792
  while (cursor < segments.length) {
3786
3793
  const body = segments[cursor] ?? "";
@@ -3796,7 +3803,7 @@ function redactStructuredValues(text2, filePath, recordFinding) {
3796
3803
  }
3797
3804
  return segments.join("");
3798
3805
  }
3799
- var DOCKERFILE_ENV = /^([ \t]*ENV[ \t]+)([A-Za-z_][A-Za-z0-9_]*)([ \t]+)(\S.*)$/;
3806
+ var DOCKERFILE_ENV = /^([ \t]*)(ENV|ARG)([ \t]+)([A-Za-z_][A-Za-z0-9_]*)([ \t]*=[ \t]*|[ \t]+)(\S.*)$/i;
3800
3807
  function redactDockerfileEnv(text2, filePath, recordFinding) {
3801
3808
  if (!isDockerfile(filePath)) return text2;
3802
3809
  const segments = text2.split(LINE_BREAK);
@@ -3805,10 +3812,9 @@ function redactDockerfileEnv(text2, filePath, recordFinding) {
3805
3812
  if (line === void 0) continue;
3806
3813
  const match = DOCKERFILE_ENV.exec(line);
3807
3814
  if (match === null) continue;
3808
- if (!CREDENTIAL_KEY_TAIL.test(match[2] ?? "")) continue;
3809
- const value = match[4] ?? "";
3810
- if (value.startsWith("=")) continue;
3811
- segments[index] = `${match[1]}${match[2]}${match[3]}${REDACTION_MARKER}`;
3815
+ if (!CREDENTIAL_KEY_TAIL.test(match[4] ?? "")) continue;
3816
+ const separator = match[5] ?? "";
3817
+ segments[index] = `${match[1]}${match[2]}${match[3]}${match[4]}${separator}${REDACTION_MARKER}`;
3812
3818
  recordFinding(index / 2 + 1, ["dockerfile-env-secret"]);
3813
3819
  }
3814
3820
  return segments.join("");
@@ -3893,6 +3899,7 @@ function isSourceCodeFile(filePath) {
3893
3899
  var PLACEHOLDER_PATTERNS = [
3894
3900
  /^<[^>]*>?$/,
3895
3901
  /^\.{3,}$/,
3902
+ /^(?:[A-Za-z0-9_-]{1,8}-)?\.{3,}$/,
3896
3903
  /^(?:x{4,}|X{4,}|\*{3,})$/,
3897
3904
  /^(?:replace|change)[-_ ]?me(?:[-_ ].*)?$/i,
3898
3905
  /^your[-_ ].*$/i,
@@ -3906,7 +3913,7 @@ function isPlaceholderValue(value) {
3906
3913
  if (trimmed.length === 0) return false;
3907
3914
  if (PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(trimmed))) return true;
3908
3915
  if (trimmed.includes(REDACTION_MARKER) || trimmed.includes(PEM_REDACTION_MARKER)) return true;
3909
- return trimmed.includes("...") || /^<[^>]*$/.test(trimmed);
3916
+ return false;
3910
3917
  }
3911
3918
  function quotesAreBalanced(text2) {
3912
3919
  let single = 0;
@@ -3958,6 +3965,7 @@ var ASSIGNMENT_FILE = /\.(?:sh|bash|zsh|ksh|fish|env|ya?ml|toml|ini|conf|cfg|pro
3958
3965
  var ASSIGNMENT_BASENAME = /^(?:\.env(?:\.[^/]*)?|\.envrc|\.profile|\.bashrc|\.zshrc|\.bash_profile)$/i;
3959
3966
  function isAssignmentFile(filePath) {
3960
3967
  if (filePath === void 0) return false;
3968
+ if (isDockerfile(filePath)) return true;
3961
3969
  const normalised = filePath.replace(/\\/g, "/");
3962
3970
  if (ASSIGNMENT_FILE.test(normalised)) return true;
3963
3971
  const base = normalised.slice(normalised.lastIndexOf("/") + 1);
@@ -4061,6 +4069,15 @@ function verifySnapshotSignature(snapshotDir) {
4061
4069
  if (sha2562 !== record.manifestSha256) {
4062
4070
  return { ok: false, reason: "manifest.json changed after it was signed" };
4063
4071
  }
4072
+ let signedFingerprint;
4073
+ try {
4074
+ signedFingerprint = JSON.parse(bytes.toString("utf8")).fingerprint;
4075
+ } catch {
4076
+ return { ok: false, reason: "the signed manifest is not JSON" };
4077
+ }
4078
+ if (typeof record.fingerprint !== "string" || record.fingerprint !== signedFingerprint) {
4079
+ return { ok: false, reason: "signature.json names a different fingerprint than the manifest" };
4080
+ }
4064
4081
  let verified = false;
4065
4082
  try {
4066
4083
  const key = crypto__namespace.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
@@ -4073,7 +4090,7 @@ function verifySnapshotSignature(snapshotDir) {
4073
4090
 
4074
4091
  // src/version.ts
4075
4092
  var GENERATOR_NAME = "codebase-snapshot";
4076
- var GENERATOR_VERSION = "0.20.4";
4093
+ var GENERATOR_VERSION = "0.20.6";
4077
4094
  var SCHEMA_VERSION = "3.0.0";
4078
4095
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
4079
4096
  function isOurGeneratorName(name) {
@@ -4105,8 +4122,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
4105
4122
  };
4106
4123
  }
4107
4124
  function isInside(root, candidate) {
4108
- const relative14 = path25__namespace.relative(root, candidate);
4109
- return relative14 === "" || !relative14.startsWith(`..${path25__namespace.sep}`) && relative14 !== ".." && !path25__namespace.isAbsolute(relative14);
4125
+ const relative15 = path25__namespace.relative(root, candidate);
4126
+ return relative15 === "" || !relative15.startsWith(`..${path25__namespace.sep}`) && relative15 !== ".." && !path25__namespace.isAbsolute(relative15);
4110
4127
  }
4111
4128
  var GIT_OUTPUT_LIMIT = 68157440;
4112
4129
  function getGitInfo(cwd, fallbackBranch = "main") {
@@ -4172,7 +4189,7 @@ var DEFAULT_IGNORED_FILES = [
4172
4189
  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;
4173
4190
  var SENSITIVE_PATH = /(?:^|\/)\.(?:aws|ssh|gnupg)\/|(?:^|\/)\.docker\/config\.json$|(?:^|\/)\.kube\/config$|(?:^|\/)\.config\/gcloud\/|(?:^|\/)\.composer\/|(?:^|\/)\.terraform\/credentials\.tfrc\.json$/i;
4174
4191
  var SENSITIVE_EXT = /\.(?:pem|key|p12|pfx|jks|keystore|ppk|asc|kdbx|tfstate|tfvars)$/i;
4175
- var TEMPLATE_SUFFIX = /^(.*)\.(?:example|sample|template|dist)(\.[A-Za-z0-9_-]+)?$/i;
4192
+ var TEMPLATE_SUFFIX = /^(.*)\.(?:example|sample|template|dist)(\.(?:json|ya?ml|toml|ini|txt|md|properties|conf|cfg))?$/i;
4176
4193
  var BACKUP_SUFFIX = /(?:~|\.(?:bak|backup|old|orig|save|copy|swp|swo|tmp|part))$/i;
4177
4194
  function normaliseName(name) {
4178
4195
  let normalised = name.trim().replace(/[. ]+$/, "");
@@ -4601,30 +4618,67 @@ function isToolOwnedDirectory2(dir) {
4601
4618
  }
4602
4619
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
4603
4620
  const marker2 = parsed;
4604
- if (marker2.generator !== GENERATOR_NAME || marker2.state !== "complete" || typeof marker2.id !== "string" || !Array.isArray(marker2.files)) {
4621
+ 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)) {
4622
+ return false;
4623
+ }
4624
+ let manifestBytes;
4625
+ try {
4626
+ manifestBytes = fs24__namespace.readFileSync(path25__namespace.join(dir, "manifest.json"));
4627
+ } catch {
4628
+ return false;
4629
+ }
4630
+ if (crypto.createHash("sha256").update(manifestBytes).digest("hex") !== marker2.manifestSha256) {
4605
4631
  return false;
4606
4632
  }
4607
- const accounted = /* @__PURE__ */ new Set();
4633
+ const recordedFiles = /* @__PURE__ */ new Set();
4608
4634
  for (const item of marker2.files) {
4609
4635
  if (!item || typeof item !== "object" || Array.isArray(item)) return false;
4610
- const entry = item.path;
4611
- if (typeof entry !== "string" || entry.length === 0) return false;
4612
- const parts = entry.split("/");
4613
- for (let depth = 1; depth <= parts.length; depth += 1) {
4614
- accounted.add(parts.slice(0, depth).join("/"));
4636
+ const record = item;
4637
+ const entry = record.path;
4638
+ if (typeof entry !== "string" || entry.length === 0 || entry.includes(String.fromCharCode(92)) || entry.includes("\0") || path25__namespace.isAbsolute(entry) || entry.split("/").includes("..") || typeof record.bytes !== "number" || !Number.isSafeInteger(record.bytes) || record.bytes < 0 || typeof record.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(record.sha256)) {
4639
+ return false;
4640
+ }
4641
+ const full = path25__namespace.join(dir, ...entry.split("/"));
4642
+ let stats;
4643
+ try {
4644
+ stats = fs24__namespace.lstatSync(full);
4645
+ } catch {
4646
+ return false;
4647
+ }
4648
+ if (!stats.isFile() || stats.size !== record.bytes) return false;
4649
+ let digest;
4650
+ try {
4651
+ digest = crypto.createHash("sha256").update(fs24__namespace.readFileSync(full)).digest("hex");
4652
+ } catch {
4653
+ return false;
4615
4654
  }
4655
+ if (digest !== record.sha256) return false;
4656
+ recordedFiles.add(entry);
4616
4657
  }
4617
- let entries;
4618
- try {
4619
- entries = fs24__namespace.readdirSync(dir);
4620
- } catch {
4621
- return false;
4658
+ const stack = [""];
4659
+ while (stack.length > 0) {
4660
+ const current = stack.pop();
4661
+ let entries;
4662
+ try {
4663
+ entries = fs24__namespace.readdirSync(path25__namespace.join(dir, current), { withFileTypes: true });
4664
+ } catch {
4665
+ return false;
4666
+ }
4667
+ for (const entry of entries) {
4668
+ const relative15 = current === "" ? entry.name : current + "/" + entry.name;
4669
+ if (relative15 === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry.name)) continue;
4670
+ if (entry.isDirectory()) {
4671
+ stack.push(relative15);
4672
+ continue;
4673
+ }
4674
+ if (!entry.isFile()) return false;
4675
+ if (relative15 === "signature.json" && !recordedFiles.has(relative15) && verifySnapshotSignature(dir).ok) {
4676
+ continue;
4677
+ }
4678
+ if (!recordedFiles.has(relative15)) return false;
4679
+ }
4622
4680
  }
4623
- return entries.every(
4624
- (entry) => entry === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry) || // A snapshot signed before signing moved into staging has a valid signature.json the old
4625
- // marker could not record. It is our artifact when the signature verifies.
4626
- entry === "signature.json" && verifySnapshotSignature(dir).ok || accounted.has(entry)
4627
- );
4681
+ return true;
4628
4682
  }
4629
4683
  function makeToolOwnedDecider(cwd, toolOwnedPaths) {
4630
4684
  const markers = /* @__PURE__ */ new Map();
@@ -4825,7 +4879,7 @@ function collectFiles(cwd, options = {}) {
4825
4879
  candidates.push(extra);
4826
4880
  }
4827
4881
  }
4828
- const files = candidates.filter((file) => {
4882
+ let files = candidates.filter((file) => {
4829
4883
  if (isToolOwned(file)) return false;
4830
4884
  const ignored = defaultIgnoreReason(file, toolDirNames);
4831
4885
  if (ignored) {
@@ -4870,8 +4924,51 @@ function collectFiles(cwd, options = {}) {
4870
4924
  }
4871
4925
  return true;
4872
4926
  }).sort();
4927
+ files = dropSymlinksToUnincludedTargets(cwd, files, skipped);
4873
4928
  return { files, skipped: maskSkipPaths(skipped, pathRules) };
4874
4929
  }
4930
+ function dropSymlinksToUnincludedTargets(cwd, files, skipped) {
4931
+ const aliases = /* @__PURE__ */ new Set();
4932
+ for (const file of files) {
4933
+ try {
4934
+ if (fs24__namespace.lstatSync(path25__namespace.join(cwd, file)).isSymbolicLink()) aliases.add(file);
4935
+ } catch {
4936
+ }
4937
+ }
4938
+ if (aliases.size === 0) return [...files];
4939
+ const includedTargets = /* @__PURE__ */ new Set();
4940
+ for (const file of files) {
4941
+ if (aliases.has(file)) continue;
4942
+ try {
4943
+ includedTargets.add(fs24__namespace.realpathSync(path25__namespace.join(cwd, file)));
4944
+ } catch {
4945
+ }
4946
+ }
4947
+ const kept = [];
4948
+ for (const file of files) {
4949
+ if (!aliases.has(file)) {
4950
+ kept.push(file);
4951
+ continue;
4952
+ }
4953
+ let target;
4954
+ try {
4955
+ target = fs24__namespace.realpathSync(path25__namespace.join(cwd, file));
4956
+ } catch {
4957
+ skipped.push({ path: file, reason: "read-error", detail: "symlink target could not be resolved" });
4958
+ continue;
4959
+ }
4960
+ if (includedTargets.has(target)) {
4961
+ kept.push(file);
4962
+ continue;
4963
+ }
4964
+ skipped.push({
4965
+ path: file,
4966
+ reason: "symlink",
4967
+ detail: "link target was excluded from the snapshot; not followed"
4968
+ });
4969
+ }
4970
+ return kept;
4971
+ }
4875
4972
  function rootRealFor(root) {
4876
4973
  try {
4877
4974
  return fs24__namespace.realpathSync(root);
@@ -5093,8 +5190,25 @@ function normalizeResolvedConfig(config) {
5093
5190
  monolithWanted,
5094
5191
  monolithWanted
5095
5192
  );
5193
+ if (!Number.isSafeInteger(config.maxPartBytes) || config.maxPartBytes < MIN_MAX_PART_BYTES) {
5194
+ throw new Error(
5195
+ `maxPartBytes must be at least ${MIN_MAX_PART_BYTES} bytes (received ${String(config.maxPartBytes)}).`
5196
+ );
5197
+ }
5198
+ if (!Number.isSafeInteger(config.largeFileBytes) || config.largeFileBytes < 0) {
5199
+ throw new Error(
5200
+ `largeFileBytes must be a non-negative integer; received ${String(config.largeFileBytes)}.`
5201
+ );
5202
+ }
5203
+ const maxPartTokens = config.maxPartTokens ?? Math.floor(config.maxPartBytes / 4);
5204
+ if (!Number.isSafeInteger(maxPartTokens) || maxPartTokens < MIN_MAX_PART_TOKENS) {
5205
+ throw new Error(
5206
+ `maxPartTokens must be at least ${MIN_MAX_PART_TOKENS} tokens; received ${String(maxPartTokens)}.`
5207
+ );
5208
+ }
5096
5209
  return markResolvedConfig({
5097
5210
  ...config,
5211
+ maxPartTokens,
5098
5212
  discovery,
5099
5213
  // A spread copy built before the field existed carries no value; the default applies, and it
5100
5214
  // is re-validated because the number reaches a rendered artifact.
@@ -5535,13 +5649,13 @@ function readConfiguredBrief(cwd, value) {
5535
5649
  'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
5536
5650
  );
5537
5651
  }
5538
- const relative14 = path25__namespace.relative(rootReal, filePath);
5539
- if (relative14.length === 0 || relative14 === ".." || relative14.startsWith(`..${path25__namespace.sep}`) || path25__namespace.isAbsolute(relative14)) {
5652
+ const relative15 = path25__namespace.relative(rootReal, filePath);
5653
+ if (relative15.length === 0 || relative15 === ".." || relative15.startsWith(`..${path25__namespace.sep}`) || path25__namespace.isAbsolute(relative15)) {
5540
5654
  throw new Error(
5541
5655
  'brief "' + value + '" resolves outside the repository. A brief must be a file inside the repository being described; an absolute or parent path is refused.'
5542
5656
  );
5543
5657
  }
5544
- const posixRelative = relative14.split(path25__namespace.sep).join("/");
5658
+ const posixRelative = relative15.split(path25__namespace.sep).join("/");
5545
5659
  if (isSensitivePath(posixRelative) || isSensitivePath(value)) {
5546
5660
  throw new Error(
5547
5661
  'brief "' + value + '" is a credential-bearing file. A snapshot must not reproduce secrets, so it cannot be used as the owner brief.'
@@ -5549,9 +5663,16 @@ function readConfiguredBrief(cwd, value) {
5549
5663
  }
5550
5664
  let text2;
5551
5665
  try {
5552
- if (!fs24__namespace.statSync(filePath).isFile()) throw new Error("not a file");
5666
+ const stats = fs24__namespace.statSync(filePath);
5667
+ if (!stats.isFile()) throw new Error("not a file");
5668
+ if (stats.size > MAX_BRIEF_BYTES) {
5669
+ throw new Error(
5670
+ '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."
5671
+ );
5672
+ }
5553
5673
  text2 = fs24__namespace.readFileSync(filePath, "utf8");
5554
- } catch {
5674
+ } catch (error) {
5675
+ if (error instanceof Error && error.message.startsWith('brief "')) throw error;
5555
5676
  throw new Error(
5556
5677
  'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
5557
5678
  );
@@ -5663,11 +5784,11 @@ function outputExcludePatterns(cwd, outDir, tmpDir) {
5663
5784
  const patterns = [];
5664
5785
  for (const dir of [outDir, tmpDir]) {
5665
5786
  const absolute = path25__namespace.resolve(cwd, dir);
5666
- const relative14 = path25__namespace.relative(cwd, absolute);
5667
- if (!relative14 || relative14 === ".." || relative14.startsWith(`..${path25__namespace.sep}`) || path25__namespace.isAbsolute(relative14)) {
5787
+ const relative15 = path25__namespace.relative(cwd, absolute);
5788
+ if (!relative15 || relative15 === ".." || relative15.startsWith(`..${path25__namespace.sep}`) || path25__namespace.isAbsolute(relative15)) {
5668
5789
  continue;
5669
5790
  }
5670
- patterns.push(`${relative14.replace(/\\/g, "/")}/**`);
5791
+ patterns.push(`${relative15.replace(/\\/g, "/")}/**`);
5671
5792
  }
5672
5793
  return patterns;
5673
5794
  }
@@ -5954,7 +6075,10 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
5954
6075
  outDir,
5955
6076
  tmpDir,
5956
6077
  maxPartBytes: resolvedMaxPartBytes,
5957
- ...maxPartTokens === void 0 ? {} : { maxPartTokens },
6078
+ // Record the effective value even when the user did not set it. normalizeResolvedConfig
6079
+ // derives it for the manifest; leaving validate's fresh resolution unset made a clean
6080
+ // snapshot report a configuration mismatch.
6081
+ maxPartTokens: maxPartTokens ?? Math.floor(resolvedMaxPartBytes / 4),
5958
6082
  largeFileBytes: largeFileBytesFor(resolvedMaxPartBytes, cliOptions, userConfig),
5959
6083
  previewHeadLines: strictPositiveInteger(userConfig?.previewHeadLines, 80, "`previewHeadLines`"),
5960
6084
  previewTailLines: strictPositiveInteger(userConfig?.previewTailLines, 40, "`previewTailLines`"),
@@ -6356,7 +6480,8 @@ function generateSarifReport(manifest, findings, rules, toolVersion) {
6356
6480
  const results = findings.filter((finding) => typeof finding.path === "string" && finding.path.length > 0).map((finding) => {
6357
6481
  const primary = finding.rules[0] ?? "unknown";
6358
6482
  const line = Math.max(1, finding.line);
6359
- const findingPath = String(finding.path).replace(/\\/g, "/");
6483
+ const rawPath = findSecretInPath(String(finding.path), rules)?.masked ?? String(finding.path);
6484
+ const findingPath = rawPath.replace(/\\/g, "/").split("/").map((segment) => encodeURIComponent(segment)).join("/");
6360
6485
  return {
6361
6486
  ruleId: ruleIdFor(primary),
6362
6487
  ruleIndex: ruleIndex.get(primary) ?? 0,
@@ -6427,6 +6552,9 @@ function countLines(content) {
6427
6552
  const last = content.charCodeAt(content.length - 1);
6428
6553
  return last === 10 || last === 13 ? breaks : breaks + 1;
6429
6554
  }
6555
+ function countBodyLines(content) {
6556
+ return content.length === 0 ? 0 : content.split("\n").length;
6557
+ }
6430
6558
  function truncateToBytes(content, maxBytes) {
6431
6559
  if (maxBytes <= 0) return { content: "", isTruncated: content.length > 0 };
6432
6560
  const buffer = Buffer.from(content, "utf8");
@@ -6778,14 +6906,16 @@ function fenceIsOpen(text2, fence) {
6778
6906
  }
6779
6907
  var OMISSION_NOTICE_LINE = /^\.\.\. \[\d+ lines omitted: [^\]]*\] \.\.\.$/;
6780
6908
  function applyTruncatedContent(file, content, reason) {
6781
- const keptLines = content.split("\n").filter((line) => !OMISSION_NOTICE_LINE.test(line)).length;
6909
+ const keptLines = content.split("\n").filter(
6910
+ (line) => !OMISSION_NOTICE_LINE.test(line) && line.trim() !== SECTION_TRUNCATION_NOTICE
6911
+ ).length;
6782
6912
  file.content = content;
6783
6913
  file.isPreviewTruncated = true;
6784
6914
  file.inclusionMode = "preview";
6785
6915
  file.truncationReason = reason;
6786
6916
  file.omittedRanges = keptLines >= file.originalLines ? file.originalLines > 0 ? [[file.originalLines, file.originalLines]] : [] : [[keptLines + 1, file.originalLines]];
6787
6917
  file.includedBytes = Buffer.byteLength(content, "utf8");
6788
- file.includedLines = countLines(content);
6918
+ file.includedLines = countBodyLines(content);
6789
6919
  }
6790
6920
  function rehashPart(part, markdown) {
6791
6921
  const estimatedTokens = estimateTokens(markdown.replace(TOKEN_LINE, ""));
@@ -6798,7 +6928,8 @@ function rehashPart(part, markdown) {
6798
6928
  byteSize: Buffer.byteLength(redistributed, "utf8"),
6799
6929
  sha256: crypto__namespace.createHash("sha256").update(redistributed).digest("hex"),
6800
6930
  lines: countLines(redistributed),
6801
- estimatedTokens
6931
+ estimatedTokens,
6932
+ hardClipped: true
6802
6933
  }
6803
6934
  };
6804
6935
  }
@@ -6920,7 +7051,7 @@ function renderFileSection(file) {
6920
7051
  const content = file.content ?? "";
6921
7052
  const body = emittedBody(content);
6922
7053
  file.includedBytes = Buffer.byteLength(body, "utf8");
6923
- file.includedLines = countLines(body);
7054
+ file.includedLines = countBodyLines(body);
6924
7055
  const fence = fenceForContent(content);
6925
7056
  const anchor = anchorForPath(file.relativePath);
6926
7057
  return [
@@ -6974,11 +7105,14 @@ function generateMonolithJson(manifest, filesWithContent) {
6974
7105
  );
6975
7106
  return JSON.stringify({ manifest: embedded, files }, null, 2);
6976
7107
  }
7108
+ function xmlSafe(value) {
7109
+ return value.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]/g, "\uFFFD");
7110
+ }
6977
7111
  function xmlAttribute(value) {
6978
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
7112
+ return xmlSafe(value).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
6979
7113
  }
6980
7114
  function cdata(value) {
6981
- return "<![CDATA[" + value.replace(/\]\]>/g, "]]]]><![CDATA[>") + "]]>";
7115
+ return "<![CDATA[" + xmlSafe(value).replace(/\]\]>/g, "]]]]><![CDATA[>") + "]]>";
6982
7116
  }
6983
7117
  function generateMonolithXml(manifest, filesWithContent) {
6984
7118
  const files = filesWithContent.map((file) => {
@@ -7079,14 +7213,19 @@ function generateNavigation(manifest) {
7079
7213
  }
7080
7214
 
7081
7215
  // src/generator/selection.ts
7216
+ function cell(value) {
7217
+ return escapeControls(value).replace(/\r?\n/g, " ").replace(/\|/g, "\\|");
7218
+ }
7082
7219
  function generateSelectionReport(manifest, selection) {
7083
7220
  const lines = [];
7084
7221
  lines.push("# Selection");
7085
7222
  lines.push("");
7086
7223
  lines.push("**Kind:** `" + selection.kind + "` ");
7087
- for (const detailLine of selection.detail.split("\n")) {
7088
- lines.push("**" + detailLine.slice(0, detailLine.indexOf(":")) + ":**" + detailLine.slice(detailLine.indexOf(":") + 1) + " ");
7089
- }
7224
+ const detail = selection.detail.replace(/\r?\n/g, " ");
7225
+ const colon = detail.indexOf(":");
7226
+ lines.push(
7227
+ "**" + (colon === -1 ? "Selection" : detail.slice(0, colon)) + ":**" + (colon === -1 ? " " + detail : detail.slice(colon + 1)) + " "
7228
+ );
7090
7229
  lines.push("**Selected files:** " + selection.files.length + " ");
7091
7230
  const spent = manifest.budget?.usedTokens ?? manifest.slice?.usedTokens ?? 0;
7092
7231
  lines.push("**Tokens spent:** " + spent.toLocaleString("en-US"));
@@ -7096,7 +7235,7 @@ function generateSelectionReport(manifest, selection) {
7096
7235
  lines.push("| File | Tokens | Reason |");
7097
7236
  lines.push("| :-- | --: | :-- |");
7098
7237
  for (const file of selection.files) {
7099
- lines.push("| `" + file.path + "` | " + file.tokens.toLocaleString("en-US") + " | " + file.why + " |");
7238
+ lines.push("| `" + cell(file.path) + "` | " + file.tokens.toLocaleString("en-US") + " | " + cell(file.why) + " |");
7100
7239
  }
7101
7240
  lines.push("");
7102
7241
  const dropped = selection.kind === "slice" ? manifest.slice?.dropped : manifest.budget?.dropped;
@@ -7116,7 +7255,7 @@ function generateSelectionReport(manifest, selection) {
7116
7255
  lines.push("| File | Tokens |");
7117
7256
  lines.push("| :-- | --: |");
7118
7257
  for (const item of next) {
7119
- lines.push("| `" + item.path + "` | " + item.tokens.toLocaleString("en-US") + " |");
7258
+ lines.push("| `" + cell(item.path) + "` | " + item.tokens.toLocaleString("en-US") + " |");
7120
7259
  }
7121
7260
  lines.push("");
7122
7261
  }
@@ -7323,7 +7462,9 @@ function planForQuestion(manifest, question, options = {}) {
7323
7462
  notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
7324
7463
  }
7325
7464
  }
7326
- scored.sort((left, right) => right.score - left.score || left.file.relativePath.localeCompare(right.file.relativePath));
7465
+ scored.sort(
7466
+ (left, right) => right.score - left.score || (left.file.relativePath < right.file.relativePath ? -1 : left.file.relativePath > right.file.relativePath ? 1 : 0)
7467
+ );
7327
7468
  const chosen = /* @__PURE__ */ new Map();
7328
7469
  const skipped = [];
7329
7470
  let used = 0;
@@ -7431,12 +7572,15 @@ function stripComments2(text2, relativePath) {
7431
7572
  if (ranges_ === void 0) return;
7432
7573
  for (const range of ranges_) ranges.push([range.pos, range.end]);
7433
7574
  };
7434
- const visit = (node) => {
7575
+ const stack = [source];
7576
+ while (stack.length > 0) {
7577
+ const node = stack.pop();
7435
7578
  collect(ts__default.default.getLeadingCommentRanges(text2, node.getFullStart()));
7436
7579
  collect(ts__default.default.getTrailingCommentRanges(text2, node.getEnd()));
7437
- ts__default.default.forEachChild(node, visit);
7438
- };
7439
- visit(source);
7580
+ ts__default.default.forEachChild(node, (child) => {
7581
+ stack.push(child);
7582
+ });
7583
+ }
7440
7584
  collect(ts__default.default.getLeadingCommentRanges(text2, source.endOfFileToken.getFullStart()));
7441
7585
  if (ranges.length === 0) return { text: text2, removed: 0 };
7442
7586
  ranges.sort((left, right) => left[0] - right[0]);
@@ -7459,25 +7603,112 @@ function stripComments2(text2, relativePath) {
7459
7603
  return { text: pieces.join(""), removed };
7460
7604
  }
7461
7605
  function runGit(cwd, args) {
7462
- const result = childProcess.spawnSync("git", args, { cwd, encoding: "utf8", windowsHide: true, maxBuffer: 64 * 1024 * 1024 });
7606
+ const result = childProcess.spawnSync(
7607
+ "git",
7608
+ [
7609
+ "-c",
7610
+ "core.quotepath=false",
7611
+ "-c",
7612
+ "diff.noprefix=false",
7613
+ "-c",
7614
+ "diff.mnemonicPrefix=false",
7615
+ ...args
7616
+ ],
7617
+ { cwd, encoding: "utf8", windowsHide: true, maxBuffer: 64 * 1024 * 1024 }
7618
+ );
7463
7619
  if (result.status !== 0) return { ok: false, out: (result.stderr ?? "").trim() };
7464
7620
  return { ok: true, out: result.stdout ?? "" };
7465
7621
  }
7466
7622
  function isGitRepository(cwd) {
7467
7623
  return runGit(cwd, ["rev-parse", "--is-inside-work-tree"]).out.trim() === "true";
7468
7624
  }
7625
+ function unquoteGitPath(value) {
7626
+ if (!value.startsWith('"') || !value.endsWith('"')) return value;
7627
+ const body = value.slice(1, -1);
7628
+ let out = "";
7629
+ let bytes = [];
7630
+ const flushBytes = () => {
7631
+ if (bytes.length === 0) return;
7632
+ out += Buffer.from(bytes).toString("utf8");
7633
+ bytes = [];
7634
+ };
7635
+ const escapes = {
7636
+ a: "\x07",
7637
+ b: "\b",
7638
+ f: "\f",
7639
+ n: "\n",
7640
+ r: "\r",
7641
+ t: " ",
7642
+ v: "\v",
7643
+ "\\": "\\",
7644
+ '"': '"'
7645
+ };
7646
+ for (let index = 0; index < body.length; index += 1) {
7647
+ const char = body[index];
7648
+ if (char !== "\\") {
7649
+ flushBytes();
7650
+ out += char;
7651
+ continue;
7652
+ }
7653
+ const next = body[index + 1];
7654
+ if (next === void 0) {
7655
+ flushBytes();
7656
+ out += "\\";
7657
+ break;
7658
+ }
7659
+ index += 1;
7660
+ if (/[0-7]/.test(next)) {
7661
+ let octal = next;
7662
+ while (octal.length < 3 && /[0-7]/.test(body[index + 1] ?? "")) {
7663
+ index += 1;
7664
+ octal += body[index];
7665
+ }
7666
+ bytes.push(Number.parseInt(octal, 8) & 255);
7667
+ continue;
7668
+ }
7669
+ flushBytes();
7670
+ out += escapes[next] ?? next;
7671
+ }
7672
+ flushBytes();
7673
+ return out;
7674
+ }
7675
+ function wholeLinePath(value, prefix) {
7676
+ const withoutTimestamp = value.endsWith(" ") ? value.slice(0, -1) : value;
7677
+ const unquoted = unquoteGitPath(withoutTimestamp);
7678
+ if (unquoted === "/dev/null") return null;
7679
+ if (!unquoted.startsWith(prefix)) return null;
7680
+ return unquoted.slice(prefix.length);
7681
+ }
7682
+ function headerPaths(value) {
7683
+ const separator = value.lastIndexOf(" b/");
7684
+ if (separator <= 0) return [];
7685
+ const left = unquoteGitPath(value.slice(0, separator));
7686
+ const right = unquoteGitPath(value.slice(separator + 1));
7687
+ const paths = [];
7688
+ if (left.startsWith("a/")) paths.push(left.slice(2));
7689
+ if (right.startsWith("b/")) paths.push(right.slice(2));
7690
+ return paths;
7691
+ }
7469
7692
  function diffSectionPaths(body) {
7470
7693
  const paths = /* @__PURE__ */ new Set();
7694
+ let header = null;
7471
7695
  for (const line of body.split("\n")) {
7472
- const plus = /^\+\+\+ b\/(.*)$/.exec(line);
7473
- if (plus !== null) paths.add(plus[1]);
7474
- const minus = /^--- a\/(.*)$/.exec(line);
7475
- if (minus !== null) paths.add(minus[1]);
7476
- const header = /^diff --git a\/(.*?) b\/(.*)$/.exec(line);
7477
- if (header !== null) {
7478
- paths.add(header[1]);
7479
- paths.add(header[2]);
7696
+ if (line.startsWith("diff --git ")) {
7697
+ header = line.slice("diff --git ".length);
7698
+ continue;
7480
7699
  }
7700
+ if (line.startsWith("+++ ")) {
7701
+ const path26 = wholeLinePath(line.slice(4), "b/");
7702
+ if (path26 !== null) paths.add(path26);
7703
+ continue;
7704
+ }
7705
+ if (line.startsWith("--- ")) {
7706
+ const path26 = wholeLinePath(line.slice(4), "a/");
7707
+ if (path26 !== null) paths.add(path26);
7708
+ }
7709
+ }
7710
+ if (paths.size === 0 && header !== null) {
7711
+ for (const path26 of headerPaths(header)) paths.add(path26);
7481
7712
  }
7482
7713
  return [...paths];
7483
7714
  }
@@ -7487,6 +7718,7 @@ function generateDiffReport(cwd, options = {}) {
7487
7718
  const sections = [];
7488
7719
  let truncated = false;
7489
7720
  let omittedSensitive = 0;
7721
+ let omittedUnparseable = 0;
7490
7722
  const commands = [
7491
7723
  ["Unstaged", ["diff", "--no-color"]],
7492
7724
  ["Staged", ["diff", "--cached", "--no-color"]]
@@ -7497,6 +7729,10 @@ function generateDiffReport(cwd, options = {}) {
7497
7729
  const rawSections = result.out.split(/(?=^diff --git )/m).filter((section) => section.length > 0);
7498
7730
  for (const rawSection of rawSections) {
7499
7731
  const paths2 = diffSectionPaths(rawSection);
7732
+ if (paths2.length === 0) {
7733
+ omittedUnparseable += 1;
7734
+ continue;
7735
+ }
7500
7736
  const blocked = paths2.some((path26) => isSensitivePath(path26) || options.excluded?.(path26) === true);
7501
7737
  if (blocked) {
7502
7738
  omittedSensitive += 1;
@@ -7508,7 +7744,13 @@ function generateDiffReport(cwd, options = {}) {
7508
7744
  truncated = true;
7509
7745
  break;
7510
7746
  }
7511
- const chunk = truncateToBytes(rawSection, remaining);
7747
+ const sourcePath = paths2[0] ?? "reports/diff.md";
7748
+ const redactedSection = scanAndRedactSecrets(
7749
+ rawSection,
7750
+ options.secretRules ?? [],
7751
+ sourcePath
7752
+ ).redacted;
7753
+ const chunk = truncateToBytes(redactedSection, remaining);
7512
7754
  if (chunk.isTruncated) truncated = true;
7513
7755
  sections.push(
7514
7756
  "## " + title + " changes\n\nRun: git " + args.join(" ") + "\n\n```diff\n" + chunk.content + "\n```"
@@ -7529,6 +7771,10 @@ function generateDiffReport(cwd, options = {}) {
7529
7771
  "> " + omittedSensitive + " file section(s) omitted: their path is credential-bearing or excluded from the snapshot.",
7530
7772
  ""
7531
7773
  ] : [],
7774
+ ...omittedUnparseable > 0 ? [
7775
+ "> " + omittedUnparseable + " file section(s) omitted: their diff header could not be attributed to a path, so the sensitive-path filter could not run.",
7776
+ ""
7777
+ ] : [],
7532
7778
  ...sections,
7533
7779
  ...truncated ? ["", "> Truncated at " + maxBytes + " bytes. Run git diff for the rest."] : [],
7534
7780
  ""
@@ -7564,28 +7810,39 @@ function generateLogReport(cwd, options = {}) {
7564
7810
  }
7565
7811
 
7566
7812
  // src/generator/tokens.ts
7813
+ function cell2(value) {
7814
+ return escapeControls(value).replace(/\r?\n/g, " ").replace(/\|/g, "\\|");
7815
+ }
7816
+ function byCodeUnit(left, right) {
7817
+ return left < right ? -1 : left > right ? 1 : 0;
7818
+ }
7567
7819
  function tokensOf2(bytes) {
7568
7820
  return Math.max(1, Math.ceil(bytes * 0.25));
7569
7821
  }
7570
7822
  function generateTokenTree(manifest) {
7571
7823
  if (manifest.files.length === 0) return null;
7572
- 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));
7824
+ 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));
7573
7825
  const byDirectory = /* @__PURE__ */ new Map();
7574
7826
  for (const row of rows) {
7575
7827
  const directory = row.path.includes("/") ? row.path.slice(0, row.path.lastIndexOf("/")) : ".";
7576
7828
  byDirectory.set(directory, (byDirectory.get(directory) ?? 0) + row.tokens);
7577
7829
  }
7578
- const directories = [...byDirectory.entries()].sort((left, right) => right[1] - left[1]);
7830
+ const directories = [...byDirectory.entries()].sort(
7831
+ (left, right) => right[1] - left[1] || byCodeUnit(left[0], right[0])
7832
+ );
7579
7833
  const total = rows.reduce((sum, row) => sum + row.tokens, 0);
7580
- const rowsTable = rows.map((row) => "| " + row.path + " | " + row.layer + " | " + row.part + " | " + row.tokens + " |");
7834
+ const rowsTable = rows.map(
7835
+ (row) => "| " + cell2(row.path) + " | " + cell2(row.layer) + " | " + cell2(row.part) + " | " + row.tokens + " |"
7836
+ );
7581
7837
  const directoryTable = directories.map(
7582
- (entry) => "| " + entry[0] + " | " + entry[1] + " | " + (entry[1] / total * 100).toFixed(1) + "% |"
7838
+ (entry) => "| " + cell2(entry[0]) + " | " + entry[1] + " | " + (entry[1] / total * 100).toFixed(1) + "% |"
7583
7839
  );
7584
7840
  const text2 = [
7585
7841
  "# Token tree",
7586
7842
  "",
7587
- "Estimated tokens per file (one token per four bytes of emitted body), sorted by cost. The total",
7588
- "is the same estimate the manifest carries: an estimate, not a count.",
7843
+ "Estimated tokens per file (one token per four bytes of emitted body), sorted by cost. Each",
7844
+ "row is an estimate; the manifest total is estimated from the assembled parts, so the two can",
7845
+ "differ slightly and neither is a tokenizer count.",
7589
7846
  "",
7590
7847
  "## Directories",
7591
7848
  "",
@@ -7787,7 +8044,9 @@ function systemSection(manifest, code, brief, escape, sawManifest) {
7787
8044
  if (brief?.system !== void 0) {
7788
8045
  out.push(...ownerBlock(brief.system, brief.path, code, escape), "", "What the index records:", "");
7789
8046
  }
7790
- const layers = Object.entries(manifest.layers).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
8047
+ const layers = Object.entries(manifest.layers).sort(
8048
+ (a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)
8049
+ );
7791
8050
  if (layers.length > 0) {
7792
8051
  const shown = layers.slice(0, MAX_LAYER_ROWS).map(([name, count]) => code(name) + " " + formatNumber(count));
7793
8052
  const rest = layers.length > MAX_LAYER_ROWS ? ", and " + formatNumber(layers.length - MAX_LAYER_ROWS) + " more" : "";
@@ -7905,7 +8164,7 @@ function coverageSection(manifest, code, auditWritten, partsWritten, sawManifest
7905
8164
  for (const record of manifest.skipped) {
7906
8165
  reasons.set(record.reason, (reasons.get(record.reason) ?? 0) + 1);
7907
8166
  }
7908
- const tally = [...reasons.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([reason, count]) => code(reason) + " " + formatNumber(count)).join(", ");
8167
+ 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(", ");
7909
8168
  const found = manifest.totals.candidateFiles;
7910
8169
  const included = manifest.totals.includedFiles;
7911
8170
  const skipped = manifest.counts.skippedCount;
@@ -8032,7 +8291,7 @@ function ownerNotesSection(brief, code, text2) {
8032
8291
  if (brief === void 0 || brief.notes.length === 0) return [];
8033
8292
  const out = ["## Owner notes", ""];
8034
8293
  for (const note of brief.notes) {
8035
- out.push("### " + note.heading, "", ...ownerBlock(note.body, brief.path, code, text2), "");
8294
+ out.push("### " + text2(note.heading), "", ...ownerBlock(note.body, brief.path, code, text2), "");
8036
8295
  }
8037
8296
  return out;
8038
8297
  }
@@ -8253,27 +8512,31 @@ function generateReadme(manifest, artifacts) {
8253
8512
  const readOrder = [];
8254
8513
  if (wrote("prompt")) {
8255
8514
  readOrder.push(
8256
- "1. Hand `PROMPT.md` to the model that receives this snapshot: it names the parts, the partial files and the fingerprint of this run."
8515
+ "Hand `PROMPT.md` to the model that receives this snapshot: it names the parts, the partial files and the fingerprint of this run."
8257
8516
  );
8258
8517
  }
8259
8518
  if (wrote("navigation") || wrote("projectTree")) {
8260
8519
  const first = [wrote("navigation") ? "`reports/navigation.md`" : null, wrote("projectTree") ? "`reports/project-tree.md`" : null].filter(Boolean).join(" or ");
8261
- readOrder.push(`1. Read ${first} first to locate target features or files.`);
8520
+ readOrder.push(`Read ${first} first to locate target features or files.`);
8262
8521
  }
8263
8522
  if (wrote("parts")) {
8264
8523
  readOrder.push(
8265
- `${readOrder.length + 1}. Open only the specific \`parts/part-XXX.md\` file holding the target modules.`
8524
+ "Open only the specific `parts/part-XXX.md` file holding the target modules."
8266
8525
  );
8267
8526
  }
8268
8527
  if (wrote("manifest")) {
8269
- readOrder.push(
8270
- `${readOrder.length + 1}. Inspect \`manifest.json\` for precise dependency and AST symbol maps.`
8271
- );
8528
+ readOrder.push("Inspect `manifest.json` for precise dependency and AST symbol maps.");
8272
8529
  }
8273
8530
  readOrder.push(
8274
- wrote("manifest") ? `${readOrder.length + 1}. Check \`manifest.validation.status\` before trusting the snapshot; \`snapshot validate\` re-checks it against disk.` : `${readOrder.length + 1}. No manifest was written, so this snapshot cannot be re-checked; regenerate with the manifest artifact enabled before trusting it.`
8531
+ wrote("manifest") ? "Check `manifest.validation.status` before trusting the snapshot; `snapshot validate` re-checks it against disk." : "No manifest was written, so this snapshot cannot be re-checked; regenerate with the manifest artifact enabled before trusting it."
8532
+ );
8533
+ lines.push(
8534
+ "",
8535
+ "## AI Agent Ingestion Guide",
8536
+ "",
8537
+ ...readOrder.map((step, index) => `${index + 1}. ${step}`),
8538
+ ""
8275
8539
  );
8276
- lines.push("", "## AI Agent Ingestion Guide", "", ...readOrder, "");
8277
8540
  return lines.join("\n");
8278
8541
  }
8279
8542
 
@@ -8496,6 +8759,10 @@ function tsconfigPathsFor(cwd) {
8496
8759
  return null;
8497
8760
  }
8498
8761
  const key = `${stats.mtimeMs}:${stats.size}`;
8762
+ if (!TSCONFIG_CACHE.has(configPath) && TSCONFIG_CACHE.size >= 64) {
8763
+ const oldest = TSCONFIG_CACHE.keys().next().value;
8764
+ if (oldest !== void 0) TSCONFIG_CACHE.delete(oldest);
8765
+ }
8499
8766
  const cached = TSCONFIG_CACHE.get(configPath);
8500
8767
  if (cached !== void 0 && cached.key === key) return cached.value;
8501
8768
  let value = null;
@@ -8524,8 +8791,8 @@ function tsconfigPathsFor(cwd) {
8524
8791
  return value;
8525
8792
  }
8526
8793
  function repositoryRelative(cwd, target) {
8527
- const relative14 = path25__namespace.relative(cwd, target).replace(/\\/g, "/");
8528
- return relative14.length === 0 || !relative14.startsWith("..") && !path25__namespace.isAbsolute(relative14) ? relative14 : null;
8794
+ const relative15 = path25__namespace.relative(cwd, target).replace(/\\/g, "/");
8795
+ return relative15.length === 0 || !relative15.startsWith("..") && !path25__namespace.isAbsolute(relative15) ? relative15 : null;
8529
8796
  }
8530
8797
  function rememberFirst(map, key, value) {
8531
8798
  if (!map.has(key)) map.set(key, value);
@@ -8655,6 +8922,77 @@ function importsChangedFile(importerPath, imports, changedPaths, resolver) {
8655
8922
  }
8656
8923
  return false;
8657
8924
  }
8925
+ function isInside2(parent, child) {
8926
+ const relative15 = path25__namespace.relative(parent, child);
8927
+ return relative15 === "" || !relative15.startsWith("..") && !path25__namespace.isAbsolute(relative15);
8928
+ }
8929
+ function resolveConfined(baseDir, relativePath) {
8930
+ if (relativePath.length === 0 || relativePath.includes("\0")) {
8931
+ return { ok: false, reason: "not-file", message: "the file name is empty or contains a NUL byte" };
8932
+ }
8933
+ if (path25__namespace.isAbsolute(relativePath)) {
8934
+ return { ok: false, reason: "outside", message: "an absolute path is not a snapshot-relative file" };
8935
+ }
8936
+ let baseReal;
8937
+ try {
8938
+ baseReal = fs24__namespace.realpathSync(path25__namespace.resolve(baseDir));
8939
+ } catch {
8940
+ return { ok: false, reason: "missing", message: "the snapshot directory does not exist" };
8941
+ }
8942
+ const candidate = path25__namespace.resolve(baseReal, relativePath);
8943
+ if (!isInside2(baseReal, candidate)) {
8944
+ return { ok: false, reason: "outside", message: "the path resolves outside the snapshot directory" };
8945
+ }
8946
+ let stats;
8947
+ try {
8948
+ stats = fs24__namespace.lstatSync(candidate);
8949
+ } catch (error) {
8950
+ const code = error.code;
8951
+ return {
8952
+ ok: false,
8953
+ reason: code === "ENOENT" || code === "ENOTDIR" ? "missing" : "unreadable",
8954
+ message: code === "ENOENT" || code === "ENOTDIR" ? "the file does not exist" : "the file could not be inspected"
8955
+ };
8956
+ }
8957
+ if (stats.isSymbolicLink()) {
8958
+ return { ok: false, reason: "not-file", message: "the file is a symbolic link" };
8959
+ }
8960
+ if (!stats.isFile()) {
8961
+ return { ok: false, reason: "not-file", message: "the path is not a regular file" };
8962
+ }
8963
+ let real;
8964
+ try {
8965
+ real = fs24__namespace.realpathSync(candidate);
8966
+ } catch {
8967
+ return { ok: false, reason: "unreadable", message: "the file could not be resolved" };
8968
+ }
8969
+ if (!isInside2(baseReal, real)) {
8970
+ return { ok: false, reason: "outside", message: "the file resolves outside the snapshot directory" };
8971
+ }
8972
+ return { ok: true, path: real, stats };
8973
+ }
8974
+ function readConfinedBytes(baseDir, relativePath) {
8975
+ const resolved = resolveConfined(baseDir, relativePath);
8976
+ if (!resolved.ok) return resolved;
8977
+ try {
8978
+ const bytes = fs24__namespace.readFileSync(resolved.path);
8979
+ return { ok: true, bytes, path: resolved.path, stats: fs24__namespace.statSync(resolved.path) };
8980
+ } catch {
8981
+ return { ok: false, reason: "unreadable", message: "the file could not be read" };
8982
+ }
8983
+ }
8984
+ function readConfinedText(baseDir, relativePath) {
8985
+ const resolved = resolveConfined(baseDir, relativePath);
8986
+ if (!resolved.ok) return resolved;
8987
+ try {
8988
+ const text2 = fs24__namespace.readFileSync(resolved.path, "utf8");
8989
+ return { ok: true, text: text2, path: resolved.path, stats: fs24__namespace.statSync(resolved.path) };
8990
+ } catch {
8991
+ return { ok: false, reason: "unreadable", message: "the file could not be read" };
8992
+ }
8993
+ }
8994
+
8995
+ // src/generator/overview.ts
8658
8996
  var SUMMARY_LIMIT = 400;
8659
8997
  var MAX_RELEASES = 2;
8660
8998
  function readProjectOverview(cwd) {
@@ -8664,15 +9002,12 @@ function readProjectOverview(cwd) {
8664
9002
  releases: readReleases(cwd)
8665
9003
  };
8666
9004
  }
8667
- function readText(file) {
8668
- try {
8669
- return fs24__namespace.readFileSync(file, "utf8");
8670
- } catch {
8671
- return null;
8672
- }
9005
+ function readText(cwd, relative15) {
9006
+ const read = readConfinedText(cwd, relative15);
9007
+ return read.ok ? read.text : null;
8673
9008
  }
8674
9009
  function readDescription(cwd) {
8675
- const raw = readText(path25__namespace.join(cwd, "package.json"));
9010
+ const raw = readText(cwd, "package.json");
8676
9011
  if (raw === null) return {};
8677
9012
  try {
8678
9013
  const parsed = JSON.parse(stripJsonComments(raw));
@@ -8682,7 +9017,7 @@ function readDescription(cwd) {
8682
9017
  }
8683
9018
  }
8684
9019
  function readSummary(cwd) {
8685
- const raw = readText(path25__namespace.join(cwd, "README.md"));
9020
+ const raw = readText(cwd, "README.md");
8686
9021
  if (raw === null) return {};
8687
9022
  const text2 = raw.replace(/<h[1-6][^>]*>[\s\S]*?<\/h[1-6]>/gi, "\n").replace(/<\/(p|div|section|header|footer|li)>/gi, "\n").replace(/<br\s*\/?>/gi, " ").replace(/<[^>]*>/g, " ").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'");
8688
9023
  const paragraph = [];
@@ -8708,7 +9043,7 @@ function truncate(text2, limit) {
8708
9043
  return (space > limit / 2 ? window.slice(0, space) : window).trim() + "\u2026";
8709
9044
  }
8710
9045
  function readReleases(cwd) {
8711
- const raw = readText(path25__namespace.join(cwd, "CHANGELOG.md"));
9046
+ const raw = readText(cwd, "CHANGELOG.md");
8712
9047
  if (raw === null) return [];
8713
9048
  const headings = raw.split(/\r?\n/).map((line) => /^##\s+(.+?)\s*$/.exec(line)?.[1]?.trim()).filter((heading) => heading !== void 0 && /^v?\d+\.\d+/.test(heading));
8714
9049
  return headings.slice(0, MAX_RELEASES);
@@ -9026,6 +9361,9 @@ function describeManifestShapeProblem(value) {
9026
9361
  if (typeof fields.relativePath !== "string") {
9027
9362
  return 'a "files" entry has no "relativePath"';
9028
9363
  }
9364
+ if (!isConfinedRelative(fields.relativePath)) {
9365
+ return 'a "files" entry "relativePath" resolves outside the repository and was not inspected';
9366
+ }
9029
9367
  if (!currentSchema) continue;
9030
9368
  if (typeof fields.part !== "string" || fields.part.length === 0) {
9031
9369
  return 'a "files" entry records no "part"';
@@ -9044,6 +9382,18 @@ function describeManifestShapeProblem(value) {
9044
9382
  }
9045
9383
  }
9046
9384
  if (!Array.isArray(candidate.skipped)) return 'missing "skipped" array';
9385
+ for (const entry of candidate.skipped) {
9386
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
9387
+ return 'a "skipped" entry is not an object';
9388
+ }
9389
+ const fields = entry;
9390
+ if (typeof fields.path !== "string" || !isConfinedRelative(fields.path)) {
9391
+ return 'a "skipped" entry "path" resolves outside the repository and was not inspected';
9392
+ }
9393
+ if (typeof fields.reason !== "string" || fields.reason.length === 0) {
9394
+ return 'a "skipped" entry has no "reason"';
9395
+ }
9396
+ }
9047
9397
  if (!Array.isArray(candidate.parts)) return 'missing "parts" array';
9048
9398
  for (const entry of candidate.parts) {
9049
9399
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
@@ -9104,10 +9454,12 @@ function validateSnapshot(configInput) {
9104
9454
  }
9105
9455
  const shapeProblem = describeManifestShapeProblem(manifest);
9106
9456
  if (shapeProblem) {
9457
+ const drift2 = emptyDrift();
9458
+ drift2.partIssues.push({ part: "manifest.json", issue: shapeProblem });
9107
9459
  return {
9108
9460
  valid: false,
9109
9461
  manifestPresent: true,
9110
- drift: emptyDrift(),
9462
+ drift: drift2,
9111
9463
  errors: [`${manifestPath} is not a snapshot manifest: ${shapeProblem}`],
9112
9464
  warnings: []
9113
9465
  };
@@ -9236,12 +9588,16 @@ function validateSnapshot(configInput) {
9236
9588
  // discovery mode" meant `validate` could enumerate files one way while the snapshot
9237
9589
  // had been generated another way, and then blame the difference on drift.
9238
9590
  discovery: config.discovery,
9591
+ // `generate --staged` adds index-only paths to the candidate list. Without the same
9592
+ // extra paths, a staged file that is absent from the working tree was invisible to
9593
+ // this scan and then reported as deleted, although the snapshot matched the index.
9594
+ ...stagedScope === null ? {} : { extraPaths: [...stagedScope] },
9239
9595
  // The same exclusion `generate` applies: without it, `validate` recounted the tool's
9240
9596
  // own output directory as a set of files missing from the snapshot, so a correct
9241
9597
  // snapshot was reported as drifting.
9242
9598
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
9243
9599
  (directory) => path25__namespace.relative(config.cwd, path25__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
9244
- ).filter((relative14) => relative14.length > 0 && !relative14.startsWith(".."))
9600
+ ).filter((relative15) => relative15.length > 0 && !relative15.startsWith(".."))
9245
9601
  });
9246
9602
  for (const diskFile of collection.files) {
9247
9603
  const snapshotHash = manifestFileMap.get(diskFile);
@@ -9282,6 +9638,12 @@ function validateSnapshot(configInput) {
9282
9638
  }
9283
9639
  }
9284
9640
  for (const snapshotFile of manifestFileMap.keys()) {
9641
+ if (recordedStaged && stagedScope?.has(snapshotFile)) {
9642
+ if (readStagedBlob(config.cwd, snapshotFile) === null) {
9643
+ drift.missingOnDisk.push(snapshotFile);
9644
+ }
9645
+ continue;
9646
+ }
9285
9647
  const confined = confineToDirectory(config.cwd, snapshotFile);
9286
9648
  if (confined === null) {
9287
9649
  drift.partIssues.push({
@@ -9325,13 +9687,15 @@ function validateSnapshot(configInput) {
9325
9687
  });
9326
9688
  continue;
9327
9689
  }
9328
- let buffer;
9329
- try {
9330
- buffer = fs24__namespace.readFileSync(partPath);
9331
- } catch {
9332
- drift.partIssues.push({ part: part.filename, issue: "missing from snapshot/parts" });
9690
+ const partRead = readConfinedBytes(partsDir, part.filename);
9691
+ if (!partRead.ok) {
9692
+ drift.partIssues.push({
9693
+ part: part.filename,
9694
+ issue: `missing or not a regular file in snapshot/parts (${partRead.reason})`
9695
+ });
9333
9696
  continue;
9334
9697
  }
9698
+ const buffer = partRead.bytes;
9335
9699
  if (buffer.length !== part.byteSize) {
9336
9700
  drift.partIssues.push({
9337
9701
  part: part.filename,
@@ -9704,15 +10068,15 @@ function validateSnapshot(configInput) {
9704
10068
  ];
9705
10069
  for (const [key, artifact] of declaredArtifacts) {
9706
10070
  if (!artifact) continue;
9707
- const artifactPath = path25__namespace.join(snapshotDir, ...key.split("/"));
9708
- let buffer;
9709
- try {
9710
- if (!fs24__namespace.statSync(artifactPath).isFile()) throw new Error("not a regular file");
9711
- buffer = fs24__namespace.readFileSync(artifactPath);
9712
- } catch {
9713
- drift.partIssues.push({ part: key, issue: "declared artifact is missing" });
10071
+ const artifactRead = readConfinedBytes(snapshotDir, key);
10072
+ if (!artifactRead.ok) {
10073
+ drift.partIssues.push({
10074
+ part: key,
10075
+ issue: `declared artifact is missing or not a regular file (${artifactRead.reason})`
10076
+ });
9714
10077
  continue;
9715
10078
  }
10079
+ const buffer = artifactRead.bytes;
9716
10080
  if (sha256Hex(buffer) !== artifact.sha256 || buffer.length !== artifact.byteSize) {
9717
10081
  drift.partIssues.push({ part: key, issue: "artifact does not match its recorded digest" });
9718
10082
  continue;
@@ -9722,8 +10086,8 @@ function validateSnapshot(configInput) {
9722
10086
  const target = match[1].split("#")[0];
9723
10087
  if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
9724
10088
  const resolved = path25__namespace.resolve(snapshotDir, "reports", target);
9725
- const relative14 = path25__namespace.relative(snapshotDir, resolved);
9726
- if (relative14.startsWith("..") || path25__namespace.isAbsolute(relative14) || !fs24__namespace.existsSync(resolved)) {
10089
+ const relative15 = path25__namespace.relative(snapshotDir, resolved);
10090
+ if (relative15.startsWith("..") || path25__namespace.isAbsolute(relative15) || !fs24__namespace.existsSync(resolved)) {
9727
10091
  drift.partIssues.push({
9728
10092
  part: key,
9729
10093
  issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
@@ -9735,13 +10099,11 @@ function validateSnapshot(configInput) {
9735
10099
  const sarifArtifact = manifest.artifacts?.sarif;
9736
10100
  if (sarifArtifact) {
9737
10101
  const sarifKey = "reports/audit.sarif";
9738
- try {
9739
- const buffer = fs24__namespace.readFileSync(path25__namespace.join(snapshotDir, "reports", "audit.sarif"));
9740
- if (sha256Hex(buffer) !== sarifArtifact.sha256 || buffer.length !== sarifArtifact.byteSize) {
9741
- drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
9742
- }
9743
- } catch {
9744
- drift.partIssues.push({ part: sarifKey, issue: "declared artifact is missing" });
10102
+ const sarifRead = readConfinedBytes(snapshotDir, "reports/audit.sarif");
10103
+ if (!sarifRead.ok) {
10104
+ drift.partIssues.push({ part: sarifKey, issue: "declared artifact is missing or not a regular file" });
10105
+ } else if (sha256Hex(sarifRead.bytes) !== sarifArtifact.sha256 || sarifRead.bytes.length !== sarifArtifact.byteSize) {
10106
+ drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
9745
10107
  }
9746
10108
  }
9747
10109
  if (manifest.git && manifest.git.branch && manifest.git.branch !== config.branch) {
@@ -9890,9 +10252,11 @@ function isPrivateIPv6(groups) {
9890
10252
  ]);
9891
10253
  if (allZeroThrough(5) && sixth === 65535) return mapped(6);
9892
10254
  if (allZeroThrough(6) && (seventh !== 0 || eighth !== 0)) return mapped(6);
10255
+ if (allZeroThrough(4) && fifth === 65535 && sixth === 0) return mapped(6);
9893
10256
  if (first === 100 && second === 65435 && third === 0 && fourth === 0 && fifth === 0 && sixth === 0) {
9894
10257
  return mapped(6);
9895
10258
  }
10259
+ if (first === 100 && second === 65435 && third === 1) return mapped(6);
9896
10260
  if (first === 8194) return mapped(1);
9897
10261
  return false;
9898
10262
  }
@@ -10006,61 +10370,69 @@ async function cloneRepository(source, options) {
10006
10370
  const dest = path25__namespace.resolve(options.dest);
10007
10371
  fs24__namespace.rmSync(dest, { recursive: true, force: true });
10008
10372
  fs24__namespace.mkdirSync(dest, { recursive: true });
10009
- const ref = options.ref ?? source.ref;
10010
- const args = [
10011
- "-c",
10012
- "http.followRedirects=false",
10013
- ...source.kind === "https" ? ["-c", "protocol.file.allow=never", "-c", "protocol.ssh.allow=never"] : [],
10014
- "clone",
10015
- "--depth",
10016
- "1",
10017
- "--single-branch",
10018
- "--no-tags",
10019
- "--quiet"
10020
- ];
10021
- if (ref !== void 0 && ref !== null && ref !== "") {
10022
- args.push("--branch", ref);
10023
- }
10024
- args.push(source.url, dest);
10025
- log("clone: " + source.url + (ref ? " (" + ref + ")" : ""));
10026
- const started = Date.now();
10027
- const result = childProcess.spawnSync("git", args, {
10028
- env: {
10029
- ...gitEnvironment(options.token, source.host === "file" ? "localhost" : source.host),
10030
- ...source.kind === "https" ? { GIT_ALLOW_PROTOCOL: "https" } : {}
10031
- },
10032
- timeout: options.timeoutMs ?? 18e4,
10033
- encoding: "utf8",
10034
- windowsHide: true
10035
- });
10036
- if (result.error !== void 0 && result.error !== null) {
10037
- throw new Error("git clone could not run: " + result.error.message);
10038
- }
10039
- if (result.status !== 0) {
10040
- const detail = (result.stderr ?? "").trim().split("\n").slice(-3).join(" ");
10041
- throw new Error("git clone failed (exit " + result.status + "): " + (detail || "no output"));
10042
- }
10043
- const head = childProcess.spawnSync("git", ["-C", dest, "rev-parse", "HEAD"], { encoding: "utf8", windowsHide: true });
10044
- const commit = head.status === 0 ? (head.stdout ?? "").trim() : "";
10045
- if (commit === "") throw new Error("the clone has no HEAD; refusing to describe it");
10046
- const bytes = directorySize(dest);
10047
- log("clone: " + (bytes / 1024 / 1024).toFixed(1) + " MB in " + ((Date.now() - started) / 1e3).toFixed(1) + "s");
10048
- if (bytes > 1e9) {
10049
- throw new Error("the clone is larger than 1 GB (" + Math.round(bytes / 1024 / 1024) + " MB); refusing to scan it");
10050
- }
10051
- return {
10052
- directory: dest,
10053
- commit,
10054
- provenance: {
10055
- url: source.url,
10056
- host: source.host,
10057
- owner: source.owner,
10058
- repo: source.repo,
10059
- ref: ref !== void 0 && ref !== null && ref !== "" ? ref : null,
10373
+ try {
10374
+ const ref = options.ref ?? source.ref;
10375
+ const args = [
10376
+ "-c",
10377
+ "http.followRedirects=false",
10378
+ ...source.kind === "https" ? ["-c", "protocol.file.allow=never", "-c", "protocol.ssh.allow=never"] : [],
10379
+ "clone",
10380
+ "--depth",
10381
+ "1",
10382
+ "--single-branch",
10383
+ "--no-tags",
10384
+ "--quiet"
10385
+ ];
10386
+ if (ref !== void 0 && ref !== null && ref !== "") {
10387
+ args.push("--branch", ref);
10388
+ }
10389
+ args.push(source.url, dest);
10390
+ log("clone: " + source.url + (ref ? " (" + ref + ")" : ""));
10391
+ const started = Date.now();
10392
+ const result = childProcess.spawnSync("git", args, {
10393
+ env: {
10394
+ ...gitEnvironment(options.token, source.host === "file" ? "localhost" : source.host),
10395
+ ...source.kind === "https" ? { GIT_ALLOW_PROTOCOL: "https" } : {}
10396
+ },
10397
+ timeout: options.timeoutMs ?? 18e4,
10398
+ encoding: "utf8",
10399
+ windowsHide: true
10400
+ });
10401
+ if (result.error !== void 0 && result.error !== null) {
10402
+ throw new Error("git clone could not run: " + result.error.message);
10403
+ }
10404
+ if (result.status !== 0) {
10405
+ const detail = (result.stderr ?? "").trim().split("\n").slice(-3).join(" ");
10406
+ throw new Error("git clone failed (exit " + result.status + "): " + (detail || "no output"));
10407
+ }
10408
+ const head = childProcess.spawnSync("git", ["-C", dest, "rev-parse", "HEAD"], { encoding: "utf8", windowsHide: true });
10409
+ const commit = head.status === 0 ? (head.stdout ?? "").trim() : "";
10410
+ if (commit === "") throw new Error("the clone has no HEAD; refusing to describe it");
10411
+ const bytes = directorySize(dest);
10412
+ log("clone: " + (bytes / 1024 / 1024).toFixed(1) + " MB in " + ((Date.now() - started) / 1e3).toFixed(1) + "s");
10413
+ if (bytes > 1e9) {
10414
+ throw new Error("the clone is larger than 1 GB (" + Math.round(bytes / 1024 / 1024) + " MB); refusing to scan it");
10415
+ }
10416
+ return {
10417
+ directory: dest,
10060
10418
  commit,
10061
- fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
10419
+ provenance: {
10420
+ url: source.url,
10421
+ host: source.host,
10422
+ owner: source.owner,
10423
+ repo: source.repo,
10424
+ ref: ref !== void 0 && ref !== null && ref !== "" ? ref : null,
10425
+ commit,
10426
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
10427
+ }
10428
+ };
10429
+ } catch (error) {
10430
+ try {
10431
+ fs24__namespace.rmSync(dest, { recursive: true, force: true });
10432
+ } catch {
10062
10433
  }
10063
- };
10434
+ throw error;
10435
+ }
10064
10436
  }
10065
10437
  function directorySize(root) {
10066
10438
  let total = 0;
@@ -10285,7 +10657,7 @@ var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
10285
10657
  var META_PREFIX = "- Meta: ";
10286
10658
  var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
10287
10659
  var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
10288
- var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
10660
+ var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures", "comments-stripped"]);
10289
10661
  var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
10290
10662
  function readIncludedLines(fields) {
10291
10663
  const last = fields[fields.length - 1];
@@ -10380,17 +10752,10 @@ var ARTIFACT_FILES = {
10380
10752
  fullXml: "full-codebase.xml",
10381
10753
  sarif: "reports/audit.sarif"
10382
10754
  };
10383
- var TEXT_ARTIFACT = /\.(md|json|txt|sarif)$/i;
10755
+ var TEXT_ARTIFACT = /\.(md|json|txt|sarif|xml)$/i;
10384
10756
  function sha256(buffer) {
10385
10757
  return crypto.createHash("sha256").update(buffer).digest("hex");
10386
10758
  }
10387
- function readBytes(file) {
10388
- try {
10389
- return fs24__namespace.readFileSync(file);
10390
- } catch {
10391
- return null;
10392
- }
10393
- }
10394
10759
  function readText2(file) {
10395
10760
  try {
10396
10761
  return fs24__namespace.readFileSync(file, "utf8");
@@ -10398,8 +10763,17 @@ function readText2(file) {
10398
10763
  return null;
10399
10764
  }
10400
10765
  }
10766
+ function snapshotText(snapshotDir, relative15) {
10767
+ const read = readConfinedText(snapshotDir, relative15);
10768
+ return read.ok ? read.text : null;
10769
+ }
10770
+ function snapshotBytes(snapshotDir, relative15) {
10771
+ const read = readConfinedBytes(snapshotDir, relative15);
10772
+ return read.ok ? read.bytes : null;
10773
+ }
10401
10774
  function readJson(file) {
10402
- const text2 = readText2(file);
10775
+ const confined = readConfinedText(path25__namespace.dirname(file), path25__namespace.basename(file));
10776
+ const text2 = confined.ok ? confined.text : null;
10403
10777
  if (text2 === null) return null;
10404
10778
  try {
10405
10779
  return JSON.parse(text2);
@@ -10416,9 +10790,9 @@ function walk(dir, prefix = "") {
10416
10790
  }
10417
10791
  const files = [];
10418
10792
  for (const entry of entries) {
10419
- const relative14 = prefix === "" ? entry.name : prefix + "/" + entry.name;
10420
- if (entry.isDirectory()) files.push(...walk(path25__namespace.join(dir, entry.name), relative14));
10421
- else if (entry.isFile()) files.push(relative14);
10793
+ const relative15 = prefix === "" ? entry.name : prefix + "/" + entry.name;
10794
+ if (entry.isDirectory()) files.push(...walk(path25__namespace.join(dir, entry.name), relative15));
10795
+ else if (entry.isFile()) files.push(relative15);
10422
10796
  }
10423
10797
  return files;
10424
10798
  }
@@ -10456,16 +10830,28 @@ function secretTokens(text2) {
10456
10830
  }
10457
10831
  return [...tokens];
10458
10832
  }
10459
- function readArtifactTexts(snapshotDir) {
10833
+ function readArtifactTexts(snapshotDir, maxBytes = 32 * 1024 * 1024) {
10460
10834
  const texts = [];
10461
- for (const relative14 of walk(snapshotDir)) {
10462
- if (!TEXT_ARTIFACT.test(relative14)) continue;
10463
- const text2 = readText2(path25__namespace.join(snapshotDir, relative14));
10464
- if (text2 !== null) texts.push(text2);
10835
+ let bytes = 0;
10836
+ for (const relative15 of walk(snapshotDir)) {
10837
+ if (!TEXT_ARTIFACT.test(relative15)) continue;
10838
+ const full = path25__namespace.join(snapshotDir, relative15);
10839
+ let size2;
10840
+ try {
10841
+ size2 = fs24__namespace.statSync(full).size;
10842
+ } catch {
10843
+ continue;
10844
+ }
10845
+ if (bytes + size2 > maxBytes) break;
10846
+ const text2 = snapshotText(snapshotDir, relative15);
10847
+ if (text2 !== null) {
10848
+ texts.push(text2);
10849
+ bytes += Buffer.byteLength(text2, "utf8");
10850
+ }
10465
10851
  }
10466
10852
  return texts;
10467
10853
  }
10468
- function findHostPaths(snapshotDir, repoDir) {
10854
+ function findHostPaths(snapshotDir, repoDir, maxBytes = 32 * 1024 * 1024) {
10469
10855
  const patterns = [
10470
10856
  /\/home\/[A-Za-z0-9._-]+/g,
10471
10857
  /\/Users\/[A-Za-z0-9._-]+/g,
@@ -10476,15 +10862,24 @@ function findHostPaths(snapshotDir, repoDir) {
10476
10862
  ];
10477
10863
  const repoPattern = new RegExp(escapeRegExp(repoDir), "g");
10478
10864
  const hits = /* @__PURE__ */ new Set();
10479
- for (const relative14 of walk(snapshotDir)) {
10480
- if (!TEXT_ARTIFACT.test(relative14)) continue;
10481
- const text2 = readText2(path25__namespace.join(snapshotDir, relative14));
10865
+ let scanned = 0;
10866
+ for (const relative15 of walk(snapshotDir)) {
10867
+ if (!TEXT_ARTIFACT.test(relative15)) continue;
10868
+ let size2;
10869
+ try {
10870
+ size2 = fs24__namespace.statSync(path25__namespace.join(snapshotDir, relative15)).size;
10871
+ } catch {
10872
+ continue;
10873
+ }
10874
+ if (scanned + size2 > maxBytes) break;
10875
+ const text2 = snapshotText(snapshotDir, relative15);
10482
10876
  if (text2 === null) continue;
10877
+ scanned += Buffer.byteLength(text2, "utf8");
10483
10878
  for (const pattern of patterns) {
10484
- for (const match of text2.match(pattern) ?? []) hits.add(relative14 + ": " + match);
10879
+ for (const match of text2.match(pattern) ?? []) hits.add(relative15 + ": " + match);
10485
10880
  }
10486
10881
  repoPattern.lastIndex = 0;
10487
- if (repoPattern.test(text2)) hits.add(relative14 + ": the repository absolute path");
10882
+ if (repoPattern.test(text2)) hits.add(relative15 + ": the repository absolute path");
10488
10883
  }
10489
10884
  return [...hits];
10490
10885
  }
@@ -10666,7 +11061,7 @@ function auditSnapshot(options) {
10666
11061
  const missingParts = [];
10667
11062
  const mismatched = [];
10668
11063
  for (const part of manifest.parts) {
10669
- const bytes = readBytes(path25__namespace.join(snapshotDir, "parts", part.filename));
11064
+ const bytes = snapshotBytes(snapshotDir, "parts/" + part.filename);
10670
11065
  if (bytes === null) {
10671
11066
  missingParts.push(part.filename);
10672
11067
  continue;
@@ -10731,13 +11126,13 @@ function auditSnapshot(options) {
10731
11126
  let artifactCount = 0;
10732
11127
  for (const [key, value] of Object.entries(artifacts)) {
10733
11128
  if (value === null || value === void 0) continue;
10734
- const relative14 = ARTIFACT_FILES[key];
10735
- if (relative14 === void 0) continue;
11129
+ const relative15 = ARTIFACT_FILES[key];
11130
+ if (relative15 === void 0) continue;
10736
11131
  artifactCount += 1;
10737
- const bytes = readBytes(path25__namespace.join(snapshotDir, relative14));
10738
- if (bytes === null) artifactProblems.push(relative14 + " is missing");
11132
+ const bytes = snapshotBytes(snapshotDir, relative15);
11133
+ if (bytes === null) artifactProblems.push(relative15 + " is missing");
10739
11134
  else if (typeof value.sha256 === "string" && sha256(bytes) !== value.sha256) {
10740
- artifactProblems.push(relative14 + " changed");
11135
+ artifactProblems.push(relative15 + " changed");
10741
11136
  }
10742
11137
  }
10743
11138
  checks.push(
@@ -10847,7 +11242,7 @@ function auditSnapshot(options) {
10847
11242
  manifest.files.map((file) => [anchorForPath(file.relativePath), file.relativePath])
10848
11243
  );
10849
11244
  for (const part of manifest.parts) {
10850
- const partText = readText2(path25__namespace.join(snapshotDir, "parts", part.filename));
11245
+ const partText = snapshotText(snapshotDir, "parts/" + part.filename);
10851
11246
  if (partText === null) continue;
10852
11247
  const sections = parsePartSections(partText);
10853
11248
  partTexts.set(part.filename, partText);
@@ -10914,7 +11309,7 @@ function auditSnapshot(options) {
10914
11309
  }
10915
11310
  };
10916
11311
  if (manifest.artifacts?.readme != null) {
10917
- const text2 = readText2(path25__namespace.join(snapshotDir, "README.md"));
11312
+ const text2 = snapshotText(snapshotDir, "README.md");
10918
11313
  if (text2 === null) {
10919
11314
  reportProblems.push("README.md is recorded but unreadable");
10920
11315
  } else {
@@ -10954,7 +11349,7 @@ function auditSnapshot(options) {
10954
11349
  }
10955
11350
  }
10956
11351
  if (manifest.artifacts?.prompt != null) {
10957
- const text2 = readText2(path25__namespace.join(snapshotDir, "PROMPT.md"));
11352
+ const text2 = snapshotText(snapshotDir, "PROMPT.md");
10958
11353
  if (text2 === null) {
10959
11354
  reportProblems.push("PROMPT.md is recorded but unreadable");
10960
11355
  } else {
@@ -11143,7 +11538,7 @@ function auditSnapshot(options) {
11143
11538
  ];
11144
11539
  for (const reader of packReaders) {
11145
11540
  if (manifest.artifacts?.[reader.key] == null) continue;
11146
- const packText = readText2(path25__namespace.join(snapshotDir, reader.file));
11541
+ const packText = snapshotText(snapshotDir, reader.file);
11147
11542
  const problems = [];
11148
11543
  if (packText === null) {
11149
11544
  problems.push(reader.file + " is recorded but unreadable");
@@ -11193,7 +11588,7 @@ function auditSnapshot(options) {
11193
11588
  bodyByPath.set(file.relativePath, section.body);
11194
11589
  bodiesChecked += 1;
11195
11590
  const bytes = Buffer.byteLength(section.body, "utf8");
11196
- const bodyLines = section.body === "" ? 0 : section.body.split("\n").length - (section.body.endsWith("\n") ? 1 : 0);
11591
+ const bodyLines = countBodyLines(section.body);
11197
11592
  if (bytes !== file.includedBytes) {
11198
11593
  bodyProblems.push(file.relativePath + ": manifest says " + file.includedBytes + " B, part holds " + bytes + " B");
11199
11594
  } else if (bodyLines !== file.includedLines) {
@@ -11306,7 +11701,7 @@ function auditSnapshot(options) {
11306
11701
  let packBodies = 0;
11307
11702
  let packSkipped = 0;
11308
11703
  for (const pack of packsWanted) {
11309
- const text2 = readText2(path25__namespace.join(snapshotDir, pack.file));
11704
+ const text2 = snapshotText(snapshotDir, pack.file);
11310
11705
  if (text2 === null) continue;
11311
11706
  const bodies = pack.read(text2);
11312
11707
  if (bodies === null) {
@@ -11370,7 +11765,8 @@ function auditSnapshot(options) {
11370
11765
  unreplayable += 1;
11371
11766
  continue;
11372
11767
  }
11373
- const bytes = readBytes(path25__namespace.join(repoDir, file.relativePath));
11768
+ const repoBytes = readConfinedBytes(repoDir, file.relativePath);
11769
+ const bytes = repoBytes.ok ? repoBytes.bytes : null;
11374
11770
  if (bytes === null || sha256(bytes) !== file.hashSha256) {
11375
11771
  unreplayable += 1;
11376
11772
  continue;
@@ -11467,30 +11863,37 @@ function auditSnapshot(options) {
11467
11863
  const scanBudget = options.maxScanBytes ?? 32 * 1024 * 1024;
11468
11864
  const leakHits = [];
11469
11865
  let scannedBytes = 0;
11470
- for (const relative14 of walk(snapshotDir)) {
11471
- if (!TEXT_ARTIFACT.test(relative14) || scannedBytes > scanBudget) continue;
11472
- if (relative14 === SIGNATURE_FILE) continue;
11473
- const text2 = readText2(path25__namespace.join(snapshotDir, relative14));
11866
+ for (const relative15 of walk(snapshotDir)) {
11867
+ if (!TEXT_ARTIFACT.test(relative15) || scannedBytes > scanBudget) continue;
11868
+ if (relative15 === SIGNATURE_FILE) continue;
11869
+ let size2;
11870
+ try {
11871
+ size2 = fs24__namespace.statSync(path25__namespace.join(snapshotDir, relative15)).size;
11872
+ } catch {
11873
+ continue;
11874
+ }
11875
+ if (scannedBytes + size2 > scanBudget) break;
11876
+ const text2 = snapshotText(snapshotDir, relative15);
11474
11877
  if (text2 === null) continue;
11475
11878
  scannedBytes += Buffer.byteLength(text2, "utf8");
11476
11879
  let findingCount = 0;
11477
- if (/^parts[\\/].*\.md$/i.test(relative14)) {
11880
+ if (/^parts[\\/].*\.md$/i.test(relative15)) {
11478
11881
  let headerText = text2;
11479
11882
  for (const section of parsePartSections(text2)) {
11480
11883
  findingCount += scanAndRedactSecrets(section.body, rules, section.path).findings.length;
11481
11884
  headerText = headerText.replace(section.body, "");
11482
11885
  }
11483
- findingCount += scanAndRedactSecrets(headerText, rules, relative14).findings.length;
11886
+ findingCount += scanAndRedactSecrets(headerText, rules, relative15).findings.length;
11484
11887
  } else {
11485
- findingCount = scanAndRedactSecrets(text2, rules, relative14).findings.length;
11888
+ findingCount = scanAndRedactSecrets(text2, rules, relative15).findings.length;
11486
11889
  }
11487
11890
  if (findingCount > 0) {
11488
- leakHits.push(relative14 + " (" + findingCount + " line(s))");
11891
+ leakHits.push(relative15 + " (" + findingCount + " line(s))");
11489
11892
  }
11490
11893
  }
11491
11894
  const signatureRecordPath = path25__namespace.join(snapshotDir, SIGNATURE_FILE);
11492
11895
  if (fs24__namespace.existsSync(signatureRecordPath)) {
11493
- const recordText = readText2(signatureRecordPath);
11896
+ const recordText = snapshotText(snapshotDir, SIGNATURE_FILE);
11494
11897
  if (recordText !== null) {
11495
11898
  scannedBytes += Buffer.byteLength(recordText, "utf8");
11496
11899
  let scanText = recordText;
@@ -11530,11 +11933,17 @@ function auditSnapshot(options) {
11530
11933
  );
11531
11934
  const leakedFrom = [];
11532
11935
  let compared = 0;
11533
- const artifactTexts = readArtifactTexts(snapshotDir);
11936
+ const artifactTexts = readArtifactTexts(snapshotDir, scanBudget);
11534
11937
  const artifactContains = (token) => artifactTexts.some((text2) => text2.includes(token));
11535
11938
  for (const record of skippedSensitive.slice(0, 40)) {
11536
11939
  if (record.path.includes("[REDACTED") || compared > 400) continue;
11537
- const text2 = readText2(path25__namespace.join(repoDir, record.path));
11940
+ try {
11941
+ if (fs24__namespace.statSync(path25__namespace.join(repoDir, record.path)).size > scanBudget) continue;
11942
+ } catch {
11943
+ continue;
11944
+ }
11945
+ const repoRead = readConfinedText(repoDir, record.path);
11946
+ const text2 = repoRead.ok ? repoRead.text : null;
11538
11947
  if (text2 === null) continue;
11539
11948
  for (const token of secretTokens(text2)) {
11540
11949
  compared += 1;
@@ -11556,7 +11965,7 @@ function auditSnapshot(options) {
11556
11965
  "A value from " + sample([...new Set(leakedFrom)]) + " appears in the snapshot."
11557
11966
  )
11558
11967
  );
11559
- const pii = findHostPaths(snapshotDir, repoDir);
11968
+ const pii = findHostPaths(snapshotDir, repoDir, scanBudget);
11560
11969
  checks.push(
11561
11970
  pii.length === 0 ? check(
11562
11971
  "pii.paths",
@@ -11677,6 +12086,17 @@ function report(snapshotDir, repoDir, checks) {
11677
12086
  counts
11678
12087
  };
11679
12088
  }
12089
+ function safeRegularFile(cwd, absolute) {
12090
+ try {
12091
+ if (!fs24__namespace.lstatSync(absolute).isFile()) return false;
12092
+ const root = fs24__namespace.realpathSync(cwd);
12093
+ const real = fs24__namespace.realpathSync(absolute);
12094
+ const relative15 = path25__namespace.relative(root, real);
12095
+ return relative15 !== ".." && !relative15.startsWith(".." + path25__namespace.sep) && !path25__namespace.isAbsolute(relative15);
12096
+ } catch {
12097
+ return false;
12098
+ }
12099
+ }
11680
12100
  function describeMatcher(matcher) {
11681
12101
  if (typeof matcher === "string") return matcher;
11682
12102
  if (matcher instanceof RegExp) return String(matcher);
@@ -11688,23 +12108,23 @@ function describeMatcher(matcher) {
11688
12108
  function normalizeTarget(cwd, target) {
11689
12109
  const resolvedCwd = path25__namespace.resolve(cwd);
11690
12110
  const absolute = path25__namespace.resolve(resolvedCwd, target);
11691
- const relative14 = path25__namespace.relative(resolvedCwd, absolute);
11692
- if (relative14 === "" || relative14 === ".." || relative14.startsWith(`..${path25__namespace.sep}`) || path25__namespace.isAbsolute(relative14)) {
12111
+ const relative15 = path25__namespace.relative(resolvedCwd, absolute);
12112
+ if (relative15 === "" || relative15 === ".." || relative15.startsWith(`..${path25__namespace.sep}`) || path25__namespace.isAbsolute(relative15)) {
11693
12113
  return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
11694
12114
  }
11695
- return { relative: relative14.split(path25__namespace.sep).join("/"), outsideRoot: false };
12115
+ return { relative: relative15.split(path25__namespace.sep).join("/"), outsideRoot: false };
11696
12116
  }
11697
12117
  function findRuleMatch(rules, relativePath) {
11698
12118
  return rules.find(
11699
12119
  (rule) => matchRule(relativePath, rule.match)
11700
12120
  );
11701
12121
  }
11702
- function findRecordedAncestor(skipped, relative14, maskedPath2) {
12122
+ function findRecordedAncestor(skipped, relative15, maskedPath2) {
11703
12123
  let nearest;
11704
12124
  for (const record of skipped) {
11705
12125
  const ancestorPath = record.path;
11706
12126
  if (ancestorPath.length === 0) continue;
11707
- const isAncestor = relative14.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
12127
+ const isAncestor = relative15.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
11708
12128
  if (!isAncestor) continue;
11709
12129
  if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
11710
12130
  }
@@ -11720,8 +12140,8 @@ function readManifest2(config) {
11720
12140
  }
11721
12141
  function explainPath(config, target) {
11722
12142
  const normalized = normalizeTarget(config.cwd, target);
11723
- const relative14 = normalized.relative;
11724
- const maskedPath2 = findSecretInPath(relative14, config.secretRules)?.masked ?? relative14;
12143
+ const relative15 = normalized.relative;
12144
+ const maskedPath2 = findSecretInPath(relative15, config.secretRules)?.masked ?? relative15;
11725
12145
  if (normalized.outsideRoot) {
11726
12146
  return {
11727
12147
  path: maskedPath2,
@@ -11731,10 +12151,14 @@ function explainPath(config, target) {
11731
12151
  detail: "path resolves outside the configured repository root and was not inspected"
11732
12152
  };
11733
12153
  }
11734
- const absolute = path25__namespace.join(config.cwd, relative14);
12154
+ const absolute = path25__namespace.join(config.cwd, relative15);
12155
+ const stagedBlob = config.staged === true ? readStagedBlob(config.cwd, relative15) : null;
11735
12156
  const result = {
11736
12157
  path: maskedPath2,
11737
- exists: fs24__namespace.existsSync(absolute),
12158
+ // `existsSync` follows a symlink, so an in-repo link to /etc/passwd answered "exists" for a
12159
+ // file the scanner refuses. `lstat` plus a canonical containment check keeps the answer about
12160
+ // a regular file the repository actually contains; a staged blob is the index's answer.
12161
+ exists: stagedBlob !== null || safeRegularFile(config.cwd, absolute),
11738
12162
  included: false
11739
12163
  };
11740
12164
  const collection = collectFiles(config.cwd, {
@@ -11749,11 +12173,11 @@ function explainPath(config, target) {
11749
12173
  // that is only missing because the walker dropped the tool's own output directory.
11750
12174
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
11751
12175
  (directory) => path25__namespace.relative(config.cwd, path25__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
11752
- ).filter((relative15) => relative15.length > 0 && !relative15.startsWith(".."))
12176
+ ).filter((relative16) => relative16.length > 0 && !relative16.startsWith(".."))
11753
12177
  });
11754
- if (!collection.files.includes(relative14)) {
12178
+ if (!collection.files.includes(relative15)) {
11755
12179
  const record = collection.skipped.find(
11756
- (entry2) => entry2.path === relative14 || entry2.path === maskedPath2
12180
+ (entry2) => entry2.path === relative15 || entry2.path === maskedPath2
11757
12181
  );
11758
12182
  if (record) {
11759
12183
  result.reason = record.reason;
@@ -11762,7 +12186,7 @@ function explainPath(config, target) {
11762
12186
  result.reason = "missing";
11763
12187
  result.detail = "no such file or directory, relative to the configured cwd";
11764
12188
  } else {
11765
- const ancestor = findRecordedAncestor(collection.skipped, relative14, maskedPath2);
12189
+ const ancestor = findRecordedAncestor(collection.skipped, relative15, maskedPath2);
11766
12190
  if (ancestor) {
11767
12191
  result.reason = ancestor.reason;
11768
12192
  result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
@@ -11782,11 +12206,11 @@ function explainPath(config, target) {
11782
12206
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
11783
12207
  ...config.staged === true ? { staged: true } : {}
11784
12208
  });
11785
- inScope = scope.paths.has(relative14);
12209
+ inScope = scope.paths.has(relative15);
11786
12210
  if (!inScope && config.withDependents === true) {
11787
12211
  inScope = importsChangedFile(
11788
- relative14,
11789
- importsOfFile(relative14, absolute),
12212
+ relative15,
12213
+ importsOfFile(relative15, absolute),
11790
12214
  scope.paths,
11791
12215
  buildImportResolver(collection.files.map((file) => ({ relativePath: file })), {
11792
12216
  tsconfig: tsconfigPathsFor(config.cwd)
@@ -11813,11 +12237,13 @@ function explainPath(config, target) {
11813
12237
  result.detail = "binary extension; generate skips it without reading and records `binary` in manifest.skipped[]";
11814
12238
  return result;
11815
12239
  }
11816
- let sizeOnDisk = null;
11817
- try {
11818
- sizeOnDisk = fs24__namespace.statSync(absolute).size;
11819
- } catch {
11820
- sizeOnDisk = null;
12240
+ let sizeOnDisk = stagedBlob?.length ?? null;
12241
+ if (sizeOnDisk === null) {
12242
+ try {
12243
+ sizeOnDisk = fs24__namespace.statSync(absolute).size;
12244
+ } catch {
12245
+ sizeOnDisk = null;
12246
+ }
11821
12247
  }
11822
12248
  if (sizeOnDisk !== null && sizeOnDisk > BINARY_SCAN_BYTES && isBinaryFile(absolute)) {
11823
12249
  result.included = false;
@@ -11825,10 +12251,10 @@ function explainPath(config, target) {
11825
12251
  result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
11826
12252
  return result;
11827
12253
  }
11828
- if (fs24__namespace.existsSync(absolute) && fs24__namespace.statSync(absolute).isFile()) {
12254
+ if (stagedBlob !== null || safeRegularFile(config.cwd, absolute)) {
11829
12255
  let buffer;
11830
12256
  try {
11831
- buffer = fs24__namespace.readFileSync(absolute);
12257
+ buffer = stagedBlob ?? fs24__namespace.readFileSync(absolute);
11832
12258
  } catch (err) {
11833
12259
  result.included = false;
11834
12260
  result.reason = "read-error";
@@ -11846,15 +12272,15 @@ function explainPath(config, target) {
11846
12272
  result.bytes = buffer.length;
11847
12273
  result.lines = countLines(text2);
11848
12274
  if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
11849
- const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative14);
12275
+ const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative15);
11850
12276
  result.secretCount = findings.length;
11851
12277
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
11852
12278
  let inclusionMode = "full";
11853
- if (config.skeleton === true && isSkeletonizable(relative14)) {
11854
- const skeleton = skeletonizeTypeScript(text2, relative14);
12279
+ if (config.skeleton === true && isSkeletonizable(relative15)) {
12280
+ const skeleton = skeletonizeTypeScript(text2, relative15);
11855
12281
  if (skeleton.collapsed > 0) inclusionMode = "signatures";
11856
12282
  }
11857
- if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative14) && stripComments2(text2, relative14).removed > 0) {
12283
+ if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative15) && stripComments2(text2, relative15).removed > 0) {
11858
12284
  inclusionMode = "comments-stripped";
11859
12285
  }
11860
12286
  if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
@@ -11863,20 +12289,36 @@ function explainPath(config, target) {
11863
12289
  }
11864
12290
  result.inclusionMode = inclusionMode;
11865
12291
  }
11866
- result.layer = classifyLayer(relative14, config.layers);
11867
- result.kind = classifyKind(relative14, config.kinds);
11868
- result.language = detectLanguage(relative14);
11869
- const layerRule = findRuleMatch(config.layers, relative14);
12292
+ result.layer = classifyLayer(relative15, config.layers);
12293
+ result.kind = classifyKind(relative15, config.kinds);
12294
+ result.language = detectLanguage(relative15);
12295
+ const layerRule = findRuleMatch(config.layers, relative15);
11870
12296
  if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
11871
- const kindRule = findRuleMatch(config.kinds, relative14);
12297
+ const kindRule = findRuleMatch(config.kinds, relative15);
11872
12298
  if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
11873
12299
  const manifest = readManifest2(config);
11874
- const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative14) : void 0;
12300
+ const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative15) : void 0;
11875
12301
  result.part = entry?.part ?? null;
11876
12302
  if (entry === void 0) {
11877
- const record = manifest?.skipped?.find((skip) => skip.path === relative14);
12303
+ const record = manifest?.skipped?.find((skip) => skip.path === relative15);
11878
12304
  if (record !== void 0 && (record.reason === "not-selected" || record.reason === "unchanged")) {
11879
12305
  result.included = false;
12306
+ for (const key of [
12307
+ "layer",
12308
+ "layerMatch",
12309
+ "kind",
12310
+ "kindMatch",
12311
+ "language",
12312
+ "inclusionMode",
12313
+ "lines",
12314
+ "bytes",
12315
+ "encoding",
12316
+ "secretCount",
12317
+ "secrets"
12318
+ ]) {
12319
+ delete result[key];
12320
+ }
12321
+ result.part = null;
11880
12322
  result.reason = record.reason;
11881
12323
  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");
11882
12324
  }
@@ -11927,7 +12369,10 @@ const { parentPort, workerData } = require("node:worker_threads");
11927
12369
  (async () => {
11928
12370
  try {
11929
12371
  const mod = await import(workerData.entryUrl);
11930
- const loaded = await mod.loadConfigFileDetailed(workerData.cwd);
12372
+ const loaded =
12373
+ workerData.config === null || workerData.config === undefined
12374
+ ? await mod.loadConfigFileDetailed(workerData.cwd, { allowExecutableConfig: false })
12375
+ : { config: workerData.config, errors: [] };
11931
12376
  if (loaded.errors.length > 0) {
11932
12377
  parentPort.postMessage({ ok: false, message: loaded.errors.join("; ") });
11933
12378
  return;
@@ -11939,6 +12384,7 @@ const { parentPort, workerData } = require("node:worker_threads");
11939
12384
  const manifest = mod.generateSnapshot(config, {
11940
12385
  dryRun: workerData.dryRun === true,
11941
12386
  ...(workerData.narrow ?? {}),
12387
+ ...(workerData.source === undefined ? {} : { source: workerData.source }),
11942
12388
  ...(workerData.runId === undefined ? {} : { runId: workerData.runId }),
11943
12389
  });
11944
12390
  const skipCounts = new Map();
@@ -11979,7 +12425,7 @@ const { parentPort, workerData } = require("node:worker_threads");
11979
12425
  })();
11980
12426
  `;
11981
12427
  function generateInWorker(cwd, cliOptions, options = {}) {
11982
- return new Promise((resolve14) => {
12428
+ return new Promise((resolve15) => {
11983
12429
  let settled = false;
11984
12430
  let worker = null;
11985
12431
  const finish = (result) => {
@@ -11990,7 +12436,7 @@ function generateInWorker(cwd, cliOptions, options = {}) {
11990
12436
  if (!result.ok && options.runId !== void 0 && options.lockRoots !== void 0) {
11991
12437
  releaseAbandonedRun(options.lockRoots, options.runId);
11992
12438
  }
11993
- resolve14(result);
12439
+ resolve15(result);
11994
12440
  });
11995
12441
  };
11996
12442
  const isCjs = typeof __dirname !== "undefined";
@@ -12004,6 +12450,8 @@ function generateInWorker(cwd, cliOptions, options = {}) {
12004
12450
  cliOptions,
12005
12451
  dryRun: options.dryRun === true,
12006
12452
  narrow: options.narrow ?? {},
12453
+ ...options.config === void 0 ? {} : { config: options.config },
12454
+ ...options.source === void 0 ? {} : { source: options.source },
12007
12455
  ...options.runId === void 0 ? {} : { runId: options.runId }
12008
12456
  }
12009
12457
  });
@@ -12067,7 +12515,7 @@ function canonicalPath(value) {
12067
12515
  return absolute;
12068
12516
  }
12069
12517
  }
12070
- function isInside2(parent, child) {
12518
+ function isInside3(parent, child) {
12071
12519
  const foldedParent = foldForComparison(parent);
12072
12520
  const foldedChild = foldForComparison(child);
12073
12521
  return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path25__namespace.sep}`);
@@ -12101,7 +12549,7 @@ function resolveRoot(requested, context) {
12101
12549
  }
12102
12550
  const resolved = canonicalPath(absolute);
12103
12551
  for (const allowed of context.roots) {
12104
- if (isInside2(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
12552
+ if (isInside3(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
12105
12553
  }
12106
12554
  const shown = context.roots.join(", ");
12107
12555
  return {
@@ -12145,7 +12593,7 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
12145
12593
  const requested = overrides.outDir.trim();
12146
12594
  const permitted = allowedRoots !== void 0 && allowedRoots.length > 0 ? allowedRoots : [root];
12147
12595
  const resolved = resolveThroughExistingAncestor(path25__namespace.resolve(root, requested));
12148
- if (!permitted.some((allowed) => isInside2(canonicalPath(allowed), resolved))) {
12596
+ if (!permitted.some((allowed) => isInside3(canonicalPath(allowed), resolved))) {
12149
12597
  const shown = permitted.map((allowed) => canonicalPath(allowed)).join(", ");
12150
12598
  return {
12151
12599
  ok: false,
@@ -12167,6 +12615,14 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
12167
12615
  if (overrides.sarif === true) cliOptions.sarif = true;
12168
12616
  if (overrides.staged === true) cliOptions.staged = true;
12169
12617
  if (overrides.withDependents === true) cliOptions.withDependents = true;
12618
+ for (const key of ["only", "ignore"]) {
12619
+ const value = overrides[key];
12620
+ if (value === void 0) continue;
12621
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
12622
+ return { ok: false, message: `"${key}" must be an array of glob strings.` };
12623
+ }
12624
+ cliOptions[key] = value;
12625
+ }
12170
12626
  try {
12171
12627
  const config = resolveConfig(loaded.config, cliOptions, root);
12172
12628
  return {
@@ -12192,8 +12648,8 @@ function partPathFor(workspace, filename) {
12192
12648
  if (filename.length === 0 || filename.includes("\0")) return null;
12193
12649
  const partsDir = path25__namespace.resolve(workspace.root, workspace.config.outDir, "parts");
12194
12650
  const resolved = path25__namespace.resolve(partsDir, filename);
12195
- const relative14 = path25__namespace.relative(partsDir, resolved);
12196
- if (relative14.length === 0 || relative14.includes(path25__namespace.sep) || relative14.includes("/") || relative14.includes("\\") || path25__namespace.isAbsolute(relative14)) {
12651
+ const relative15 = path25__namespace.relative(partsDir, resolved);
12652
+ if (relative15.length === 0 || relative15.includes(path25__namespace.sep) || relative15.includes("/") || relative15.includes("\\") || path25__namespace.isAbsolute(relative15)) {
12197
12653
  return null;
12198
12654
  }
12199
12655
  let stats;
@@ -12213,30 +12669,27 @@ function partPathFor(workspace, filename) {
12213
12669
  function readManifest3(workspace) {
12214
12670
  const file = manifestPathFor(workspace);
12215
12671
  const shown = path25__namespace.relative(workspace.root, file).split(path25__namespace.sep).join("/") || file;
12216
- let stats;
12217
- try {
12218
- stats = fs24__namespace.statSync(file);
12219
- } catch {
12672
+ const confined = readConfinedText(path25__namespace.dirname(file), path25__namespace.basename(file));
12673
+ if (!confined.ok) {
12674
+ if (confined.reason === "missing") {
12675
+ return {
12676
+ ok: false,
12677
+ missing: true,
12678
+ message: `There is no snapshot manifest at ${shown}. Call snapshot_plan to preview what would be included, or snapshot_generate to write it.`
12679
+ };
12680
+ }
12220
12681
  return {
12221
12682
  ok: false,
12222
- missing: true,
12223
- message: `There is no snapshot manifest at ${shown}. Call snapshot_plan to preview what would be included, or snapshot_generate to write it.`
12683
+ missing: false,
12684
+ message: `${shown} could not be read as a snapshot manifest: ${confined.message}.`
12224
12685
  };
12225
12686
  }
12687
+ const stats = confined.stats;
12688
+ const raw = confined.text;
12226
12689
  const cached = manifestCache.get(file);
12227
12690
  if (cached && cached.mtimeMs === stats.mtimeMs && cached.ctimeMs === stats.ctimeMs && cached.size === stats.size) {
12228
12691
  return { ok: true, manifest: cached.manifest, file };
12229
12692
  }
12230
- let raw;
12231
- try {
12232
- raw = fs24__namespace.readFileSync(file, "utf8");
12233
- } catch (error) {
12234
- return {
12235
- ok: false,
12236
- missing: false,
12237
- message: `${shown} exists but could not be read: ${error instanceof Error ? error.message : String(error)}`
12238
- };
12239
- }
12240
12693
  let parsed;
12241
12694
  try {
12242
12695
  parsed = JSON.parse(raw);
@@ -12266,6 +12719,123 @@ function forgetManifest(file) {
12266
12719
  manifestCache.delete(file);
12267
12720
  }
12268
12721
 
12722
+ // src/security/regex.ts
12723
+ var MAX_PATTERN_LENGTH = 256;
12724
+ var MAX_QUANTIFIER_REPEAT = 1e4;
12725
+ function unsafeRegExpReason(source) {
12726
+ if (source.length === 0) return null;
12727
+ if (source.length > MAX_PATTERN_LENGTH) {
12728
+ return `the pattern is longer than ${MAX_PATTERN_LENGTH} characters`;
12729
+ }
12730
+ let inClass = false;
12731
+ let unbounded = 0;
12732
+ const groups = [];
12733
+ for (let index = 0; index < source.length; index += 1) {
12734
+ const char = source[index];
12735
+ if (char === "\\") {
12736
+ index += 1;
12737
+ continue;
12738
+ }
12739
+ if (inClass) {
12740
+ if (char === "]") inClass = false;
12741
+ continue;
12742
+ }
12743
+ if (char === "[") {
12744
+ inClass = true;
12745
+ continue;
12746
+ }
12747
+ if (char === "(") {
12748
+ groups.push({ quantified: false, alternation: false });
12749
+ continue;
12750
+ }
12751
+ if (char === ")") {
12752
+ const group = groups.pop();
12753
+ if (group === void 0) continue;
12754
+ if (isQuantifiedAt(source, index + 1)) {
12755
+ if (group.quantified || group.alternation) {
12756
+ return "a quantified group contains another quantifier or an alternation";
12757
+ }
12758
+ group.quantified = true;
12759
+ } else if (isOptionalQuantifierAt(source, index + 1)) {
12760
+ group.quantified = true;
12761
+ }
12762
+ const parent = groups[groups.length - 1];
12763
+ if (parent !== void 0) {
12764
+ parent.quantified = parent.quantified || group.quantified;
12765
+ parent.alternation = parent.alternation || group.alternation;
12766
+ }
12767
+ continue;
12768
+ }
12769
+ if (char === "|") {
12770
+ const group = groups[groups.length - 1];
12771
+ if (group !== void 0) group.alternation = true;
12772
+ continue;
12773
+ }
12774
+ if (char === "?") {
12775
+ const previous = source[index - 1];
12776
+ if (previous !== "(" && previous !== "?" && previous !== "*" && previous !== "+" && previous !== "}") {
12777
+ const group = groups[groups.length - 1];
12778
+ if (group !== void 0) group.quantified = true;
12779
+ }
12780
+ continue;
12781
+ }
12782
+ if (char === "*" || char === "+") {
12783
+ unbounded += 1;
12784
+ const group = groups[groups.length - 1];
12785
+ if (group !== void 0) group.quantified = true;
12786
+ continue;
12787
+ }
12788
+ if (char === "{") {
12789
+ const close = source.indexOf("}", index + 1);
12790
+ if (close === -1) continue;
12791
+ const body = source.slice(index + 1, close);
12792
+ const match = /^(\d+)(?:,(\d*))?$/.exec(body);
12793
+ if (match === null) {
12794
+ index = close;
12795
+ continue;
12796
+ }
12797
+ const max = match[2] === void 0 ? Number(match[1]) : match[2] === "" ? Infinity : Number(match[2]);
12798
+ if (max > MAX_QUANTIFIER_REPEAT) {
12799
+ return "a repetition bound is larger than the search budget can evaluate safely";
12800
+ }
12801
+ if (max === Infinity) unbounded += 1;
12802
+ const group = groups[groups.length - 1];
12803
+ if (group !== void 0) group.quantified = true;
12804
+ index = close;
12805
+ }
12806
+ }
12807
+ if (unbounded > 1) {
12808
+ return "the pattern has more than one unbounded repetition";
12809
+ }
12810
+ return null;
12811
+ }
12812
+ function isOptionalQuantifierAt(source, start) {
12813
+ if (source[start] === "?") return true;
12814
+ if (source[start] !== "{") return false;
12815
+ const close = source.indexOf("}", start + 1);
12816
+ if (close === -1) return false;
12817
+ const body = source.slice(start + 1, close);
12818
+ const match = /^(\d+)(?:,(\d*))?$/.exec(body);
12819
+ if (match === null) return false;
12820
+ const minimum = Number(match[1]);
12821
+ if (match[2] === void 0) return minimum <= 1;
12822
+ const maximum = match[2] === "" ? Infinity : Number(match[2]);
12823
+ return maximum <= 1;
12824
+ }
12825
+ function isQuantifiedAt(source, start) {
12826
+ const char = source[start];
12827
+ if (char === "*" || char === "+") return true;
12828
+ if (char !== "{") return false;
12829
+ const close = source.indexOf("}", start + 1);
12830
+ if (close === -1) return false;
12831
+ const body = source.slice(start + 1, close);
12832
+ const match = /^(\d+)(?:,(\d*))?$/.exec(body);
12833
+ if (match === null) return false;
12834
+ if (match[2] === void 0) return Number(match[1]) > 1;
12835
+ if (match[2] === "") return true;
12836
+ return Number(match[2]) > 1;
12837
+ }
12838
+
12269
12839
  // src/mcp/tools.ts
12270
12840
  var MAX_SEARCH_BYTES = 4 * 1024 * 1024;
12271
12841
  var READ_ONLY = {
@@ -12297,6 +12867,16 @@ var OUT_DIR_PROPERTY = {
12297
12867
  };
12298
12868
  var outDirOverride = (args) => ({ outDir: args.outDir });
12299
12869
  var SCOPE_PROPERTIES = {
12870
+ only: {
12871
+ type: "array",
12872
+ items: { type: "string" },
12873
+ description: "Globs to include: replaces the config allow-list for this run."
12874
+ },
12875
+ ignore: {
12876
+ type: "array",
12877
+ items: { type: "string" },
12878
+ description: "Globs to exclude, added to the config deny-list for this run."
12879
+ },
12300
12880
  maxPartTokens: {
12301
12881
  type: "string",
12302
12882
  description: 'Token ceiling per part, for example 32000 or "32k". Narrower than maxPartBytes; it converts at four bytes per token.'
@@ -12331,7 +12911,9 @@ function workspaceOverrides(args) {
12331
12911
  sarif: args.sarif,
12332
12912
  changedSince: args.changedSince,
12333
12913
  staged: args.staged,
12334
- withDependents: args.withDependents
12914
+ withDependents: args.withDependents,
12915
+ only: args.only,
12916
+ ignore: args.ignore
12335
12917
  };
12336
12918
  }
12337
12919
  function failure(message) {
@@ -12367,11 +12949,11 @@ function toRelativePath(root, value) {
12367
12949
  if (cleaned.length === 0 || cleaned.includes("\0")) return null;
12368
12950
  const resolvedRoot = path25__namespace.resolve(root);
12369
12951
  const absolute = path25__namespace.resolve(resolvedRoot, cleaned);
12370
- const relative14 = path25__namespace.relative(resolvedRoot, absolute);
12371
- if (relative14 === "" || relative14 === ".." || relative14.startsWith(`..${path25__namespace.sep}`) || path25__namespace.isAbsolute(relative14)) {
12952
+ const relative15 = path25__namespace.relative(resolvedRoot, absolute);
12953
+ if (relative15 === "" || relative15 === ".." || relative15.startsWith(`..${path25__namespace.sep}`) || path25__namespace.isAbsolute(relative15)) {
12372
12954
  return null;
12373
12955
  }
12374
- return relative14.split(path25__namespace.sep).join("/");
12956
+ return relative15.split(path25__namespace.sep).join("/");
12375
12957
  }
12376
12958
  function symbolsOf(entry) {
12377
12959
  const summary = entry.summary;
@@ -12464,16 +13046,15 @@ var historyTool = {
12464
13046
  async handler(args, context) {
12465
13047
  const prepared = await prepare(args, context, outDirOverride(args));
12466
13048
  if (!prepared.ok) return prepared.outcome;
12467
- const reportPath = path25__namespace.resolve(prepared.workspace.root, prepared.workspace.config.outDir, "reports", "log.md");
12468
- let text2;
12469
- try {
12470
- text2 = fs24__namespace.readFileSync(reportPath, "utf8");
12471
- } catch {
13049
+ const snapshotDir = path25__namespace.resolve(prepared.workspace.root, prepared.workspace.config.outDir);
13050
+ const reportRead = readConfinedText(snapshotDir, path25__namespace.posix.join("reports", "log.md"));
13051
+ if (!reportRead.ok) {
12472
13052
  return {
12473
- text: "This snapshot has no reports/log.md. Generate it with `snapshot_generate { includeLogs: 20 }`, or `generate --include-logs 20` on the command line; the report is opt-in because the commit subjects are repository content.",
13053
+ text: "This snapshot has no readable reports/log.md. Generate it with `snapshot_generate { includeLogs: 20 }`, or `generate --include-logs 20` on the command line; the report is opt-in because the commit subjects are repository content, and it must be a regular file inside the snapshot.",
12474
13054
  isError: true
12475
13055
  };
12476
13056
  }
13057
+ const text2 = reportRead.text;
12477
13058
  const manifestRead = readManifest3(prepared.workspace);
12478
13059
  const recordedLog = manifestRead.ok ? manifestRead.manifest.artifacts?.log : void 0;
12479
13060
  if (recordedLog !== void 0 && recordedLog !== null) {
@@ -12637,21 +13218,22 @@ var workspaceTool = {
12637
13218
  async handler(args, context) {
12638
13219
  const prepared = await prepare(args, context, outDirOverride(args));
12639
13220
  if (!prepared.ok) return prepared.outcome;
12640
- const index = path25__namespace.resolve(
12641
- prepared.workspace.root,
12642
- prepared.workspace.config.outDir,
12643
- "WORKSPACE.json"
12644
- );
12645
- let text2;
12646
- try {
12647
- text2 = fs24__namespace.readFileSync(index, "utf8");
12648
- } catch {
13221
+ const snapshotDir = path25__namespace.resolve(prepared.workspace.root, prepared.workspace.config.outDir);
13222
+ const index = path25__namespace.join(snapshotDir, "WORKSPACE.json");
13223
+ const read = readConfinedText(snapshotDir, "WORKSPACE.json");
13224
+ if (!read.ok) {
12649
13225
  return {
12650
- text: "No workspace index at " + index + ". Generate one with `generate --workspace member-a,member-b`; a single snapshot has no members to list.",
13226
+ text: "No workspace index at " + index + " (the file is absent, or it is not a regular file inside the snapshot). Generate one with `generate --workspace member-a,member-b`; a single snapshot has no members to list.",
12651
13227
  isError: true
12652
13228
  };
12653
13229
  }
12654
- const document = JSON.parse(text2);
13230
+ const text2 = read.text;
13231
+ let document;
13232
+ try {
13233
+ document = JSON.parse(text2);
13234
+ } catch (error) {
13235
+ return { text: "WORKSPACE.json is not valid JSON: " + error.message, isError: true };
13236
+ }
12655
13237
  const members = document.members ?? [];
12656
13238
  const links = document.links ?? [];
12657
13239
  const lines = [
@@ -12791,6 +13373,10 @@ var routesTool = {
12791
13373
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
12792
13374
  let filter = null;
12793
13375
  if (typeof args.pattern === "string") {
13376
+ const unsafe = unsafeRegExpReason(args.pattern);
13377
+ if (unsafe !== null) {
13378
+ return { text: "pattern is refused: " + unsafe + ".", isError: true };
13379
+ }
12794
13380
  try {
12795
13381
  filter = new RegExp(args.pattern, "i");
12796
13382
  } catch (error) {
@@ -12934,6 +13520,12 @@ var searchTool = {
12934
13520
  const cap = Math.max(1, Math.min(500, typeof args.maxMatches === "number" ? args.maxMatches : 50));
12935
13521
  const contextLines = Math.max(0, Math.min(10, typeof args.contextLines === "number" ? args.contextLines : 0));
12936
13522
  let pattern;
13523
+ if (args.regex === true) {
13524
+ const unsafe = unsafeRegExpReason(query);
13525
+ if (unsafe !== null) {
13526
+ return { text: "regex is refused: " + unsafe + ".", isError: true };
13527
+ }
13528
+ }
12937
13529
  try {
12938
13530
  pattern = args.regex === true ? new RegExp(query, "i") : new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i");
12939
13531
  } catch (error) {
@@ -12956,11 +13548,17 @@ var searchTool = {
12956
13548
  } catch {
12957
13549
  continue;
12958
13550
  }
12959
- if (Buffer.byteLength(text2, "utf8") > MAX_SEARCH_BYTES) {
13551
+ const partBytes = Buffer.byteLength(text2, "utf8");
13552
+ if (partBytes > MAX_SEARCH_BYTES) {
12960
13553
  skippedOversize.push(part.filename);
13554
+ truncated = true;
12961
13555
  continue;
12962
13556
  }
12963
- scanned += text2.length;
13557
+ if (scanned + partBytes > MAX_SEARCH_BYTES) {
13558
+ truncated = true;
13559
+ break;
13560
+ }
13561
+ scanned += partBytes;
12964
13562
  for (const section of parsePartSections(text2)) {
12965
13563
  if (matches.length >= cap) {
12966
13564
  truncated = true;
@@ -13326,28 +13924,39 @@ var symbolTool = {
13326
13924
  };
13327
13925
  }
13328
13926
  const callSites = [];
13927
+ let referencesTruncated = false;
13329
13928
  if (args.references !== false) {
13330
13929
  const limit = Math.max(1, typeof args.maxReferences === "number" ? args.maxReferences : 20);
13331
13930
  const definitionKeys = new Set(matches.map((match) => match.path + ":" + match.line));
13332
13931
  const word = new RegExp("\\b" + name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\b");
13333
- const parts = /* @__PURE__ */ new Map();
13932
+ const sectionsByPart = /* @__PURE__ */ new Map();
13334
13933
  let scanned = 0;
13335
13934
  for (const file of read.manifest.files) {
13336
13935
  if (callSites.length >= limit) break;
13337
13936
  const partPath = partPathFor(workspace, file.part);
13338
13937
  if (partPath === null) continue;
13339
- let partText = parts.get(partPath);
13340
- if (partText === void 0) {
13938
+ let sections = sectionsByPart.get(partPath);
13939
+ if (sections === void 0) {
13940
+ if (scanned >= MAX_SEARCH_BYTES) {
13941
+ referencesTruncated = true;
13942
+ break;
13943
+ }
13944
+ let partText;
13341
13945
  try {
13342
13946
  partText = fs24__namespace.readFileSync(partPath, "utf8");
13343
13947
  } catch {
13344
13948
  continue;
13345
13949
  }
13346
- parts.set(partPath, partText);
13950
+ const bytes = Buffer.byteLength(partText, "utf8");
13951
+ if (scanned + bytes > MAX_SEARCH_BYTES) {
13952
+ referencesTruncated = true;
13953
+ break;
13954
+ }
13955
+ scanned += bytes;
13956
+ sections = parsePartSections(partText);
13957
+ sectionsByPart.set(partPath, sections);
13347
13958
  }
13348
- if (scanned > MAX_SEARCH_BYTES) break;
13349
- scanned += Buffer.byteLength(partText, "utf8");
13350
- const section = findSection(parsePartSections(partText), file.relativePath);
13959
+ const section = findSection(sections, file.relativePath);
13351
13960
  if (section === null) continue;
13352
13961
  const bodyLines = section.body.split("\n");
13353
13962
  for (let index = 0; index < bodyLines.length && callSites.length < limit; index += 1) {
@@ -13361,8 +13970,11 @@ var symbolTool = {
13361
13970
  }
13362
13971
  }
13363
13972
  }
13364
- const text2 = matches.map((match) => "### " + match.path + " (" + match.part + ", line " + match.line + ")\n" + match.text).join("\n\n") + (args.references === false ? "" : "\n\n" + (callSites.length === 0 ? "No call site was found in the snapshot." : "Call sites (" + callSites.length + "):\n" + callSites.map((site) => " " + site.path + ":" + site.line + " " + site.text).join("\n")));
13365
- return { text: text2, structured: { found: matches.length, matches, references: callSites } };
13973
+ const text2 = matches.map((match) => "### " + match.path + " (" + match.part + ", line " + match.line + ")\n" + match.text).join("\n\n") + (args.references === false ? "" : "\n\n" + (callSites.length === 0 ? "No call site was found in the snapshot." : "Call sites (" + callSites.length + "):\n" + callSites.map((site) => " " + site.path + ":" + site.line + " " + site.text).join("\n"))) + (referencesTruncated ? "\n\nSearch stopped at the 4 MB part budget; call sites in later parts were not read. Narrow the name or inspect the remaining parts directly." : "");
13974
+ return {
13975
+ text: text2,
13976
+ structured: { found: matches.length, matches, references: callSites, truncated: referencesTruncated }
13977
+ };
13366
13978
  }
13367
13979
  };
13368
13980
  var contextTool = {
@@ -13520,6 +14132,10 @@ var queryTool = {
13520
14132
  const maxFiles = typeof args.maxFiles === "number" ? Math.min(200, Math.max(1, args.maxFiles)) : 40;
13521
14133
  let pattern = null;
13522
14134
  if (typeof args.pathPattern === "string") {
14135
+ const unsafe = unsafeRegExpReason(args.pathPattern);
14136
+ if (unsafe !== null) {
14137
+ return { text: "pathPattern is refused: " + unsafe + ".", isError: true };
14138
+ }
13523
14139
  try {
13524
14140
  pattern = new RegExp(args.pathPattern, "i");
13525
14141
  } catch (error) {
@@ -13905,7 +14521,12 @@ var planTool = {
13905
14521
  const prepared = await prepare(args, context, workspaceOverrides(args));
13906
14522
  if (!prepared.ok) return prepared.outcome;
13907
14523
  const workspace = prepared.workspace;
13908
- const result = await generateInWorker(workspace.root, workspace.cliOptions, { dryRun: true });
14524
+ const controller = new AbortController();
14525
+ context.onCancel?.(() => controller.abort());
14526
+ const result = await generateInWorker(workspace.root, workspace.cliOptions, {
14527
+ dryRun: true,
14528
+ signal: controller.signal
14529
+ });
13909
14530
  if (!result.ok) return failure(result.message);
13910
14531
  const summary = result.summary;
13911
14532
  const topReasons = summary.skipReasons;
@@ -13995,16 +14616,6 @@ var generateTool = {
13995
14616
  minimum: 500,
13996
14617
  description: "Fit the snapshot into this token budget, highest value first."
13997
14618
  },
13998
- only: {
13999
- type: "array",
14000
- items: { type: "string" },
14001
- description: "Globs to include: replaces the config allow-list for this run."
14002
- },
14003
- ignore: {
14004
- type: "array",
14005
- items: { type: "string" },
14006
- description: "Globs to exclude, added to the config deny-list for this run."
14007
- },
14008
14619
  ...SCOPE_PROPERTIES
14009
14620
  },
14010
14621
  additionalProperties: false
@@ -14123,7 +14734,12 @@ function configAsGenerated(workspace, manifest) {
14123
14734
  ...cli.includeLogs !== void 0 || configured("logCount") || recorded?.logCount !== void 0 ? { logCount: choose("logCount", recorded?.logCount, workspace.config.logCount, cli.includeLogs) } : {},
14124
14735
  ...cli.skeleton === true || configured("skeleton") || recorded?.skeleton !== void 0 ? { skeleton: choose("skeleton", recorded?.skeleton, workspace.config.skeleton, cli.skeleton === true ? true : void 0) } : {},
14125
14736
  ...cli.sarif === true || configured("sarif") || recorded?.sarif !== void 0 ? { sarif: choose("sarif", recorded?.sarif, workspace.config.sarif, cli.sarif === true ? true : void 0) } : {},
14126
- ...configured("maxParts") || recorded?.maxParts !== void 0 ? { maxParts: choose("maxParts", recorded?.maxParts, workspace.config.maxParts) } : {}
14737
+ ...configured("maxParts") || recorded?.maxParts !== void 0 ? { maxParts: choose("maxParts", recorded?.maxParts, workspace.config.maxParts) } : {},
14738
+ ...cli.maxPartTokens !== void 0 || configured("maxPartTokens") || recorded?.maxPartTokens !== void 0 ? { maxPartTokens: choose("maxPartTokens", recorded?.maxPartTokens, workspace.config.maxPartTokens, cli.maxPartTokens) } : {},
14739
+ ...cli.changedSince !== void 0 || configured("changedSince") || recorded?.changedSince !== void 0 ? { changedSince: choose("changedSince", recorded?.changedSince, workspace.config.changedSince, cli.changedSince) } : {},
14740
+ ...cli.staged === true || configured("staged") || recorded?.staged !== void 0 ? { staged: choose("staged", recorded?.staged, workspace.config.staged, cli.staged === true ? true : void 0) } : {},
14741
+ ...cli.withDependents === true || configured("withDependents") || recorded?.withDependents !== void 0 ? { withDependents: choose("withDependents", recorded?.withDependents, workspace.config.withDependents, cli.withDependents === true ? true : void 0) } : {},
14742
+ ...configured("promptTask") || recorded?.promptTask !== void 0 ? { promptTask: choose("promptTask", recorded?.promptTask, workspace.config.promptTask) } : {}
14127
14743
  };
14128
14744
  }
14129
14745
  var validateTool = {
@@ -15014,7 +15630,7 @@ var COMMAND_OPTION_SCOPE = {
15014
15630
  "version"
15015
15631
  ],
15016
15632
  diff: ["format", "mode", "no-config", "no-update-check", "help", "version"],
15017
- describe: ["format", "mode", "help", "version"],
15633
+ describe: ["format", "mode", "no-update-check", "help", "version"],
15018
15634
  init: [
15019
15635
  "install-hook",
15020
15636
  "cwd",
@@ -15035,7 +15651,7 @@ var COMMAND_OPTION_SCOPE = {
15035
15651
  "help",
15036
15652
  "version"
15037
15653
  ],
15038
- skill: ["cwd", "format", "mode", "install", "target", "help", "version"],
15654
+ skill: ["cwd", "format", "mode", "install", "target", "no-update-check", "help", "version"],
15039
15655
  // `mcp` reads the repository, so it takes --cwd. It has no --format: stdout carries JSON-RPC
15040
15656
  // messages, and there is no second shape to choose, so offering the flag would be a lie.
15041
15657
  serve: ["port", "host", "token", "no-auth", "allow-private", "cwd", "no-update-check", "help"],
@@ -15094,6 +15710,7 @@ var COMMAND_ORDER = [
15094
15710
  "health",
15095
15711
  "report",
15096
15712
  "explain",
15713
+ "update",
15097
15714
  "init",
15098
15715
  "setup",
15099
15716
  "diff",
@@ -15486,24 +16103,28 @@ function buildAgentContract() {
15486
16103
  {
15487
16104
  flag: "--only",
15488
16105
  type: "string",
16106
+ default: "unset",
15489
16107
  summary: "Comma-separated globs to include: overrides the config include list for this run.",
15490
16108
  appliesTo: optionAppliesTo("only")
15491
16109
  },
15492
16110
  {
15493
16111
  flag: "--ignore",
15494
16112
  type: "string",
16113
+ default: "unset",
15495
16114
  summary: "Comma-separated globs to exclude, added to the config exclude list for this run.",
15496
16115
  appliesTo: optionAppliesTo("ignore")
15497
16116
  },
15498
16117
  {
15499
16118
  flag: "--remove-empty-lines",
15500
16119
  type: "boolean",
16120
+ default: false,
15501
16121
  summary: "Drop blank and whitespace-only lines from emitted bodies; line numbers no longer match the source.",
15502
16122
  appliesTo: optionAppliesTo("remove-empty-lines")
15503
16123
  },
15504
16124
  {
15505
16125
  flag: "--all-members",
15506
16126
  type: "boolean",
16127
+ default: false,
15507
16128
  summary: "Audit every snapshot a --workspace run wrote, not only the one at outDir.",
15508
16129
  appliesTo: optionAppliesTo("all-members")
15509
16130
  },
@@ -16217,36 +16838,46 @@ function buildResourceProvider() {
16217
16838
  }
16218
16839
  const workspace = await workspaceFor(context);
16219
16840
  if ("error" in workspace) return null;
16841
+ const snapshotDir = path25__namespace.resolve(workspace.root, workspace.config.outDir);
16220
16842
  if (uri === PROMPT_URI) {
16221
- const text2 = readFileIfPresent(
16222
- path25__namespace.resolve(workspace.root, workspace.config.outDir, "PROMPT.md")
16223
- );
16224
- if (text2 === null) {
16843
+ const read = readConfinedText(snapshotDir, "PROMPT.md");
16844
+ if (!read.ok) {
16225
16845
  throw new ResourceNotFoundError(
16226
16846
  uri,
16227
- "This snapshot contains no PROMPT.md: the prompt artifact was disabled (artifacts.prompt = false or --skip-artifacts prompt), or nothing has been generated yet. Run snapshot_generate first."
16847
+ "This snapshot contains no readable PROMPT.md: the prompt artifact was disabled (artifacts.prompt = false or --skip-artifacts prompt), nothing has been generated yet, or the file is not a regular file inside the snapshot. Run snapshot_generate first."
16228
16848
  );
16229
16849
  }
16230
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, PROMPT_ADVICE) };
16850
+ return {
16851
+ uri,
16852
+ mimeType: "text/markdown",
16853
+ text: ensureSingleRead(uri, read.text, PROMPT_ADVICE)
16854
+ };
16231
16855
  }
16232
16856
  const report2 = REPORT_URIS.get(uri);
16233
16857
  if (report2) {
16234
- const text2 = readFileIfPresent(
16235
- path25__namespace.resolve(workspace.root, workspace.config.outDir, "reports", report2.file)
16236
- );
16237
- if (text2 === null) {
16858
+ const read = readConfinedText(snapshotDir, path25__namespace.posix.join("reports", report2.file));
16859
+ if (!read.ok) {
16238
16860
  throw new ResourceNotFoundError(
16239
16861
  uri,
16240
- "This snapshot contains no " + report2.file + ": that report was disabled, or nothing has been generated yet. Run snapshot_generate first."
16862
+ "This snapshot contains no readable " + report2.file + ": that report was disabled, nothing has been generated yet, or the file is not a regular file inside the snapshot. Run snapshot_generate first."
16241
16863
  );
16242
16864
  }
16243
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, REPORT_ADVICE) };
16865
+ return {
16866
+ uri,
16867
+ mimeType: "text/markdown",
16868
+ text: ensureSingleRead(uri, read.text, REPORT_ADVICE)
16869
+ };
16244
16870
  }
16245
16871
  if (uri === "snapshot://manifest") {
16246
16872
  const read = readManifest3(workspace);
16247
16873
  if (!read.ok) return null;
16248
- const text2 = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
16249
- return { uri, mimeType: "application/json", text: ensureSingleRead(uri, text2, MANIFEST_ADVICE) };
16874
+ const confined = readConfinedText(path25__namespace.dirname(read.file), path25__namespace.basename(read.file));
16875
+ if (!confined.ok) return null;
16876
+ return {
16877
+ uri,
16878
+ mimeType: "application/json",
16879
+ text: ensureSingleRead(uri, confined.text, MANIFEST_ADVICE)
16880
+ };
16250
16881
  }
16251
16882
  const partMatch = PART_URI.exec(uri);
16252
16883
  if (partMatch) {
@@ -16748,30 +17379,44 @@ function crc32(data) {
16748
17379
  return (crc ^ 4294967295) >>> 0;
16749
17380
  }
16750
17381
  function dosDateTime(date) {
16751
- const year = Math.max(1980, date.getFullYear());
17382
+ const year = Math.max(1980, date.getUTCFullYear());
16752
17383
  return {
16753
- time: date.getHours() << 11 | date.getMinutes() << 5 | Math.floor(date.getSeconds() / 2),
16754
- date: year - 1980 << 9 | date.getMonth() + 1 << 5 | date.getDate()
17384
+ time: date.getUTCHours() << 11 | date.getUTCMinutes() << 5 | Math.floor(date.getUTCSeconds() / 2),
17385
+ date: year - 1980 << 9 | date.getUTCMonth() + 1 << 5 | date.getUTCDate()
16755
17386
  };
16756
17387
  }
16757
17388
  function walkFiles(root, prefix = "") {
16758
17389
  const files = [];
16759
- for (const entry of fs24__namespace.readdirSync(path25__namespace.join(root, prefix), { withFileTypes: true })) {
16760
- const relative14 = prefix === "" ? entry.name : prefix + "/" + entry.name;
16761
- if (entry.isDirectory()) files.push(...walkFiles(root, relative14));
16762
- else if (entry.isFile()) files.push(relative14);
17390
+ const stack = [prefix];
17391
+ while (stack.length > 0) {
17392
+ const current = stack.pop();
17393
+ for (const entry of fs24__namespace.readdirSync(path25__namespace.join(root, current), { withFileTypes: true })) {
17394
+ const relative15 = current === "" ? entry.name : current + "/" + entry.name;
17395
+ if (entry.isDirectory()) stack.push(relative15);
17396
+ else if (entry.isFile()) files.push(relative15);
17397
+ }
16763
17398
  }
16764
17399
  return files;
16765
17400
  }
16766
17401
  function writeZip(options) {
16767
17402
  const entries = [...options.entries ?? []];
17403
+ const maxTotalBytes = options.maxTotalBytes ?? 256 * 1024 * 1024;
17404
+ let totalBytes = entries.reduce((total, entry) => total + entry.content.length, 0);
17405
+ if (totalBytes > maxTotalBytes) {
17406
+ throw new Error("zip: uncompressed content exceeds " + maxTotalBytes + " bytes");
17407
+ }
16768
17408
  if (options.directory !== void 0) {
16769
17409
  const root = options.directory;
16770
- for (const relative14 of walkFiles(root)) {
16771
- if (options.skip !== void 0 && options.skip(relative14)) continue;
16772
- const full = path25__namespace.join(root, relative14);
17410
+ for (const relative15 of walkFiles(root)) {
17411
+ if (options.skip !== void 0 && options.skip(relative15)) continue;
17412
+ const full = path25__namespace.join(root, relative15);
16773
17413
  const stat = fs24__namespace.statSync(full);
16774
- entries.push({ name: relative14, content: fs24__namespace.readFileSync(full), mtime: stat.mtime });
17414
+ if (totalBytes + stat.size > maxTotalBytes) {
17415
+ throw new Error("zip: uncompressed content exceeds " + maxTotalBytes + " bytes");
17416
+ }
17417
+ const content = fs24__namespace.readFileSync(full);
17418
+ totalBytes += content.length;
17419
+ entries.push({ name: relative15, content, mtime: stat.mtime });
16775
17420
  }
16776
17421
  }
16777
17422
  if (entries.length > 65535) {
@@ -16991,6 +17636,7 @@ var SERVE_PAGE = `<!doctype html>
16991
17636
  var DEFAULT_PORT = 4788;
16992
17637
  var MAX_BODY = 64 * 1024;
16993
17638
  var MAX_PREVIEW = 64 * 1024;
17639
+ var MAX_MCP_IN_FLIGHT = 4;
16994
17640
  function isLoopback(origin) {
16995
17641
  try {
16996
17642
  const url = new URL(origin);
@@ -17008,6 +17654,23 @@ async function startWebServer(options) {
17008
17654
  throw new Error("Refusing to serve " + host + " without a token.");
17009
17655
  }
17010
17656
  const createMcp = () => createServer({ cwd: options.cwd, log });
17657
+ const toolCount = buildTools().length;
17658
+ const rateWindows = /* @__PURE__ */ new Map();
17659
+ const rateLimited = (request) => {
17660
+ const remote = request.socket.remoteAddress ?? "unknown";
17661
+ const now = Date.now();
17662
+ const window = rateWindows.get(remote);
17663
+ if (window === void 0 || window.resetAt <= now) {
17664
+ if (!rateWindows.has(remote) && rateWindows.size >= 1024) {
17665
+ for (const [key, value] of rateWindows) if (value.resetAt <= now) rateWindows.delete(key);
17666
+ }
17667
+ rateWindows.set(remote, { count: 1, resetAt: now + 1e4 });
17668
+ return false;
17669
+ }
17670
+ if (window.count >= 120) return true;
17671
+ window.count += 1;
17672
+ return false;
17673
+ };
17011
17674
  const mcpPerSocket = /* @__PURE__ */ new WeakMap();
17012
17675
  const mcpFor = (socket) => {
17013
17676
  let server2 = mcpPerSocket.get(socket);
@@ -17018,6 +17681,7 @@ async function startWebServer(options) {
17018
17681
  return server2;
17019
17682
  };
17020
17683
  const temporaryClones = /* @__PURE__ */ new Set();
17684
+ let mcpInFlight = 0;
17021
17685
  const allowedRoots = [path25__namespace.resolve(options.cwd)];
17022
17686
  const canonical = (candidate) => {
17023
17687
  try {
@@ -17026,21 +17690,22 @@ async function startWebServer(options) {
17026
17690
  return null;
17027
17691
  }
17028
17692
  };
17693
+ const fold = (value) => process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
17029
17694
  const inside = (resolved) => allowedRoots.some((root) => {
17030
17695
  const canonicalRoot = canonical(root);
17031
17696
  if (canonicalRoot === null) return false;
17032
- const relative14 = path25__namespace.relative(canonicalRoot, resolved);
17033
- return relative14 === "" || !relative14.startsWith(`..${path25__namespace.sep}`) && relative14 !== ".." && !path25__namespace.isAbsolute(relative14);
17697
+ const relative15 = path25__namespace.relative(fold(canonicalRoot), fold(resolved));
17698
+ return relative15 === "" || !relative15.startsWith(`..${path25__namespace.sep}`) && relative15 !== ".." && !path25__namespace.isAbsolute(relative15);
17034
17699
  });
17035
17700
  const insideAllowedRoots = (candidate) => {
17036
17701
  const resolved = canonical(candidate);
17037
17702
  return resolved === null ? false : inside(resolved);
17038
17703
  };
17039
17704
  const lexicallyInside = (candidate) => {
17040
- const resolved = path25__namespace.resolve(candidate);
17705
+ const resolved = fold(path25__namespace.resolve(candidate));
17041
17706
  return allowedRoots.some((root) => {
17042
- const prefix = path25__namespace.resolve(root) + path25__namespace.sep;
17043
- return resolved === path25__namespace.resolve(root) || resolved.startsWith(prefix);
17707
+ const resolvedRoot = fold(path25__namespace.resolve(root));
17708
+ return resolved === resolvedRoot || resolved.startsWith(resolvedRoot + path25__namespace.sep);
17044
17709
  });
17045
17710
  };
17046
17711
  const insideAllowedRootsForWrite = (candidate) => {
@@ -17098,8 +17763,12 @@ async function startWebServer(options) {
17098
17763
  response.end();
17099
17764
  return;
17100
17765
  }
17766
+ if (rateLimited(request)) {
17767
+ send(429, { error: "too many requests" }, { "retry-after": "10" });
17768
+ return;
17769
+ }
17101
17770
  if (request.method === "GET" && request.url === "/healthz") {
17102
- send(200, { ok: true, name: "codebase-snapshot", tools: 12 });
17771
+ send(200, { ok: true, name: "codebase-snapshot", tools: toolCount });
17103
17772
  return;
17104
17773
  }
17105
17774
  if (request.method === "GET" && (request.url === "/" || request.url === "/index.html")) {
@@ -17144,12 +17813,35 @@ async function startWebServer(options) {
17144
17813
  const server2 = mcpFor(request.socket);
17145
17814
  const answers = [];
17146
17815
  for (const item of batch) {
17147
- const answer = await server2.handle(item);
17148
- if (answer !== null) answers.push(answer);
17816
+ const gated = item !== null && typeof item === "object" && item.method === "tools/call";
17817
+ if (gated && mcpInFlight >= MAX_MCP_IN_FLIGHT) {
17818
+ answers.push({
17819
+ jsonrpc: "2.0",
17820
+ id: item.id ?? null,
17821
+ error: {
17822
+ code: -32001,
17823
+ message: "server busy: too many tool calls are already in flight"
17824
+ }
17825
+ });
17826
+ continue;
17827
+ }
17828
+ if (gated) mcpInFlight += 1;
17829
+ try {
17830
+ const answer = await server2.handle(item);
17831
+ if (answer !== null) answers.push(answer);
17832
+ } finally {
17833
+ if (gated) mcpInFlight -= 1;
17834
+ }
17149
17835
  }
17150
17836
  if (answers.length === 0) send(202, "");
17151
17837
  else send(200, Array.isArray(message) ? answers : answers[0]);
17152
- })();
17838
+ })().catch((error) => {
17839
+ log("serve: " + error.message);
17840
+ try {
17841
+ send(500, { error: "internal error" });
17842
+ } catch {
17843
+ }
17844
+ });
17153
17845
  });
17154
17846
  return;
17155
17847
  }
@@ -17242,13 +17934,12 @@ async function startWebServer(options) {
17242
17934
  send(400, { error: "not a directory: " + target });
17243
17935
  return;
17244
17936
  }
17245
- const loaded = await loadConfigFileDetailed(target, { allowExecutableConfig: false });
17937
+ const loaded = isRemote ? { config: null, errors: [] } : await loadConfigFileDetailed(target, { allowExecutableConfig: false });
17246
17938
  if (loaded.errors.length > 0) {
17247
17939
  send(400, { error: loaded.errors.join("; ") });
17248
17940
  return;
17249
17941
  }
17250
17942
  const runConfig = isRemote ? {
17251
- ...loaded.config ?? {},
17252
17943
  outDir: "snapshot",
17253
17944
  tmpDir: "snapshot.tmp",
17254
17945
  hooks: {}
@@ -17259,13 +17950,39 @@ async function startWebServer(options) {
17259
17950
  send(403, { error: "the configured outDir resolves outside the served directory" });
17260
17951
  return;
17261
17952
  }
17953
+ const configuredTmpDir = typeof runConfig.tmpDir === "string" && runConfig.tmpDir.trim() !== "" ? runConfig.tmpDir : "snapshot.tmp";
17954
+ const stagingDir = path25__namespace.resolve(target, configuredTmpDir);
17955
+ if (!insideAllowedRootsForWrite(stagingDir)) {
17956
+ send(403, { error: "the configured tmpDir resolves outside the served directory" });
17957
+ return;
17958
+ }
17262
17959
  const started = Date.now();
17263
17960
  try {
17264
- const manifest = generateSnapshot({ ...runConfig, cwd: target }, {
17265
- ...provenance === void 0 ? {} : { source: provenance },
17266
- ...mode === "slice" ? { slice: { question } } : {},
17267
- ...mode === "budget" && budgetTokens !== void 0 ? { budgetTokens } : {}
17268
- });
17961
+ const generated = await generateInWorker(
17962
+ target,
17963
+ { cwd: target },
17964
+ {
17965
+ config: runConfig,
17966
+ ...provenance === void 0 ? {} : { source: provenance },
17967
+ ...mode === "slice" && question.length >= 3 ? { narrow: { slice: { question } } } : {},
17968
+ ...mode === "budget" && budgetTokens !== void 0 ? { narrow: { budgetTokens } } : {}
17969
+ }
17970
+ );
17971
+ if (!generated.ok) {
17972
+ send(500, { error: generated.message });
17973
+ return;
17974
+ }
17975
+ const manifestRead = readConfinedText(snapshotDir, "manifest.json");
17976
+ if (!manifestRead.ok) {
17977
+ send(500, { error: "the generate worker did not write manifest.json" });
17978
+ return;
17979
+ }
17980
+ const manifest = JSON.parse(manifestRead.text);
17981
+ const shape = describeManifestShapeProblem(manifest);
17982
+ if (shape !== null) {
17983
+ send(500, { error: "the generated manifest is not a snapshot manifest: " + shape });
17984
+ return;
17985
+ }
17269
17986
  const seconds = ((Date.now() - started) / 1e3).toFixed(2);
17270
17987
  const health = auditSnapshot({ snapshotDir, repoDir: target });
17271
17988
  send(200, {
@@ -17288,7 +18005,13 @@ async function startWebServer(options) {
17288
18005
  } catch (error) {
17289
18006
  send(500, { error: error.message });
17290
18007
  }
17291
- })();
18008
+ })().catch((error) => {
18009
+ log("serve: " + error.message);
18010
+ try {
18011
+ send(500, { error: "internal error" });
18012
+ } catch {
18013
+ }
18014
+ });
17292
18015
  });
17293
18016
  return;
17294
18017
  }
@@ -17298,15 +18021,24 @@ async function startWebServer(options) {
17298
18021
  send(403, { error: "outside the served directory: " + target });
17299
18022
  return;
17300
18023
  }
17301
- if (!fs24__namespace.existsSync(path25__namespace.join(target, "manifest.json"))) {
17302
- send(404, { error: "no manifest.json under " + target });
18024
+ if (!fs24__namespace.existsSync(target)) {
18025
+ send(404, { error: "no snapshot directory at " + target });
17303
18026
  return;
17304
18027
  }
17305
18028
  if (!insideAllowedRoots(target)) {
17306
18029
  send(403, { error: "outside the served directory: " + target });
17307
18030
  return;
17308
18031
  }
17309
- const report2 = auditSnapshot({ snapshotDir: target, repoDir: path25__namespace.dirname(target) });
18032
+ const repoDir = path25__namespace.dirname(target);
18033
+ if (!insideAllowedRoots(repoDir)) {
18034
+ send(403, { error: "the repository root for this snapshot is outside the served directory" });
18035
+ return;
18036
+ }
18037
+ if (!fs24__namespace.existsSync(path25__namespace.join(target, "manifest.json"))) {
18038
+ send(404, { error: "no manifest.json under " + target });
18039
+ return;
18040
+ }
18041
+ const report2 = auditSnapshot({ snapshotDir: target, repoDir });
17310
18042
  send(200, { score: report2.score, counts: report2.counts, checks: report2.checks });
17311
18043
  return;
17312
18044
  }
@@ -17316,7 +18048,7 @@ async function startWebServer(options) {
17316
18048
  send(403, { error: "outside the served directory: " + target });
17317
18049
  return;
17318
18050
  }
17319
- if (!fs24__namespace.existsSync(path25__namespace.join(target, "manifest.json"))) {
18051
+ if (!fs24__namespace.existsSync(target)) {
17320
18052
  send(404, { error: "no manifest.json under " + target });
17321
18053
  return;
17322
18054
  }
@@ -17324,10 +18056,18 @@ async function startWebServer(options) {
17324
18056
  send(403, { error: "outside the served directory: " + target });
17325
18057
  return;
17326
18058
  }
17327
- const manifestFile = path25__namespace.join(target, "manifest.json");
18059
+ const manifestRead = readConfinedText(target, "manifest.json");
18060
+ if (!manifestRead.ok) {
18061
+ if (manifestRead.reason === "outside") {
18062
+ send(403, { error: "manifest.json resolves outside the snapshot directory" });
18063
+ } else {
18064
+ send(404, { error: "no readable manifest.json under " + target });
18065
+ }
18066
+ return;
18067
+ }
17328
18068
  let manifest;
17329
18069
  try {
17330
- manifest = JSON.parse(fs24__namespace.readFileSync(manifestFile, "utf8"));
18070
+ manifest = JSON.parse(manifestRead.text);
17331
18071
  } catch {
17332
18072
  send(404, { error: "no manifest.json under " + target });
17333
18073
  return;
@@ -17337,12 +18077,8 @@ async function startWebServer(options) {
17337
18077
  send(400, { error: "manifest.json is not a snapshot manifest: " + shapeProblem });
17338
18078
  return;
17339
18079
  }
17340
- let prompt = "";
17341
- try {
17342
- prompt = fs24__namespace.readFileSync(path25__namespace.join(target, "PROMPT.md"), "utf8").slice(0, MAX_PREVIEW);
17343
- } catch {
17344
- prompt = "(this snapshot has no PROMPT.md)";
17345
- }
18080
+ const promptRead = readConfinedText(target, "PROMPT.md");
18081
+ const prompt = promptRead.ok ? promptRead.text.slice(0, MAX_PREVIEW) : "(this snapshot has no readable PROMPT.md)";
17346
18082
  send(200, {
17347
18083
  fingerprint: manifest.fingerprint ?? "",
17348
18084
  generatedAt: manifest.generatedAt ?? "",
@@ -17360,7 +18096,7 @@ async function startWebServer(options) {
17360
18096
  send(403, { error: "outside the served directory: " + target });
17361
18097
  return;
17362
18098
  }
17363
- if (!fs24__namespace.existsSync(path25__namespace.join(target, "manifest.json")) && !fs24__namespace.existsSync(path25__namespace.join(target, ".codebase-snapshot"))) {
18099
+ if (!fs24__namespace.existsSync(target)) {
17364
18100
  send(404, { error: "not a snapshot directory: " + target });
17365
18101
  return;
17366
18102
  }
@@ -17368,6 +18104,10 @@ async function startWebServer(options) {
17368
18104
  send(403, { error: "outside the served directory: " + target });
17369
18105
  return;
17370
18106
  }
18107
+ if (!fs24__namespace.existsSync(path25__namespace.join(target, "manifest.json")) && !fs24__namespace.existsSync(path25__namespace.join(target, ".codebase-snapshot"))) {
18108
+ send(404, { error: "not a snapshot directory: " + target });
18109
+ return;
18110
+ }
17371
18111
  try {
17372
18112
  const zip = writeZip({ directory: target });
17373
18113
  response.writeHead(200, {
@@ -17384,11 +18124,11 @@ async function startWebServer(options) {
17384
18124
  }
17385
18125
  send(404, { error: "not found" });
17386
18126
  });
17387
- await new Promise((resolve14, reject) => {
18127
+ await new Promise((resolve15, reject) => {
17388
18128
  server.once("error", reject);
17389
18129
  server.listen(port, host, () => {
17390
18130
  server.removeListener("error", reject);
17391
- resolve14();
18131
+ resolve15();
17392
18132
  });
17393
18133
  });
17394
18134
  const address = server.address();
@@ -17400,14 +18140,14 @@ async function startWebServer(options) {
17400
18140
  port: actualPort,
17401
18141
  host,
17402
18142
  token,
17403
- close: () => new Promise((resolve14) => {
18143
+ close: () => new Promise((resolve15) => {
17404
18144
  for (const directory of temporaryClones) {
17405
18145
  try {
17406
18146
  fs24__namespace.rmSync(directory, { recursive: true, force: true });
17407
18147
  } catch {
17408
18148
  }
17409
18149
  }
17410
- server.close(() => resolve14());
18150
+ server.close(() => resolve15());
17411
18151
  })
17412
18152
  };
17413
18153
  }
@@ -17523,14 +18263,14 @@ function writeCache(file, entry) {
17523
18263
  }
17524
18264
  }
17525
18265
  function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOUT_MS) {
17526
- return new Promise((resolve14) => {
18266
+ return new Promise((resolve15) => {
17527
18267
  let settled = false;
17528
18268
  let request = null;
17529
18269
  const finish = (value) => {
17530
18270
  if (settled) return;
17531
18271
  settled = true;
17532
18272
  clearTimeout(deadline);
17533
- resolve14(value);
18273
+ resolve15(value);
17534
18274
  };
17535
18275
  const deadline = setTimeout(() => {
17536
18276
  request?.destroy();
@@ -17939,9 +18679,25 @@ function appendGitignoreEntries(cwd, entries) {
17939
18679
  let decoded = { text: "", bom: Buffer.alloc(0), encoding: "utf8" };
17940
18680
  try {
17941
18681
  if (fs24__namespace.existsSync(ignorePath)) {
17942
- if (fs24__namespace.statSync(ignorePath).isDirectory()) {
18682
+ const stats = fs24__namespace.lstatSync(ignorePath);
18683
+ if (stats.isDirectory()) {
17943
18684
  return { added: [], note: `${ignorePath} is a directory, so it was not updated. ${manual}` };
17944
18685
  }
18686
+ if (stats.isSymbolicLink() || !stats.isFile() || stats.nlink > 1) {
18687
+ return {
18688
+ added: [],
18689
+ note: `${ignorePath} is a symbolic link, a hard link, or not a regular file, so it was not updated. ` + manual
18690
+ };
18691
+ }
18692
+ const rootReal = fs24__namespace.realpathSync(cwd);
18693
+ const fileReal = fs24__namespace.realpathSync(ignorePath);
18694
+ const relative15 = path25__namespace.relative(rootReal, fileReal);
18695
+ if (relative15 === ".." || relative15.startsWith(`..${path25__namespace.sep}`) || path25__namespace.isAbsolute(relative15)) {
18696
+ return {
18697
+ added: [],
18698
+ note: `${ignorePath} resolves outside the repository, so it was not updated. ${manual}`
18699
+ };
18700
+ }
17945
18701
  const read = decodeGitignore(fs24__namespace.readFileSync(ignorePath));
17946
18702
  if (read === null) {
17947
18703
  return {
@@ -17963,12 +18719,19 @@ function appendGitignoreEntries(cwd, entries) {
17963
18719
  if (added.length === 0) return { added: [], note: null };
17964
18720
  const newline = existing.includes("\r\n") ? "\r\n" : "\n";
17965
18721
  const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : newline;
18722
+ const tempPath = `${ignorePath}.${process.pid}.${Date.now()}.tmp`;
17966
18723
  try {
17967
18724
  fs24__namespace.writeFileSync(
17968
- ignorePath,
17969
- encodeGitignore(decoded, `${existing}${prefix}${added.join(newline)}${newline}`)
18725
+ tempPath,
18726
+ encodeGitignore(decoded, `${existing}${prefix}${added.join(newline)}${newline}`),
18727
+ { flag: "wx" }
17970
18728
  );
18729
+ fs24__namespace.renameSync(tempPath, ignorePath);
17971
18730
  } catch (err) {
18731
+ try {
18732
+ fs24__namespace.rmSync(tempPath, { force: true });
18733
+ } catch {
18734
+ }
17972
18735
  return { added: [], note: `${err.message}. ${manual}` };
17973
18736
  }
17974
18737
  return { added, note: null };
@@ -18364,7 +19127,7 @@ function keyReader(input) {
18364
19127
  next() {
18365
19128
  const queued = queue.shift();
18366
19129
  if (queued) return Promise.resolve(queued);
18367
- return new Promise((resolve14) => waiters.push(resolve14));
19130
+ return new Promise((resolve15) => waiters.push(resolve15));
18368
19131
  },
18369
19132
  close() {
18370
19133
  input.off("keypress", onKey);
@@ -18797,11 +19560,11 @@ function gitignoreEntriesFor(cwd, outDir, tmpDir) {
18797
19560
  const entries = [];
18798
19561
  for (const directory of [outDir, tmpDir]) {
18799
19562
  if (directory === null) continue;
18800
- const relative14 = path25__namespace.relative(cwd, path25__namespace.resolve(cwd, directory)).replace(/\\/g, "/");
18801
- if (relative14 === "" || relative14 === "." || relative14.startsWith("..") || path25__namespace.isAbsolute(relative14)) {
19563
+ const relative15 = path25__namespace.relative(cwd, path25__namespace.resolve(cwd, directory)).replace(/\\/g, "/");
19564
+ if (relative15 === "" || relative15 === "." || relative15.startsWith("..") || path25__namespace.isAbsolute(relative15)) {
18802
19565
  continue;
18803
19566
  }
18804
- entries.push(`/${relative14}/`);
19567
+ entries.push(`/${relative15}/`);
18805
19568
  }
18806
19569
  return [...new Set(entries)];
18807
19570
  }
@@ -18957,7 +19720,14 @@ async function runInit(options) {
18957
19720
  try {
18958
19721
  const raw = await text(io, "Part size (e.g. 150k, 1.5mb, 900000)", {
18959
19722
  defaultValue: currentBudget,
18960
- validate: (value) => parseByteSize(value) === void 0 ? "Not a valid size." : null,
19723
+ validate: (value) => {
19724
+ const parsed = parseByteSize(value);
19725
+ if (parsed === void 0) return "Not a valid size.";
19726
+ if (parsed < MIN_MAX_PART_BYTES) {
19727
+ return `A part budget below ${MIN_MAX_PART_BYTES} bytes cannot hold the truncation notice.`;
19728
+ }
19729
+ return null;
19730
+ },
18961
19731
  allowBack: true
18962
19732
  });
18963
19733
  answers.maxPartBytes = parseByteSize(raw) ?? answers.maxPartBytes;
@@ -19132,10 +19902,10 @@ async function runInit(options) {
19132
19902
  };
19133
19903
  }
19134
19904
  function describeTarget(cwd) {
19135
- const relative14 = path25__namespace.relative(process.cwd(), cwd);
19136
- if (relative14 === "") return "this directory";
19137
- if (relative14.startsWith("..") || path25__namespace.isAbsolute(relative14)) return cwd;
19138
- return relative14;
19905
+ const relative15 = path25__namespace.relative(process.cwd(), cwd);
19906
+ if (relative15 === "") return "this directory";
19907
+ if (relative15.startsWith("..") || path25__namespace.isAbsolute(relative15)) return cwd;
19908
+ return relative15;
19139
19909
  }
19140
19910
  function firstRunMessage(reason, cwd) {
19141
19911
  const where = describeTarget(cwd);
@@ -19205,7 +19975,7 @@ if [ ! -f "$SNAPSHOT_DIR/manifest.json" ]; then
19205
19975
  exit 1
19206
19976
  fi
19207
19977
 
19208
- if ! npx --no-install ${GENERATOR_NAME} validate >/dev/null 2>&1; then
19978
+ if ! npx --no-install ${GENERATOR_NAME} validate --out-dir "$SNAPSHOT_DIR" >/dev/null 2>&1; then
19209
19979
  echo "${GENERATOR_NAME}: the snapshot is out of date." >&2
19210
19980
  echo " Run \\"npx ${GENERATOR_NAME} generate\\", stage the change, and commit again." >&2
19211
19981
  echo " (npx --no-install is used on purpose: this hook must not install anything)" >&2
@@ -19229,16 +19999,36 @@ function gitDirectory(cwd) {
19229
19999
  if (!match) return null;
19230
20000
  const target = match[1];
19231
20001
  const resolved = path25__namespace.isAbsolute(target.trim()) ? target.trim() : path25__namespace.join(cwd, target.trim());
19232
- if (!fs24__namespace.statSync(resolved).isDirectory()) return null;
19233
- if (isInside3(path25__namespace.resolve(cwd), path25__namespace.resolve(resolved))) return resolved;
19234
- return isRegisteredWorktree(path25__namespace.resolve(resolved), cwd) ? resolved : null;
20002
+ const cwdReal = canonicalForWrite(cwd);
20003
+ const resolvedReal = canonicalForWrite(resolved);
20004
+ if (cwdReal === null || resolvedReal === null || !fs24__namespace.statSync(resolvedReal).isDirectory()) {
20005
+ return null;
20006
+ }
20007
+ if (isInside4(cwdReal, resolvedReal)) return resolvedReal;
20008
+ return isRegisteredWorktree(path25__namespace.resolve(resolved), cwd) ? resolvedReal : null;
19235
20009
  } catch {
19236
20010
  return null;
19237
20011
  }
19238
20012
  }
19239
- function isInside3(parent, child) {
19240
- const relative14 = path25__namespace.relative(parent, child);
19241
- return relative14 === "" || !relative14.startsWith("..") && !path25__namespace.isAbsolute(relative14);
20013
+ function isInside4(parent, child) {
20014
+ const relative15 = path25__namespace.relative(parent, child);
20015
+ return relative15 === "" || !relative15.startsWith("..") && !path25__namespace.isAbsolute(relative15);
20016
+ }
20017
+ function canonicalForWrite(target) {
20018
+ let existing = path25__namespace.resolve(target);
20019
+ const tail = [];
20020
+ while (!fs24__namespace.existsSync(existing)) {
20021
+ tail.unshift(path25__namespace.basename(existing));
20022
+ const parent = path25__namespace.dirname(existing);
20023
+ if (parent === existing) break;
20024
+ existing = parent;
20025
+ }
20026
+ try {
20027
+ const real = fs24__namespace.realpathSync(existing);
20028
+ return tail.length === 0 ? real : path25__namespace.join(real, ...tail);
20029
+ } catch {
20030
+ return null;
20031
+ }
19242
20032
  }
19243
20033
  function isRegisteredWorktree(gitDir, cwd) {
19244
20034
  try {
@@ -19266,9 +20056,16 @@ function configuredHooksDirectory(cwd) {
19266
20056
  if (hooks === null) return null;
19267
20057
  const resolved = path25__namespace.resolve(cwd, hooks);
19268
20058
  const common = gitOutput(cwd, ["rev-parse", "--git-common-dir"]);
19269
- const commonDir = common === null ? null : path25__namespace.resolve(cwd, common);
19270
- if (isInside3(path25__namespace.resolve(cwd), resolved)) return { dir: resolved };
19271
- if (commonDir !== null && isInside3(commonDir, resolved)) return { dir: resolved };
20059
+ const commonDir = common === null ? null : canonicalForWrite(path25__namespace.resolve(cwd, common));
20060
+ const cwdReal = canonicalForWrite(cwd);
20061
+ const hooksReal = canonicalForWrite(resolved);
20062
+ if (hooksReal === null || cwdReal === null) {
20063
+ return {
20064
+ refusal: `The hooks directory git reports (${resolved}) could not be resolved, so no hook was written.`
20065
+ };
20066
+ }
20067
+ if (isInside4(cwdReal, hooksReal)) return { dir: hooksReal };
20068
+ if (commonDir !== null && isInside4(commonDir, hooksReal)) return { dir: hooksReal };
19272
20069
  return {
19273
20070
  refusal: `The hooks directory git reports (${resolved}) is outside this repository, so no hook was written. Add \`npx ${GENERATOR_NAME} validate\` to the hook manager that owns it instead.`
19274
20071
  };
@@ -19288,8 +20085,48 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
19288
20085
  ]
19289
20086
  };
19290
20087
  }
19291
- const hooksDir = configured === null ? path25__namespace.join(gitDir, "hooks") : configured.dir;
20088
+ const hooksDirRaw = configured === null ? path25__namespace.join(gitDir, "hooks") : configured.dir;
20089
+ const hooksDir = canonicalForWrite(hooksDirRaw);
20090
+ if (hooksDir === null) {
20091
+ return {
20092
+ path: null,
20093
+ written: false,
20094
+ notes: [`Refusing to write the hooks directory: ${hooksDirRaw} could not be resolved.`]
20095
+ };
20096
+ }
19292
20097
  const hookPath = path25__namespace.join(hooksDir, "pre-commit");
20098
+ try {
20099
+ const existingStats = fs24__namespace.lstatSync(hookPath);
20100
+ if (existingStats.isSymbolicLink()) {
20101
+ return {
20102
+ path: hookPath,
20103
+ written: false,
20104
+ notes: [`Refusing to write ${hookPath}: it is a symbolic link.`]
20105
+ };
20106
+ }
20107
+ if (existingStats.isFile() && existingStats.nlink > 1) {
20108
+ return {
20109
+ path: hookPath,
20110
+ written: false,
20111
+ notes: [`Refusing to write ${hookPath}: it has ${existingStats.nlink} hard links.`]
20112
+ };
20113
+ }
20114
+ if (!existingStats.isFile()) {
20115
+ return {
20116
+ path: hookPath,
20117
+ written: false,
20118
+ notes: [`Refusing to write ${hookPath}: it is not a regular file.`]
20119
+ };
20120
+ }
20121
+ } catch (error) {
20122
+ if (error.code !== "ENOENT") {
20123
+ return {
20124
+ path: hookPath,
20125
+ written: false,
20126
+ notes: [`Refusing to write ${hookPath}: ${error.message}`]
20127
+ };
20128
+ }
20129
+ }
19293
20130
  try {
19294
20131
  fs24__namespace.mkdirSync(hooksDir, { recursive: true });
19295
20132
  } catch (err) {
@@ -19339,23 +20176,23 @@ var SUMMARY_MAX_SOURCE_BYTES2 = SUMMARY_MAX_SOURCE_BYTES;
19339
20176
  var FILE_DERIVATIONS = /* @__PURE__ */ new Map();
19340
20177
  var FILE_DERIVATION_LIMIT_BYTES = 64 * 1024 * 1024;
19341
20178
  var fileDerivationBytes = 0;
19342
- function takeDerivation(path26, hash, settings) {
19343
- const cached = FILE_DERIVATIONS.get(path26);
20179
+ function takeDerivation(path26, relativePath, hash, settings) {
20180
+ const key = path26 + "\0" + relativePath;
20181
+ const cached = FILE_DERIVATIONS.get(key);
19344
20182
  if (cached === void 0 || cached.hash !== hash || cached.settings !== settings) return void 0;
19345
- FILE_DERIVATIONS.delete(path26);
19346
- FILE_DERIVATIONS.set(path26, cached);
20183
+ FILE_DERIVATIONS.delete(key);
20184
+ FILE_DERIVATIONS.set(key, cached);
19347
20185
  return cached;
19348
20186
  }
19349
- function rememberDerivation(path26, hash, settings, derivation) {
20187
+ function rememberDerivation(path26, relativePath, hash, settings, derivation) {
20188
+ const key = path26 + "\0" + relativePath;
19350
20189
  const bodyBytes = derivation.finalContent === derivation.redacted ? derivation.redacted.length : derivation.redacted.length + derivation.finalContent.length;
19351
20190
  const bytes = bodyBytes * 2 + 512;
19352
20191
  if (bytes > FILE_DERIVATION_LIMIT_BYTES / 4) return;
19353
- const previous = FILE_DERIVATIONS.get(path26);
20192
+ const previous = FILE_DERIVATIONS.get(key);
19354
20193
  if (previous !== void 0) {
19355
- FILE_DERIVATIONS.delete(path26);
20194
+ FILE_DERIVATIONS.delete(key);
19356
20195
  fileDerivationBytes -= previous.bytes;
19357
- } else {
19358
- FILE_DERIVATIONS.delete(path26);
19359
20196
  }
19360
20197
  while (fileDerivationBytes + bytes > FILE_DERIVATION_LIMIT_BYTES) {
19361
20198
  const oldest = FILE_DERIVATIONS.keys().next();
@@ -19364,7 +20201,7 @@ function rememberDerivation(path26, hash, settings, derivation) {
19364
20201
  FILE_DERIVATIONS.delete(oldest.value);
19365
20202
  if (evicted !== void 0) fileDerivationBytes -= evicted.bytes;
19366
20203
  }
19367
- FILE_DERIVATIONS.set(path26, { ...derivation, hash, settings, bytes });
20204
+ FILE_DERIVATIONS.set(key, { ...derivation, hash, settings, bytes });
19368
20205
  fileDerivationBytes += bytes;
19369
20206
  }
19370
20207
  function derivationSettings(config) {
@@ -19620,6 +20457,11 @@ function verifyInMemory(files, parts, unaccounted) {
19620
20457
  }
19621
20458
  }
19622
20459
  for (const part of parts) {
20460
+ if (part.metadata.hardClipped === true) {
20461
+ errors.push(
20462
+ `${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.`
20463
+ );
20464
+ }
19623
20465
  if (sha256Hex2(part.markdown) !== part.metadata.sha256) {
19624
20466
  errors.push(`${part.filename} content does not match its recorded sha256.`);
19625
20467
  }
@@ -19648,7 +20490,12 @@ function resolveSafeOutputDirs(config) {
19648
20490
  const outDir = path25__namespace.resolve(cwd, config.outDir);
19649
20491
  const tmpDir = path25__namespace.resolve(cwd, config.tmpDir);
19650
20492
  const root = path25__namespace.parse(cwd).root;
19651
- const contains = (parent, child) => child === parent || child.startsWith(`${parent}${path25__namespace.sep}`);
20493
+ const fold = (value) => process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
20494
+ const contains = (parent, child) => {
20495
+ const foldedParent = fold(parent);
20496
+ const foldedChild = fold(child);
20497
+ return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path25__namespace.sep}`);
20498
+ };
19652
20499
  const reject = (reason) => {
19653
20500
  throw new Error(
19654
20501
  `Refusing to generate: ${reason}. outDir=${outDir} tmpDir=${tmpDir} cwd=${cwd}`
@@ -19690,7 +20537,7 @@ function maskPathText(value, secretRules) {
19690
20537
  }
19691
20538
  function maskOwnerBrief(brief, secretRules) {
19692
20539
  if (brief === void 0) return void 0;
19693
- const mask = (value) => scanAndRedactSecrets(value, secretRules ?? [], "owner-brief").redacted;
20540
+ const mask = (value) => maskProse(value, secretRules, "owner-brief");
19694
20541
  return {
19695
20542
  ...brief,
19696
20543
  path: mask(brief.path),
@@ -19700,11 +20547,17 @@ function maskOwnerBrief(brief, secretRules) {
19700
20547
  ...brief.bar === void 0 ? {} : { bar: mask(brief.bar) },
19701
20548
  ...brief.calibration === void 0 ? {} : { calibration: mask(brief.calibration) },
19702
20549
  ...brief.preamble === void 0 ? {} : { preamble: mask(brief.preamble) },
19703
- notes: brief.notes.map((note) => ({ heading: note.heading, body: mask(note.body) }))
20550
+ // The heading is prose too. Masking only the body left `## Incident ghp_…` in PROMPT.md:
20551
+ // ownerNotesSection reproduced the heading as a Markdown title, where no line rule that
20552
+ // expects `key: value` can see it.
20553
+ notes: brief.notes.map((note) => ({ heading: mask(note.heading), body: mask(note.body) }))
19704
20554
  };
19705
20555
  }
20556
+ function maskProse(value, secretRules, scope) {
20557
+ return scanAndRedactSecrets(value, secretRules ?? [], scope).redacted;
20558
+ }
19706
20559
  function maskOverview(overview, secretRules) {
19707
- const mask = (value) => maskPathText(value, secretRules);
20560
+ const mask = (value) => maskProse(value, secretRules, "overview");
19708
20561
  return {
19709
20562
  ...overview.description === void 0 ? {} : { description: mask(overview.description) },
19710
20563
  ...overview.summary === void 0 ? {} : { summary: mask(overview.summary) },
@@ -19736,9 +20589,9 @@ function listEntries(dir) {
19736
20589
  return;
19737
20590
  }
19738
20591
  for (const child of children) {
19739
- const relative14 = prefix === "" ? child.name : `${prefix}/${child.name}`;
19740
- entries.push(relative14);
19741
- if (child.isDirectory()) walk2(path25__namespace.join(absolute, child.name), relative14);
20592
+ const relative15 = prefix === "" ? child.name : `${prefix}/${child.name}`;
20593
+ entries.push(relative15);
20594
+ if (child.isDirectory()) walk2(path25__namespace.join(absolute, child.name), relative15);
19742
20595
  }
19743
20596
  };
19744
20597
  walk2(dir, "");
@@ -20193,6 +21046,7 @@ function ensureParentDirectory(target, label) {
20193
21046
  }
20194
21047
  var LOCK_HEARTBEAT_MS = 5e3;
20195
21048
  var LOCK_STALE_HEARTBEAT_MS = 12e4;
21049
+ var LOCK_EMPTY_GRACE_MS = 5e3;
20196
21050
  var LOCK_HEARTBEAT_SOURCE = `
20197
21051
  const { parentPort, workerData } = require("node:worker_threads");
20198
21052
  const fs = require("node:fs");
@@ -20334,9 +21188,11 @@ function lockOwnerIsGone(lockPath) {
20334
21188
  try {
20335
21189
  pid = JSON.parse(raw).pid;
20336
21190
  } catch {
20337
- return lockFileIsAncient(lockPath);
21191
+ return lockFileIsAncient(lockPath, LOCK_EMPTY_GRACE_MS);
21192
+ }
21193
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) {
21194
+ return lockFileIsAncient(lockPath, LOCK_EMPTY_GRACE_MS);
20338
21195
  }
20339
- if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return lockFileIsAncient(lockPath);
20340
21196
  try {
20341
21197
  process.kill(pid, 0);
20342
21198
  return lockFileIsAncient(lockPath);
@@ -20363,8 +21219,8 @@ function reclaimStaleLock(lockPath) {
20363
21219
  return false;
20364
21220
  }
20365
21221
  }
20366
- function lockFileIsAncient(lockPath) {
20367
- return lockHeartbeatAgeMs(lockPath) > LOCK_STALE_HEARTBEAT_MS;
21222
+ function lockFileIsAncient(lockPath, thresholdMs = LOCK_STALE_HEARTBEAT_MS) {
21223
+ return lockHeartbeatAgeMs(lockPath) > thresholdMs;
20368
21224
  }
20369
21225
  function writeManifestAtomically(manifestPath, manifest) {
20370
21226
  const tempPath = `${manifestPath}.${process.pid}.tmp`;
@@ -20379,13 +21235,13 @@ function writeManifestAtomically(manifestPath, manifest) {
20379
21235
  throw err;
20380
21236
  }
20381
21237
  }
20382
- function swapIntoPlace(stagingDir, outDir, beforeSwap) {
21238
+ function swapIntoPlace(stagingDir, outDir, beforeSwap, onStagingPreserved) {
20383
21239
  ensureParentDirectory(outDir, "outDir");
20384
21240
  const deadline = Date.now() + 3e3;
20385
21241
  let delay = 25;
20386
21242
  for (; ; ) {
20387
21243
  try {
20388
- swapOnce(stagingDir, outDir, beforeSwap);
21244
+ swapOnce(stagingDir, outDir, beforeSwap, onStagingPreserved);
20389
21245
  return;
20390
21246
  } catch (err) {
20391
21247
  const code = err.code;
@@ -20420,7 +21276,7 @@ function recoverInterruptedPublish(outDir) {
20420
21276
  } catch {
20421
21277
  }
20422
21278
  }
20423
- function swapOnce(stagingDir, outDir, beforeSwap) {
21279
+ function swapOnce(stagingDir, outDir, beforeSwap, onStagingPreserved) {
20424
21280
  const backupDir = `${outDir}.backup-${process.pid}-${Date.now()}`;
20425
21281
  const hadPrevious = fs24__namespace.existsSync(outDir);
20426
21282
  if (hadPrevious) beforeSwap?.();
@@ -20431,6 +21287,7 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
20431
21287
  movedAside = true;
20432
21288
  } catch (err) {
20433
21289
  if (!isLockError(err)) throw err;
21290
+ onStagingPreserved?.();
20434
21291
  fs24__namespace.rmSync(outDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
20435
21292
  process.stderr.write(
20436
21293
  `\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.
@@ -20461,6 +21318,7 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
20461
21318
  if (fs24__namespace.existsSync(outDir)) fs24__namespace.rmSync(outDir, { recursive: true, force: true });
20462
21319
  fs24__namespace.renameSync(backupDir, outDir);
20463
21320
  } else if (hadPrevious && !movedAside) {
21321
+ onStagingPreserved?.();
20464
21322
  process.stderr.write(
20465
21323
  `\u26A0 The previous snapshot at ${outDir} was removed and the new one could not be moved into place. It is complete at ${stagingDir}.
20466
21324
  `
@@ -20650,7 +21508,7 @@ function generateSnapshot(configInput, options) {
20650
21508
  // output — but only at these exact paths, not at every directory that shares the name.
20651
21509
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
20652
21510
  (directory) => path25__namespace.relative(config.cwd, path25__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
20653
- ).filter((relative14) => relative14.length > 0 && !relative14.startsWith("..")),
21511
+ ).filter((relative15) => relative15.length > 0 && !relative15.startsWith("..")),
20654
21512
  // A staged path can be absent from the working tree while its index blob exists. Discovery
20655
21513
  // lists the working tree, so those paths would never reach the scan at all.
20656
21514
  ...stagedPaths.size > 0 ? { extraPaths: [...stagedPaths] } : {}
@@ -20796,9 +21654,9 @@ function generateSnapshot(configInput, options) {
20796
21654
  const language = detectLanguage(relativePath);
20797
21655
  bump(layerCounts, layer2);
20798
21656
  bump(kindCounts, kind);
20799
- const derivation = takeDerivation(absolutePath, hashSha256, derivationKey) ?? (() => {
21657
+ const derivation = takeDerivation(absolutePath, relativePath, hashSha256, derivationKey) ?? (() => {
20800
21658
  const fresh = deriveFile(relativePath, rawContent, sizeBytes, config);
20801
- rememberDerivation(absolutePath, hashSha256, derivationKey, fresh);
21659
+ rememberDerivation(absolutePath, relativePath, hashSha256, derivationKey, fresh);
20802
21660
  return fresh;
20803
21661
  })();
20804
21662
  const { lineCount } = derivation;
@@ -20978,7 +21836,9 @@ function generateSnapshot(configInput, options) {
20978
21836
  const tokens = Math.max(1, Math.ceil(file.includedBytes / 4));
20979
21837
  const value = (entry(file.relativePath) ? 100 : 0) + layerWeight(file.layer) + Math.min(60, (importers.get(file.relativePath) ?? 0) * 6) - Math.min(40, tokens / 250);
20980
21838
  return { file, tokens, value };
20981
- }).sort((left, right) => right.value - left.value || left.tokens - right.tokens || left.file.relativePath.localeCompare(right.file.relativePath));
21839
+ }).sort(
21840
+ (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)
21841
+ );
20982
21842
  const keep = /* @__PURE__ */ new Set();
20983
21843
  let used = 0;
20984
21844
  const selected = [];
@@ -21340,7 +22200,7 @@ function generateSnapshot(configInput, options) {
21340
22200
  const reportExcludes = [...config.excludePatterns, ...config.presetExclude];
21341
22201
  const diffReport = artifacts.diff ? generateDiffReport(config.cwd, {
21342
22202
  secretRules: config.secretRules,
21343
- excluded: (relativePath) => reportExcludes.some((pattern) => matchesExclude(relativePath, pattern))
22203
+ excluded: (relativePath) => isSensitivePath(relativePath) || defaultIgnoreReason(relativePath) !== null || config.include.length > 0 && !config.include.some((pattern) => matchesExclude(relativePath, pattern)) || reportExcludes.some((pattern) => matchesExclude(relativePath, pattern))
21344
22204
  }) : null;
21345
22205
  if (diffReport !== null) manifest.artifacts.diff = artifactRecord(diffReport.text);
21346
22206
  const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount, secretRules: config.secretRules }) : null;
@@ -21366,8 +22226,8 @@ function generateSnapshot(configInput, options) {
21366
22226
  task: config.promptTask,
21367
22227
  brief: maskOwnerBrief(config.brief, config.secretRules),
21368
22228
  history: recentCommits(config.cwd).map((commit) => ({
21369
- subject: maskPathText(commit.subject, config.secretRules),
21370
- body: maskPathText(commit.body, config.secretRules)
22229
+ subject: maskProse(commit.subject, config.secretRules, "git-log"),
22230
+ body: maskProse(commit.body, config.secretRules, "git-log")
21371
22231
  })),
21372
22232
  overview: maskOverview(readProjectOverview(config.cwd), config.secretRules)
21373
22233
  }) : null;
@@ -21387,8 +22247,11 @@ function generateSnapshot(configInput, options) {
21387
22247
  const entry = {
21388
22248
  ...file,
21389
22249
  content,
21390
- inclusionMode: file.inclusionMode === "comments-stripped" ? "comments-stripped" : "full",
21391
- ...file.emptyLinesRemoved === true ? { emptyLinesRemoved: true } : {},
22250
+ // `fullContents` is the pre-preview body but still carries comments and blank lines: the
22251
+ // monolith is the whole source, not the comments-stripped variant. Calling it
22252
+ // `comments-stripped` (or copying `emptyLinesRemoved`) described a transformation this
22253
+ // artifact did not perform.
22254
+ inclusionMode: "full",
21392
22255
  isPreviewTruncated: false,
21393
22256
  includedBytes: Buffer.byteLength(content, "utf8"),
21394
22257
  includedLines: countLines(content)
@@ -21467,6 +22330,7 @@ function generateSnapshot(configInput, options) {
21467
22330
  recoverInterruptedPublish(outDir);
21468
22331
  assertReplaceable(outDir, "outDir", config.secretRules);
21469
22332
  let stagingDir = null;
22333
+ let stagingPreserved = false;
21470
22334
  let releaseDeferred = false;
21471
22335
  try {
21472
22336
  ensureParentDirectory(outDir, "outDir");
@@ -21493,21 +22357,25 @@ function generateSnapshot(configInput, options) {
21493
22357
  fs24__namespace.mkdirSync(reportsDir, { recursive: true });
21494
22358
  }
21495
22359
  const writtenArtifacts = /* @__PURE__ */ new Map();
22360
+ const ledgerRoot = (targetDir) => stagingDir !== null && (targetDir === stagingDir || targetDir.startsWith(stagingDir + path25__namespace.sep)) ? stagingDir : outDir;
22361
+ const ledgerEntry = (targetDir, relativeEntry) => path25__namespace.relative(ledgerRoot(targetDir), path25__namespace.join(targetDir, ...relativeEntry.split("/"))).split(path25__namespace.sep).join("/");
21496
22362
  const writeArtifact = (targetDir, relativeEntry, data) => {
21497
22363
  const full = path25__namespace.join(targetDir, ...relativeEntry.split("/"));
21498
22364
  fs24__namespace.writeFileSync(full, data, "utf8");
21499
22365
  const stats = fs24__namespace.statSync(full);
21500
- writtenArtifacts.set(relativeEntry, {
21501
- digest: { path: relativeEntry, bytes: stats.size, sha256: sha256Hex2(data) },
22366
+ const entry = ledgerEntry(targetDir, relativeEntry);
22367
+ writtenArtifacts.set(entry, {
22368
+ digest: { path: entry, bytes: stats.size, sha256: sha256Hex2(data) },
21502
22369
  mtimeMs: stats.mtimeMs
21503
22370
  });
21504
22371
  };
21505
22372
  const recordArtifact = (targetDir, relativeEntry) => {
21506
22373
  const full = path25__namespace.join(targetDir, ...relativeEntry.split("/"));
21507
22374
  const stats = fs24__namespace.statSync(full);
21508
- writtenArtifacts.set(relativeEntry, {
22375
+ const entry = ledgerEntry(targetDir, relativeEntry);
22376
+ writtenArtifacts.set(entry, {
21509
22377
  digest: {
21510
- path: relativeEntry,
22378
+ path: entry,
21511
22379
  bytes: stats.size,
21512
22380
  sha256: sha256Hex2(fs24__namespace.readFileSync(full))
21513
22381
  },
@@ -21576,7 +22444,14 @@ function generateSnapshot(configInput, options) {
21576
22444
  stagingDir,
21577
22445
  markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts, runId)
21578
22446
  );
21579
- swapIntoPlace(stagingDir, outDir, () => assertReplaceable(outDir, "outDir", config.secretRules));
22447
+ swapIntoPlace(
22448
+ stagingDir,
22449
+ outDir,
22450
+ () => assertReplaceable(outDir, "outDir", config.secretRules),
22451
+ () => {
22452
+ stagingPreserved = true;
22453
+ }
22454
+ );
21580
22455
  stagingDir = null;
21581
22456
  const warningsBeforeHook = manifest.warnings.length;
21582
22457
  const pendingHook = runAfterGenerate(config, manifest);
@@ -21630,7 +22505,7 @@ function generateSnapshot(configInput, options) {
21630
22505
  }
21631
22506
  return manifest;
21632
22507
  } catch (err) {
21633
- if (stagingDir !== null) {
22508
+ if (stagingDir !== null && !stagingPreserved) {
21634
22509
  try {
21635
22510
  fs24__namespace.rmSync(stagingDir, { recursive: true, force: true });
21636
22511
  } catch {