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.
@@ -116,7 +116,7 @@ function finalizeSummary(summary) {
116
116
  }
117
117
  function eachLine(content, visit) {
118
118
  const text2 = content.length > MAX_SUMMARY_CHARS ? content.slice(0, MAX_SUMMARY_CHARS) : content;
119
- for (const line of text2.split(/\r?\n/)) visit(line);
119
+ for (const line of text2.split(/\r\n|\n|\r/)) visit(line);
120
120
  }
121
121
  function isTopLevel(line) {
122
122
  return !/^[\s]/.test(line);
@@ -621,9 +621,9 @@ var rubyProfile = {
621
621
  eachLine(content, (line) => {
622
622
  const trimmed = line.trim();
623
623
  if (!trimmed || trimmed.startsWith("#")) return;
624
- const relative14 = REQUIRE_RELATIVE.exec(trimmed);
625
- if (relative14) {
626
- summary.imports.push(`./${relative14[1]}`);
624
+ const relative15 = REQUIRE_RELATIVE.exec(trimmed);
625
+ if (relative15) {
626
+ summary.imports.push(`./${relative15[1]}`);
627
627
  return;
628
628
  }
629
629
  const required = REQUIRE.exec(trimmed);
@@ -807,7 +807,7 @@ function summarizeTypeScriptSource(relativePath, content) {
807
807
  routeHandlers: []
808
808
  };
809
809
  const lowerPath = relativePath.toLowerCase();
810
- const scriptKind2 = /.tsx$/.test(lowerPath) ? ts.ScriptKind.TSX : /.jsx$/.test(lowerPath) ? ts.ScriptKind.JSX : /.(?:js|mjs|cjs)$/.test(lowerPath) ? ts.ScriptKind.JS : ts.ScriptKind.TS;
810
+ const scriptKind2 = /\.tsx$/.test(lowerPath) ? ts.ScriptKind.TSX : /\.jsx$/.test(lowerPath) ? ts.ScriptKind.JSX : /.(?:js|mjs|cjs)$/.test(lowerPath) ? ts.ScriptKind.JS : ts.ScriptKind.TS;
811
811
  const sourceFile = ts.createSourceFile(
812
812
  relativePath,
813
813
  content,
@@ -1399,17 +1399,17 @@ function decodeText(buffer) {
1399
1399
  };
1400
1400
  }
1401
1401
  const invalidBytes = countInvalidUtf8Bytes(buffer);
1402
+ const controlBytes = countControlBytes(buffer);
1403
+ if (controlBytes > CONTROL_BYTES_FLOOR && controlBytes * 100 > buffer.length) {
1404
+ return {
1405
+ text: "",
1406
+ encoding: "utf-8",
1407
+ invalidBytes,
1408
+ binary: true,
1409
+ binaryReason: `${controlBytes} control byte(s) in ${buffer.length} B; not text`
1410
+ };
1411
+ }
1402
1412
  if (invalidBytes === 0) {
1403
- const controlBytes = countControlBytes(buffer);
1404
- if (controlBytes > CONTROL_BYTES_FLOOR && controlBytes * 100 > buffer.length) {
1405
- return {
1406
- text: "",
1407
- encoding: "utf-8",
1408
- invalidBytes: 0,
1409
- binary: true,
1410
- binaryReason: `${controlBytes} control byte(s) in ${buffer.length} B; valid UTF-8 but not text`
1411
- };
1412
- }
1413
1413
  return {
1414
1414
  text: new TextDecoder("utf-8").decode(buffer),
1415
1415
  encoding: "utf-8",
@@ -1708,9 +1708,15 @@ function skeletonizeTypeScript(source, fileName = "file.ts") {
1708
1708
  if (end > start) spans.push({ start, end });
1709
1709
  }
1710
1710
  }
1711
- ts.forEachChild(node, visit);
1712
1711
  };
1713
- visit(sourceFile);
1712
+ const stack = [sourceFile];
1713
+ while (stack.length > 0) {
1714
+ const node = stack.pop();
1715
+ visit(node);
1716
+ ts.forEachChild(node, (child) => {
1717
+ stack.push(child);
1718
+ });
1719
+ }
1714
1720
  if (spans.length === 0) return { text: source, collapsed: 0 };
1715
1721
  const outermost = [];
1716
1722
  for (const span of spans.sort((a, b) => a.start - b.start || b.end - a.end)) {
@@ -1880,7 +1886,7 @@ function readManifest(cwd, name) {
1880
1886
  function dependenciesFromPackageJson(raw) {
1881
1887
  const names = /* @__PURE__ */ new Set();
1882
1888
  try {
1883
- const parsed = JSON.parse(raw);
1889
+ const parsed = JSON.parse(stripJsonComments(raw.replace(/^\uFEFF/, "")));
1884
1890
  for (const section of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
1885
1891
  const block = parsed[section];
1886
1892
  if (block && typeof block === "object") {
@@ -1970,8 +1976,8 @@ function workspacePackageDirs(cwd, patterns) {
1970
1976
  function scanWorkspacePackages(cwd, patterns) {
1971
1977
  const files = /* @__PURE__ */ new Set();
1972
1978
  const dependencies = /* @__PURE__ */ new Set();
1973
- for (const relative14 of workspacePackageDirs(cwd, patterns)) {
1974
- const full = path25.join(cwd, relative14);
1979
+ for (const relative15 of workspacePackageDirs(cwd, patterns)) {
1980
+ const full = path25.join(cwd, relative15);
1975
1981
  try {
1976
1982
  for (const entry of fs24.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
1977
1983
  } catch {
@@ -3185,7 +3191,7 @@ var DEFAULT_SECRET_PATTERNS = [
3185
3191
  // rendering of textual userinfo mixes cases, while the prose the earlier rules were
3186
3192
  // protecting (`Bearer authentication`) is a lowercase word.
3187
3193
  rule: "authorization-header",
3188
- pattern: /(?<=[Aa]uthorization["']?\s*[:=]\s*["']?[A-Za-z][A-Za-z0-9._~+/-]{0,31}\s{1,8})(?:[A-Za-z0-9_.+/-]{0,31}[0-9][A-Za-z0-9_.+/-]{0,1024}|[A-Za-z0-9_.+/-]{32,1024}|[A-Za-z0-9_.+/-]{8,1024}={1,2}|(?=[A-Za-z0-9_.+/-]{0,1023}[A-Z])(?=[A-Za-z0-9_.+/-]{0,1023}[a-z])[A-Za-z0-9_.+/-]{12,1024})(?![A-Za-z0-9_.+/=-])/
3194
+ pattern: /(?<=[Aa][Uu][Tt][Hh][Oo][Rr][Ii][Zz][Aa][Tt][Ii][Oo][Nn]["']?\s*[:=]\s*["']?[A-Za-z][A-Za-z0-9._~+/-]{0,31}\s{1,8})(?:[A-Za-z0-9_.+/-]{0,31}[0-9][A-Za-z0-9_.+/-]{0,1024}|[A-Za-z0-9_.+/-]{32,1024}|[A-Za-z0-9_.+/-]{8,1024}={1,2}|(?=[A-Za-z0-9_.+/-]{0,1023}[A-Z])(?=[A-Za-z0-9_.+/-]{0,1023}[a-z])[A-Za-z0-9_.+/-]{12,1024})(?![A-Za-z0-9_.+/=-])/
3189
3195
  },
3190
3196
  {
3191
3197
  // Broader names than before (`apiKey`, `clientSecret`, `privateKey` were
@@ -3763,6 +3769,7 @@ function redactStructuredValues(text2, filePath, recordFinding) {
3763
3769
  if (firstValue === void 0) continue;
3764
3770
  const valueIndent = (/^[ \t]*/.exec(firstValue)?.[0] ?? "").length;
3765
3771
  if (valueIndent <= baseIndent) continue;
3772
+ if (STRUCTURED_KEY.test(firstValue) || /^[ \t]*-[ \t]/.test(firstValue)) continue;
3766
3773
  let masked = false;
3767
3774
  while (cursor < segments.length) {
3768
3775
  const body = segments[cursor] ?? "";
@@ -3778,7 +3785,7 @@ function redactStructuredValues(text2, filePath, recordFinding) {
3778
3785
  }
3779
3786
  return segments.join("");
3780
3787
  }
3781
- var DOCKERFILE_ENV = /^([ \t]*ENV[ \t]+)([A-Za-z_][A-Za-z0-9_]*)([ \t]+)(\S.*)$/;
3788
+ var DOCKERFILE_ENV = /^([ \t]*)(ENV|ARG)([ \t]+)([A-Za-z_][A-Za-z0-9_]*)([ \t]*=[ \t]*|[ \t]+)(\S.*)$/i;
3782
3789
  function redactDockerfileEnv(text2, filePath, recordFinding) {
3783
3790
  if (!isDockerfile(filePath)) return text2;
3784
3791
  const segments = text2.split(LINE_BREAK);
@@ -3787,10 +3794,9 @@ function redactDockerfileEnv(text2, filePath, recordFinding) {
3787
3794
  if (line === void 0) continue;
3788
3795
  const match = DOCKERFILE_ENV.exec(line);
3789
3796
  if (match === null) continue;
3790
- if (!CREDENTIAL_KEY_TAIL.test(match[2] ?? "")) continue;
3791
- const value = match[4] ?? "";
3792
- if (value.startsWith("=")) continue;
3793
- segments[index] = `${match[1]}${match[2]}${match[3]}${REDACTION_MARKER}`;
3797
+ if (!CREDENTIAL_KEY_TAIL.test(match[4] ?? "")) continue;
3798
+ const separator = match[5] ?? "";
3799
+ segments[index] = `${match[1]}${match[2]}${match[3]}${match[4]}${separator}${REDACTION_MARKER}`;
3794
3800
  recordFinding(index / 2 + 1, ["dockerfile-env-secret"]);
3795
3801
  }
3796
3802
  return segments.join("");
@@ -3875,6 +3881,7 @@ function isSourceCodeFile(filePath) {
3875
3881
  var PLACEHOLDER_PATTERNS = [
3876
3882
  /^<[^>]*>?$/,
3877
3883
  /^\.{3,}$/,
3884
+ /^(?:[A-Za-z0-9_-]{1,8}-)?\.{3,}$/,
3878
3885
  /^(?:x{4,}|X{4,}|\*{3,})$/,
3879
3886
  /^(?:replace|change)[-_ ]?me(?:[-_ ].*)?$/i,
3880
3887
  /^your[-_ ].*$/i,
@@ -3888,7 +3895,7 @@ function isPlaceholderValue(value) {
3888
3895
  if (trimmed.length === 0) return false;
3889
3896
  if (PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(trimmed))) return true;
3890
3897
  if (trimmed.includes(REDACTION_MARKER) || trimmed.includes(PEM_REDACTION_MARKER)) return true;
3891
- return trimmed.includes("...") || /^<[^>]*$/.test(trimmed);
3898
+ return false;
3892
3899
  }
3893
3900
  function quotesAreBalanced(text2) {
3894
3901
  let single = 0;
@@ -3940,6 +3947,7 @@ var ASSIGNMENT_FILE = /\.(?:sh|bash|zsh|ksh|fish|env|ya?ml|toml|ini|conf|cfg|pro
3940
3947
  var ASSIGNMENT_BASENAME = /^(?:\.env(?:\.[^/]*)?|\.envrc|\.profile|\.bashrc|\.zshrc|\.bash_profile)$/i;
3941
3948
  function isAssignmentFile(filePath) {
3942
3949
  if (filePath === void 0) return false;
3950
+ if (isDockerfile(filePath)) return true;
3943
3951
  const normalised = filePath.replace(/\\/g, "/");
3944
3952
  if (ASSIGNMENT_FILE.test(normalised)) return true;
3945
3953
  const base = normalised.slice(normalised.lastIndexOf("/") + 1);
@@ -4048,6 +4056,15 @@ function verifySnapshotSignature(snapshotDir) {
4048
4056
  if (sha2562 !== record.manifestSha256) {
4049
4057
  return { ok: false, reason: "manifest.json changed after it was signed" };
4050
4058
  }
4059
+ let signedFingerprint;
4060
+ try {
4061
+ signedFingerprint = JSON.parse(bytes.toString("utf8")).fingerprint;
4062
+ } catch {
4063
+ return { ok: false, reason: "the signed manifest is not JSON" };
4064
+ }
4065
+ if (typeof record.fingerprint !== "string" || record.fingerprint !== signedFingerprint) {
4066
+ return { ok: false, reason: "signature.json names a different fingerprint than the manifest" };
4067
+ }
4051
4068
  let verified = false;
4052
4069
  try {
4053
4070
  const key = crypto.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
@@ -4060,7 +4077,7 @@ function verifySnapshotSignature(snapshotDir) {
4060
4077
 
4061
4078
  // src/version.ts
4062
4079
  var GENERATOR_NAME = "codebase-snapshot";
4063
- var GENERATOR_VERSION = "0.20.4";
4080
+ var GENERATOR_VERSION = "0.20.6";
4064
4081
  var SCHEMA_VERSION = "3.0.0";
4065
4082
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
4066
4083
  function isOurGeneratorName(name) {
@@ -4092,8 +4109,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
4092
4109
  };
4093
4110
  }
4094
4111
  function isInside(root, candidate) {
4095
- const relative14 = path25.relative(root, candidate);
4096
- return relative14 === "" || !relative14.startsWith(`..${path25.sep}`) && relative14 !== ".." && !path25.isAbsolute(relative14);
4112
+ const relative15 = path25.relative(root, candidate);
4113
+ return relative15 === "" || !relative15.startsWith(`..${path25.sep}`) && relative15 !== ".." && !path25.isAbsolute(relative15);
4097
4114
  }
4098
4115
  var GIT_OUTPUT_LIMIT = 68157440;
4099
4116
  function getGitInfo(cwd, fallbackBranch = "main") {
@@ -4159,7 +4176,7 @@ var DEFAULT_IGNORED_FILES = [
4159
4176
  var SENSITIVE_BASENAME = /^(?:\.env(?:[._-][A-Za-z0-9_-]*)*|\.env(?:backup|bak|old|orig|copy|save)|\.envrc|\.npmrc(?:\.[A-Za-z0-9_-]+)?|\.yarnrc(?:\.yml)?|\.netrc(?:\.[A-Za-z0-9_-]+)?|\.git-credentials|\.htpasswd|\.pgpass|\.pypirc|\.vault-token|vault[-_]agent[-_]token|\.composer-auth\.json|auth\.json|application_default_credentials\.json|id_[a-z0-9_]+(?:\.[A-Za-z0-9_-]+)?|credentials(?:\.(?:json|ya?ml|toml))?|service[-_]?account(?:\.[a-z0-9_-]+)*\.json|secrets?\.(?:json|ya?ml|toml)|env|[A-Za-z0-9_-]{1,64}\.env)$/i;
4160
4177
  var SENSITIVE_PATH = /(?:^|\/)\.(?:aws|ssh|gnupg)\/|(?:^|\/)\.docker\/config\.json$|(?:^|\/)\.kube\/config$|(?:^|\/)\.config\/gcloud\/|(?:^|\/)\.composer\/|(?:^|\/)\.terraform\/credentials\.tfrc\.json$/i;
4161
4178
  var SENSITIVE_EXT = /\.(?:pem|key|p12|pfx|jks|keystore|ppk|asc|kdbx|tfstate|tfvars)$/i;
4162
- var TEMPLATE_SUFFIX = /^(.*)\.(?:example|sample|template|dist)(\.[A-Za-z0-9_-]+)?$/i;
4179
+ var TEMPLATE_SUFFIX = /^(.*)\.(?:example|sample|template|dist)(\.(?:json|ya?ml|toml|ini|txt|md|properties|conf|cfg))?$/i;
4163
4180
  var BACKUP_SUFFIX = /(?:~|\.(?:bak|backup|old|orig|save|copy|swp|swo|tmp|part))$/i;
4164
4181
  function normaliseName(name) {
4165
4182
  let normalised = name.trim().replace(/[. ]+$/, "");
@@ -4588,30 +4605,67 @@ function isToolOwnedDirectory2(dir) {
4588
4605
  }
4589
4606
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
4590
4607
  const marker2 = parsed;
4591
- if (marker2.generator !== GENERATOR_NAME || marker2.state !== "complete" || typeof marker2.id !== "string" || !Array.isArray(marker2.files)) {
4608
+ if (marker2.generator !== GENERATOR_NAME || marker2.state !== "complete" || marker2.schemaVersion !== SCHEMA_VERSION || typeof marker2.id !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(marker2.id) || typeof marker2.manifestSha256 !== "string" || !Array.isArray(marker2.files)) {
4609
+ return false;
4610
+ }
4611
+ let manifestBytes;
4612
+ try {
4613
+ manifestBytes = fs24.readFileSync(path25.join(dir, "manifest.json"));
4614
+ } catch {
4615
+ return false;
4616
+ }
4617
+ if (createHash("sha256").update(manifestBytes).digest("hex") !== marker2.manifestSha256) {
4592
4618
  return false;
4593
4619
  }
4594
- const accounted = /* @__PURE__ */ new Set();
4620
+ const recordedFiles = /* @__PURE__ */ new Set();
4595
4621
  for (const item of marker2.files) {
4596
4622
  if (!item || typeof item !== "object" || Array.isArray(item)) return false;
4597
- const entry = item.path;
4598
- if (typeof entry !== "string" || entry.length === 0) return false;
4599
- const parts = entry.split("/");
4600
- for (let depth = 1; depth <= parts.length; depth += 1) {
4601
- accounted.add(parts.slice(0, depth).join("/"));
4623
+ const record = item;
4624
+ const entry = record.path;
4625
+ if (typeof entry !== "string" || entry.length === 0 || entry.includes(String.fromCharCode(92)) || entry.includes("\0") || path25.isAbsolute(entry) || entry.split("/").includes("..") || typeof record.bytes !== "number" || !Number.isSafeInteger(record.bytes) || record.bytes < 0 || typeof record.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(record.sha256)) {
4626
+ return false;
4602
4627
  }
4628
+ const full = path25.join(dir, ...entry.split("/"));
4629
+ let stats;
4630
+ try {
4631
+ stats = fs24.lstatSync(full);
4632
+ } catch {
4633
+ return false;
4634
+ }
4635
+ if (!stats.isFile() || stats.size !== record.bytes) return false;
4636
+ let digest;
4637
+ try {
4638
+ digest = createHash("sha256").update(fs24.readFileSync(full)).digest("hex");
4639
+ } catch {
4640
+ return false;
4641
+ }
4642
+ if (digest !== record.sha256) return false;
4643
+ recordedFiles.add(entry);
4603
4644
  }
4604
- let entries;
4605
- try {
4606
- entries = fs24.readdirSync(dir);
4607
- } catch {
4608
- return false;
4645
+ const stack = [""];
4646
+ while (stack.length > 0) {
4647
+ const current = stack.pop();
4648
+ let entries;
4649
+ try {
4650
+ entries = fs24.readdirSync(path25.join(dir, current), { withFileTypes: true });
4651
+ } catch {
4652
+ return false;
4653
+ }
4654
+ for (const entry of entries) {
4655
+ const relative15 = current === "" ? entry.name : current + "/" + entry.name;
4656
+ if (relative15 === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry.name)) continue;
4657
+ if (entry.isDirectory()) {
4658
+ stack.push(relative15);
4659
+ continue;
4660
+ }
4661
+ if (!entry.isFile()) return false;
4662
+ if (relative15 === "signature.json" && !recordedFiles.has(relative15) && verifySnapshotSignature(dir).ok) {
4663
+ continue;
4664
+ }
4665
+ if (!recordedFiles.has(relative15)) return false;
4666
+ }
4609
4667
  }
4610
- return entries.every(
4611
- (entry) => entry === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry) || // A snapshot signed before signing moved into staging has a valid signature.json the old
4612
- // marker could not record. It is our artifact when the signature verifies.
4613
- entry === "signature.json" && verifySnapshotSignature(dir).ok || accounted.has(entry)
4614
- );
4668
+ return true;
4615
4669
  }
4616
4670
  function makeToolOwnedDecider(cwd, toolOwnedPaths) {
4617
4671
  const markers = /* @__PURE__ */ new Map();
@@ -4812,7 +4866,7 @@ function collectFiles(cwd, options = {}) {
4812
4866
  candidates.push(extra);
4813
4867
  }
4814
4868
  }
4815
- const files = candidates.filter((file) => {
4869
+ let files = candidates.filter((file) => {
4816
4870
  if (isToolOwned(file)) return false;
4817
4871
  const ignored = defaultIgnoreReason(file, toolDirNames);
4818
4872
  if (ignored) {
@@ -4857,8 +4911,51 @@ function collectFiles(cwd, options = {}) {
4857
4911
  }
4858
4912
  return true;
4859
4913
  }).sort();
4914
+ files = dropSymlinksToUnincludedTargets(cwd, files, skipped);
4860
4915
  return { files, skipped: maskSkipPaths(skipped, pathRules) };
4861
4916
  }
4917
+ function dropSymlinksToUnincludedTargets(cwd, files, skipped) {
4918
+ const aliases = /* @__PURE__ */ new Set();
4919
+ for (const file of files) {
4920
+ try {
4921
+ if (fs24.lstatSync(path25.join(cwd, file)).isSymbolicLink()) aliases.add(file);
4922
+ } catch {
4923
+ }
4924
+ }
4925
+ if (aliases.size === 0) return [...files];
4926
+ const includedTargets = /* @__PURE__ */ new Set();
4927
+ for (const file of files) {
4928
+ if (aliases.has(file)) continue;
4929
+ try {
4930
+ includedTargets.add(fs24.realpathSync(path25.join(cwd, file)));
4931
+ } catch {
4932
+ }
4933
+ }
4934
+ const kept = [];
4935
+ for (const file of files) {
4936
+ if (!aliases.has(file)) {
4937
+ kept.push(file);
4938
+ continue;
4939
+ }
4940
+ let target;
4941
+ try {
4942
+ target = fs24.realpathSync(path25.join(cwd, file));
4943
+ } catch {
4944
+ skipped.push({ path: file, reason: "read-error", detail: "symlink target could not be resolved" });
4945
+ continue;
4946
+ }
4947
+ if (includedTargets.has(target)) {
4948
+ kept.push(file);
4949
+ continue;
4950
+ }
4951
+ skipped.push({
4952
+ path: file,
4953
+ reason: "symlink",
4954
+ detail: "link target was excluded from the snapshot; not followed"
4955
+ });
4956
+ }
4957
+ return kept;
4958
+ }
4862
4959
  function rootRealFor(root) {
4863
4960
  try {
4864
4961
  return fs24.realpathSync(root);
@@ -5102,8 +5199,25 @@ function normalizeResolvedConfig(config) {
5102
5199
  monolithWanted,
5103
5200
  monolithWanted
5104
5201
  );
5202
+ if (!Number.isSafeInteger(config.maxPartBytes) || config.maxPartBytes < MIN_MAX_PART_BYTES) {
5203
+ throw new Error(
5204
+ `maxPartBytes must be at least ${MIN_MAX_PART_BYTES} bytes (received ${String(config.maxPartBytes)}).`
5205
+ );
5206
+ }
5207
+ if (!Number.isSafeInteger(config.largeFileBytes) || config.largeFileBytes < 0) {
5208
+ throw new Error(
5209
+ `largeFileBytes must be a non-negative integer; received ${String(config.largeFileBytes)}.`
5210
+ );
5211
+ }
5212
+ const maxPartTokens = config.maxPartTokens ?? Math.floor(config.maxPartBytes / 4);
5213
+ if (!Number.isSafeInteger(maxPartTokens) || maxPartTokens < MIN_MAX_PART_TOKENS) {
5214
+ throw new Error(
5215
+ `maxPartTokens must be at least ${MIN_MAX_PART_TOKENS} tokens; received ${String(maxPartTokens)}.`
5216
+ );
5217
+ }
5105
5218
  return markResolvedConfig({
5106
5219
  ...config,
5220
+ maxPartTokens,
5107
5221
  discovery,
5108
5222
  // A spread copy built before the field existed carries no value; the default applies, and it
5109
5223
  // is re-validated because the number reaches a rendered artifact.
@@ -5544,13 +5658,13 @@ function readConfiguredBrief(cwd, value) {
5544
5658
  'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
5545
5659
  );
5546
5660
  }
5547
- const relative14 = path25.relative(rootReal, filePath);
5548
- if (relative14.length === 0 || relative14 === ".." || relative14.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative14)) {
5661
+ const relative15 = path25.relative(rootReal, filePath);
5662
+ if (relative15.length === 0 || relative15 === ".." || relative15.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative15)) {
5549
5663
  throw new Error(
5550
5664
  'brief "' + value + '" resolves outside the repository. A brief must be a file inside the repository being described; an absolute or parent path is refused.'
5551
5665
  );
5552
5666
  }
5553
- const posixRelative = relative14.split(path25.sep).join("/");
5667
+ const posixRelative = relative15.split(path25.sep).join("/");
5554
5668
  if (isSensitivePath(posixRelative) || isSensitivePath(value)) {
5555
5669
  throw new Error(
5556
5670
  'brief "' + value + '" is a credential-bearing file. A snapshot must not reproduce secrets, so it cannot be used as the owner brief.'
@@ -5558,9 +5672,16 @@ function readConfiguredBrief(cwd, value) {
5558
5672
  }
5559
5673
  let text2;
5560
5674
  try {
5561
- if (!fs24.statSync(filePath).isFile()) throw new Error("not a file");
5675
+ const stats = fs24.statSync(filePath);
5676
+ if (!stats.isFile()) throw new Error("not a file");
5677
+ if (stats.size > MAX_BRIEF_BYTES) {
5678
+ throw new Error(
5679
+ 'brief "' + value + '" is ' + stats.size + " bytes; the limit is " + MAX_BRIEF_BYTES + ". Keep it to what a reader can act on, or move the detail into a document the snapshot carries."
5680
+ );
5681
+ }
5562
5682
  text2 = fs24.readFileSync(filePath, "utf8");
5563
- } catch {
5683
+ } catch (error) {
5684
+ if (error instanceof Error && error.message.startsWith('brief "')) throw error;
5564
5685
  throw new Error(
5565
5686
  'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
5566
5687
  );
@@ -5672,11 +5793,11 @@ function outputExcludePatterns(cwd, outDir, tmpDir) {
5672
5793
  const patterns = [];
5673
5794
  for (const dir of [outDir, tmpDir]) {
5674
5795
  const absolute = path25.resolve(cwd, dir);
5675
- const relative14 = path25.relative(cwd, absolute);
5676
- if (!relative14 || relative14 === ".." || relative14.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative14)) {
5796
+ const relative15 = path25.relative(cwd, absolute);
5797
+ if (!relative15 || relative15 === ".." || relative15.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative15)) {
5677
5798
  continue;
5678
5799
  }
5679
- patterns.push(`${relative14.replace(/\\/g, "/")}/**`);
5800
+ patterns.push(`${relative15.replace(/\\/g, "/")}/**`);
5680
5801
  }
5681
5802
  return patterns;
5682
5803
  }
@@ -5963,7 +6084,10 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
5963
6084
  outDir,
5964
6085
  tmpDir,
5965
6086
  maxPartBytes: resolvedMaxPartBytes,
5966
- ...maxPartTokens === void 0 ? {} : { maxPartTokens },
6087
+ // Record the effective value even when the user did not set it. normalizeResolvedConfig
6088
+ // derives it for the manifest; leaving validate's fresh resolution unset made a clean
6089
+ // snapshot report a configuration mismatch.
6090
+ maxPartTokens: maxPartTokens ?? Math.floor(resolvedMaxPartBytes / 4),
5967
6091
  largeFileBytes: largeFileBytesFor(resolvedMaxPartBytes, cliOptions, userConfig),
5968
6092
  previewHeadLines: strictPositiveInteger(userConfig?.previewHeadLines, 80, "`previewHeadLines`"),
5969
6093
  previewTailLines: strictPositiveInteger(userConfig?.previewTailLines, 40, "`previewTailLines`"),
@@ -6365,7 +6489,8 @@ function generateSarifReport(manifest, findings, rules, toolVersion) {
6365
6489
  const results = findings.filter((finding) => typeof finding.path === "string" && finding.path.length > 0).map((finding) => {
6366
6490
  const primary = finding.rules[0] ?? "unknown";
6367
6491
  const line = Math.max(1, finding.line);
6368
- const findingPath = String(finding.path).replace(/\\/g, "/");
6492
+ const rawPath = findSecretInPath(String(finding.path), rules)?.masked ?? String(finding.path);
6493
+ const findingPath = rawPath.replace(/\\/g, "/").split("/").map((segment) => encodeURIComponent(segment)).join("/");
6369
6494
  return {
6370
6495
  ruleId: ruleIdFor(primary),
6371
6496
  ruleIndex: ruleIndex.get(primary) ?? 0,
@@ -6436,6 +6561,9 @@ function countLines(content) {
6436
6561
  const last = content.charCodeAt(content.length - 1);
6437
6562
  return last === 10 || last === 13 ? breaks : breaks + 1;
6438
6563
  }
6564
+ function countBodyLines(content) {
6565
+ return content.length === 0 ? 0 : content.split("\n").length;
6566
+ }
6439
6567
  function truncateToBytes(content, maxBytes) {
6440
6568
  if (maxBytes <= 0) return { content: "", isTruncated: content.length > 0 };
6441
6569
  const buffer = Buffer.from(content, "utf8");
@@ -6787,14 +6915,16 @@ function fenceIsOpen(text2, fence) {
6787
6915
  }
6788
6916
  var OMISSION_NOTICE_LINE = /^\.\.\. \[\d+ lines omitted: [^\]]*\] \.\.\.$/;
6789
6917
  function applyTruncatedContent(file, content, reason) {
6790
- const keptLines = content.split("\n").filter((line) => !OMISSION_NOTICE_LINE.test(line)).length;
6918
+ const keptLines = content.split("\n").filter(
6919
+ (line) => !OMISSION_NOTICE_LINE.test(line) && line.trim() !== SECTION_TRUNCATION_NOTICE
6920
+ ).length;
6791
6921
  file.content = content;
6792
6922
  file.isPreviewTruncated = true;
6793
6923
  file.inclusionMode = "preview";
6794
6924
  file.truncationReason = reason;
6795
6925
  file.omittedRanges = keptLines >= file.originalLines ? file.originalLines > 0 ? [[file.originalLines, file.originalLines]] : [] : [[keptLines + 1, file.originalLines]];
6796
6926
  file.includedBytes = Buffer.byteLength(content, "utf8");
6797
- file.includedLines = countLines(content);
6927
+ file.includedLines = countBodyLines(content);
6798
6928
  }
6799
6929
  function rehashPart(part, markdown) {
6800
6930
  const estimatedTokens = estimateTokens(markdown.replace(TOKEN_LINE, ""));
@@ -6807,7 +6937,8 @@ function rehashPart(part, markdown) {
6807
6937
  byteSize: Buffer.byteLength(redistributed, "utf8"),
6808
6938
  sha256: crypto.createHash("sha256").update(redistributed).digest("hex"),
6809
6939
  lines: countLines(redistributed),
6810
- estimatedTokens
6940
+ estimatedTokens,
6941
+ hardClipped: true
6811
6942
  }
6812
6943
  };
6813
6944
  }
@@ -6929,7 +7060,7 @@ function renderFileSection(file) {
6929
7060
  const content = file.content ?? "";
6930
7061
  const body = emittedBody(content);
6931
7062
  file.includedBytes = Buffer.byteLength(body, "utf8");
6932
- file.includedLines = countLines(body);
7063
+ file.includedLines = countBodyLines(body);
6933
7064
  const fence = fenceForContent(content);
6934
7065
  const anchor = anchorForPath(file.relativePath);
6935
7066
  return [
@@ -6983,11 +7114,14 @@ function generateMonolithJson(manifest, filesWithContent) {
6983
7114
  );
6984
7115
  return JSON.stringify({ manifest: embedded, files }, null, 2);
6985
7116
  }
7117
+ function xmlSafe(value) {
7118
+ return value.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]/g, "\uFFFD");
7119
+ }
6986
7120
  function xmlAttribute(value) {
6987
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
7121
+ return xmlSafe(value).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
6988
7122
  }
6989
7123
  function cdata(value) {
6990
- return "<![CDATA[" + value.replace(/\]\]>/g, "]]]]><![CDATA[>") + "]]>";
7124
+ return "<![CDATA[" + xmlSafe(value).replace(/\]\]>/g, "]]]]><![CDATA[>") + "]]>";
6991
7125
  }
6992
7126
  function generateMonolithXml(manifest, filesWithContent) {
6993
7127
  const files = filesWithContent.map((file) => {
@@ -7088,14 +7222,19 @@ function generateNavigation(manifest) {
7088
7222
  }
7089
7223
 
7090
7224
  // src/generator/selection.ts
7225
+ function cell(value) {
7226
+ return escapeControls(value).replace(/\r?\n/g, " ").replace(/\|/g, "\\|");
7227
+ }
7091
7228
  function generateSelectionReport(manifest, selection) {
7092
7229
  const lines = [];
7093
7230
  lines.push("# Selection");
7094
7231
  lines.push("");
7095
7232
  lines.push("**Kind:** `" + selection.kind + "` ");
7096
- for (const detailLine of selection.detail.split("\n")) {
7097
- lines.push("**" + detailLine.slice(0, detailLine.indexOf(":")) + ":**" + detailLine.slice(detailLine.indexOf(":") + 1) + " ");
7098
- }
7233
+ const detail = selection.detail.replace(/\r?\n/g, " ");
7234
+ const colon = detail.indexOf(":");
7235
+ lines.push(
7236
+ "**" + (colon === -1 ? "Selection" : detail.slice(0, colon)) + ":**" + (colon === -1 ? " " + detail : detail.slice(colon + 1)) + " "
7237
+ );
7099
7238
  lines.push("**Selected files:** " + selection.files.length + " ");
7100
7239
  const spent = manifest.budget?.usedTokens ?? manifest.slice?.usedTokens ?? 0;
7101
7240
  lines.push("**Tokens spent:** " + spent.toLocaleString("en-US"));
@@ -7105,7 +7244,7 @@ function generateSelectionReport(manifest, selection) {
7105
7244
  lines.push("| File | Tokens | Reason |");
7106
7245
  lines.push("| :-- | --: | :-- |");
7107
7246
  for (const file of selection.files) {
7108
- lines.push("| `" + file.path + "` | " + file.tokens.toLocaleString("en-US") + " | " + file.why + " |");
7247
+ lines.push("| `" + cell(file.path) + "` | " + file.tokens.toLocaleString("en-US") + " | " + cell(file.why) + " |");
7109
7248
  }
7110
7249
  lines.push("");
7111
7250
  const dropped = selection.kind === "slice" ? manifest.slice?.dropped : manifest.budget?.dropped;
@@ -7125,7 +7264,7 @@ function generateSelectionReport(manifest, selection) {
7125
7264
  lines.push("| File | Tokens |");
7126
7265
  lines.push("| :-- | --: |");
7127
7266
  for (const item of next) {
7128
- lines.push("| `" + item.path + "` | " + item.tokens.toLocaleString("en-US") + " |");
7267
+ lines.push("| `" + cell(item.path) + "` | " + item.tokens.toLocaleString("en-US") + " |");
7129
7268
  }
7130
7269
  lines.push("");
7131
7270
  }
@@ -7332,7 +7471,9 @@ function planForQuestion(manifest, question, options = {}) {
7332
7471
  notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
7333
7472
  }
7334
7473
  }
7335
- scored.sort((left, right) => right.score - left.score || left.file.relativePath.localeCompare(right.file.relativePath));
7474
+ scored.sort(
7475
+ (left, right) => right.score - left.score || (left.file.relativePath < right.file.relativePath ? -1 : left.file.relativePath > right.file.relativePath ? 1 : 0)
7476
+ );
7336
7477
  const chosen = /* @__PURE__ */ new Map();
7337
7478
  const skipped = [];
7338
7479
  let used = 0;
@@ -7440,12 +7581,15 @@ function stripComments2(text2, relativePath) {
7440
7581
  if (ranges_ === void 0) return;
7441
7582
  for (const range of ranges_) ranges.push([range.pos, range.end]);
7442
7583
  };
7443
- const visit = (node) => {
7584
+ const stack = [source];
7585
+ while (stack.length > 0) {
7586
+ const node = stack.pop();
7444
7587
  collect(ts.getLeadingCommentRanges(text2, node.getFullStart()));
7445
7588
  collect(ts.getTrailingCommentRanges(text2, node.getEnd()));
7446
- ts.forEachChild(node, visit);
7447
- };
7448
- visit(source);
7589
+ ts.forEachChild(node, (child) => {
7590
+ stack.push(child);
7591
+ });
7592
+ }
7449
7593
  collect(ts.getLeadingCommentRanges(text2, source.endOfFileToken.getFullStart()));
7450
7594
  if (ranges.length === 0) return { text: text2, removed: 0 };
7451
7595
  ranges.sort((left, right) => left[0] - right[0]);
@@ -7468,25 +7612,112 @@ function stripComments2(text2, relativePath) {
7468
7612
  return { text: pieces.join(""), removed };
7469
7613
  }
7470
7614
  function runGit(cwd, args) {
7471
- const result = spawnSync("git", args, { cwd, encoding: "utf8", windowsHide: true, maxBuffer: 64 * 1024 * 1024 });
7615
+ const result = spawnSync(
7616
+ "git",
7617
+ [
7618
+ "-c",
7619
+ "core.quotepath=false",
7620
+ "-c",
7621
+ "diff.noprefix=false",
7622
+ "-c",
7623
+ "diff.mnemonicPrefix=false",
7624
+ ...args
7625
+ ],
7626
+ { cwd, encoding: "utf8", windowsHide: true, maxBuffer: 64 * 1024 * 1024 }
7627
+ );
7472
7628
  if (result.status !== 0) return { ok: false, out: (result.stderr ?? "").trim() };
7473
7629
  return { ok: true, out: result.stdout ?? "" };
7474
7630
  }
7475
7631
  function isGitRepository(cwd) {
7476
7632
  return runGit(cwd, ["rev-parse", "--is-inside-work-tree"]).out.trim() === "true";
7477
7633
  }
7634
+ function unquoteGitPath(value) {
7635
+ if (!value.startsWith('"') || !value.endsWith('"')) return value;
7636
+ const body = value.slice(1, -1);
7637
+ let out = "";
7638
+ let bytes = [];
7639
+ const flushBytes = () => {
7640
+ if (bytes.length === 0) return;
7641
+ out += Buffer.from(bytes).toString("utf8");
7642
+ bytes = [];
7643
+ };
7644
+ const escapes = {
7645
+ a: "\x07",
7646
+ b: "\b",
7647
+ f: "\f",
7648
+ n: "\n",
7649
+ r: "\r",
7650
+ t: " ",
7651
+ v: "\v",
7652
+ "\\": "\\",
7653
+ '"': '"'
7654
+ };
7655
+ for (let index = 0; index < body.length; index += 1) {
7656
+ const char = body[index];
7657
+ if (char !== "\\") {
7658
+ flushBytes();
7659
+ out += char;
7660
+ continue;
7661
+ }
7662
+ const next = body[index + 1];
7663
+ if (next === void 0) {
7664
+ flushBytes();
7665
+ out += "\\";
7666
+ break;
7667
+ }
7668
+ index += 1;
7669
+ if (/[0-7]/.test(next)) {
7670
+ let octal = next;
7671
+ while (octal.length < 3 && /[0-7]/.test(body[index + 1] ?? "")) {
7672
+ index += 1;
7673
+ octal += body[index];
7674
+ }
7675
+ bytes.push(Number.parseInt(octal, 8) & 255);
7676
+ continue;
7677
+ }
7678
+ flushBytes();
7679
+ out += escapes[next] ?? next;
7680
+ }
7681
+ flushBytes();
7682
+ return out;
7683
+ }
7684
+ function wholeLinePath(value, prefix) {
7685
+ const withoutTimestamp = value.endsWith(" ") ? value.slice(0, -1) : value;
7686
+ const unquoted = unquoteGitPath(withoutTimestamp);
7687
+ if (unquoted === "/dev/null") return null;
7688
+ if (!unquoted.startsWith(prefix)) return null;
7689
+ return unquoted.slice(prefix.length);
7690
+ }
7691
+ function headerPaths(value) {
7692
+ const separator = value.lastIndexOf(" b/");
7693
+ if (separator <= 0) return [];
7694
+ const left = unquoteGitPath(value.slice(0, separator));
7695
+ const right = unquoteGitPath(value.slice(separator + 1));
7696
+ const paths = [];
7697
+ if (left.startsWith("a/")) paths.push(left.slice(2));
7698
+ if (right.startsWith("b/")) paths.push(right.slice(2));
7699
+ return paths;
7700
+ }
7478
7701
  function diffSectionPaths(body) {
7479
7702
  const paths = /* @__PURE__ */ new Set();
7703
+ let header = null;
7480
7704
  for (const line of body.split("\n")) {
7481
- const plus = /^\+\+\+ b\/(.*)$/.exec(line);
7482
- if (plus !== null) paths.add(plus[1]);
7483
- const minus = /^--- a\/(.*)$/.exec(line);
7484
- if (minus !== null) paths.add(minus[1]);
7485
- const header = /^diff --git a\/(.*?) b\/(.*)$/.exec(line);
7486
- if (header !== null) {
7487
- paths.add(header[1]);
7488
- paths.add(header[2]);
7705
+ if (line.startsWith("diff --git ")) {
7706
+ header = line.slice("diff --git ".length);
7707
+ continue;
7489
7708
  }
7709
+ if (line.startsWith("+++ ")) {
7710
+ const path26 = wholeLinePath(line.slice(4), "b/");
7711
+ if (path26 !== null) paths.add(path26);
7712
+ continue;
7713
+ }
7714
+ if (line.startsWith("--- ")) {
7715
+ const path26 = wholeLinePath(line.slice(4), "a/");
7716
+ if (path26 !== null) paths.add(path26);
7717
+ }
7718
+ }
7719
+ if (paths.size === 0 && header !== null) {
7720
+ for (const path26 of headerPaths(header)) paths.add(path26);
7490
7721
  }
7491
7722
  return [...paths];
7492
7723
  }
@@ -7496,6 +7727,7 @@ function generateDiffReport(cwd, options = {}) {
7496
7727
  const sections = [];
7497
7728
  let truncated = false;
7498
7729
  let omittedSensitive = 0;
7730
+ let omittedUnparseable = 0;
7499
7731
  const commands = [
7500
7732
  ["Unstaged", ["diff", "--no-color"]],
7501
7733
  ["Staged", ["diff", "--cached", "--no-color"]]
@@ -7506,6 +7738,10 @@ function generateDiffReport(cwd, options = {}) {
7506
7738
  const rawSections = result.out.split(/(?=^diff --git )/m).filter((section) => section.length > 0);
7507
7739
  for (const rawSection of rawSections) {
7508
7740
  const paths2 = diffSectionPaths(rawSection);
7741
+ if (paths2.length === 0) {
7742
+ omittedUnparseable += 1;
7743
+ continue;
7744
+ }
7509
7745
  const blocked = paths2.some((path26) => isSensitivePath(path26) || options.excluded?.(path26) === true);
7510
7746
  if (blocked) {
7511
7747
  omittedSensitive += 1;
@@ -7517,7 +7753,13 @@ function generateDiffReport(cwd, options = {}) {
7517
7753
  truncated = true;
7518
7754
  break;
7519
7755
  }
7520
- const chunk = truncateToBytes(rawSection, remaining);
7756
+ const sourcePath = paths2[0] ?? "reports/diff.md";
7757
+ const redactedSection = scanAndRedactSecrets(
7758
+ rawSection,
7759
+ options.secretRules ?? [],
7760
+ sourcePath
7761
+ ).redacted;
7762
+ const chunk = truncateToBytes(redactedSection, remaining);
7521
7763
  if (chunk.isTruncated) truncated = true;
7522
7764
  sections.push(
7523
7765
  "## " + title + " changes\n\nRun: git " + args.join(" ") + "\n\n```diff\n" + chunk.content + "\n```"
@@ -7538,6 +7780,10 @@ function generateDiffReport(cwd, options = {}) {
7538
7780
  "> " + omittedSensitive + " file section(s) omitted: their path is credential-bearing or excluded from the snapshot.",
7539
7781
  ""
7540
7782
  ] : [],
7783
+ ...omittedUnparseable > 0 ? [
7784
+ "> " + omittedUnparseable + " file section(s) omitted: their diff header could not be attributed to a path, so the sensitive-path filter could not run.",
7785
+ ""
7786
+ ] : [],
7541
7787
  ...sections,
7542
7788
  ...truncated ? ["", "> Truncated at " + maxBytes + " bytes. Run git diff for the rest."] : [],
7543
7789
  ""
@@ -7573,28 +7819,39 @@ function generateLogReport(cwd, options = {}) {
7573
7819
  }
7574
7820
 
7575
7821
  // src/generator/tokens.ts
7822
+ function cell2(value) {
7823
+ return escapeControls(value).replace(/\r?\n/g, " ").replace(/\|/g, "\\|");
7824
+ }
7825
+ function byCodeUnit(left, right) {
7826
+ return left < right ? -1 : left > right ? 1 : 0;
7827
+ }
7576
7828
  function tokensOf2(bytes) {
7577
7829
  return Math.max(1, Math.ceil(bytes * 0.25));
7578
7830
  }
7579
7831
  function generateTokenTree(manifest) {
7580
7832
  if (manifest.files.length === 0) return null;
7581
- const rows = manifest.files.map((file) => ({ path: file.relativePath, layer: file.layer, part: file.part, tokens: tokensOf2(file.includedBytes) })).sort((left, right) => right.tokens - left.tokens || left.path.localeCompare(right.path));
7833
+ const rows = manifest.files.map((file) => ({ path: file.relativePath, layer: file.layer, part: file.part, tokens: tokensOf2(file.includedBytes) })).sort((left, right) => right.tokens - left.tokens || byCodeUnit(left.path, right.path));
7582
7834
  const byDirectory = /* @__PURE__ */ new Map();
7583
7835
  for (const row of rows) {
7584
7836
  const directory = row.path.includes("/") ? row.path.slice(0, row.path.lastIndexOf("/")) : ".";
7585
7837
  byDirectory.set(directory, (byDirectory.get(directory) ?? 0) + row.tokens);
7586
7838
  }
7587
- const directories = [...byDirectory.entries()].sort((left, right) => right[1] - left[1]);
7839
+ const directories = [...byDirectory.entries()].sort(
7840
+ (left, right) => right[1] - left[1] || byCodeUnit(left[0], right[0])
7841
+ );
7588
7842
  const total = rows.reduce((sum, row) => sum + row.tokens, 0);
7589
- const rowsTable = rows.map((row) => "| " + row.path + " | " + row.layer + " | " + row.part + " | " + row.tokens + " |");
7843
+ const rowsTable = rows.map(
7844
+ (row) => "| " + cell2(row.path) + " | " + cell2(row.layer) + " | " + cell2(row.part) + " | " + row.tokens + " |"
7845
+ );
7590
7846
  const directoryTable = directories.map(
7591
- (entry) => "| " + entry[0] + " | " + entry[1] + " | " + (entry[1] / total * 100).toFixed(1) + "% |"
7847
+ (entry) => "| " + cell2(entry[0]) + " | " + entry[1] + " | " + (entry[1] / total * 100).toFixed(1) + "% |"
7592
7848
  );
7593
7849
  const text2 = [
7594
7850
  "# Token tree",
7595
7851
  "",
7596
- "Estimated tokens per file (one token per four bytes of emitted body), sorted by cost. The total",
7597
- "is the same estimate the manifest carries: an estimate, not a count.",
7852
+ "Estimated tokens per file (one token per four bytes of emitted body), sorted by cost. Each",
7853
+ "row is an estimate; the manifest total is estimated from the assembled parts, so the two can",
7854
+ "differ slightly and neither is a tokenizer count.",
7598
7855
  "",
7599
7856
  "## Directories",
7600
7857
  "",
@@ -7796,7 +8053,9 @@ function systemSection(manifest, code, brief, escape, sawManifest) {
7796
8053
  if (brief?.system !== void 0) {
7797
8054
  out.push(...ownerBlock(brief.system, brief.path, code, escape), "", "What the index records:", "");
7798
8055
  }
7799
- const layers = Object.entries(manifest.layers).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
8056
+ const layers = Object.entries(manifest.layers).sort(
8057
+ (a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)
8058
+ );
7800
8059
  if (layers.length > 0) {
7801
8060
  const shown = layers.slice(0, MAX_LAYER_ROWS).map(([name, count]) => code(name) + " " + formatNumber(count));
7802
8061
  const rest = layers.length > MAX_LAYER_ROWS ? ", and " + formatNumber(layers.length - MAX_LAYER_ROWS) + " more" : "";
@@ -7914,7 +8173,7 @@ function coverageSection(manifest, code, auditWritten, partsWritten, sawManifest
7914
8173
  for (const record of manifest.skipped) {
7915
8174
  reasons.set(record.reason, (reasons.get(record.reason) ?? 0) + 1);
7916
8175
  }
7917
- const tally = [...reasons.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([reason, count]) => code(reason) + " " + formatNumber(count)).join(", ");
8176
+ const tally = [...reasons.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([reason, count]) => code(reason) + " " + formatNumber(count)).join(", ");
7918
8177
  const found = manifest.totals.candidateFiles;
7919
8178
  const included = manifest.totals.includedFiles;
7920
8179
  const skipped = manifest.counts.skippedCount;
@@ -8041,7 +8300,7 @@ function ownerNotesSection(brief, code, text2) {
8041
8300
  if (brief === void 0 || brief.notes.length === 0) return [];
8042
8301
  const out = ["## Owner notes", ""];
8043
8302
  for (const note of brief.notes) {
8044
- out.push("### " + note.heading, "", ...ownerBlock(note.body, brief.path, code, text2), "");
8303
+ out.push("### " + text2(note.heading), "", ...ownerBlock(note.body, brief.path, code, text2), "");
8045
8304
  }
8046
8305
  return out;
8047
8306
  }
@@ -8262,27 +8521,31 @@ function generateReadme(manifest, artifacts) {
8262
8521
  const readOrder = [];
8263
8522
  if (wrote("prompt")) {
8264
8523
  readOrder.push(
8265
- "1. Hand `PROMPT.md` to the model that receives this snapshot: it names the parts, the partial files and the fingerprint of this run."
8524
+ "Hand `PROMPT.md` to the model that receives this snapshot: it names the parts, the partial files and the fingerprint of this run."
8266
8525
  );
8267
8526
  }
8268
8527
  if (wrote("navigation") || wrote("projectTree")) {
8269
8528
  const first = [wrote("navigation") ? "`reports/navigation.md`" : null, wrote("projectTree") ? "`reports/project-tree.md`" : null].filter(Boolean).join(" or ");
8270
- readOrder.push(`1. Read ${first} first to locate target features or files.`);
8529
+ readOrder.push(`Read ${first} first to locate target features or files.`);
8271
8530
  }
8272
8531
  if (wrote("parts")) {
8273
8532
  readOrder.push(
8274
- `${readOrder.length + 1}. Open only the specific \`parts/part-XXX.md\` file holding the target modules.`
8533
+ "Open only the specific `parts/part-XXX.md` file holding the target modules."
8275
8534
  );
8276
8535
  }
8277
8536
  if (wrote("manifest")) {
8278
- readOrder.push(
8279
- `${readOrder.length + 1}. Inspect \`manifest.json\` for precise dependency and AST symbol maps.`
8280
- );
8537
+ readOrder.push("Inspect `manifest.json` for precise dependency and AST symbol maps.");
8281
8538
  }
8282
8539
  readOrder.push(
8283
- wrote("manifest") ? `${readOrder.length + 1}. Check \`manifest.validation.status\` before trusting the snapshot; \`snapshot validate\` re-checks it against disk.` : `${readOrder.length + 1}. No manifest was written, so this snapshot cannot be re-checked; regenerate with the manifest artifact enabled before trusting it.`
8540
+ 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."
8541
+ );
8542
+ lines.push(
8543
+ "",
8544
+ "## AI Agent Ingestion Guide",
8545
+ "",
8546
+ ...readOrder.map((step, index) => `${index + 1}. ${step}`),
8547
+ ""
8284
8548
  );
8285
- lines.push("", "## AI Agent Ingestion Guide", "", ...readOrder, "");
8286
8549
  return lines.join("\n");
8287
8550
  }
8288
8551
 
@@ -8505,6 +8768,10 @@ function tsconfigPathsFor(cwd) {
8505
8768
  return null;
8506
8769
  }
8507
8770
  const key = `${stats.mtimeMs}:${stats.size}`;
8771
+ if (!TSCONFIG_CACHE.has(configPath) && TSCONFIG_CACHE.size >= 64) {
8772
+ const oldest = TSCONFIG_CACHE.keys().next().value;
8773
+ if (oldest !== void 0) TSCONFIG_CACHE.delete(oldest);
8774
+ }
8508
8775
  const cached = TSCONFIG_CACHE.get(configPath);
8509
8776
  if (cached !== void 0 && cached.key === key) return cached.value;
8510
8777
  let value = null;
@@ -8533,8 +8800,8 @@ function tsconfigPathsFor(cwd) {
8533
8800
  return value;
8534
8801
  }
8535
8802
  function repositoryRelative(cwd, target) {
8536
- const relative14 = path25.relative(cwd, target).replace(/\\/g, "/");
8537
- return relative14.length === 0 || !relative14.startsWith("..") && !path25.isAbsolute(relative14) ? relative14 : null;
8803
+ const relative15 = path25.relative(cwd, target).replace(/\\/g, "/");
8804
+ return relative15.length === 0 || !relative15.startsWith("..") && !path25.isAbsolute(relative15) ? relative15 : null;
8538
8805
  }
8539
8806
  function rememberFirst(map, key, value) {
8540
8807
  if (!map.has(key)) map.set(key, value);
@@ -8664,6 +8931,77 @@ function importsChangedFile(importerPath, imports, changedPaths, resolver) {
8664
8931
  }
8665
8932
  return false;
8666
8933
  }
8934
+ function isInside2(parent, child) {
8935
+ const relative15 = path25.relative(parent, child);
8936
+ return relative15 === "" || !relative15.startsWith("..") && !path25.isAbsolute(relative15);
8937
+ }
8938
+ function resolveConfined(baseDir, relativePath) {
8939
+ if (relativePath.length === 0 || relativePath.includes("\0")) {
8940
+ return { ok: false, reason: "not-file", message: "the file name is empty or contains a NUL byte" };
8941
+ }
8942
+ if (path25.isAbsolute(relativePath)) {
8943
+ return { ok: false, reason: "outside", message: "an absolute path is not a snapshot-relative file" };
8944
+ }
8945
+ let baseReal;
8946
+ try {
8947
+ baseReal = fs24.realpathSync(path25.resolve(baseDir));
8948
+ } catch {
8949
+ return { ok: false, reason: "missing", message: "the snapshot directory does not exist" };
8950
+ }
8951
+ const candidate = path25.resolve(baseReal, relativePath);
8952
+ if (!isInside2(baseReal, candidate)) {
8953
+ return { ok: false, reason: "outside", message: "the path resolves outside the snapshot directory" };
8954
+ }
8955
+ let stats;
8956
+ try {
8957
+ stats = fs24.lstatSync(candidate);
8958
+ } catch (error) {
8959
+ const code = error.code;
8960
+ return {
8961
+ ok: false,
8962
+ reason: code === "ENOENT" || code === "ENOTDIR" ? "missing" : "unreadable",
8963
+ message: code === "ENOENT" || code === "ENOTDIR" ? "the file does not exist" : "the file could not be inspected"
8964
+ };
8965
+ }
8966
+ if (stats.isSymbolicLink()) {
8967
+ return { ok: false, reason: "not-file", message: "the file is a symbolic link" };
8968
+ }
8969
+ if (!stats.isFile()) {
8970
+ return { ok: false, reason: "not-file", message: "the path is not a regular file" };
8971
+ }
8972
+ let real;
8973
+ try {
8974
+ real = fs24.realpathSync(candidate);
8975
+ } catch {
8976
+ return { ok: false, reason: "unreadable", message: "the file could not be resolved" };
8977
+ }
8978
+ if (!isInside2(baseReal, real)) {
8979
+ return { ok: false, reason: "outside", message: "the file resolves outside the snapshot directory" };
8980
+ }
8981
+ return { ok: true, path: real, stats };
8982
+ }
8983
+ function readConfinedBytes(baseDir, relativePath) {
8984
+ const resolved = resolveConfined(baseDir, relativePath);
8985
+ if (!resolved.ok) return resolved;
8986
+ try {
8987
+ const bytes = fs24.readFileSync(resolved.path);
8988
+ return { ok: true, bytes, path: resolved.path, stats: fs24.statSync(resolved.path) };
8989
+ } catch {
8990
+ return { ok: false, reason: "unreadable", message: "the file could not be read" };
8991
+ }
8992
+ }
8993
+ function readConfinedText(baseDir, relativePath) {
8994
+ const resolved = resolveConfined(baseDir, relativePath);
8995
+ if (!resolved.ok) return resolved;
8996
+ try {
8997
+ const text2 = fs24.readFileSync(resolved.path, "utf8");
8998
+ return { ok: true, text: text2, path: resolved.path, stats: fs24.statSync(resolved.path) };
8999
+ } catch {
9000
+ return { ok: false, reason: "unreadable", message: "the file could not be read" };
9001
+ }
9002
+ }
9003
+
9004
+ // src/generator/overview.ts
8667
9005
  var SUMMARY_LIMIT = 400;
8668
9006
  var MAX_RELEASES = 2;
8669
9007
  function readProjectOverview(cwd) {
@@ -8673,15 +9011,12 @@ function readProjectOverview(cwd) {
8673
9011
  releases: readReleases(cwd)
8674
9012
  };
8675
9013
  }
8676
- function readText(file) {
8677
- try {
8678
- return fs24.readFileSync(file, "utf8");
8679
- } catch {
8680
- return null;
8681
- }
9014
+ function readText(cwd, relative15) {
9015
+ const read = readConfinedText(cwd, relative15);
9016
+ return read.ok ? read.text : null;
8682
9017
  }
8683
9018
  function readDescription(cwd) {
8684
- const raw = readText(path25.join(cwd, "package.json"));
9019
+ const raw = readText(cwd, "package.json");
8685
9020
  if (raw === null) return {};
8686
9021
  try {
8687
9022
  const parsed = JSON.parse(stripJsonComments(raw));
@@ -8691,7 +9026,7 @@ function readDescription(cwd) {
8691
9026
  }
8692
9027
  }
8693
9028
  function readSummary(cwd) {
8694
- const raw = readText(path25.join(cwd, "README.md"));
9029
+ const raw = readText(cwd, "README.md");
8695
9030
  if (raw === null) return {};
8696
9031
  const text2 = raw.replace(/<h[1-6][^>]*>[\s\S]*?<\/h[1-6]>/gi, "\n").replace(/<\/(p|div|section|header|footer|li)>/gi, "\n").replace(/<br\s*\/?>/gi, " ").replace(/<[^>]*>/g, " ").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'");
8697
9032
  const paragraph = [];
@@ -8717,7 +9052,7 @@ function truncate(text2, limit) {
8717
9052
  return (space > limit / 2 ? window.slice(0, space) : window).trim() + "\u2026";
8718
9053
  }
8719
9054
  function readReleases(cwd) {
8720
- const raw = readText(path25.join(cwd, "CHANGELOG.md"));
9055
+ const raw = readText(cwd, "CHANGELOG.md");
8721
9056
  if (raw === null) return [];
8722
9057
  const headings = raw.split(/\r?\n/).map((line) => /^##\s+(.+?)\s*$/.exec(line)?.[1]?.trim()).filter((heading) => heading !== void 0 && /^v?\d+\.\d+/.test(heading));
8723
9058
  return headings.slice(0, MAX_RELEASES);
@@ -9035,6 +9370,9 @@ function describeManifestShapeProblem(value) {
9035
9370
  if (typeof fields.relativePath !== "string") {
9036
9371
  return 'a "files" entry has no "relativePath"';
9037
9372
  }
9373
+ if (!isConfinedRelative(fields.relativePath)) {
9374
+ return 'a "files" entry "relativePath" resolves outside the repository and was not inspected';
9375
+ }
9038
9376
  if (!currentSchema) continue;
9039
9377
  if (typeof fields.part !== "string" || fields.part.length === 0) {
9040
9378
  return 'a "files" entry records no "part"';
@@ -9053,6 +9391,18 @@ function describeManifestShapeProblem(value) {
9053
9391
  }
9054
9392
  }
9055
9393
  if (!Array.isArray(candidate.skipped)) return 'missing "skipped" array';
9394
+ for (const entry of candidate.skipped) {
9395
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
9396
+ return 'a "skipped" entry is not an object';
9397
+ }
9398
+ const fields = entry;
9399
+ if (typeof fields.path !== "string" || !isConfinedRelative(fields.path)) {
9400
+ return 'a "skipped" entry "path" resolves outside the repository and was not inspected';
9401
+ }
9402
+ if (typeof fields.reason !== "string" || fields.reason.length === 0) {
9403
+ return 'a "skipped" entry has no "reason"';
9404
+ }
9405
+ }
9056
9406
  if (!Array.isArray(candidate.parts)) return 'missing "parts" array';
9057
9407
  for (const entry of candidate.parts) {
9058
9408
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
@@ -9113,10 +9463,12 @@ function validateSnapshot(configInput) {
9113
9463
  }
9114
9464
  const shapeProblem = describeManifestShapeProblem(manifest);
9115
9465
  if (shapeProblem) {
9466
+ const drift2 = emptyDrift();
9467
+ drift2.partIssues.push({ part: "manifest.json", issue: shapeProblem });
9116
9468
  return {
9117
9469
  valid: false,
9118
9470
  manifestPresent: true,
9119
- drift: emptyDrift(),
9471
+ drift: drift2,
9120
9472
  errors: [`${manifestPath} is not a snapshot manifest: ${shapeProblem}`],
9121
9473
  warnings: []
9122
9474
  };
@@ -9245,12 +9597,16 @@ function validateSnapshot(configInput) {
9245
9597
  // discovery mode" meant `validate` could enumerate files one way while the snapshot
9246
9598
  // had been generated another way, and then blame the difference on drift.
9247
9599
  discovery: config.discovery,
9600
+ // `generate --staged` adds index-only paths to the candidate list. Without the same
9601
+ // extra paths, a staged file that is absent from the working tree was invisible to
9602
+ // this scan and then reported as deleted, although the snapshot matched the index.
9603
+ ...stagedScope === null ? {} : { extraPaths: [...stagedScope] },
9248
9604
  // The same exclusion `generate` applies: without it, `validate` recounted the tool's
9249
9605
  // own output directory as a set of files missing from the snapshot, so a correct
9250
9606
  // snapshot was reported as drifting.
9251
9607
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
9252
9608
  (directory) => path25.relative(config.cwd, path25.resolve(config.cwd, directory)).replace(/\\/g, "/")
9253
- ).filter((relative14) => relative14.length > 0 && !relative14.startsWith(".."))
9609
+ ).filter((relative15) => relative15.length > 0 && !relative15.startsWith(".."))
9254
9610
  });
9255
9611
  for (const diskFile of collection.files) {
9256
9612
  const snapshotHash = manifestFileMap.get(diskFile);
@@ -9291,6 +9647,12 @@ function validateSnapshot(configInput) {
9291
9647
  }
9292
9648
  }
9293
9649
  for (const snapshotFile of manifestFileMap.keys()) {
9650
+ if (recordedStaged && stagedScope?.has(snapshotFile)) {
9651
+ if (readStagedBlob(config.cwd, snapshotFile) === null) {
9652
+ drift.missingOnDisk.push(snapshotFile);
9653
+ }
9654
+ continue;
9655
+ }
9294
9656
  const confined = confineToDirectory(config.cwd, snapshotFile);
9295
9657
  if (confined === null) {
9296
9658
  drift.partIssues.push({
@@ -9334,13 +9696,15 @@ function validateSnapshot(configInput) {
9334
9696
  });
9335
9697
  continue;
9336
9698
  }
9337
- let buffer;
9338
- try {
9339
- buffer = fs24.readFileSync(partPath);
9340
- } catch {
9341
- drift.partIssues.push({ part: part.filename, issue: "missing from snapshot/parts" });
9699
+ const partRead = readConfinedBytes(partsDir, part.filename);
9700
+ if (!partRead.ok) {
9701
+ drift.partIssues.push({
9702
+ part: part.filename,
9703
+ issue: `missing or not a regular file in snapshot/parts (${partRead.reason})`
9704
+ });
9342
9705
  continue;
9343
9706
  }
9707
+ const buffer = partRead.bytes;
9344
9708
  if (buffer.length !== part.byteSize) {
9345
9709
  drift.partIssues.push({
9346
9710
  part: part.filename,
@@ -9713,15 +10077,15 @@ function validateSnapshot(configInput) {
9713
10077
  ];
9714
10078
  for (const [key, artifact] of declaredArtifacts) {
9715
10079
  if (!artifact) continue;
9716
- const artifactPath = path25.join(snapshotDir, ...key.split("/"));
9717
- let buffer;
9718
- try {
9719
- if (!fs24.statSync(artifactPath).isFile()) throw new Error("not a regular file");
9720
- buffer = fs24.readFileSync(artifactPath);
9721
- } catch {
9722
- drift.partIssues.push({ part: key, issue: "declared artifact is missing" });
10080
+ const artifactRead = readConfinedBytes(snapshotDir, key);
10081
+ if (!artifactRead.ok) {
10082
+ drift.partIssues.push({
10083
+ part: key,
10084
+ issue: `declared artifact is missing or not a regular file (${artifactRead.reason})`
10085
+ });
9723
10086
  continue;
9724
10087
  }
10088
+ const buffer = artifactRead.bytes;
9725
10089
  if (sha256Hex(buffer) !== artifact.sha256 || buffer.length !== artifact.byteSize) {
9726
10090
  drift.partIssues.push({ part: key, issue: "artifact does not match its recorded digest" });
9727
10091
  continue;
@@ -9731,8 +10095,8 @@ function validateSnapshot(configInput) {
9731
10095
  const target = match[1].split("#")[0];
9732
10096
  if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
9733
10097
  const resolved = path25.resolve(snapshotDir, "reports", target);
9734
- const relative14 = path25.relative(snapshotDir, resolved);
9735
- if (relative14.startsWith("..") || path25.isAbsolute(relative14) || !fs24.existsSync(resolved)) {
10098
+ const relative15 = path25.relative(snapshotDir, resolved);
10099
+ if (relative15.startsWith("..") || path25.isAbsolute(relative15) || !fs24.existsSync(resolved)) {
9736
10100
  drift.partIssues.push({
9737
10101
  part: key,
9738
10102
  issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
@@ -9744,13 +10108,11 @@ function validateSnapshot(configInput) {
9744
10108
  const sarifArtifact = manifest.artifacts?.sarif;
9745
10109
  if (sarifArtifact) {
9746
10110
  const sarifKey = "reports/audit.sarif";
9747
- try {
9748
- const buffer = fs24.readFileSync(path25.join(snapshotDir, "reports", "audit.sarif"));
9749
- if (sha256Hex(buffer) !== sarifArtifact.sha256 || buffer.length !== sarifArtifact.byteSize) {
9750
- drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
9751
- }
9752
- } catch {
9753
- drift.partIssues.push({ part: sarifKey, issue: "declared artifact is missing" });
10111
+ const sarifRead = readConfinedBytes(snapshotDir, "reports/audit.sarif");
10112
+ if (!sarifRead.ok) {
10113
+ drift.partIssues.push({ part: sarifKey, issue: "declared artifact is missing or not a regular file" });
10114
+ } else if (sha256Hex(sarifRead.bytes) !== sarifArtifact.sha256 || sarifRead.bytes.length !== sarifArtifact.byteSize) {
10115
+ drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
9754
10116
  }
9755
10117
  }
9756
10118
  if (manifest.git && manifest.git.branch && manifest.git.branch !== config.branch) {
@@ -9899,9 +10261,11 @@ function isPrivateIPv6(groups) {
9899
10261
  ]);
9900
10262
  if (allZeroThrough(5) && sixth === 65535) return mapped(6);
9901
10263
  if (allZeroThrough(6) && (seventh !== 0 || eighth !== 0)) return mapped(6);
10264
+ if (allZeroThrough(4) && fifth === 65535 && sixth === 0) return mapped(6);
9902
10265
  if (first === 100 && second === 65435 && third === 0 && fourth === 0 && fifth === 0 && sixth === 0) {
9903
10266
  return mapped(6);
9904
10267
  }
10268
+ if (first === 100 && second === 65435 && third === 1) return mapped(6);
9905
10269
  if (first === 8194) return mapped(1);
9906
10270
  return false;
9907
10271
  }
@@ -10015,61 +10379,69 @@ async function cloneRepository(source, options) {
10015
10379
  const dest = path25.resolve(options.dest);
10016
10380
  fs24.rmSync(dest, { recursive: true, force: true });
10017
10381
  fs24.mkdirSync(dest, { recursive: true });
10018
- const ref = options.ref ?? source.ref;
10019
- const args = [
10020
- "-c",
10021
- "http.followRedirects=false",
10022
- ...source.kind === "https" ? ["-c", "protocol.file.allow=never", "-c", "protocol.ssh.allow=never"] : [],
10023
- "clone",
10024
- "--depth",
10025
- "1",
10026
- "--single-branch",
10027
- "--no-tags",
10028
- "--quiet"
10029
- ];
10030
- if (ref !== void 0 && ref !== null && ref !== "") {
10031
- args.push("--branch", ref);
10032
- }
10033
- args.push(source.url, dest);
10034
- log("clone: " + source.url + (ref ? " (" + ref + ")" : ""));
10035
- const started = Date.now();
10036
- const result = spawnSync("git", args, {
10037
- env: {
10038
- ...gitEnvironment(options.token, source.host === "file" ? "localhost" : source.host),
10039
- ...source.kind === "https" ? { GIT_ALLOW_PROTOCOL: "https" } : {}
10040
- },
10041
- timeout: options.timeoutMs ?? 18e4,
10042
- encoding: "utf8",
10043
- windowsHide: true
10044
- });
10045
- if (result.error !== void 0 && result.error !== null) {
10046
- throw new Error("git clone could not run: " + result.error.message);
10047
- }
10048
- if (result.status !== 0) {
10049
- const detail = (result.stderr ?? "").trim().split("\n").slice(-3).join(" ");
10050
- throw new Error("git clone failed (exit " + result.status + "): " + (detail || "no output"));
10051
- }
10052
- const head = spawnSync("git", ["-C", dest, "rev-parse", "HEAD"], { encoding: "utf8", windowsHide: true });
10053
- const commit = head.status === 0 ? (head.stdout ?? "").trim() : "";
10054
- if (commit === "") throw new Error("the clone has no HEAD; refusing to describe it");
10055
- const bytes = directorySize(dest);
10056
- log("clone: " + (bytes / 1024 / 1024).toFixed(1) + " MB in " + ((Date.now() - started) / 1e3).toFixed(1) + "s");
10057
- if (bytes > 1e9) {
10058
- throw new Error("the clone is larger than 1 GB (" + Math.round(bytes / 1024 / 1024) + " MB); refusing to scan it");
10059
- }
10060
- return {
10061
- directory: dest,
10062
- commit,
10063
- provenance: {
10064
- url: source.url,
10065
- host: source.host,
10066
- owner: source.owner,
10067
- repo: source.repo,
10068
- ref: ref !== void 0 && ref !== null && ref !== "" ? ref : null,
10382
+ try {
10383
+ const ref = options.ref ?? source.ref;
10384
+ const args = [
10385
+ "-c",
10386
+ "http.followRedirects=false",
10387
+ ...source.kind === "https" ? ["-c", "protocol.file.allow=never", "-c", "protocol.ssh.allow=never"] : [],
10388
+ "clone",
10389
+ "--depth",
10390
+ "1",
10391
+ "--single-branch",
10392
+ "--no-tags",
10393
+ "--quiet"
10394
+ ];
10395
+ if (ref !== void 0 && ref !== null && ref !== "") {
10396
+ args.push("--branch", ref);
10397
+ }
10398
+ args.push(source.url, dest);
10399
+ log("clone: " + source.url + (ref ? " (" + ref + ")" : ""));
10400
+ const started = Date.now();
10401
+ const result = spawnSync("git", args, {
10402
+ env: {
10403
+ ...gitEnvironment(options.token, source.host === "file" ? "localhost" : source.host),
10404
+ ...source.kind === "https" ? { GIT_ALLOW_PROTOCOL: "https" } : {}
10405
+ },
10406
+ timeout: options.timeoutMs ?? 18e4,
10407
+ encoding: "utf8",
10408
+ windowsHide: true
10409
+ });
10410
+ if (result.error !== void 0 && result.error !== null) {
10411
+ throw new Error("git clone could not run: " + result.error.message);
10412
+ }
10413
+ if (result.status !== 0) {
10414
+ const detail = (result.stderr ?? "").trim().split("\n").slice(-3).join(" ");
10415
+ throw new Error("git clone failed (exit " + result.status + "): " + (detail || "no output"));
10416
+ }
10417
+ const head = spawnSync("git", ["-C", dest, "rev-parse", "HEAD"], { encoding: "utf8", windowsHide: true });
10418
+ const commit = head.status === 0 ? (head.stdout ?? "").trim() : "";
10419
+ if (commit === "") throw new Error("the clone has no HEAD; refusing to describe it");
10420
+ const bytes = directorySize(dest);
10421
+ log("clone: " + (bytes / 1024 / 1024).toFixed(1) + " MB in " + ((Date.now() - started) / 1e3).toFixed(1) + "s");
10422
+ if (bytes > 1e9) {
10423
+ throw new Error("the clone is larger than 1 GB (" + Math.round(bytes / 1024 / 1024) + " MB); refusing to scan it");
10424
+ }
10425
+ return {
10426
+ directory: dest,
10069
10427
  commit,
10070
- fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
10428
+ provenance: {
10429
+ url: source.url,
10430
+ host: source.host,
10431
+ owner: source.owner,
10432
+ repo: source.repo,
10433
+ ref: ref !== void 0 && ref !== null && ref !== "" ? ref : null,
10434
+ commit,
10435
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
10436
+ }
10437
+ };
10438
+ } catch (error) {
10439
+ try {
10440
+ fs24.rmSync(dest, { recursive: true, force: true });
10441
+ } catch {
10071
10442
  }
10072
- };
10443
+ throw error;
10444
+ }
10073
10445
  }
10074
10446
  function directorySize(root) {
10075
10447
  let total = 0;
@@ -10304,7 +10676,7 @@ var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
10304
10676
  var META_PREFIX = "- Meta: ";
10305
10677
  var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
10306
10678
  var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
10307
- var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
10679
+ var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures", "comments-stripped"]);
10308
10680
  var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
10309
10681
  function readIncludedLines(fields) {
10310
10682
  const last = fields[fields.length - 1];
@@ -10399,17 +10771,10 @@ var ARTIFACT_FILES = {
10399
10771
  fullXml: "full-codebase.xml",
10400
10772
  sarif: "reports/audit.sarif"
10401
10773
  };
10402
- var TEXT_ARTIFACT = /\.(md|json|txt|sarif)$/i;
10774
+ var TEXT_ARTIFACT = /\.(md|json|txt|sarif|xml)$/i;
10403
10775
  function sha256(buffer) {
10404
10776
  return createHash("sha256").update(buffer).digest("hex");
10405
10777
  }
10406
- function readBytes(file) {
10407
- try {
10408
- return fs24.readFileSync(file);
10409
- } catch {
10410
- return null;
10411
- }
10412
- }
10413
10778
  function readText2(file) {
10414
10779
  try {
10415
10780
  return fs24.readFileSync(file, "utf8");
@@ -10417,8 +10782,17 @@ function readText2(file) {
10417
10782
  return null;
10418
10783
  }
10419
10784
  }
10785
+ function snapshotText(snapshotDir, relative15) {
10786
+ const read = readConfinedText(snapshotDir, relative15);
10787
+ return read.ok ? read.text : null;
10788
+ }
10789
+ function snapshotBytes(snapshotDir, relative15) {
10790
+ const read = readConfinedBytes(snapshotDir, relative15);
10791
+ return read.ok ? read.bytes : null;
10792
+ }
10420
10793
  function readJson(file) {
10421
- const text2 = readText2(file);
10794
+ const confined = readConfinedText(path25.dirname(file), path25.basename(file));
10795
+ const text2 = confined.ok ? confined.text : null;
10422
10796
  if (text2 === null) return null;
10423
10797
  try {
10424
10798
  return JSON.parse(text2);
@@ -10435,9 +10809,9 @@ function walk(dir, prefix = "") {
10435
10809
  }
10436
10810
  const files = [];
10437
10811
  for (const entry of entries) {
10438
- const relative14 = prefix === "" ? entry.name : prefix + "/" + entry.name;
10439
- if (entry.isDirectory()) files.push(...walk(path25.join(dir, entry.name), relative14));
10440
- else if (entry.isFile()) files.push(relative14);
10812
+ const relative15 = prefix === "" ? entry.name : prefix + "/" + entry.name;
10813
+ if (entry.isDirectory()) files.push(...walk(path25.join(dir, entry.name), relative15));
10814
+ else if (entry.isFile()) files.push(relative15);
10441
10815
  }
10442
10816
  return files;
10443
10817
  }
@@ -10475,16 +10849,28 @@ function secretTokens(text2) {
10475
10849
  }
10476
10850
  return [...tokens];
10477
10851
  }
10478
- function readArtifactTexts(snapshotDir) {
10852
+ function readArtifactTexts(snapshotDir, maxBytes = 32 * 1024 * 1024) {
10479
10853
  const texts = [];
10480
- for (const relative14 of walk(snapshotDir)) {
10481
- if (!TEXT_ARTIFACT.test(relative14)) continue;
10482
- const text2 = readText2(path25.join(snapshotDir, relative14));
10483
- if (text2 !== null) texts.push(text2);
10854
+ let bytes = 0;
10855
+ for (const relative15 of walk(snapshotDir)) {
10856
+ if (!TEXT_ARTIFACT.test(relative15)) continue;
10857
+ const full = path25.join(snapshotDir, relative15);
10858
+ let size2;
10859
+ try {
10860
+ size2 = fs24.statSync(full).size;
10861
+ } catch {
10862
+ continue;
10863
+ }
10864
+ if (bytes + size2 > maxBytes) break;
10865
+ const text2 = snapshotText(snapshotDir, relative15);
10866
+ if (text2 !== null) {
10867
+ texts.push(text2);
10868
+ bytes += Buffer.byteLength(text2, "utf8");
10869
+ }
10484
10870
  }
10485
10871
  return texts;
10486
10872
  }
10487
- function findHostPaths(snapshotDir, repoDir) {
10873
+ function findHostPaths(snapshotDir, repoDir, maxBytes = 32 * 1024 * 1024) {
10488
10874
  const patterns = [
10489
10875
  /\/home\/[A-Za-z0-9._-]+/g,
10490
10876
  /\/Users\/[A-Za-z0-9._-]+/g,
@@ -10495,15 +10881,24 @@ function findHostPaths(snapshotDir, repoDir) {
10495
10881
  ];
10496
10882
  const repoPattern = new RegExp(escapeRegExp(repoDir), "g");
10497
10883
  const hits = /* @__PURE__ */ new Set();
10498
- for (const relative14 of walk(snapshotDir)) {
10499
- if (!TEXT_ARTIFACT.test(relative14)) continue;
10500
- const text2 = readText2(path25.join(snapshotDir, relative14));
10884
+ let scanned = 0;
10885
+ for (const relative15 of walk(snapshotDir)) {
10886
+ if (!TEXT_ARTIFACT.test(relative15)) continue;
10887
+ let size2;
10888
+ try {
10889
+ size2 = fs24.statSync(path25.join(snapshotDir, relative15)).size;
10890
+ } catch {
10891
+ continue;
10892
+ }
10893
+ if (scanned + size2 > maxBytes) break;
10894
+ const text2 = snapshotText(snapshotDir, relative15);
10501
10895
  if (text2 === null) continue;
10896
+ scanned += Buffer.byteLength(text2, "utf8");
10502
10897
  for (const pattern of patterns) {
10503
- for (const match of text2.match(pattern) ?? []) hits.add(relative14 + ": " + match);
10898
+ for (const match of text2.match(pattern) ?? []) hits.add(relative15 + ": " + match);
10504
10899
  }
10505
10900
  repoPattern.lastIndex = 0;
10506
- if (repoPattern.test(text2)) hits.add(relative14 + ": the repository absolute path");
10901
+ if (repoPattern.test(text2)) hits.add(relative15 + ": the repository absolute path");
10507
10902
  }
10508
10903
  return [...hits];
10509
10904
  }
@@ -10685,7 +11080,7 @@ function auditSnapshot(options) {
10685
11080
  const missingParts = [];
10686
11081
  const mismatched = [];
10687
11082
  for (const part of manifest.parts) {
10688
- const bytes = readBytes(path25.join(snapshotDir, "parts", part.filename));
11083
+ const bytes = snapshotBytes(snapshotDir, "parts/" + part.filename);
10689
11084
  if (bytes === null) {
10690
11085
  missingParts.push(part.filename);
10691
11086
  continue;
@@ -10750,13 +11145,13 @@ function auditSnapshot(options) {
10750
11145
  let artifactCount = 0;
10751
11146
  for (const [key, value] of Object.entries(artifacts)) {
10752
11147
  if (value === null || value === void 0) continue;
10753
- const relative14 = ARTIFACT_FILES[key];
10754
- if (relative14 === void 0) continue;
11148
+ const relative15 = ARTIFACT_FILES[key];
11149
+ if (relative15 === void 0) continue;
10755
11150
  artifactCount += 1;
10756
- const bytes = readBytes(path25.join(snapshotDir, relative14));
10757
- if (bytes === null) artifactProblems.push(relative14 + " is missing");
11151
+ const bytes = snapshotBytes(snapshotDir, relative15);
11152
+ if (bytes === null) artifactProblems.push(relative15 + " is missing");
10758
11153
  else if (typeof value.sha256 === "string" && sha256(bytes) !== value.sha256) {
10759
- artifactProblems.push(relative14 + " changed");
11154
+ artifactProblems.push(relative15 + " changed");
10760
11155
  }
10761
11156
  }
10762
11157
  checks.push(
@@ -10866,7 +11261,7 @@ function auditSnapshot(options) {
10866
11261
  manifest.files.map((file) => [anchorForPath(file.relativePath), file.relativePath])
10867
11262
  );
10868
11263
  for (const part of manifest.parts) {
10869
- const partText = readText2(path25.join(snapshotDir, "parts", part.filename));
11264
+ const partText = snapshotText(snapshotDir, "parts/" + part.filename);
10870
11265
  if (partText === null) continue;
10871
11266
  const sections = parsePartSections(partText);
10872
11267
  partTexts.set(part.filename, partText);
@@ -10933,7 +11328,7 @@ function auditSnapshot(options) {
10933
11328
  }
10934
11329
  };
10935
11330
  if (manifest.artifacts?.readme != null) {
10936
- const text2 = readText2(path25.join(snapshotDir, "README.md"));
11331
+ const text2 = snapshotText(snapshotDir, "README.md");
10937
11332
  if (text2 === null) {
10938
11333
  reportProblems.push("README.md is recorded but unreadable");
10939
11334
  } else {
@@ -10973,7 +11368,7 @@ function auditSnapshot(options) {
10973
11368
  }
10974
11369
  }
10975
11370
  if (manifest.artifacts?.prompt != null) {
10976
- const text2 = readText2(path25.join(snapshotDir, "PROMPT.md"));
11371
+ const text2 = snapshotText(snapshotDir, "PROMPT.md");
10977
11372
  if (text2 === null) {
10978
11373
  reportProblems.push("PROMPT.md is recorded but unreadable");
10979
11374
  } else {
@@ -11162,7 +11557,7 @@ function auditSnapshot(options) {
11162
11557
  ];
11163
11558
  for (const reader of packReaders) {
11164
11559
  if (manifest.artifacts?.[reader.key] == null) continue;
11165
- const packText = readText2(path25.join(snapshotDir, reader.file));
11560
+ const packText = snapshotText(snapshotDir, reader.file);
11166
11561
  const problems = [];
11167
11562
  if (packText === null) {
11168
11563
  problems.push(reader.file + " is recorded but unreadable");
@@ -11212,7 +11607,7 @@ function auditSnapshot(options) {
11212
11607
  bodyByPath.set(file.relativePath, section.body);
11213
11608
  bodiesChecked += 1;
11214
11609
  const bytes = Buffer.byteLength(section.body, "utf8");
11215
- const bodyLines = section.body === "" ? 0 : section.body.split("\n").length - (section.body.endsWith("\n") ? 1 : 0);
11610
+ const bodyLines = countBodyLines(section.body);
11216
11611
  if (bytes !== file.includedBytes) {
11217
11612
  bodyProblems.push(file.relativePath + ": manifest says " + file.includedBytes + " B, part holds " + bytes + " B");
11218
11613
  } else if (bodyLines !== file.includedLines) {
@@ -11325,7 +11720,7 @@ function auditSnapshot(options) {
11325
11720
  let packBodies = 0;
11326
11721
  let packSkipped = 0;
11327
11722
  for (const pack of packsWanted) {
11328
- const text2 = readText2(path25.join(snapshotDir, pack.file));
11723
+ const text2 = snapshotText(snapshotDir, pack.file);
11329
11724
  if (text2 === null) continue;
11330
11725
  const bodies = pack.read(text2);
11331
11726
  if (bodies === null) {
@@ -11389,7 +11784,8 @@ function auditSnapshot(options) {
11389
11784
  unreplayable += 1;
11390
11785
  continue;
11391
11786
  }
11392
- const bytes = readBytes(path25.join(repoDir, file.relativePath));
11787
+ const repoBytes = readConfinedBytes(repoDir, file.relativePath);
11788
+ const bytes = repoBytes.ok ? repoBytes.bytes : null;
11393
11789
  if (bytes === null || sha256(bytes) !== file.hashSha256) {
11394
11790
  unreplayable += 1;
11395
11791
  continue;
@@ -11486,30 +11882,37 @@ function auditSnapshot(options) {
11486
11882
  const scanBudget = options.maxScanBytes ?? 32 * 1024 * 1024;
11487
11883
  const leakHits = [];
11488
11884
  let scannedBytes = 0;
11489
- for (const relative14 of walk(snapshotDir)) {
11490
- if (!TEXT_ARTIFACT.test(relative14) || scannedBytes > scanBudget) continue;
11491
- if (relative14 === SIGNATURE_FILE) continue;
11492
- const text2 = readText2(path25.join(snapshotDir, relative14));
11885
+ for (const relative15 of walk(snapshotDir)) {
11886
+ if (!TEXT_ARTIFACT.test(relative15) || scannedBytes > scanBudget) continue;
11887
+ if (relative15 === SIGNATURE_FILE) continue;
11888
+ let size2;
11889
+ try {
11890
+ size2 = fs24.statSync(path25.join(snapshotDir, relative15)).size;
11891
+ } catch {
11892
+ continue;
11893
+ }
11894
+ if (scannedBytes + size2 > scanBudget) break;
11895
+ const text2 = snapshotText(snapshotDir, relative15);
11493
11896
  if (text2 === null) continue;
11494
11897
  scannedBytes += Buffer.byteLength(text2, "utf8");
11495
11898
  let findingCount = 0;
11496
- if (/^parts[\\/].*\.md$/i.test(relative14)) {
11899
+ if (/^parts[\\/].*\.md$/i.test(relative15)) {
11497
11900
  let headerText = text2;
11498
11901
  for (const section of parsePartSections(text2)) {
11499
11902
  findingCount += scanAndRedactSecrets(section.body, rules, section.path).findings.length;
11500
11903
  headerText = headerText.replace(section.body, "");
11501
11904
  }
11502
- findingCount += scanAndRedactSecrets(headerText, rules, relative14).findings.length;
11905
+ findingCount += scanAndRedactSecrets(headerText, rules, relative15).findings.length;
11503
11906
  } else {
11504
- findingCount = scanAndRedactSecrets(text2, rules, relative14).findings.length;
11907
+ findingCount = scanAndRedactSecrets(text2, rules, relative15).findings.length;
11505
11908
  }
11506
11909
  if (findingCount > 0) {
11507
- leakHits.push(relative14 + " (" + findingCount + " line(s))");
11910
+ leakHits.push(relative15 + " (" + findingCount + " line(s))");
11508
11911
  }
11509
11912
  }
11510
11913
  const signatureRecordPath = path25.join(snapshotDir, SIGNATURE_FILE);
11511
11914
  if (fs24.existsSync(signatureRecordPath)) {
11512
- const recordText = readText2(signatureRecordPath);
11915
+ const recordText = snapshotText(snapshotDir, SIGNATURE_FILE);
11513
11916
  if (recordText !== null) {
11514
11917
  scannedBytes += Buffer.byteLength(recordText, "utf8");
11515
11918
  let scanText = recordText;
@@ -11549,11 +11952,17 @@ function auditSnapshot(options) {
11549
11952
  );
11550
11953
  const leakedFrom = [];
11551
11954
  let compared = 0;
11552
- const artifactTexts = readArtifactTexts(snapshotDir);
11955
+ const artifactTexts = readArtifactTexts(snapshotDir, scanBudget);
11553
11956
  const artifactContains = (token) => artifactTexts.some((text2) => text2.includes(token));
11554
11957
  for (const record of skippedSensitive.slice(0, 40)) {
11555
11958
  if (record.path.includes("[REDACTED") || compared > 400) continue;
11556
- const text2 = readText2(path25.join(repoDir, record.path));
11959
+ try {
11960
+ if (fs24.statSync(path25.join(repoDir, record.path)).size > scanBudget) continue;
11961
+ } catch {
11962
+ continue;
11963
+ }
11964
+ const repoRead = readConfinedText(repoDir, record.path);
11965
+ const text2 = repoRead.ok ? repoRead.text : null;
11557
11966
  if (text2 === null) continue;
11558
11967
  for (const token of secretTokens(text2)) {
11559
11968
  compared += 1;
@@ -11575,7 +11984,7 @@ function auditSnapshot(options) {
11575
11984
  "A value from " + sample([...new Set(leakedFrom)]) + " appears in the snapshot."
11576
11985
  )
11577
11986
  );
11578
- const pii = findHostPaths(snapshotDir, repoDir);
11987
+ const pii = findHostPaths(snapshotDir, repoDir, scanBudget);
11579
11988
  checks.push(
11580
11989
  pii.length === 0 ? check(
11581
11990
  "pii.paths",
@@ -11696,6 +12105,17 @@ function report(snapshotDir, repoDir, checks) {
11696
12105
  counts
11697
12106
  };
11698
12107
  }
12108
+ function safeRegularFile(cwd, absolute) {
12109
+ try {
12110
+ if (!fs24.lstatSync(absolute).isFile()) return false;
12111
+ const root = fs24.realpathSync(cwd);
12112
+ const real = fs24.realpathSync(absolute);
12113
+ const relative15 = path25.relative(root, real);
12114
+ return relative15 !== ".." && !relative15.startsWith(".." + path25.sep) && !path25.isAbsolute(relative15);
12115
+ } catch {
12116
+ return false;
12117
+ }
12118
+ }
11699
12119
  function describeMatcher(matcher) {
11700
12120
  if (typeof matcher === "string") return matcher;
11701
12121
  if (matcher instanceof RegExp) return String(matcher);
@@ -11707,23 +12127,23 @@ function describeMatcher(matcher) {
11707
12127
  function normalizeTarget(cwd, target) {
11708
12128
  const resolvedCwd = path25.resolve(cwd);
11709
12129
  const absolute = path25.resolve(resolvedCwd, target);
11710
- const relative14 = path25.relative(resolvedCwd, absolute);
11711
- if (relative14 === "" || relative14 === ".." || relative14.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative14)) {
12130
+ const relative15 = path25.relative(resolvedCwd, absolute);
12131
+ if (relative15 === "" || relative15 === ".." || relative15.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative15)) {
11712
12132
  return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
11713
12133
  }
11714
- return { relative: relative14.split(path25.sep).join("/"), outsideRoot: false };
12134
+ return { relative: relative15.split(path25.sep).join("/"), outsideRoot: false };
11715
12135
  }
11716
12136
  function findRuleMatch(rules, relativePath) {
11717
12137
  return rules.find(
11718
12138
  (rule) => matchRule(relativePath, rule.match)
11719
12139
  );
11720
12140
  }
11721
- function findRecordedAncestor(skipped, relative14, maskedPath2) {
12141
+ function findRecordedAncestor(skipped, relative15, maskedPath2) {
11722
12142
  let nearest;
11723
12143
  for (const record of skipped) {
11724
12144
  const ancestorPath = record.path;
11725
12145
  if (ancestorPath.length === 0) continue;
11726
- const isAncestor = relative14.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
12146
+ const isAncestor = relative15.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
11727
12147
  if (!isAncestor) continue;
11728
12148
  if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
11729
12149
  }
@@ -11739,8 +12159,8 @@ function readManifest2(config) {
11739
12159
  }
11740
12160
  function explainPath(config, target) {
11741
12161
  const normalized = normalizeTarget(config.cwd, target);
11742
- const relative14 = normalized.relative;
11743
- const maskedPath2 = findSecretInPath(relative14, config.secretRules)?.masked ?? relative14;
12162
+ const relative15 = normalized.relative;
12163
+ const maskedPath2 = findSecretInPath(relative15, config.secretRules)?.masked ?? relative15;
11744
12164
  if (normalized.outsideRoot) {
11745
12165
  return {
11746
12166
  path: maskedPath2,
@@ -11750,10 +12170,14 @@ function explainPath(config, target) {
11750
12170
  detail: "path resolves outside the configured repository root and was not inspected"
11751
12171
  };
11752
12172
  }
11753
- const absolute = path25.join(config.cwd, relative14);
12173
+ const absolute = path25.join(config.cwd, relative15);
12174
+ const stagedBlob = config.staged === true ? readStagedBlob(config.cwd, relative15) : null;
11754
12175
  const result = {
11755
12176
  path: maskedPath2,
11756
- exists: fs24.existsSync(absolute),
12177
+ // `existsSync` follows a symlink, so an in-repo link to /etc/passwd answered "exists" for a
12178
+ // file the scanner refuses. `lstat` plus a canonical containment check keeps the answer about
12179
+ // a regular file the repository actually contains; a staged blob is the index's answer.
12180
+ exists: stagedBlob !== null || safeRegularFile(config.cwd, absolute),
11757
12181
  included: false
11758
12182
  };
11759
12183
  const collection = collectFiles(config.cwd, {
@@ -11768,11 +12192,11 @@ function explainPath(config, target) {
11768
12192
  // that is only missing because the walker dropped the tool's own output directory.
11769
12193
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
11770
12194
  (directory) => path25.relative(config.cwd, path25.resolve(config.cwd, directory)).replace(/\\/g, "/")
11771
- ).filter((relative15) => relative15.length > 0 && !relative15.startsWith(".."))
12195
+ ).filter((relative16) => relative16.length > 0 && !relative16.startsWith(".."))
11772
12196
  });
11773
- if (!collection.files.includes(relative14)) {
12197
+ if (!collection.files.includes(relative15)) {
11774
12198
  const record = collection.skipped.find(
11775
- (entry2) => entry2.path === relative14 || entry2.path === maskedPath2
12199
+ (entry2) => entry2.path === relative15 || entry2.path === maskedPath2
11776
12200
  );
11777
12201
  if (record) {
11778
12202
  result.reason = record.reason;
@@ -11781,7 +12205,7 @@ function explainPath(config, target) {
11781
12205
  result.reason = "missing";
11782
12206
  result.detail = "no such file or directory, relative to the configured cwd";
11783
12207
  } else {
11784
- const ancestor = findRecordedAncestor(collection.skipped, relative14, maskedPath2);
12208
+ const ancestor = findRecordedAncestor(collection.skipped, relative15, maskedPath2);
11785
12209
  if (ancestor) {
11786
12210
  result.reason = ancestor.reason;
11787
12211
  result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
@@ -11801,11 +12225,11 @@ function explainPath(config, target) {
11801
12225
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
11802
12226
  ...config.staged === true ? { staged: true } : {}
11803
12227
  });
11804
- inScope = scope.paths.has(relative14);
12228
+ inScope = scope.paths.has(relative15);
11805
12229
  if (!inScope && config.withDependents === true) {
11806
12230
  inScope = importsChangedFile(
11807
- relative14,
11808
- importsOfFile(relative14, absolute),
12231
+ relative15,
12232
+ importsOfFile(relative15, absolute),
11809
12233
  scope.paths,
11810
12234
  buildImportResolver(collection.files.map((file) => ({ relativePath: file })), {
11811
12235
  tsconfig: tsconfigPathsFor(config.cwd)
@@ -11832,11 +12256,13 @@ function explainPath(config, target) {
11832
12256
  result.detail = "binary extension; generate skips it without reading and records `binary` in manifest.skipped[]";
11833
12257
  return result;
11834
12258
  }
11835
- let sizeOnDisk = null;
11836
- try {
11837
- sizeOnDisk = fs24.statSync(absolute).size;
11838
- } catch {
11839
- sizeOnDisk = null;
12259
+ let sizeOnDisk = stagedBlob?.length ?? null;
12260
+ if (sizeOnDisk === null) {
12261
+ try {
12262
+ sizeOnDisk = fs24.statSync(absolute).size;
12263
+ } catch {
12264
+ sizeOnDisk = null;
12265
+ }
11840
12266
  }
11841
12267
  if (sizeOnDisk !== null && sizeOnDisk > BINARY_SCAN_BYTES && isBinaryFile(absolute)) {
11842
12268
  result.included = false;
@@ -11844,10 +12270,10 @@ function explainPath(config, target) {
11844
12270
  result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
11845
12271
  return result;
11846
12272
  }
11847
- if (fs24.existsSync(absolute) && fs24.statSync(absolute).isFile()) {
12273
+ if (stagedBlob !== null || safeRegularFile(config.cwd, absolute)) {
11848
12274
  let buffer;
11849
12275
  try {
11850
- buffer = fs24.readFileSync(absolute);
12276
+ buffer = stagedBlob ?? fs24.readFileSync(absolute);
11851
12277
  } catch (err) {
11852
12278
  result.included = false;
11853
12279
  result.reason = "read-error";
@@ -11865,15 +12291,15 @@ function explainPath(config, target) {
11865
12291
  result.bytes = buffer.length;
11866
12292
  result.lines = countLines(text2);
11867
12293
  if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
11868
- const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative14);
12294
+ const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative15);
11869
12295
  result.secretCount = findings.length;
11870
12296
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
11871
12297
  let inclusionMode = "full";
11872
- if (config.skeleton === true && isSkeletonizable(relative14)) {
11873
- const skeleton = skeletonizeTypeScript(text2, relative14);
12298
+ if (config.skeleton === true && isSkeletonizable(relative15)) {
12299
+ const skeleton = skeletonizeTypeScript(text2, relative15);
11874
12300
  if (skeleton.collapsed > 0) inclusionMode = "signatures";
11875
12301
  }
11876
- if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative14) && stripComments2(text2, relative14).removed > 0) {
12302
+ if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative15) && stripComments2(text2, relative15).removed > 0) {
11877
12303
  inclusionMode = "comments-stripped";
11878
12304
  }
11879
12305
  if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
@@ -11882,20 +12308,36 @@ function explainPath(config, target) {
11882
12308
  }
11883
12309
  result.inclusionMode = inclusionMode;
11884
12310
  }
11885
- result.layer = classifyLayer(relative14, config.layers);
11886
- result.kind = classifyKind(relative14, config.kinds);
11887
- result.language = detectLanguage(relative14);
11888
- const layerRule = findRuleMatch(config.layers, relative14);
12311
+ result.layer = classifyLayer(relative15, config.layers);
12312
+ result.kind = classifyKind(relative15, config.kinds);
12313
+ result.language = detectLanguage(relative15);
12314
+ const layerRule = findRuleMatch(config.layers, relative15);
11889
12315
  if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
11890
- const kindRule = findRuleMatch(config.kinds, relative14);
12316
+ const kindRule = findRuleMatch(config.kinds, relative15);
11891
12317
  if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
11892
12318
  const manifest = readManifest2(config);
11893
- const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative14) : void 0;
12319
+ const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative15) : void 0;
11894
12320
  result.part = entry?.part ?? null;
11895
12321
  if (entry === void 0) {
11896
- const record = manifest?.skipped?.find((skip) => skip.path === relative14);
12322
+ const record = manifest?.skipped?.find((skip) => skip.path === relative15);
11897
12323
  if (record !== void 0 && (record.reason === "not-selected" || record.reason === "unchanged")) {
11898
12324
  result.included = false;
12325
+ for (const key of [
12326
+ "layer",
12327
+ "layerMatch",
12328
+ "kind",
12329
+ "kindMatch",
12330
+ "language",
12331
+ "inclusionMode",
12332
+ "lines",
12333
+ "bytes",
12334
+ "encoding",
12335
+ "secretCount",
12336
+ "secrets"
12337
+ ]) {
12338
+ delete result[key];
12339
+ }
12340
+ result.part = null;
11899
12341
  result.reason = record.reason;
11900
12342
  result.detail = record.detail ?? (record.reason === "not-selected" ? "the snapshot was generated for a selection (--slice or --budget-tokens) that did not include this path" : "the snapshot was generated with a changed-files scope that did not include this path");
11901
12343
  }
@@ -11946,7 +12388,10 @@ const { parentPort, workerData } = require("node:worker_threads");
11946
12388
  (async () => {
11947
12389
  try {
11948
12390
  const mod = await import(workerData.entryUrl);
11949
- const loaded = await mod.loadConfigFileDetailed(workerData.cwd);
12391
+ const loaded =
12392
+ workerData.config === null || workerData.config === undefined
12393
+ ? await mod.loadConfigFileDetailed(workerData.cwd, { allowExecutableConfig: false })
12394
+ : { config: workerData.config, errors: [] };
11950
12395
  if (loaded.errors.length > 0) {
11951
12396
  parentPort.postMessage({ ok: false, message: loaded.errors.join("; ") });
11952
12397
  return;
@@ -11958,6 +12403,7 @@ const { parentPort, workerData } = require("node:worker_threads");
11958
12403
  const manifest = mod.generateSnapshot(config, {
11959
12404
  dryRun: workerData.dryRun === true,
11960
12405
  ...(workerData.narrow ?? {}),
12406
+ ...(workerData.source === undefined ? {} : { source: workerData.source }),
11961
12407
  ...(workerData.runId === undefined ? {} : { runId: workerData.runId }),
11962
12408
  });
11963
12409
  const skipCounts = new Map();
@@ -11998,7 +12444,7 @@ const { parentPort, workerData } = require("node:worker_threads");
11998
12444
  })();
11999
12445
  `;
12000
12446
  function generateInWorker(cwd, cliOptions, options = {}) {
12001
- return new Promise((resolve14) => {
12447
+ return new Promise((resolve15) => {
12002
12448
  let settled = false;
12003
12449
  let worker = null;
12004
12450
  const finish = (result) => {
@@ -12009,7 +12455,7 @@ function generateInWorker(cwd, cliOptions, options = {}) {
12009
12455
  if (!result.ok && options.runId !== void 0 && options.lockRoots !== void 0) {
12010
12456
  releaseAbandonedRun(options.lockRoots, options.runId);
12011
12457
  }
12012
- resolve14(result);
12458
+ resolve15(result);
12013
12459
  });
12014
12460
  };
12015
12461
  const isCjs = typeof __dirname !== "undefined";
@@ -12023,6 +12469,8 @@ function generateInWorker(cwd, cliOptions, options = {}) {
12023
12469
  cliOptions,
12024
12470
  dryRun: options.dryRun === true,
12025
12471
  narrow: options.narrow ?? {},
12472
+ ...options.config === void 0 ? {} : { config: options.config },
12473
+ ...options.source === void 0 ? {} : { source: options.source },
12026
12474
  ...options.runId === void 0 ? {} : { runId: options.runId }
12027
12475
  }
12028
12476
  });
@@ -12086,7 +12534,7 @@ function canonicalPath(value) {
12086
12534
  return absolute;
12087
12535
  }
12088
12536
  }
12089
- function isInside2(parent, child) {
12537
+ function isInside3(parent, child) {
12090
12538
  const foldedParent = foldForComparison(parent);
12091
12539
  const foldedChild = foldForComparison(child);
12092
12540
  return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path25.sep}`);
@@ -12120,7 +12568,7 @@ function resolveRoot(requested, context) {
12120
12568
  }
12121
12569
  const resolved = canonicalPath(absolute);
12122
12570
  for (const allowed of context.roots) {
12123
- if (isInside2(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
12571
+ if (isInside3(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
12124
12572
  }
12125
12573
  const shown = context.roots.join(", ");
12126
12574
  return {
@@ -12164,7 +12612,7 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
12164
12612
  const requested = overrides.outDir.trim();
12165
12613
  const permitted = allowedRoots !== void 0 && allowedRoots.length > 0 ? allowedRoots : [root];
12166
12614
  const resolved = resolveThroughExistingAncestor(path25.resolve(root, requested));
12167
- if (!permitted.some((allowed) => isInside2(canonicalPath(allowed), resolved))) {
12615
+ if (!permitted.some((allowed) => isInside3(canonicalPath(allowed), resolved))) {
12168
12616
  const shown = permitted.map((allowed) => canonicalPath(allowed)).join(", ");
12169
12617
  return {
12170
12618
  ok: false,
@@ -12186,6 +12634,14 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
12186
12634
  if (overrides.sarif === true) cliOptions.sarif = true;
12187
12635
  if (overrides.staged === true) cliOptions.staged = true;
12188
12636
  if (overrides.withDependents === true) cliOptions.withDependents = true;
12637
+ for (const key of ["only", "ignore"]) {
12638
+ const value = overrides[key];
12639
+ if (value === void 0) continue;
12640
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
12641
+ return { ok: false, message: `"${key}" must be an array of glob strings.` };
12642
+ }
12643
+ cliOptions[key] = value;
12644
+ }
12189
12645
  try {
12190
12646
  const config = resolveConfig(loaded.config, cliOptions, root);
12191
12647
  return {
@@ -12211,8 +12667,8 @@ function partPathFor(workspace, filename) {
12211
12667
  if (filename.length === 0 || filename.includes("\0")) return null;
12212
12668
  const partsDir = path25.resolve(workspace.root, workspace.config.outDir, "parts");
12213
12669
  const resolved = path25.resolve(partsDir, filename);
12214
- const relative14 = path25.relative(partsDir, resolved);
12215
- if (relative14.length === 0 || relative14.includes(path25.sep) || relative14.includes("/") || relative14.includes("\\") || path25.isAbsolute(relative14)) {
12670
+ const relative15 = path25.relative(partsDir, resolved);
12671
+ if (relative15.length === 0 || relative15.includes(path25.sep) || relative15.includes("/") || relative15.includes("\\") || path25.isAbsolute(relative15)) {
12216
12672
  return null;
12217
12673
  }
12218
12674
  let stats;
@@ -12232,30 +12688,27 @@ function partPathFor(workspace, filename) {
12232
12688
  function readManifest3(workspace) {
12233
12689
  const file = manifestPathFor(workspace);
12234
12690
  const shown = path25.relative(workspace.root, file).split(path25.sep).join("/") || file;
12235
- let stats;
12236
- try {
12237
- stats = fs24.statSync(file);
12238
- } catch {
12691
+ const confined = readConfinedText(path25.dirname(file), path25.basename(file));
12692
+ if (!confined.ok) {
12693
+ if (confined.reason === "missing") {
12694
+ return {
12695
+ ok: false,
12696
+ missing: true,
12697
+ message: `There is no snapshot manifest at ${shown}. Call snapshot_plan to preview what would be included, or snapshot_generate to write it.`
12698
+ };
12699
+ }
12239
12700
  return {
12240
12701
  ok: false,
12241
- missing: true,
12242
- message: `There is no snapshot manifest at ${shown}. Call snapshot_plan to preview what would be included, or snapshot_generate to write it.`
12702
+ missing: false,
12703
+ message: `${shown} could not be read as a snapshot manifest: ${confined.message}.`
12243
12704
  };
12244
12705
  }
12706
+ const stats = confined.stats;
12707
+ const raw = confined.text;
12245
12708
  const cached = manifestCache.get(file);
12246
12709
  if (cached && cached.mtimeMs === stats.mtimeMs && cached.ctimeMs === stats.ctimeMs && cached.size === stats.size) {
12247
12710
  return { ok: true, manifest: cached.manifest, file };
12248
12711
  }
12249
- let raw;
12250
- try {
12251
- raw = fs24.readFileSync(file, "utf8");
12252
- } catch (error) {
12253
- return {
12254
- ok: false,
12255
- missing: false,
12256
- message: `${shown} exists but could not be read: ${error instanceof Error ? error.message : String(error)}`
12257
- };
12258
- }
12259
12712
  let parsed;
12260
12713
  try {
12261
12714
  parsed = JSON.parse(raw);
@@ -12285,6 +12738,123 @@ function forgetManifest(file) {
12285
12738
  manifestCache.delete(file);
12286
12739
  }
12287
12740
 
12741
+ // src/security/regex.ts
12742
+ var MAX_PATTERN_LENGTH = 256;
12743
+ var MAX_QUANTIFIER_REPEAT = 1e4;
12744
+ function unsafeRegExpReason(source) {
12745
+ if (source.length === 0) return null;
12746
+ if (source.length > MAX_PATTERN_LENGTH) {
12747
+ return `the pattern is longer than ${MAX_PATTERN_LENGTH} characters`;
12748
+ }
12749
+ let inClass = false;
12750
+ let unbounded = 0;
12751
+ const groups = [];
12752
+ for (let index = 0; index < source.length; index += 1) {
12753
+ const char = source[index];
12754
+ if (char === "\\") {
12755
+ index += 1;
12756
+ continue;
12757
+ }
12758
+ if (inClass) {
12759
+ if (char === "]") inClass = false;
12760
+ continue;
12761
+ }
12762
+ if (char === "[") {
12763
+ inClass = true;
12764
+ continue;
12765
+ }
12766
+ if (char === "(") {
12767
+ groups.push({ quantified: false, alternation: false });
12768
+ continue;
12769
+ }
12770
+ if (char === ")") {
12771
+ const group = groups.pop();
12772
+ if (group === void 0) continue;
12773
+ if (isQuantifiedAt(source, index + 1)) {
12774
+ if (group.quantified || group.alternation) {
12775
+ return "a quantified group contains another quantifier or an alternation";
12776
+ }
12777
+ group.quantified = true;
12778
+ } else if (isOptionalQuantifierAt(source, index + 1)) {
12779
+ group.quantified = true;
12780
+ }
12781
+ const parent = groups[groups.length - 1];
12782
+ if (parent !== void 0) {
12783
+ parent.quantified = parent.quantified || group.quantified;
12784
+ parent.alternation = parent.alternation || group.alternation;
12785
+ }
12786
+ continue;
12787
+ }
12788
+ if (char === "|") {
12789
+ const group = groups[groups.length - 1];
12790
+ if (group !== void 0) group.alternation = true;
12791
+ continue;
12792
+ }
12793
+ if (char === "?") {
12794
+ const previous = source[index - 1];
12795
+ if (previous !== "(" && previous !== "?" && previous !== "*" && previous !== "+" && previous !== "}") {
12796
+ const group = groups[groups.length - 1];
12797
+ if (group !== void 0) group.quantified = true;
12798
+ }
12799
+ continue;
12800
+ }
12801
+ if (char === "*" || char === "+") {
12802
+ unbounded += 1;
12803
+ const group = groups[groups.length - 1];
12804
+ if (group !== void 0) group.quantified = true;
12805
+ continue;
12806
+ }
12807
+ if (char === "{") {
12808
+ const close = source.indexOf("}", index + 1);
12809
+ if (close === -1) continue;
12810
+ const body = source.slice(index + 1, close);
12811
+ const match = /^(\d+)(?:,(\d*))?$/.exec(body);
12812
+ if (match === null) {
12813
+ index = close;
12814
+ continue;
12815
+ }
12816
+ const max = match[2] === void 0 ? Number(match[1]) : match[2] === "" ? Infinity : Number(match[2]);
12817
+ if (max > MAX_QUANTIFIER_REPEAT) {
12818
+ return "a repetition bound is larger than the search budget can evaluate safely";
12819
+ }
12820
+ if (max === Infinity) unbounded += 1;
12821
+ const group = groups[groups.length - 1];
12822
+ if (group !== void 0) group.quantified = true;
12823
+ index = close;
12824
+ }
12825
+ }
12826
+ if (unbounded > 1) {
12827
+ return "the pattern has more than one unbounded repetition";
12828
+ }
12829
+ return null;
12830
+ }
12831
+ function isOptionalQuantifierAt(source, start) {
12832
+ if (source[start] === "?") return true;
12833
+ if (source[start] !== "{") return false;
12834
+ const close = source.indexOf("}", start + 1);
12835
+ if (close === -1) return false;
12836
+ const body = source.slice(start + 1, close);
12837
+ const match = /^(\d+)(?:,(\d*))?$/.exec(body);
12838
+ if (match === null) return false;
12839
+ const minimum = Number(match[1]);
12840
+ if (match[2] === void 0) return minimum <= 1;
12841
+ const maximum = match[2] === "" ? Infinity : Number(match[2]);
12842
+ return maximum <= 1;
12843
+ }
12844
+ function isQuantifiedAt(source, start) {
12845
+ const char = source[start];
12846
+ if (char === "*" || char === "+") return true;
12847
+ if (char !== "{") return false;
12848
+ const close = source.indexOf("}", start + 1);
12849
+ if (close === -1) return false;
12850
+ const body = source.slice(start + 1, close);
12851
+ const match = /^(\d+)(?:,(\d*))?$/.exec(body);
12852
+ if (match === null) return false;
12853
+ if (match[2] === void 0) return Number(match[1]) > 1;
12854
+ if (match[2] === "") return true;
12855
+ return Number(match[2]) > 1;
12856
+ }
12857
+
12288
12858
  // src/mcp/tools.ts
12289
12859
  var MAX_SEARCH_BYTES = 4 * 1024 * 1024;
12290
12860
  var READ_ONLY = {
@@ -12316,6 +12886,16 @@ var OUT_DIR_PROPERTY = {
12316
12886
  };
12317
12887
  var outDirOverride = (args) => ({ outDir: args.outDir });
12318
12888
  var SCOPE_PROPERTIES = {
12889
+ only: {
12890
+ type: "array",
12891
+ items: { type: "string" },
12892
+ description: "Globs to include: replaces the config allow-list for this run."
12893
+ },
12894
+ ignore: {
12895
+ type: "array",
12896
+ items: { type: "string" },
12897
+ description: "Globs to exclude, added to the config deny-list for this run."
12898
+ },
12319
12899
  maxPartTokens: {
12320
12900
  type: "string",
12321
12901
  description: 'Token ceiling per part, for example 32000 or "32k". Narrower than maxPartBytes; it converts at four bytes per token.'
@@ -12350,7 +12930,9 @@ function workspaceOverrides(args) {
12350
12930
  sarif: args.sarif,
12351
12931
  changedSince: args.changedSince,
12352
12932
  staged: args.staged,
12353
- withDependents: args.withDependents
12933
+ withDependents: args.withDependents,
12934
+ only: args.only,
12935
+ ignore: args.ignore
12354
12936
  };
12355
12937
  }
12356
12938
  function failure(message) {
@@ -12386,11 +12968,11 @@ function toRelativePath(root, value) {
12386
12968
  if (cleaned.length === 0 || cleaned.includes("\0")) return null;
12387
12969
  const resolvedRoot = path25.resolve(root);
12388
12970
  const absolute = path25.resolve(resolvedRoot, cleaned);
12389
- const relative14 = path25.relative(resolvedRoot, absolute);
12390
- if (relative14 === "" || relative14 === ".." || relative14.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative14)) {
12971
+ const relative15 = path25.relative(resolvedRoot, absolute);
12972
+ if (relative15 === "" || relative15 === ".." || relative15.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative15)) {
12391
12973
  return null;
12392
12974
  }
12393
- return relative14.split(path25.sep).join("/");
12975
+ return relative15.split(path25.sep).join("/");
12394
12976
  }
12395
12977
  function symbolsOf(entry) {
12396
12978
  const summary = entry.summary;
@@ -12483,16 +13065,15 @@ var historyTool = {
12483
13065
  async handler(args, context) {
12484
13066
  const prepared = await prepare(args, context, outDirOverride(args));
12485
13067
  if (!prepared.ok) return prepared.outcome;
12486
- const reportPath = path25.resolve(prepared.workspace.root, prepared.workspace.config.outDir, "reports", "log.md");
12487
- let text2;
12488
- try {
12489
- text2 = fs24.readFileSync(reportPath, "utf8");
12490
- } catch {
13068
+ const snapshotDir = path25.resolve(prepared.workspace.root, prepared.workspace.config.outDir);
13069
+ const reportRead = readConfinedText(snapshotDir, path25.posix.join("reports", "log.md"));
13070
+ if (!reportRead.ok) {
12491
13071
  return {
12492
- text: "This snapshot has no reports/log.md. Generate it with `snapshot_generate { includeLogs: 20 }`, or `generate --include-logs 20` on the command line; the report is opt-in because the commit subjects are repository content.",
13072
+ text: "This snapshot has no readable reports/log.md. Generate it with `snapshot_generate { includeLogs: 20 }`, or `generate --include-logs 20` on the command line; the report is opt-in because the commit subjects are repository content, and it must be a regular file inside the snapshot.",
12493
13073
  isError: true
12494
13074
  };
12495
13075
  }
13076
+ const text2 = reportRead.text;
12496
13077
  const manifestRead = readManifest3(prepared.workspace);
12497
13078
  const recordedLog = manifestRead.ok ? manifestRead.manifest.artifacts?.log : void 0;
12498
13079
  if (recordedLog !== void 0 && recordedLog !== null) {
@@ -12656,21 +13237,22 @@ var workspaceTool = {
12656
13237
  async handler(args, context) {
12657
13238
  const prepared = await prepare(args, context, outDirOverride(args));
12658
13239
  if (!prepared.ok) return prepared.outcome;
12659
- const index = path25.resolve(
12660
- prepared.workspace.root,
12661
- prepared.workspace.config.outDir,
12662
- "WORKSPACE.json"
12663
- );
12664
- let text2;
12665
- try {
12666
- text2 = fs24.readFileSync(index, "utf8");
12667
- } catch {
13240
+ const snapshotDir = path25.resolve(prepared.workspace.root, prepared.workspace.config.outDir);
13241
+ const index = path25.join(snapshotDir, "WORKSPACE.json");
13242
+ const read = readConfinedText(snapshotDir, "WORKSPACE.json");
13243
+ if (!read.ok) {
12668
13244
  return {
12669
- text: "No workspace index at " + index + ". Generate one with `generate --workspace member-a,member-b`; a single snapshot has no members to list.",
13245
+ text: "No workspace index at " + index + " (the file is absent, or it is not a regular file inside the snapshot). Generate one with `generate --workspace member-a,member-b`; a single snapshot has no members to list.",
12670
13246
  isError: true
12671
13247
  };
12672
13248
  }
12673
- const document = JSON.parse(text2);
13249
+ const text2 = read.text;
13250
+ let document;
13251
+ try {
13252
+ document = JSON.parse(text2);
13253
+ } catch (error) {
13254
+ return { text: "WORKSPACE.json is not valid JSON: " + error.message, isError: true };
13255
+ }
12674
13256
  const members = document.members ?? [];
12675
13257
  const links = document.links ?? [];
12676
13258
  const lines = [
@@ -12810,6 +13392,10 @@ var routesTool = {
12810
13392
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
12811
13393
  let filter = null;
12812
13394
  if (typeof args.pattern === "string") {
13395
+ const unsafe = unsafeRegExpReason(args.pattern);
13396
+ if (unsafe !== null) {
13397
+ return { text: "pattern is refused: " + unsafe + ".", isError: true };
13398
+ }
12813
13399
  try {
12814
13400
  filter = new RegExp(args.pattern, "i");
12815
13401
  } catch (error) {
@@ -12953,6 +13539,12 @@ var searchTool = {
12953
13539
  const cap = Math.max(1, Math.min(500, typeof args.maxMatches === "number" ? args.maxMatches : 50));
12954
13540
  const contextLines = Math.max(0, Math.min(10, typeof args.contextLines === "number" ? args.contextLines : 0));
12955
13541
  let pattern;
13542
+ if (args.regex === true) {
13543
+ const unsafe = unsafeRegExpReason(query);
13544
+ if (unsafe !== null) {
13545
+ return { text: "regex is refused: " + unsafe + ".", isError: true };
13546
+ }
13547
+ }
12956
13548
  try {
12957
13549
  pattern = args.regex === true ? new RegExp(query, "i") : new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i");
12958
13550
  } catch (error) {
@@ -12975,11 +13567,17 @@ var searchTool = {
12975
13567
  } catch {
12976
13568
  continue;
12977
13569
  }
12978
- if (Buffer.byteLength(text2, "utf8") > MAX_SEARCH_BYTES) {
13570
+ const partBytes = Buffer.byteLength(text2, "utf8");
13571
+ if (partBytes > MAX_SEARCH_BYTES) {
12979
13572
  skippedOversize.push(part.filename);
13573
+ truncated = true;
12980
13574
  continue;
12981
13575
  }
12982
- scanned += text2.length;
13576
+ if (scanned + partBytes > MAX_SEARCH_BYTES) {
13577
+ truncated = true;
13578
+ break;
13579
+ }
13580
+ scanned += partBytes;
12983
13581
  for (const section of parsePartSections(text2)) {
12984
13582
  if (matches.length >= cap) {
12985
13583
  truncated = true;
@@ -13345,28 +13943,39 @@ var symbolTool = {
13345
13943
  };
13346
13944
  }
13347
13945
  const callSites = [];
13946
+ let referencesTruncated = false;
13348
13947
  if (args.references !== false) {
13349
13948
  const limit = Math.max(1, typeof args.maxReferences === "number" ? args.maxReferences : 20);
13350
13949
  const definitionKeys = new Set(matches.map((match) => match.path + ":" + match.line));
13351
13950
  const word = new RegExp("\\b" + name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\b");
13352
- const parts = /* @__PURE__ */ new Map();
13951
+ const sectionsByPart = /* @__PURE__ */ new Map();
13353
13952
  let scanned = 0;
13354
13953
  for (const file of read.manifest.files) {
13355
13954
  if (callSites.length >= limit) break;
13356
13955
  const partPath = partPathFor(workspace, file.part);
13357
13956
  if (partPath === null) continue;
13358
- let partText = parts.get(partPath);
13359
- if (partText === void 0) {
13957
+ let sections = sectionsByPart.get(partPath);
13958
+ if (sections === void 0) {
13959
+ if (scanned >= MAX_SEARCH_BYTES) {
13960
+ referencesTruncated = true;
13961
+ break;
13962
+ }
13963
+ let partText;
13360
13964
  try {
13361
13965
  partText = fs24.readFileSync(partPath, "utf8");
13362
13966
  } catch {
13363
13967
  continue;
13364
13968
  }
13365
- parts.set(partPath, partText);
13969
+ const bytes = Buffer.byteLength(partText, "utf8");
13970
+ if (scanned + bytes > MAX_SEARCH_BYTES) {
13971
+ referencesTruncated = true;
13972
+ break;
13973
+ }
13974
+ scanned += bytes;
13975
+ sections = parsePartSections(partText);
13976
+ sectionsByPart.set(partPath, sections);
13366
13977
  }
13367
- if (scanned > MAX_SEARCH_BYTES) break;
13368
- scanned += Buffer.byteLength(partText, "utf8");
13369
- const section = findSection(parsePartSections(partText), file.relativePath);
13978
+ const section = findSection(sections, file.relativePath);
13370
13979
  if (section === null) continue;
13371
13980
  const bodyLines = section.body.split("\n");
13372
13981
  for (let index = 0; index < bodyLines.length && callSites.length < limit; index += 1) {
@@ -13380,8 +13989,11 @@ var symbolTool = {
13380
13989
  }
13381
13990
  }
13382
13991
  }
13383
- const text2 = matches.map((match) => "### " + match.path + " (" + match.part + ", line " + match.line + ")\n" + match.text).join("\n\n") + (args.references === false ? "" : "\n\n" + (callSites.length === 0 ? "No call site was found in the snapshot." : "Call sites (" + callSites.length + "):\n" + callSites.map((site) => " " + site.path + ":" + site.line + " " + site.text).join("\n")));
13384
- return { text: text2, structured: { found: matches.length, matches, references: callSites } };
13992
+ 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." : "");
13993
+ return {
13994
+ text: text2,
13995
+ structured: { found: matches.length, matches, references: callSites, truncated: referencesTruncated }
13996
+ };
13385
13997
  }
13386
13998
  };
13387
13999
  var contextTool = {
@@ -13539,6 +14151,10 @@ var queryTool = {
13539
14151
  const maxFiles = typeof args.maxFiles === "number" ? Math.min(200, Math.max(1, args.maxFiles)) : 40;
13540
14152
  let pattern = null;
13541
14153
  if (typeof args.pathPattern === "string") {
14154
+ const unsafe = unsafeRegExpReason(args.pathPattern);
14155
+ if (unsafe !== null) {
14156
+ return { text: "pathPattern is refused: " + unsafe + ".", isError: true };
14157
+ }
13542
14158
  try {
13543
14159
  pattern = new RegExp(args.pathPattern, "i");
13544
14160
  } catch (error) {
@@ -13924,7 +14540,12 @@ var planTool = {
13924
14540
  const prepared = await prepare(args, context, workspaceOverrides(args));
13925
14541
  if (!prepared.ok) return prepared.outcome;
13926
14542
  const workspace = prepared.workspace;
13927
- const result = await generateInWorker(workspace.root, workspace.cliOptions, { dryRun: true });
14543
+ const controller = new AbortController();
14544
+ context.onCancel?.(() => controller.abort());
14545
+ const result = await generateInWorker(workspace.root, workspace.cliOptions, {
14546
+ dryRun: true,
14547
+ signal: controller.signal
14548
+ });
13928
14549
  if (!result.ok) return failure(result.message);
13929
14550
  const summary = result.summary;
13930
14551
  const topReasons = summary.skipReasons;
@@ -14014,16 +14635,6 @@ var generateTool = {
14014
14635
  minimum: 500,
14015
14636
  description: "Fit the snapshot into this token budget, highest value first."
14016
14637
  },
14017
- only: {
14018
- type: "array",
14019
- items: { type: "string" },
14020
- description: "Globs to include: replaces the config allow-list for this run."
14021
- },
14022
- ignore: {
14023
- type: "array",
14024
- items: { type: "string" },
14025
- description: "Globs to exclude, added to the config deny-list for this run."
14026
- },
14027
14638
  ...SCOPE_PROPERTIES
14028
14639
  },
14029
14640
  additionalProperties: false
@@ -14142,7 +14753,12 @@ function configAsGenerated(workspace, manifest) {
14142
14753
  ...cli.includeLogs !== void 0 || configured("logCount") || recorded?.logCount !== void 0 ? { logCount: choose("logCount", recorded?.logCount, workspace.config.logCount, cli.includeLogs) } : {},
14143
14754
  ...cli.skeleton === true || configured("skeleton") || recorded?.skeleton !== void 0 ? { skeleton: choose("skeleton", recorded?.skeleton, workspace.config.skeleton, cli.skeleton === true ? true : void 0) } : {},
14144
14755
  ...cli.sarif === true || configured("sarif") || recorded?.sarif !== void 0 ? { sarif: choose("sarif", recorded?.sarif, workspace.config.sarif, cli.sarif === true ? true : void 0) } : {},
14145
- ...configured("maxParts") || recorded?.maxParts !== void 0 ? { maxParts: choose("maxParts", recorded?.maxParts, workspace.config.maxParts) } : {}
14756
+ ...configured("maxParts") || recorded?.maxParts !== void 0 ? { maxParts: choose("maxParts", recorded?.maxParts, workspace.config.maxParts) } : {},
14757
+ ...cli.maxPartTokens !== void 0 || configured("maxPartTokens") || recorded?.maxPartTokens !== void 0 ? { maxPartTokens: choose("maxPartTokens", recorded?.maxPartTokens, workspace.config.maxPartTokens, cli.maxPartTokens) } : {},
14758
+ ...cli.changedSince !== void 0 || configured("changedSince") || recorded?.changedSince !== void 0 ? { changedSince: choose("changedSince", recorded?.changedSince, workspace.config.changedSince, cli.changedSince) } : {},
14759
+ ...cli.staged === true || configured("staged") || recorded?.staged !== void 0 ? { staged: choose("staged", recorded?.staged, workspace.config.staged, cli.staged === true ? true : void 0) } : {},
14760
+ ...cli.withDependents === true || configured("withDependents") || recorded?.withDependents !== void 0 ? { withDependents: choose("withDependents", recorded?.withDependents, workspace.config.withDependents, cli.withDependents === true ? true : void 0) } : {},
14761
+ ...configured("promptTask") || recorded?.promptTask !== void 0 ? { promptTask: choose("promptTask", recorded?.promptTask, workspace.config.promptTask) } : {}
14146
14762
  };
14147
14763
  }
14148
14764
  var validateTool = {
@@ -15033,7 +15649,7 @@ var COMMAND_OPTION_SCOPE = {
15033
15649
  "version"
15034
15650
  ],
15035
15651
  diff: ["format", "mode", "no-config", "no-update-check", "help", "version"],
15036
- describe: ["format", "mode", "help", "version"],
15652
+ describe: ["format", "mode", "no-update-check", "help", "version"],
15037
15653
  init: [
15038
15654
  "install-hook",
15039
15655
  "cwd",
@@ -15054,7 +15670,7 @@ var COMMAND_OPTION_SCOPE = {
15054
15670
  "help",
15055
15671
  "version"
15056
15672
  ],
15057
- skill: ["cwd", "format", "mode", "install", "target", "help", "version"],
15673
+ skill: ["cwd", "format", "mode", "install", "target", "no-update-check", "help", "version"],
15058
15674
  // `mcp` reads the repository, so it takes --cwd. It has no --format: stdout carries JSON-RPC
15059
15675
  // messages, and there is no second shape to choose, so offering the flag would be a lie.
15060
15676
  serve: ["port", "host", "token", "no-auth", "allow-private", "cwd", "no-update-check", "help"],
@@ -15113,6 +15729,7 @@ var COMMAND_ORDER = [
15113
15729
  "health",
15114
15730
  "report",
15115
15731
  "explain",
15732
+ "update",
15116
15733
  "init",
15117
15734
  "setup",
15118
15735
  "diff",
@@ -15574,24 +16191,28 @@ function buildAgentContract() {
15574
16191
  {
15575
16192
  flag: "--only",
15576
16193
  type: "string",
16194
+ default: "unset",
15577
16195
  summary: "Comma-separated globs to include: overrides the config include list for this run.",
15578
16196
  appliesTo: optionAppliesTo("only")
15579
16197
  },
15580
16198
  {
15581
16199
  flag: "--ignore",
15582
16200
  type: "string",
16201
+ default: "unset",
15583
16202
  summary: "Comma-separated globs to exclude, added to the config exclude list for this run.",
15584
16203
  appliesTo: optionAppliesTo("ignore")
15585
16204
  },
15586
16205
  {
15587
16206
  flag: "--remove-empty-lines",
15588
16207
  type: "boolean",
16208
+ default: false,
15589
16209
  summary: "Drop blank and whitespace-only lines from emitted bodies; line numbers no longer match the source.",
15590
16210
  appliesTo: optionAppliesTo("remove-empty-lines")
15591
16211
  },
15592
16212
  {
15593
16213
  flag: "--all-members",
15594
16214
  type: "boolean",
16215
+ default: false,
15595
16216
  summary: "Audit every snapshot a --workspace run wrote, not only the one at outDir.",
15596
16217
  appliesTo: optionAppliesTo("all-members")
15597
16218
  },
@@ -16305,36 +16926,46 @@ function buildResourceProvider() {
16305
16926
  }
16306
16927
  const workspace = await workspaceFor(context);
16307
16928
  if ("error" in workspace) return null;
16929
+ const snapshotDir = path25.resolve(workspace.root, workspace.config.outDir);
16308
16930
  if (uri === PROMPT_URI) {
16309
- const text2 = readFileIfPresent(
16310
- path25.resolve(workspace.root, workspace.config.outDir, "PROMPT.md")
16311
- );
16312
- if (text2 === null) {
16931
+ const read = readConfinedText(snapshotDir, "PROMPT.md");
16932
+ if (!read.ok) {
16313
16933
  throw new ResourceNotFoundError(
16314
16934
  uri,
16315
- "This snapshot contains no PROMPT.md: the prompt artifact was disabled (artifacts.prompt = false or --skip-artifacts prompt), or nothing has been generated yet. Run snapshot_generate first."
16935
+ "This snapshot contains no readable PROMPT.md: the prompt artifact was disabled (artifacts.prompt = false or --skip-artifacts prompt), nothing has been generated yet, or the file is not a regular file inside the snapshot. Run snapshot_generate first."
16316
16936
  );
16317
16937
  }
16318
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, PROMPT_ADVICE) };
16938
+ return {
16939
+ uri,
16940
+ mimeType: "text/markdown",
16941
+ text: ensureSingleRead(uri, read.text, PROMPT_ADVICE)
16942
+ };
16319
16943
  }
16320
16944
  const report2 = REPORT_URIS.get(uri);
16321
16945
  if (report2) {
16322
- const text2 = readFileIfPresent(
16323
- path25.resolve(workspace.root, workspace.config.outDir, "reports", report2.file)
16324
- );
16325
- if (text2 === null) {
16946
+ const read = readConfinedText(snapshotDir, path25.posix.join("reports", report2.file));
16947
+ if (!read.ok) {
16326
16948
  throw new ResourceNotFoundError(
16327
16949
  uri,
16328
- "This snapshot contains no " + report2.file + ": that report was disabled, or nothing has been generated yet. Run snapshot_generate first."
16950
+ "This snapshot contains no readable " + report2.file + ": that report was disabled, nothing has been generated yet, or the file is not a regular file inside the snapshot. Run snapshot_generate first."
16329
16951
  );
16330
16952
  }
16331
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, REPORT_ADVICE) };
16953
+ return {
16954
+ uri,
16955
+ mimeType: "text/markdown",
16956
+ text: ensureSingleRead(uri, read.text, REPORT_ADVICE)
16957
+ };
16332
16958
  }
16333
16959
  if (uri === "snapshot://manifest") {
16334
16960
  const read = readManifest3(workspace);
16335
16961
  if (!read.ok) return null;
16336
- const text2 = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
16337
- return { uri, mimeType: "application/json", text: ensureSingleRead(uri, text2, MANIFEST_ADVICE) };
16962
+ const confined = readConfinedText(path25.dirname(read.file), path25.basename(read.file));
16963
+ if (!confined.ok) return null;
16964
+ return {
16965
+ uri,
16966
+ mimeType: "application/json",
16967
+ text: ensureSingleRead(uri, confined.text, MANIFEST_ADVICE)
16968
+ };
16338
16969
  }
16339
16970
  const partMatch = PART_URI.exec(uri);
16340
16971
  if (partMatch) {
@@ -16794,11 +17425,11 @@ var MAX_LINE_BYTES = 32 * 1024 * 1024;
16794
17425
  function createWriter(output) {
16795
17426
  return {
16796
17427
  write(value) {
16797
- return new Promise((resolve14, reject) => {
17428
+ return new Promise((resolve15, reject) => {
16798
17429
  output.write(`${JSON.stringify(value)}
16799
17430
  `, (error) => {
16800
17431
  if (error) reject(error);
16801
- else resolve14();
17432
+ else resolve15();
16802
17433
  });
16803
17434
  });
16804
17435
  }
@@ -16941,8 +17572,8 @@ async function runStdioServer(options) {
16941
17572
  let inFlight = 0;
16942
17573
  let inputEnded = false;
16943
17574
  let resolveDone = () => void 0;
16944
- const finished = new Promise((resolve14) => {
16945
- resolveDone = resolve14;
17575
+ const finished = new Promise((resolve15) => {
17576
+ resolveDone = resolve15;
16946
17577
  });
16947
17578
  const finishIfIdle = () => {
16948
17579
  if (inputEnded && inFlight === 0) resolveDone(0);
@@ -16976,10 +17607,22 @@ async function runStdioServer(options) {
16976
17607
  )
16977
17608
  );
16978
17609
  };
17610
+ const isCancellation = (line) => {
17611
+ try {
17612
+ const parsed = JSON.parse(line);
17613
+ return parsed !== null && typeof parsed === "object" && parsed.method === "notifications/cancelled";
17614
+ } catch {
17615
+ return false;
17616
+ }
17617
+ };
16979
17618
  const stopReading = createLineReader(process.stdin, {
16980
17619
  onOverflow: (bytes) => log(`mcp: discarded an oversized message (${bytes} bytes)`),
16981
17620
  onLine: (line) => {
16982
17621
  if (inFlight >= MAX_IN_FLIGHT) {
17622
+ if (isCancellation(line)) {
17623
+ void handleLine(line);
17624
+ return;
17625
+ }
16983
17626
  rejectOverloaded(line);
16984
17627
  return;
16985
17628
  }
@@ -17025,30 +17668,44 @@ function crc32(data) {
17025
17668
  return (crc ^ 4294967295) >>> 0;
17026
17669
  }
17027
17670
  function dosDateTime(date) {
17028
- const year = Math.max(1980, date.getFullYear());
17671
+ const year = Math.max(1980, date.getUTCFullYear());
17029
17672
  return {
17030
- time: date.getHours() << 11 | date.getMinutes() << 5 | Math.floor(date.getSeconds() / 2),
17031
- date: year - 1980 << 9 | date.getMonth() + 1 << 5 | date.getDate()
17673
+ time: date.getUTCHours() << 11 | date.getUTCMinutes() << 5 | Math.floor(date.getUTCSeconds() / 2),
17674
+ date: year - 1980 << 9 | date.getUTCMonth() + 1 << 5 | date.getUTCDate()
17032
17675
  };
17033
17676
  }
17034
17677
  function walkFiles(root, prefix = "") {
17035
17678
  const files = [];
17036
- for (const entry of fs24.readdirSync(path25.join(root, prefix), { withFileTypes: true })) {
17037
- const relative14 = prefix === "" ? entry.name : prefix + "/" + entry.name;
17038
- if (entry.isDirectory()) files.push(...walkFiles(root, relative14));
17039
- else if (entry.isFile()) files.push(relative14);
17679
+ const stack = [prefix];
17680
+ while (stack.length > 0) {
17681
+ const current = stack.pop();
17682
+ for (const entry of fs24.readdirSync(path25.join(root, current), { withFileTypes: true })) {
17683
+ const relative15 = current === "" ? entry.name : current + "/" + entry.name;
17684
+ if (entry.isDirectory()) stack.push(relative15);
17685
+ else if (entry.isFile()) files.push(relative15);
17686
+ }
17040
17687
  }
17041
17688
  return files;
17042
17689
  }
17043
17690
  function writeZip(options) {
17044
17691
  const entries = [...options.entries ?? []];
17692
+ const maxTotalBytes = options.maxTotalBytes ?? 256 * 1024 * 1024;
17693
+ let totalBytes = entries.reduce((total, entry) => total + entry.content.length, 0);
17694
+ if (totalBytes > maxTotalBytes) {
17695
+ throw new Error("zip: uncompressed content exceeds " + maxTotalBytes + " bytes");
17696
+ }
17045
17697
  if (options.directory !== void 0) {
17046
17698
  const root = options.directory;
17047
- for (const relative14 of walkFiles(root)) {
17048
- if (options.skip !== void 0 && options.skip(relative14)) continue;
17049
- const full = path25.join(root, relative14);
17699
+ for (const relative15 of walkFiles(root)) {
17700
+ if (options.skip !== void 0 && options.skip(relative15)) continue;
17701
+ const full = path25.join(root, relative15);
17050
17702
  const stat = fs24.statSync(full);
17051
- entries.push({ name: relative14, content: fs24.readFileSync(full), mtime: stat.mtime });
17703
+ if (totalBytes + stat.size > maxTotalBytes) {
17704
+ throw new Error("zip: uncompressed content exceeds " + maxTotalBytes + " bytes");
17705
+ }
17706
+ const content = fs24.readFileSync(full);
17707
+ totalBytes += content.length;
17708
+ entries.push({ name: relative15, content, mtime: stat.mtime });
17052
17709
  }
17053
17710
  }
17054
17711
  if (entries.length > 65535) {
@@ -17268,6 +17925,7 @@ var SERVE_PAGE = `<!doctype html>
17268
17925
  var DEFAULT_PORT = 4788;
17269
17926
  var MAX_BODY = 64 * 1024;
17270
17927
  var MAX_PREVIEW = 64 * 1024;
17928
+ var MAX_MCP_IN_FLIGHT = 4;
17271
17929
  function isLoopback(origin) {
17272
17930
  try {
17273
17931
  const url = new URL(origin);
@@ -17285,6 +17943,23 @@ async function startWebServer(options) {
17285
17943
  throw new Error("Refusing to serve " + host + " without a token.");
17286
17944
  }
17287
17945
  const createMcp = () => createServer({ cwd: options.cwd, log });
17946
+ const toolCount = buildTools().length;
17947
+ const rateWindows = /* @__PURE__ */ new Map();
17948
+ const rateLimited = (request) => {
17949
+ const remote = request.socket.remoteAddress ?? "unknown";
17950
+ const now = Date.now();
17951
+ const window = rateWindows.get(remote);
17952
+ if (window === void 0 || window.resetAt <= now) {
17953
+ if (!rateWindows.has(remote) && rateWindows.size >= 1024) {
17954
+ for (const [key, value] of rateWindows) if (value.resetAt <= now) rateWindows.delete(key);
17955
+ }
17956
+ rateWindows.set(remote, { count: 1, resetAt: now + 1e4 });
17957
+ return false;
17958
+ }
17959
+ if (window.count >= 120) return true;
17960
+ window.count += 1;
17961
+ return false;
17962
+ };
17288
17963
  const mcpPerSocket = /* @__PURE__ */ new WeakMap();
17289
17964
  const mcpFor = (socket) => {
17290
17965
  let server2 = mcpPerSocket.get(socket);
@@ -17295,6 +17970,7 @@ async function startWebServer(options) {
17295
17970
  return server2;
17296
17971
  };
17297
17972
  const temporaryClones = /* @__PURE__ */ new Set();
17973
+ let mcpInFlight = 0;
17298
17974
  const allowedRoots = [path25.resolve(options.cwd)];
17299
17975
  const canonical = (candidate) => {
17300
17976
  try {
@@ -17303,21 +17979,22 @@ async function startWebServer(options) {
17303
17979
  return null;
17304
17980
  }
17305
17981
  };
17982
+ const fold = (value) => process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
17306
17983
  const inside = (resolved) => allowedRoots.some((root) => {
17307
17984
  const canonicalRoot = canonical(root);
17308
17985
  if (canonicalRoot === null) return false;
17309
- const relative14 = path25.relative(canonicalRoot, resolved);
17310
- return relative14 === "" || !relative14.startsWith(`..${path25.sep}`) && relative14 !== ".." && !path25.isAbsolute(relative14);
17986
+ const relative15 = path25.relative(fold(canonicalRoot), fold(resolved));
17987
+ return relative15 === "" || !relative15.startsWith(`..${path25.sep}`) && relative15 !== ".." && !path25.isAbsolute(relative15);
17311
17988
  });
17312
17989
  const insideAllowedRoots = (candidate) => {
17313
17990
  const resolved = canonical(candidate);
17314
17991
  return resolved === null ? false : inside(resolved);
17315
17992
  };
17316
17993
  const lexicallyInside = (candidate) => {
17317
- const resolved = path25.resolve(candidate);
17994
+ const resolved = fold(path25.resolve(candidate));
17318
17995
  return allowedRoots.some((root) => {
17319
- const prefix = path25.resolve(root) + path25.sep;
17320
- return resolved === path25.resolve(root) || resolved.startsWith(prefix);
17996
+ const resolvedRoot = fold(path25.resolve(root));
17997
+ return resolved === resolvedRoot || resolved.startsWith(resolvedRoot + path25.sep);
17321
17998
  });
17322
17999
  };
17323
18000
  const insideAllowedRootsForWrite = (candidate) => {
@@ -17375,8 +18052,12 @@ async function startWebServer(options) {
17375
18052
  response.end();
17376
18053
  return;
17377
18054
  }
18055
+ if (rateLimited(request)) {
18056
+ send(429, { error: "too many requests" }, { "retry-after": "10" });
18057
+ return;
18058
+ }
17378
18059
  if (request.method === "GET" && request.url === "/healthz") {
17379
- send(200, { ok: true, name: "codebase-snapshot", tools: 12 });
18060
+ send(200, { ok: true, name: "codebase-snapshot", tools: toolCount });
17380
18061
  return;
17381
18062
  }
17382
18063
  if (request.method === "GET" && (request.url === "/" || request.url === "/index.html")) {
@@ -17421,12 +18102,35 @@ async function startWebServer(options) {
17421
18102
  const server2 = mcpFor(request.socket);
17422
18103
  const answers = [];
17423
18104
  for (const item of batch) {
17424
- const answer = await server2.handle(item);
17425
- if (answer !== null) answers.push(answer);
18105
+ const gated = item !== null && typeof item === "object" && item.method === "tools/call";
18106
+ if (gated && mcpInFlight >= MAX_MCP_IN_FLIGHT) {
18107
+ answers.push({
18108
+ jsonrpc: "2.0",
18109
+ id: item.id ?? null,
18110
+ error: {
18111
+ code: -32001,
18112
+ message: "server busy: too many tool calls are already in flight"
18113
+ }
18114
+ });
18115
+ continue;
18116
+ }
18117
+ if (gated) mcpInFlight += 1;
18118
+ try {
18119
+ const answer = await server2.handle(item);
18120
+ if (answer !== null) answers.push(answer);
18121
+ } finally {
18122
+ if (gated) mcpInFlight -= 1;
18123
+ }
17426
18124
  }
17427
18125
  if (answers.length === 0) send(202, "");
17428
18126
  else send(200, Array.isArray(message) ? answers : answers[0]);
17429
- })();
18127
+ })().catch((error) => {
18128
+ log("serve: " + error.message);
18129
+ try {
18130
+ send(500, { error: "internal error" });
18131
+ } catch {
18132
+ }
18133
+ });
17430
18134
  });
17431
18135
  return;
17432
18136
  }
@@ -17519,13 +18223,12 @@ async function startWebServer(options) {
17519
18223
  send(400, { error: "not a directory: " + target });
17520
18224
  return;
17521
18225
  }
17522
- const loaded = await loadConfigFileDetailed(target, { allowExecutableConfig: false });
18226
+ const loaded = isRemote ? { config: null, errors: [] } : await loadConfigFileDetailed(target, { allowExecutableConfig: false });
17523
18227
  if (loaded.errors.length > 0) {
17524
18228
  send(400, { error: loaded.errors.join("; ") });
17525
18229
  return;
17526
18230
  }
17527
18231
  const runConfig = isRemote ? {
17528
- ...loaded.config ?? {},
17529
18232
  outDir: "snapshot",
17530
18233
  tmpDir: "snapshot.tmp",
17531
18234
  hooks: {}
@@ -17536,13 +18239,39 @@ async function startWebServer(options) {
17536
18239
  send(403, { error: "the configured outDir resolves outside the served directory" });
17537
18240
  return;
17538
18241
  }
18242
+ const configuredTmpDir = typeof runConfig.tmpDir === "string" && runConfig.tmpDir.trim() !== "" ? runConfig.tmpDir : "snapshot.tmp";
18243
+ const stagingDir = path25.resolve(target, configuredTmpDir);
18244
+ if (!insideAllowedRootsForWrite(stagingDir)) {
18245
+ send(403, { error: "the configured tmpDir resolves outside the served directory" });
18246
+ return;
18247
+ }
17539
18248
  const started = Date.now();
17540
18249
  try {
17541
- const manifest = generateSnapshot({ ...runConfig, cwd: target }, {
17542
- ...provenance === void 0 ? {} : { source: provenance },
17543
- ...mode === "slice" ? { slice: { question } } : {},
17544
- ...mode === "budget" && budgetTokens !== void 0 ? { budgetTokens } : {}
17545
- });
18250
+ const generated = await generateInWorker(
18251
+ target,
18252
+ { cwd: target },
18253
+ {
18254
+ config: runConfig,
18255
+ ...provenance === void 0 ? {} : { source: provenance },
18256
+ ...mode === "slice" && question.length >= 3 ? { narrow: { slice: { question } } } : {},
18257
+ ...mode === "budget" && budgetTokens !== void 0 ? { narrow: { budgetTokens } } : {}
18258
+ }
18259
+ );
18260
+ if (!generated.ok) {
18261
+ send(500, { error: generated.message });
18262
+ return;
18263
+ }
18264
+ const manifestRead = readConfinedText(snapshotDir, "manifest.json");
18265
+ if (!manifestRead.ok) {
18266
+ send(500, { error: "the generate worker did not write manifest.json" });
18267
+ return;
18268
+ }
18269
+ const manifest = JSON.parse(manifestRead.text);
18270
+ const shape = describeManifestShapeProblem(manifest);
18271
+ if (shape !== null) {
18272
+ send(500, { error: "the generated manifest is not a snapshot manifest: " + shape });
18273
+ return;
18274
+ }
17546
18275
  const seconds = ((Date.now() - started) / 1e3).toFixed(2);
17547
18276
  const health = auditSnapshot({ snapshotDir, repoDir: target });
17548
18277
  send(200, {
@@ -17565,7 +18294,13 @@ async function startWebServer(options) {
17565
18294
  } catch (error) {
17566
18295
  send(500, { error: error.message });
17567
18296
  }
17568
- })();
18297
+ })().catch((error) => {
18298
+ log("serve: " + error.message);
18299
+ try {
18300
+ send(500, { error: "internal error" });
18301
+ } catch {
18302
+ }
18303
+ });
17569
18304
  });
17570
18305
  return;
17571
18306
  }
@@ -17575,15 +18310,24 @@ async function startWebServer(options) {
17575
18310
  send(403, { error: "outside the served directory: " + target });
17576
18311
  return;
17577
18312
  }
17578
- if (!fs24.existsSync(path25.join(target, "manifest.json"))) {
17579
- send(404, { error: "no manifest.json under " + target });
18313
+ if (!fs24.existsSync(target)) {
18314
+ send(404, { error: "no snapshot directory at " + target });
17580
18315
  return;
17581
18316
  }
17582
18317
  if (!insideAllowedRoots(target)) {
17583
18318
  send(403, { error: "outside the served directory: " + target });
17584
18319
  return;
17585
18320
  }
17586
- const report2 = auditSnapshot({ snapshotDir: target, repoDir: path25.dirname(target) });
18321
+ const repoDir = path25.dirname(target);
18322
+ if (!insideAllowedRoots(repoDir)) {
18323
+ send(403, { error: "the repository root for this snapshot is outside the served directory" });
18324
+ return;
18325
+ }
18326
+ if (!fs24.existsSync(path25.join(target, "manifest.json"))) {
18327
+ send(404, { error: "no manifest.json under " + target });
18328
+ return;
18329
+ }
18330
+ const report2 = auditSnapshot({ snapshotDir: target, repoDir });
17587
18331
  send(200, { score: report2.score, counts: report2.counts, checks: report2.checks });
17588
18332
  return;
17589
18333
  }
@@ -17593,7 +18337,7 @@ async function startWebServer(options) {
17593
18337
  send(403, { error: "outside the served directory: " + target });
17594
18338
  return;
17595
18339
  }
17596
- if (!fs24.existsSync(path25.join(target, "manifest.json"))) {
18340
+ if (!fs24.existsSync(target)) {
17597
18341
  send(404, { error: "no manifest.json under " + target });
17598
18342
  return;
17599
18343
  }
@@ -17601,10 +18345,18 @@ async function startWebServer(options) {
17601
18345
  send(403, { error: "outside the served directory: " + target });
17602
18346
  return;
17603
18347
  }
17604
- const manifestFile = path25.join(target, "manifest.json");
18348
+ const manifestRead = readConfinedText(target, "manifest.json");
18349
+ if (!manifestRead.ok) {
18350
+ if (manifestRead.reason === "outside") {
18351
+ send(403, { error: "manifest.json resolves outside the snapshot directory" });
18352
+ } else {
18353
+ send(404, { error: "no readable manifest.json under " + target });
18354
+ }
18355
+ return;
18356
+ }
17605
18357
  let manifest;
17606
18358
  try {
17607
- manifest = JSON.parse(fs24.readFileSync(manifestFile, "utf8"));
18359
+ manifest = JSON.parse(manifestRead.text);
17608
18360
  } catch {
17609
18361
  send(404, { error: "no manifest.json under " + target });
17610
18362
  return;
@@ -17614,12 +18366,8 @@ async function startWebServer(options) {
17614
18366
  send(400, { error: "manifest.json is not a snapshot manifest: " + shapeProblem });
17615
18367
  return;
17616
18368
  }
17617
- let prompt = "";
17618
- try {
17619
- prompt = fs24.readFileSync(path25.join(target, "PROMPT.md"), "utf8").slice(0, MAX_PREVIEW);
17620
- } catch {
17621
- prompt = "(this snapshot has no PROMPT.md)";
17622
- }
18369
+ const promptRead = readConfinedText(target, "PROMPT.md");
18370
+ const prompt = promptRead.ok ? promptRead.text.slice(0, MAX_PREVIEW) : "(this snapshot has no readable PROMPT.md)";
17623
18371
  send(200, {
17624
18372
  fingerprint: manifest.fingerprint ?? "",
17625
18373
  generatedAt: manifest.generatedAt ?? "",
@@ -17637,7 +18385,7 @@ async function startWebServer(options) {
17637
18385
  send(403, { error: "outside the served directory: " + target });
17638
18386
  return;
17639
18387
  }
17640
- if (!fs24.existsSync(path25.join(target, "manifest.json")) && !fs24.existsSync(path25.join(target, ".codebase-snapshot"))) {
18388
+ if (!fs24.existsSync(target)) {
17641
18389
  send(404, { error: "not a snapshot directory: " + target });
17642
18390
  return;
17643
18391
  }
@@ -17645,6 +18393,10 @@ async function startWebServer(options) {
17645
18393
  send(403, { error: "outside the served directory: " + target });
17646
18394
  return;
17647
18395
  }
18396
+ if (!fs24.existsSync(path25.join(target, "manifest.json")) && !fs24.existsSync(path25.join(target, ".codebase-snapshot"))) {
18397
+ send(404, { error: "not a snapshot directory: " + target });
18398
+ return;
18399
+ }
17648
18400
  try {
17649
18401
  const zip = writeZip({ directory: target });
17650
18402
  response.writeHead(200, {
@@ -17661,11 +18413,11 @@ async function startWebServer(options) {
17661
18413
  }
17662
18414
  send(404, { error: "not found" });
17663
18415
  });
17664
- await new Promise((resolve14, reject) => {
18416
+ await new Promise((resolve15, reject) => {
17665
18417
  server.once("error", reject);
17666
18418
  server.listen(port, host, () => {
17667
18419
  server.removeListener("error", reject);
17668
- resolve14();
18420
+ resolve15();
17669
18421
  });
17670
18422
  });
17671
18423
  const address = server.address();
@@ -17677,14 +18429,14 @@ async function startWebServer(options) {
17677
18429
  port: actualPort,
17678
18430
  host,
17679
18431
  token,
17680
- close: () => new Promise((resolve14) => {
18432
+ close: () => new Promise((resolve15) => {
17681
18433
  for (const directory of temporaryClones) {
17682
18434
  try {
17683
18435
  fs24.rmSync(directory, { recursive: true, force: true });
17684
18436
  } catch {
17685
18437
  }
17686
18438
  }
17687
- server.close(() => resolve14());
18439
+ server.close(() => resolve15());
17688
18440
  })
17689
18441
  };
17690
18442
  }
@@ -17800,14 +18552,14 @@ function writeCache(file, entry) {
17800
18552
  }
17801
18553
  }
17802
18554
  function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOUT_MS) {
17803
- return new Promise((resolve14) => {
18555
+ return new Promise((resolve15) => {
17804
18556
  let settled = false;
17805
18557
  let request = null;
17806
18558
  const finish = (value) => {
17807
18559
  if (settled) return;
17808
18560
  settled = true;
17809
18561
  clearTimeout(deadline);
17810
- resolve14(value);
18562
+ resolve15(value);
17811
18563
  };
17812
18564
  const deadline = setTimeout(() => {
17813
18565
  request?.destroy();
@@ -18216,9 +18968,25 @@ function appendGitignoreEntries(cwd, entries) {
18216
18968
  let decoded = { text: "", bom: Buffer.alloc(0), encoding: "utf8" };
18217
18969
  try {
18218
18970
  if (fs24.existsSync(ignorePath)) {
18219
- if (fs24.statSync(ignorePath).isDirectory()) {
18971
+ const stats = fs24.lstatSync(ignorePath);
18972
+ if (stats.isDirectory()) {
18220
18973
  return { added: [], note: `${ignorePath} is a directory, so it was not updated. ${manual}` };
18221
18974
  }
18975
+ if (stats.isSymbolicLink() || !stats.isFile() || stats.nlink > 1) {
18976
+ return {
18977
+ added: [],
18978
+ note: `${ignorePath} is a symbolic link, a hard link, or not a regular file, so it was not updated. ` + manual
18979
+ };
18980
+ }
18981
+ const rootReal = fs24.realpathSync(cwd);
18982
+ const fileReal = fs24.realpathSync(ignorePath);
18983
+ const relative15 = path25.relative(rootReal, fileReal);
18984
+ if (relative15 === ".." || relative15.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative15)) {
18985
+ return {
18986
+ added: [],
18987
+ note: `${ignorePath} resolves outside the repository, so it was not updated. ${manual}`
18988
+ };
18989
+ }
18222
18990
  const read = decodeGitignore(fs24.readFileSync(ignorePath));
18223
18991
  if (read === null) {
18224
18992
  return {
@@ -18240,12 +19008,19 @@ function appendGitignoreEntries(cwd, entries) {
18240
19008
  if (added.length === 0) return { added: [], note: null };
18241
19009
  const newline = existing.includes("\r\n") ? "\r\n" : "\n";
18242
19010
  const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : newline;
19011
+ const tempPath = `${ignorePath}.${process.pid}.${Date.now()}.tmp`;
18243
19012
  try {
18244
19013
  fs24.writeFileSync(
18245
- ignorePath,
18246
- encodeGitignore(decoded, `${existing}${prefix}${added.join(newline)}${newline}`)
19014
+ tempPath,
19015
+ encodeGitignore(decoded, `${existing}${prefix}${added.join(newline)}${newline}`),
19016
+ { flag: "wx" }
18247
19017
  );
19018
+ fs24.renameSync(tempPath, ignorePath);
18248
19019
  } catch (err) {
19020
+ try {
19021
+ fs24.rmSync(tempPath, { force: true });
19022
+ } catch {
19023
+ }
18249
19024
  return { added: [], note: `${err.message}. ${manual}` };
18250
19025
  }
18251
19026
  return { added, note: null };
@@ -18641,7 +19416,7 @@ function keyReader(input) {
18641
19416
  next() {
18642
19417
  const queued = queue.shift();
18643
19418
  if (queued) return Promise.resolve(queued);
18644
- return new Promise((resolve14) => waiters.push(resolve14));
19419
+ return new Promise((resolve15) => waiters.push(resolve15));
18645
19420
  },
18646
19421
  close() {
18647
19422
  input.off("keypress", onKey);
@@ -19074,11 +19849,11 @@ function gitignoreEntriesFor(cwd, outDir, tmpDir) {
19074
19849
  const entries = [];
19075
19850
  for (const directory of [outDir, tmpDir]) {
19076
19851
  if (directory === null) continue;
19077
- const relative14 = path25.relative(cwd, path25.resolve(cwd, directory)).replace(/\\/g, "/");
19078
- if (relative14 === "" || relative14 === "." || relative14.startsWith("..") || path25.isAbsolute(relative14)) {
19852
+ const relative15 = path25.relative(cwd, path25.resolve(cwd, directory)).replace(/\\/g, "/");
19853
+ if (relative15 === "" || relative15 === "." || relative15.startsWith("..") || path25.isAbsolute(relative15)) {
19079
19854
  continue;
19080
19855
  }
19081
- entries.push(`/${relative14}/`);
19856
+ entries.push(`/${relative15}/`);
19082
19857
  }
19083
19858
  return [...new Set(entries)];
19084
19859
  }
@@ -19234,7 +20009,14 @@ async function runInit(options) {
19234
20009
  try {
19235
20010
  const raw = await text(io, "Part size (e.g. 150k, 1.5mb, 900000)", {
19236
20011
  defaultValue: currentBudget,
19237
- validate: (value) => parseByteSize(value) === void 0 ? "Not a valid size." : null,
20012
+ validate: (value) => {
20013
+ const parsed = parseByteSize(value);
20014
+ if (parsed === void 0) return "Not a valid size.";
20015
+ if (parsed < MIN_MAX_PART_BYTES) {
20016
+ return `A part budget below ${MIN_MAX_PART_BYTES} bytes cannot hold the truncation notice.`;
20017
+ }
20018
+ return null;
20019
+ },
19238
20020
  allowBack: true
19239
20021
  });
19240
20022
  answers.maxPartBytes = parseByteSize(raw) ?? answers.maxPartBytes;
@@ -19409,10 +20191,10 @@ async function runInit(options) {
19409
20191
  };
19410
20192
  }
19411
20193
  function describeTarget(cwd) {
19412
- const relative14 = path25.relative(process.cwd(), cwd);
19413
- if (relative14 === "") return "this directory";
19414
- if (relative14.startsWith("..") || path25.isAbsolute(relative14)) return cwd;
19415
- return relative14;
20194
+ const relative15 = path25.relative(process.cwd(), cwd);
20195
+ if (relative15 === "") return "this directory";
20196
+ if (relative15.startsWith("..") || path25.isAbsolute(relative15)) return cwd;
20197
+ return relative15;
19416
20198
  }
19417
20199
  function firstRunMessage(reason, cwd) {
19418
20200
  const where = describeTarget(cwd);
@@ -19482,7 +20264,7 @@ if [ ! -f "$SNAPSHOT_DIR/manifest.json" ]; then
19482
20264
  exit 1
19483
20265
  fi
19484
20266
 
19485
- if ! npx --no-install ${GENERATOR_NAME} validate >/dev/null 2>&1; then
20267
+ if ! npx --no-install ${GENERATOR_NAME} validate --out-dir "$SNAPSHOT_DIR" >/dev/null 2>&1; then
19486
20268
  echo "${GENERATOR_NAME}: the snapshot is out of date." >&2
19487
20269
  echo " Run \\"npx ${GENERATOR_NAME} generate\\", stage the change, and commit again." >&2
19488
20270
  echo " (npx --no-install is used on purpose: this hook must not install anything)" >&2
@@ -19506,16 +20288,36 @@ function gitDirectory(cwd) {
19506
20288
  if (!match) return null;
19507
20289
  const target = match[1];
19508
20290
  const resolved = path25.isAbsolute(target.trim()) ? target.trim() : path25.join(cwd, target.trim());
19509
- if (!fs24.statSync(resolved).isDirectory()) return null;
19510
- if (isInside3(path25.resolve(cwd), path25.resolve(resolved))) return resolved;
19511
- return isRegisteredWorktree(path25.resolve(resolved), cwd) ? resolved : null;
20291
+ const cwdReal = canonicalForWrite(cwd);
20292
+ const resolvedReal = canonicalForWrite(resolved);
20293
+ if (cwdReal === null || resolvedReal === null || !fs24.statSync(resolvedReal).isDirectory()) {
20294
+ return null;
20295
+ }
20296
+ if (isInside4(cwdReal, resolvedReal)) return resolvedReal;
20297
+ return isRegisteredWorktree(path25.resolve(resolved), cwd) ? resolvedReal : null;
19512
20298
  } catch {
19513
20299
  return null;
19514
20300
  }
19515
20301
  }
19516
- function isInside3(parent, child) {
19517
- const relative14 = path25.relative(parent, child);
19518
- return relative14 === "" || !relative14.startsWith("..") && !path25.isAbsolute(relative14);
20302
+ function isInside4(parent, child) {
20303
+ const relative15 = path25.relative(parent, child);
20304
+ return relative15 === "" || !relative15.startsWith("..") && !path25.isAbsolute(relative15);
20305
+ }
20306
+ function canonicalForWrite(target) {
20307
+ let existing = path25.resolve(target);
20308
+ const tail = [];
20309
+ while (!fs24.existsSync(existing)) {
20310
+ tail.unshift(path25.basename(existing));
20311
+ const parent = path25.dirname(existing);
20312
+ if (parent === existing) break;
20313
+ existing = parent;
20314
+ }
20315
+ try {
20316
+ const real = fs24.realpathSync(existing);
20317
+ return tail.length === 0 ? real : path25.join(real, ...tail);
20318
+ } catch {
20319
+ return null;
20320
+ }
19519
20321
  }
19520
20322
  function isRegisteredWorktree(gitDir, cwd) {
19521
20323
  try {
@@ -19543,9 +20345,16 @@ function configuredHooksDirectory(cwd) {
19543
20345
  if (hooks === null) return null;
19544
20346
  const resolved = path25.resolve(cwd, hooks);
19545
20347
  const common = gitOutput(cwd, ["rev-parse", "--git-common-dir"]);
19546
- const commonDir = common === null ? null : path25.resolve(cwd, common);
19547
- if (isInside3(path25.resolve(cwd), resolved)) return { dir: resolved };
19548
- if (commonDir !== null && isInside3(commonDir, resolved)) return { dir: resolved };
20348
+ const commonDir = common === null ? null : canonicalForWrite(path25.resolve(cwd, common));
20349
+ const cwdReal = canonicalForWrite(cwd);
20350
+ const hooksReal = canonicalForWrite(resolved);
20351
+ if (hooksReal === null || cwdReal === null) {
20352
+ return {
20353
+ refusal: `The hooks directory git reports (${resolved}) could not be resolved, so no hook was written.`
20354
+ };
20355
+ }
20356
+ if (isInside4(cwdReal, hooksReal)) return { dir: hooksReal };
20357
+ if (commonDir !== null && isInside4(commonDir, hooksReal)) return { dir: hooksReal };
19549
20358
  return {
19550
20359
  refusal: `The hooks directory git reports (${resolved}) is outside this repository, so no hook was written. Add \`npx ${GENERATOR_NAME} validate\` to the hook manager that owns it instead.`
19551
20360
  };
@@ -19565,8 +20374,48 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
19565
20374
  ]
19566
20375
  };
19567
20376
  }
19568
- const hooksDir = configured === null ? path25.join(gitDir, "hooks") : configured.dir;
20377
+ const hooksDirRaw = configured === null ? path25.join(gitDir, "hooks") : configured.dir;
20378
+ const hooksDir = canonicalForWrite(hooksDirRaw);
20379
+ if (hooksDir === null) {
20380
+ return {
20381
+ path: null,
20382
+ written: false,
20383
+ notes: [`Refusing to write the hooks directory: ${hooksDirRaw} could not be resolved.`]
20384
+ };
20385
+ }
19569
20386
  const hookPath = path25.join(hooksDir, "pre-commit");
20387
+ try {
20388
+ const existingStats = fs24.lstatSync(hookPath);
20389
+ if (existingStats.isSymbolicLink()) {
20390
+ return {
20391
+ path: hookPath,
20392
+ written: false,
20393
+ notes: [`Refusing to write ${hookPath}: it is a symbolic link.`]
20394
+ };
20395
+ }
20396
+ if (existingStats.isFile() && existingStats.nlink > 1) {
20397
+ return {
20398
+ path: hookPath,
20399
+ written: false,
20400
+ notes: [`Refusing to write ${hookPath}: it has ${existingStats.nlink} hard links.`]
20401
+ };
20402
+ }
20403
+ if (!existingStats.isFile()) {
20404
+ return {
20405
+ path: hookPath,
20406
+ written: false,
20407
+ notes: [`Refusing to write ${hookPath}: it is not a regular file.`]
20408
+ };
20409
+ }
20410
+ } catch (error) {
20411
+ if (error.code !== "ENOENT") {
20412
+ return {
20413
+ path: hookPath,
20414
+ written: false,
20415
+ notes: [`Refusing to write ${hookPath}: ${error.message}`]
20416
+ };
20417
+ }
20418
+ }
19570
20419
  try {
19571
20420
  fs24.mkdirSync(hooksDir, { recursive: true });
19572
20421
  } catch (err) {
@@ -19616,23 +20465,23 @@ var SUMMARY_MAX_SOURCE_BYTES2 = SUMMARY_MAX_SOURCE_BYTES;
19616
20465
  var FILE_DERIVATIONS = /* @__PURE__ */ new Map();
19617
20466
  var FILE_DERIVATION_LIMIT_BYTES = 64 * 1024 * 1024;
19618
20467
  var fileDerivationBytes = 0;
19619
- function takeDerivation(path26, hash, settings) {
19620
- const cached = FILE_DERIVATIONS.get(path26);
20468
+ function takeDerivation(path26, relativePath, hash, settings) {
20469
+ const key = path26 + "\0" + relativePath;
20470
+ const cached = FILE_DERIVATIONS.get(key);
19621
20471
  if (cached === void 0 || cached.hash !== hash || cached.settings !== settings) return void 0;
19622
- FILE_DERIVATIONS.delete(path26);
19623
- FILE_DERIVATIONS.set(path26, cached);
20472
+ FILE_DERIVATIONS.delete(key);
20473
+ FILE_DERIVATIONS.set(key, cached);
19624
20474
  return cached;
19625
20475
  }
19626
- function rememberDerivation(path26, hash, settings, derivation) {
20476
+ function rememberDerivation(path26, relativePath, hash, settings, derivation) {
20477
+ const key = path26 + "\0" + relativePath;
19627
20478
  const bodyBytes = derivation.finalContent === derivation.redacted ? derivation.redacted.length : derivation.redacted.length + derivation.finalContent.length;
19628
20479
  const bytes = bodyBytes * 2 + 512;
19629
20480
  if (bytes > FILE_DERIVATION_LIMIT_BYTES / 4) return;
19630
- const previous = FILE_DERIVATIONS.get(path26);
20481
+ const previous = FILE_DERIVATIONS.get(key);
19631
20482
  if (previous !== void 0) {
19632
- FILE_DERIVATIONS.delete(path26);
20483
+ FILE_DERIVATIONS.delete(key);
19633
20484
  fileDerivationBytes -= previous.bytes;
19634
- } else {
19635
- FILE_DERIVATIONS.delete(path26);
19636
20485
  }
19637
20486
  while (fileDerivationBytes + bytes > FILE_DERIVATION_LIMIT_BYTES) {
19638
20487
  const oldest = FILE_DERIVATIONS.keys().next();
@@ -19641,7 +20490,7 @@ function rememberDerivation(path26, hash, settings, derivation) {
19641
20490
  FILE_DERIVATIONS.delete(oldest.value);
19642
20491
  if (evicted !== void 0) fileDerivationBytes -= evicted.bytes;
19643
20492
  }
19644
- FILE_DERIVATIONS.set(path26, { ...derivation, hash, settings, bytes });
20493
+ FILE_DERIVATIONS.set(key, { ...derivation, hash, settings, bytes });
19645
20494
  fileDerivationBytes += bytes;
19646
20495
  }
19647
20496
  function derivationSettings(config) {
@@ -19897,6 +20746,11 @@ function verifyInMemory(files, parts, unaccounted) {
19897
20746
  }
19898
20747
  }
19899
20748
  for (const part of parts) {
20749
+ if (part.metadata.hardClipped === true) {
20750
+ errors.push(
20751
+ `${part.filename} was hard-clipped by the part budget; its manifest entries cannot describe the surviving sections. Increase the budget or split the file instead of shipping a lie.`
20752
+ );
20753
+ }
19900
20754
  if (sha256Hex2(part.markdown) !== part.metadata.sha256) {
19901
20755
  errors.push(`${part.filename} content does not match its recorded sha256.`);
19902
20756
  }
@@ -19925,7 +20779,12 @@ function resolveSafeOutputDirs(config) {
19925
20779
  const outDir = path25.resolve(cwd, config.outDir);
19926
20780
  const tmpDir = path25.resolve(cwd, config.tmpDir);
19927
20781
  const root = path25.parse(cwd).root;
19928
- const contains = (parent, child) => child === parent || child.startsWith(`${parent}${path25.sep}`);
20782
+ const fold = (value) => process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
20783
+ const contains = (parent, child) => {
20784
+ const foldedParent = fold(parent);
20785
+ const foldedChild = fold(child);
20786
+ return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path25.sep}`);
20787
+ };
19929
20788
  const reject = (reason) => {
19930
20789
  throw new Error(
19931
20790
  `Refusing to generate: ${reason}. outDir=${outDir} tmpDir=${tmpDir} cwd=${cwd}`
@@ -19967,7 +20826,7 @@ function maskPathText(value, secretRules) {
19967
20826
  }
19968
20827
  function maskOwnerBrief(brief, secretRules) {
19969
20828
  if (brief === void 0) return void 0;
19970
- const mask = (value) => scanAndRedactSecrets(value, secretRules ?? [], "owner-brief").redacted;
20829
+ const mask = (value) => maskProse(value, secretRules, "owner-brief");
19971
20830
  return {
19972
20831
  ...brief,
19973
20832
  path: mask(brief.path),
@@ -19977,11 +20836,17 @@ function maskOwnerBrief(brief, secretRules) {
19977
20836
  ...brief.bar === void 0 ? {} : { bar: mask(brief.bar) },
19978
20837
  ...brief.calibration === void 0 ? {} : { calibration: mask(brief.calibration) },
19979
20838
  ...brief.preamble === void 0 ? {} : { preamble: mask(brief.preamble) },
19980
- notes: brief.notes.map((note) => ({ heading: note.heading, body: mask(note.body) }))
20839
+ // The heading is prose too. Masking only the body left `## Incident ghp_…` in PROMPT.md:
20840
+ // ownerNotesSection reproduced the heading as a Markdown title, where no line rule that
20841
+ // expects `key: value` can see it.
20842
+ notes: brief.notes.map((note) => ({ heading: mask(note.heading), body: mask(note.body) }))
19981
20843
  };
19982
20844
  }
20845
+ function maskProse(value, secretRules, scope) {
20846
+ return scanAndRedactSecrets(value, secretRules ?? [], scope).redacted;
20847
+ }
19983
20848
  function maskOverview(overview, secretRules) {
19984
- const mask = (value) => maskPathText(value, secretRules);
20849
+ const mask = (value) => maskProse(value, secretRules, "overview");
19985
20850
  return {
19986
20851
  ...overview.description === void 0 ? {} : { description: mask(overview.description) },
19987
20852
  ...overview.summary === void 0 ? {} : { summary: mask(overview.summary) },
@@ -20013,9 +20878,9 @@ function listEntries(dir) {
20013
20878
  return;
20014
20879
  }
20015
20880
  for (const child of children) {
20016
- const relative14 = prefix === "" ? child.name : `${prefix}/${child.name}`;
20017
- entries.push(relative14);
20018
- if (child.isDirectory()) walk2(path25.join(absolute, child.name), relative14);
20881
+ const relative15 = prefix === "" ? child.name : `${prefix}/${child.name}`;
20882
+ entries.push(relative15);
20883
+ if (child.isDirectory()) walk2(path25.join(absolute, child.name), relative15);
20019
20884
  }
20020
20885
  };
20021
20886
  walk2(dir, "");
@@ -20470,6 +21335,7 @@ function ensureParentDirectory(target, label) {
20470
21335
  }
20471
21336
  var LOCK_HEARTBEAT_MS = 5e3;
20472
21337
  var LOCK_STALE_HEARTBEAT_MS = 12e4;
21338
+ var LOCK_EMPTY_GRACE_MS = 5e3;
20473
21339
  var LOCK_HEARTBEAT_SOURCE = `
20474
21340
  const { parentPort, workerData } = require("node:worker_threads");
20475
21341
  const fs = require("node:fs");
@@ -20611,9 +21477,11 @@ function lockOwnerIsGone(lockPath) {
20611
21477
  try {
20612
21478
  pid = JSON.parse(raw).pid;
20613
21479
  } catch {
20614
- return lockFileIsAncient(lockPath);
21480
+ return lockFileIsAncient(lockPath, LOCK_EMPTY_GRACE_MS);
21481
+ }
21482
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) {
21483
+ return lockFileIsAncient(lockPath, LOCK_EMPTY_GRACE_MS);
20615
21484
  }
20616
- if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return lockFileIsAncient(lockPath);
20617
21485
  try {
20618
21486
  process.kill(pid, 0);
20619
21487
  return lockFileIsAncient(lockPath);
@@ -20640,8 +21508,8 @@ function reclaimStaleLock(lockPath) {
20640
21508
  return false;
20641
21509
  }
20642
21510
  }
20643
- function lockFileIsAncient(lockPath) {
20644
- return lockHeartbeatAgeMs(lockPath) > LOCK_STALE_HEARTBEAT_MS;
21511
+ function lockFileIsAncient(lockPath, thresholdMs = LOCK_STALE_HEARTBEAT_MS) {
21512
+ return lockHeartbeatAgeMs(lockPath) > thresholdMs;
20645
21513
  }
20646
21514
  function writeManifestAtomically(manifestPath, manifest) {
20647
21515
  const tempPath = `${manifestPath}.${process.pid}.tmp`;
@@ -20656,13 +21524,13 @@ function writeManifestAtomically(manifestPath, manifest) {
20656
21524
  throw err;
20657
21525
  }
20658
21526
  }
20659
- function swapIntoPlace(stagingDir, outDir, beforeSwap) {
21527
+ function swapIntoPlace(stagingDir, outDir, beforeSwap, onStagingPreserved) {
20660
21528
  ensureParentDirectory(outDir, "outDir");
20661
21529
  const deadline = Date.now() + 3e3;
20662
21530
  let delay = 25;
20663
21531
  for (; ; ) {
20664
21532
  try {
20665
- swapOnce(stagingDir, outDir, beforeSwap);
21533
+ swapOnce(stagingDir, outDir, beforeSwap, onStagingPreserved);
20666
21534
  return;
20667
21535
  } catch (err) {
20668
21536
  const code = err.code;
@@ -20697,7 +21565,7 @@ function recoverInterruptedPublish(outDir) {
20697
21565
  } catch {
20698
21566
  }
20699
21567
  }
20700
- function swapOnce(stagingDir, outDir, beforeSwap) {
21568
+ function swapOnce(stagingDir, outDir, beforeSwap, onStagingPreserved) {
20701
21569
  const backupDir = `${outDir}.backup-${process.pid}-${Date.now()}`;
20702
21570
  const hadPrevious = fs24.existsSync(outDir);
20703
21571
  if (hadPrevious) beforeSwap?.();
@@ -20708,6 +21576,7 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
20708
21576
  movedAside = true;
20709
21577
  } catch (err) {
20710
21578
  if (!isLockError(err)) throw err;
21579
+ onStagingPreserved?.();
20711
21580
  fs24.rmSync(outDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
20712
21581
  process.stderr.write(
20713
21582
  `\u26A0 ${outDir} could not be moved aside (${err.message}), so it was replaced in place. Close anything holding the old snapshot open to avoid this next time.
@@ -20738,6 +21607,7 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
20738
21607
  if (fs24.existsSync(outDir)) fs24.rmSync(outDir, { recursive: true, force: true });
20739
21608
  fs24.renameSync(backupDir, outDir);
20740
21609
  } else if (hadPrevious && !movedAside) {
21610
+ onStagingPreserved?.();
20741
21611
  process.stderr.write(
20742
21612
  `\u26A0 The previous snapshot at ${outDir} was removed and the new one could not be moved into place. It is complete at ${stagingDir}.
20743
21613
  `
@@ -20927,7 +21797,7 @@ function generateSnapshot(configInput, options) {
20927
21797
  // output — but only at these exact paths, not at every directory that shares the name.
20928
21798
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
20929
21799
  (directory) => path25.relative(config.cwd, path25.resolve(config.cwd, directory)).replace(/\\/g, "/")
20930
- ).filter((relative14) => relative14.length > 0 && !relative14.startsWith("..")),
21800
+ ).filter((relative15) => relative15.length > 0 && !relative15.startsWith("..")),
20931
21801
  // A staged path can be absent from the working tree while its index blob exists. Discovery
20932
21802
  // lists the working tree, so those paths would never reach the scan at all.
20933
21803
  ...stagedPaths.size > 0 ? { extraPaths: [...stagedPaths] } : {}
@@ -21073,9 +21943,9 @@ function generateSnapshot(configInput, options) {
21073
21943
  const language = detectLanguage(relativePath);
21074
21944
  bump(layerCounts, layer2);
21075
21945
  bump(kindCounts, kind);
21076
- const derivation = takeDerivation(absolutePath, hashSha256, derivationKey) ?? (() => {
21946
+ const derivation = takeDerivation(absolutePath, relativePath, hashSha256, derivationKey) ?? (() => {
21077
21947
  const fresh = deriveFile(relativePath, rawContent, sizeBytes, config);
21078
- rememberDerivation(absolutePath, hashSha256, derivationKey, fresh);
21948
+ rememberDerivation(absolutePath, relativePath, hashSha256, derivationKey, fresh);
21079
21949
  return fresh;
21080
21950
  })();
21081
21951
  const { lineCount } = derivation;
@@ -21255,7 +22125,9 @@ function generateSnapshot(configInput, options) {
21255
22125
  const tokens = Math.max(1, Math.ceil(file.includedBytes / 4));
21256
22126
  const value = (entry(file.relativePath) ? 100 : 0) + layerWeight(file.layer) + Math.min(60, (importers.get(file.relativePath) ?? 0) * 6) - Math.min(40, tokens / 250);
21257
22127
  return { file, tokens, value };
21258
- }).sort((left, right) => right.value - left.value || left.tokens - right.tokens || left.file.relativePath.localeCompare(right.file.relativePath));
22128
+ }).sort(
22129
+ (left, right) => right.value - left.value || left.tokens - right.tokens || (left.file.relativePath < right.file.relativePath ? -1 : left.file.relativePath > right.file.relativePath ? 1 : 0)
22130
+ );
21259
22131
  const keep = /* @__PURE__ */ new Set();
21260
22132
  let used = 0;
21261
22133
  const selected = [];
@@ -21617,7 +22489,7 @@ function generateSnapshot(configInput, options) {
21617
22489
  const reportExcludes = [...config.excludePatterns, ...config.presetExclude];
21618
22490
  const diffReport = artifacts.diff ? generateDiffReport(config.cwd, {
21619
22491
  secretRules: config.secretRules,
21620
- excluded: (relativePath) => reportExcludes.some((pattern) => matchesExclude(relativePath, pattern))
22492
+ excluded: (relativePath) => isSensitivePath(relativePath) || defaultIgnoreReason(relativePath) !== null || config.include.length > 0 && !config.include.some((pattern) => matchesExclude(relativePath, pattern)) || reportExcludes.some((pattern) => matchesExclude(relativePath, pattern))
21621
22493
  }) : null;
21622
22494
  if (diffReport !== null) manifest.artifacts.diff = artifactRecord(diffReport.text);
21623
22495
  const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount, secretRules: config.secretRules }) : null;
@@ -21643,8 +22515,8 @@ function generateSnapshot(configInput, options) {
21643
22515
  task: config.promptTask,
21644
22516
  brief: maskOwnerBrief(config.brief, config.secretRules),
21645
22517
  history: recentCommits(config.cwd).map((commit) => ({
21646
- subject: maskPathText(commit.subject, config.secretRules),
21647
- body: maskPathText(commit.body, config.secretRules)
22518
+ subject: maskProse(commit.subject, config.secretRules, "git-log"),
22519
+ body: maskProse(commit.body, config.secretRules, "git-log")
21648
22520
  })),
21649
22521
  overview: maskOverview(readProjectOverview(config.cwd), config.secretRules)
21650
22522
  }) : null;
@@ -21664,8 +22536,11 @@ function generateSnapshot(configInput, options) {
21664
22536
  const entry = {
21665
22537
  ...file,
21666
22538
  content,
21667
- inclusionMode: file.inclusionMode === "comments-stripped" ? "comments-stripped" : "full",
21668
- ...file.emptyLinesRemoved === true ? { emptyLinesRemoved: true } : {},
22539
+ // `fullContents` is the pre-preview body but still carries comments and blank lines: the
22540
+ // monolith is the whole source, not the comments-stripped variant. Calling it
22541
+ // `comments-stripped` (or copying `emptyLinesRemoved`) described a transformation this
22542
+ // artifact did not perform.
22543
+ inclusionMode: "full",
21669
22544
  isPreviewTruncated: false,
21670
22545
  includedBytes: Buffer.byteLength(content, "utf8"),
21671
22546
  includedLines: countLines(content)
@@ -21744,6 +22619,7 @@ function generateSnapshot(configInput, options) {
21744
22619
  recoverInterruptedPublish(outDir);
21745
22620
  assertReplaceable(outDir, "outDir", config.secretRules);
21746
22621
  let stagingDir = null;
22622
+ let stagingPreserved = false;
21747
22623
  let releaseDeferred = false;
21748
22624
  try {
21749
22625
  ensureParentDirectory(outDir, "outDir");
@@ -21770,21 +22646,25 @@ function generateSnapshot(configInput, options) {
21770
22646
  fs24.mkdirSync(reportsDir, { recursive: true });
21771
22647
  }
21772
22648
  const writtenArtifacts = /* @__PURE__ */ new Map();
22649
+ const ledgerRoot = (targetDir) => stagingDir !== null && (targetDir === stagingDir || targetDir.startsWith(stagingDir + path25.sep)) ? stagingDir : outDir;
22650
+ const ledgerEntry = (targetDir, relativeEntry) => path25.relative(ledgerRoot(targetDir), path25.join(targetDir, ...relativeEntry.split("/"))).split(path25.sep).join("/");
21773
22651
  const writeArtifact = (targetDir, relativeEntry, data) => {
21774
22652
  const full = path25.join(targetDir, ...relativeEntry.split("/"));
21775
22653
  fs24.writeFileSync(full, data, "utf8");
21776
22654
  const stats = fs24.statSync(full);
21777
- writtenArtifacts.set(relativeEntry, {
21778
- digest: { path: relativeEntry, bytes: stats.size, sha256: sha256Hex2(data) },
22655
+ const entry = ledgerEntry(targetDir, relativeEntry);
22656
+ writtenArtifacts.set(entry, {
22657
+ digest: { path: entry, bytes: stats.size, sha256: sha256Hex2(data) },
21779
22658
  mtimeMs: stats.mtimeMs
21780
22659
  });
21781
22660
  };
21782
22661
  const recordArtifact = (targetDir, relativeEntry) => {
21783
22662
  const full = path25.join(targetDir, ...relativeEntry.split("/"));
21784
22663
  const stats = fs24.statSync(full);
21785
- writtenArtifacts.set(relativeEntry, {
22664
+ const entry = ledgerEntry(targetDir, relativeEntry);
22665
+ writtenArtifacts.set(entry, {
21786
22666
  digest: {
21787
- path: relativeEntry,
22667
+ path: entry,
21788
22668
  bytes: stats.size,
21789
22669
  sha256: sha256Hex2(fs24.readFileSync(full))
21790
22670
  },
@@ -21853,7 +22733,14 @@ function generateSnapshot(configInput, options) {
21853
22733
  stagingDir,
21854
22734
  markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts, runId)
21855
22735
  );
21856
- swapIntoPlace(stagingDir, outDir, () => assertReplaceable(outDir, "outDir", config.secretRules));
22736
+ swapIntoPlace(
22737
+ stagingDir,
22738
+ outDir,
22739
+ () => assertReplaceable(outDir, "outDir", config.secretRules),
22740
+ () => {
22741
+ stagingPreserved = true;
22742
+ }
22743
+ );
21857
22744
  stagingDir = null;
21858
22745
  const warningsBeforeHook = manifest.warnings.length;
21859
22746
  const pendingHook = runAfterGenerate(config, manifest);
@@ -21907,7 +22794,7 @@ function generateSnapshot(configInput, options) {
21907
22794
  }
21908
22795
  return manifest;
21909
22796
  } catch (err) {
21910
- if (stagingDir !== null) {
22797
+ if (stagingDir !== null && !stagingPreserved) {
21911
22798
  try {
21912
22799
  fs24.rmSync(stagingDir, { recursive: true, force: true });
21913
22800
  } catch {