codebase-snapshot 0.10.0 → 0.10.2

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.
@@ -620,9 +620,9 @@ var rubyProfile = {
620
620
  eachLine(content, (line) => {
621
621
  const trimmed = line.trim();
622
622
  if (!trimmed || trimmed.startsWith("#")) return;
623
- const relative10 = REQUIRE_RELATIVE.exec(trimmed);
624
- if (relative10) {
625
- summary.imports.push(`./${relative10[1]}`);
623
+ const relative11 = REQUIRE_RELATIVE.exec(trimmed);
624
+ if (relative11) {
625
+ summary.imports.push(`./${relative11[1]}`);
626
626
  return;
627
627
  }
628
628
  const required = REQUIRE.exec(trimmed);
@@ -981,6 +981,8 @@ function summarizeTypeScriptSource(relativePath, content) {
981
981
  if (cjsExports.length > 0) {
982
982
  summary.exportsKind = summary.exports.length > 0 ? "mixed" : "cjs";
983
983
  summary.exports.push(...cjsExports);
984
+ } else if (summary.exports.length > 0) {
985
+ summary.exportsKind = "esm";
984
986
  }
985
987
  const dedupeSorted2 = (values) => Array.from(new Set(values)).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
986
988
  summary.directives = dedupeSorted2(summary.directives);
@@ -1880,8 +1882,8 @@ function workspacePackageDirs(cwd, patterns) {
1880
1882
  function scanWorkspacePackages(cwd, patterns) {
1881
1883
  const files = /* @__PURE__ */ new Set();
1882
1884
  const dependencies = /* @__PURE__ */ new Set();
1883
- for (const relative10 of workspacePackageDirs(cwd, patterns)) {
1884
- const full = path16.join(cwd, relative10);
1885
+ for (const relative11 of workspacePackageDirs(cwd, patterns)) {
1886
+ const full = path16.join(cwd, relative11);
1885
1887
  try {
1886
1888
  for (const entry of fs15.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
1887
1889
  } catch {
@@ -3000,6 +3002,24 @@ var DEFAULT_SECRET_PATTERNS = [
3000
3002
  ),
3001
3003
  valueGroup: 2
3002
3004
  },
3005
+ {
3006
+ // A quoted assignment whose closing quote is **not on this line**.
3007
+ //
3008
+ // The rule above requires `\1`, so an unterminated literal never matched it and the
3009
+ // credential reached the artefact in clear with no finding at all. That is the shape a
3010
+ // truncated file, a hand-edited `.env` and a string that continues on the next line all
3011
+ // produce, and it was the only branch of the redaction pass that was silent.
3012
+ //
3013
+ // The value runs to the end of the line on purpose — there is no delimiter to stop at — and
3014
+ // a later quote of the same kind disables the rule (`(?!\1)`), so a balanced literal is
3015
+ // never matched here: `password: "abc" and "def"` belongs to the rule above.
3016
+ rule: "credential-assignment-unterminated",
3017
+ pattern: new RegExp(
3018
+ `(?:${QUOTED_CREDENTIAL_KEY}|${NOT_AFTER_QUOTE}(?<!id[-_])${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}(["'\`])((?:(?!\\1)[^\\\\\\n]|\\\\.){1,512})$`,
3019
+ "i"
3020
+ ),
3021
+ valueGroup: 2
3022
+ },
3003
3023
  {
3004
3024
  // `pass` and `credentials` are ambiguous on their own, so they
3005
3025
  // are accepted only against a quoted value long enough to be a credential.
@@ -3559,10 +3579,8 @@ function scanAndRedactSecrets(content, rules, filePath) {
3559
3579
  }
3560
3580
  if (spans.length > 0) {
3561
3581
  const maskedLine = applySpans(line, spans);
3562
- if (!quotesAreBalanced(line) || quotesAreBalanced(maskedLine)) {
3563
- recordFinding(lineNumber, matchedRules);
3564
- segments[index] = maskedLine;
3565
- }
3582
+ recordFinding(lineNumber, matchedRules);
3583
+ segments[index] = !quotesAreBalanced(line) || quotesAreBalanced(maskedLine) ? maskedLine : applySpansKeepingQuotes(line, spans);
3566
3584
  }
3567
3585
  }
3568
3586
  if (index + 1 < segments.length) lineNumber += 1;
@@ -3840,6 +3858,17 @@ function isDeclaredBinding(line, matchIndex, filePath) {
3840
3858
  return DECLARATION_KEYWORDS.test(line.slice(from, runStart));
3841
3859
  }
3842
3860
  function applySpans(line, spans) {
3861
+ let out = "";
3862
+ let cursor = 0;
3863
+ for (const span of mergedSpans(line, spans)) {
3864
+ out += line.slice(cursor, span.start);
3865
+ out += REDACTION_MARKER;
3866
+ cursor = span.end;
3867
+ }
3868
+ out += line.slice(cursor);
3869
+ return out;
3870
+ }
3871
+ function mergedSpans(line, spans) {
3843
3872
  const ordered = [...spans].sort((a, b) => a.start - b.start || a.end - b.end);
3844
3873
  const merged = [];
3845
3874
  for (const span of ordered) {
@@ -3850,11 +3879,25 @@ function applySpans(line, spans) {
3850
3879
  if (last && start <= last.end) last.end = Math.max(last.end, end);
3851
3880
  else merged.push({ start, end });
3852
3881
  }
3882
+ return merged;
3883
+ }
3884
+ function applySpansKeepingQuotes(line, spans) {
3853
3885
  let out = "";
3854
3886
  let cursor = 0;
3855
- for (const span of merged) {
3887
+ for (const span of mergedSpans(line, spans)) {
3856
3888
  out += line.slice(cursor, span.start);
3857
- out += REDACTION_MARKER;
3889
+ let run = false;
3890
+ for (let index = span.start; index < span.end; index += 1) {
3891
+ const char = line[index];
3892
+ if (char === '"' || char === "'" || char === "`" || char === "\\") {
3893
+ if (run) out += REDACTION_MARKER;
3894
+ run = false;
3895
+ out += char;
3896
+ continue;
3897
+ }
3898
+ run = true;
3899
+ }
3900
+ if (run) out += REDACTION_MARKER;
3858
3901
  cursor = span.end;
3859
3902
  }
3860
3903
  out += line.slice(cursor);
@@ -3863,7 +3906,7 @@ function applySpans(line, spans) {
3863
3906
 
3864
3907
  // src/version.ts
3865
3908
  var GENERATOR_NAME = "codebase-snapshot";
3866
- var GENERATOR_VERSION = "0.10.0";
3909
+ var GENERATOR_VERSION = "0.10.2";
3867
3910
  var SCHEMA_VERSION = "3.0.0";
3868
3911
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
3869
3912
  function isOurGeneratorName(name) {
@@ -3895,8 +3938,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
3895
3938
  };
3896
3939
  }
3897
3940
  function isInside(root, candidate) {
3898
- const relative10 = path16.relative(root, candidate);
3899
- return relative10 === "" || !relative10.startsWith(`..${path16.sep}`) && relative10 !== ".." && !path16.isAbsolute(relative10);
3941
+ const relative11 = path16.relative(root, candidate);
3942
+ return relative11 === "" || !relative11.startsWith(`..${path16.sep}`) && relative11 !== ".." && !path16.isAbsolute(relative11);
3900
3943
  }
3901
3944
  var GIT_OUTPUT_LIMIT = 68157440;
3902
3945
  function getGitInfo(cwd, fallbackBranch = "main") {
@@ -4795,7 +4838,7 @@ function findConfigFile(cwd) {
4795
4838
  const pkgJsonPath = path16.join(cwd, "package.json");
4796
4839
  if (!fs15.existsSync(pkgJsonPath)) return null;
4797
4840
  try {
4798
- const parsed = JSON.parse(stripJsonComments2(fs15.readFileSync(pkgJsonPath, "utf8")));
4841
+ const parsed = JSON.parse(stripJsonComments(fs15.readFileSync(pkgJsonPath, "utf8")));
4799
4842
  const snapshot = parsed?.snapshot;
4800
4843
  return typeof snapshot === "object" && snapshot !== null && !Array.isArray(snapshot) ? pkgJsonPath : null;
4801
4844
  } catch {
@@ -4903,73 +4946,9 @@ function supportsTypeScriptImports() {
4903
4946
  if (!Number.isFinite(major)) return false;
4904
4947
  return major > 22 || major === 22 && minor >= 6;
4905
4948
  }
4906
- function stripJsonComments2(raw) {
4907
- const text2 = raw.replace(/^\uFEFF/, "");
4908
- let out = "";
4909
- let inString = false;
4910
- let escaped = false;
4911
- for (let index = 0; index < text2.length; index += 1) {
4912
- const char = text2[index];
4913
- if (inString) {
4914
- out += char;
4915
- if (escaped) escaped = false;
4916
- else if (char === "\\") escaped = true;
4917
- else if (char === '"') inString = false;
4918
- continue;
4919
- }
4920
- if (char === '"') {
4921
- inString = true;
4922
- out += char;
4923
- continue;
4924
- }
4925
- if (char === "/" && text2[index + 1] === "/") {
4926
- while (index < text2.length && text2[index] !== "\n" && text2[index] !== "\r") index += 1;
4927
- index -= 1;
4928
- continue;
4929
- }
4930
- if (char === "/" && text2[index + 1] === "*") {
4931
- index += 2;
4932
- while (index < text2.length && !(text2[index] === "*" && text2[index + 1] === "/")) {
4933
- if (text2[index] === "\n" || text2[index] === "\r") out += text2[index];
4934
- index += 1;
4935
- }
4936
- index += 1;
4937
- continue;
4938
- }
4939
- out += char;
4940
- }
4941
- return stripTrailingCommas2(out);
4942
- }
4943
- function stripTrailingCommas2(text2) {
4944
- let out = "";
4945
- let inString = false;
4946
- let escaped = false;
4947
- for (let index = 0; index < text2.length; index += 1) {
4948
- const char = text2[index];
4949
- if (inString) {
4950
- out += char;
4951
- if (escaped) escaped = false;
4952
- else if (char === "\\") escaped = true;
4953
- else if (char === '"') inString = false;
4954
- continue;
4955
- }
4956
- if (char === '"') {
4957
- inString = true;
4958
- out += char;
4959
- continue;
4960
- }
4961
- if (char === ",") {
4962
- let next = index + 1;
4963
- while (next < text2.length && /\s/.test(text2[next])) next += 1;
4964
- if (text2[next] === "}" || text2[next] === "]") continue;
4965
- }
4966
- out += char;
4967
- }
4968
- return out;
4969
- }
4970
4949
  function parseJsonish(raw, file) {
4971
4950
  try {
4972
- return JSON.parse(stripJsonComments2(raw));
4951
+ return JSON.parse(stripJsonComments(raw));
4973
4952
  } catch (err) {
4974
4953
  throw new Error(`Could not parse ${file}: ${err.message}`);
4975
4954
  }
@@ -4987,7 +4966,7 @@ function describeValue2(value) {
4987
4966
  return `${typeof value} (${String(value)})`;
4988
4967
  }
4989
4968
  var isThenable = (value) => typeof value.then === "function";
4990
- var CONFIG_KEYS = /* @__PURE__ */ new Set([
4969
+ var CONFIG_KEY_NAMES = [
4991
4970
  "artifacts",
4992
4971
  "branch",
4993
4972
  "budgets",
@@ -5018,7 +4997,8 @@ var CONFIG_KEYS = /* @__PURE__ */ new Set([
5018
4997
  "skeleton",
5019
4998
  "tmpDir",
5020
4999
  "withDependents"
5021
- ]);
5000
+ ];
5001
+ var CONFIG_KEYS = new Set(CONFIG_KEY_NAMES);
5022
5002
  function assertKnownConfigKeys(value, file) {
5023
5003
  const unknownKeys = Object.keys(value).filter((key) => !CONFIG_KEYS.has(key));
5024
5004
  if (unknownKeys.length === 0) return;
@@ -5372,11 +5352,11 @@ function outputExcludePatterns(cwd, outDir, tmpDir) {
5372
5352
  const patterns = [];
5373
5353
  for (const dir of [outDir, tmpDir]) {
5374
5354
  const absolute = path16.resolve(cwd, dir);
5375
- const relative10 = path16.relative(cwd, absolute);
5376
- if (!relative10 || relative10 === ".." || relative10.startsWith(`..${path16.sep}`) || path16.isAbsolute(relative10)) {
5355
+ const relative11 = path16.relative(cwd, absolute);
5356
+ if (!relative11 || relative11 === ".." || relative11.startsWith(`..${path16.sep}`) || path16.isAbsolute(relative11)) {
5377
5357
  continue;
5378
5358
  }
5379
- patterns.push(`${relative10.replace(/\\/g, "/")}/**`);
5359
+ patterns.push(`${relative11.replace(/\\/g, "/")}/**`);
5380
5360
  }
5381
5361
  return patterns;
5382
5362
  }
@@ -5911,7 +5891,7 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
5911
5891
  );
5912
5892
  for (const file of affected) {
5913
5893
  const status = file.isPreviewTruncated ? "Truncated" : "Full";
5914
- const cutBy = file.truncationReason === "part-budget" ? "maxPartBytes" : "largeFileBytes";
5894
+ const cutBy = file.truncationReason === "part-budget" ? "part budget (maxPartBytes)" : "large-file budget (largeFileBytes)";
5915
5895
  lines.push(
5916
5896
  `| ${code(file.relativePath)} | ${file.sizeBytes} | ${file.lines} | ${file.includedBytes} | ${file.includedLines} | ${status} | ${cutBy} |`
5917
5897
  );
@@ -6024,11 +6004,11 @@ function generateSarifReport(manifest, findings, rules, toolVersion) {
6024
6004
  codebaseSnapshotFinding: `${findingPath}#L${line}#${finding.rules.join("+")}`
6025
6005
  }
6026
6006
  };
6027
- }).sort(
6028
- (a, b) => a.locations[0].physicalLocation.artifactLocation.uri.localeCompare(
6029
- b.locations[0].physicalLocation.artifactLocation.uri
6030
- ) || a.locations[0].physicalLocation.region.startLine - b.locations[0].physicalLocation.region.startLine
6031
- );
6007
+ }).sort((a, b) => {
6008
+ const left = a.locations[0].physicalLocation.artifactLocation.uri;
6009
+ const right = b.locations[0].physicalLocation.artifactLocation.uri;
6010
+ return (left < right ? -1 : left > right ? 1 : 0) || a.locations[0].physicalLocation.region.startLine - b.locations[0].physicalLocation.region.startLine;
6011
+ });
6032
6012
  const log = {
6033
6013
  $schema: SARIF_SCHEMA,
6034
6014
  version: SARIF_VERSION,
@@ -6119,6 +6099,7 @@ function truncatePreview(content, headLines, tailLines) {
6119
6099
  // src/partitioner/chunker.ts
6120
6100
  var HEADER_RESERVE_BYTES = 2048 + Buffer.byteLength(UNTRUSTED_CONTENT_NOTICE, "utf8") + 8;
6121
6101
  var MIN_SECTION_BUDGET_BYTES = 512;
6102
+ var MIN_PART_BUDGET_BYTES = MIN_SECTION_BUDGET_BYTES + HEADER_RESERVE_BYTES;
6122
6103
  var MAX_SPLIT_PASSES = 64;
6123
6104
  var BUDGET_MARKER_RESERVE = 96;
6124
6105
  function insertTokenLine(markdown, tokens) {
@@ -6157,10 +6138,17 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
6157
6138
  const groups = [];
6158
6139
  for (const bucket of buckets) {
6159
6140
  if (bucket.files.length === 0) continue;
6160
- const budget = Math.max(
6161
- MIN_SECTION_BUDGET_BYTES + HEADER_RESERVE_BYTES,
6162
- bucket.budgetBytes
6163
- );
6141
+ if (!Number.isFinite(bucket.budgetBytes)) {
6142
+ throw new Error(
6143
+ `A part budget must be a finite number of bytes; received ${String(bucket.budgetBytes)}.`
6144
+ );
6145
+ }
6146
+ if (bucket.budgetBytes < MIN_PART_BUDGET_BYTES) {
6147
+ throw new Error(
6148
+ `A part budget of ${bucket.budgetBytes} B is below the ${MIN_PART_BUDGET_BYTES} B minimum: the header every part must carry is larger than that, so the budget could not be honoured. Use a budget of at least 4096 B.`
6149
+ );
6150
+ }
6151
+ const budget = bucket.budgetBytes;
6164
6152
  const sectionBudget = budget - HEADER_RESERVE_BYTES;
6165
6153
  const prepared = bucket.files.map((file) => prepareSection(file, sectionBudget, budget));
6166
6154
  for (const sections of greedyGroups(prepared, budget)) groups.push({ sections, budget });
@@ -6851,6 +6839,22 @@ function generateProjectTree(filePaths) {
6851
6839
  const fence = fenceForText(lines.join("\n"), 3);
6852
6840
  return ["# Project Tree", "", `${fence}text`, ...lines, fence, ""].join("\n");
6853
6841
  }
6842
+ function treeTruncationWarnings(treeText) {
6843
+ const warnings = [];
6844
+ const depth = /\[tree truncated at (\d+) levels\]/.exec(treeText);
6845
+ if (depth) {
6846
+ warnings.push(
6847
+ `reports/project-tree.md was truncated at the ${depth[1]}-level depth cap: deeper directories are not listed there.`
6848
+ );
6849
+ }
6850
+ const lines = /\[tree truncated at (\d+) lines\]/.exec(treeText);
6851
+ if (lines) {
6852
+ warnings.push(
6853
+ `reports/project-tree.md was truncated at the ${lines[1]}-line cap: the rest of the tree is not listed there.`
6854
+ );
6855
+ }
6856
+ return warnings;
6857
+ }
6854
6858
  function gitPaths(cwd, args) {
6855
6859
  let output;
6856
6860
  try {
@@ -7015,8 +7019,8 @@ function tsconfigPathsFor(cwd) {
7015
7019
  return value;
7016
7020
  }
7017
7021
  function repositoryRelative(cwd, target) {
7018
- const relative10 = path16.relative(cwd, target).replace(/\\/g, "/");
7019
- return relative10.length === 0 || !relative10.startsWith("..") && !path16.isAbsolute(relative10) ? relative10 : null;
7022
+ const relative11 = path16.relative(cwd, target).replace(/\\/g, "/");
7023
+ return relative11.length === 0 || !relative11.startsWith("..") && !path16.isAbsolute(relative11) ? relative11 : null;
7020
7024
  }
7021
7025
  function rememberFirst(map, key, value) {
7022
7026
  if (!map.has(key)) map.set(key, value);
@@ -7286,6 +7290,16 @@ function wouldNowBeIncluded(cwd, relativePath) {
7286
7290
  return false;
7287
7291
  }
7288
7292
  }
7293
+ var TRUNCATION_REASONS = /* @__PURE__ */ new Set([
7294
+ "large-file-budget",
7295
+ "part-budget",
7296
+ "section-metadata"
7297
+ ]);
7298
+ function isConfinedRelative(value) {
7299
+ if (value.length === 0 || value.includes("\0") || value.includes("\\")) return false;
7300
+ if (path16.isAbsolute(value)) return false;
7301
+ return !value.split("/").includes("..");
7302
+ }
7289
7303
  function describeManifestShapeProblem(value) {
7290
7304
  if (!value || typeof value !== "object" || Array.isArray(value)) return "not a JSON object";
7291
7305
  const candidate = value;
@@ -7351,6 +7365,68 @@ function describeManifestShapeProblem(value) {
7351
7365
  if (!candidate.kinds || typeof candidate.kinds !== "object" || Array.isArray(candidate.kinds)) {
7352
7366
  return 'missing "kinds" object';
7353
7367
  }
7368
+ const incompleteCount = counts.incompleteCount;
7369
+ if (typeof incompleteCount !== "number" || !Number.isSafeInteger(incompleteCount) || incompleteCount < 0) {
7370
+ return "missing numeric `counts.incompleteCount`";
7371
+ }
7372
+ const incomplete = candidate.incomplete;
7373
+ if (!Array.isArray(incomplete)) return 'missing "incomplete" array';
7374
+ if (incompleteCount !== incomplete.length) {
7375
+ return "`counts.incompleteCount` does not match the length of `incomplete`";
7376
+ }
7377
+ for (const entry of incomplete) {
7378
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
7379
+ return 'an "incomplete" entry is not an object';
7380
+ }
7381
+ const fields = entry;
7382
+ const relativePath = fields.relativePath;
7383
+ if (typeof relativePath !== "string" || relativePath.length === 0) {
7384
+ return 'an "incomplete" entry has no "relativePath"';
7385
+ }
7386
+ if (!isConfinedRelative(relativePath)) {
7387
+ return 'an "incomplete" entry "relativePath" must stay inside the repository';
7388
+ }
7389
+ if (typeof fields.part !== "string" || fields.part.trim() === "") {
7390
+ return 'an "incomplete" entry has no "part"';
7391
+ }
7392
+ if (typeof fields.reason !== "string" || !TRUNCATION_REASONS.has(fields.reason)) {
7393
+ return 'an "incomplete" entry has an unknown "reason"';
7394
+ }
7395
+ for (const key of ["omittedLines", "includedLines", "lines"]) {
7396
+ const value2 = fields[key];
7397
+ if (typeof value2 !== "number" || !Number.isSafeInteger(value2) || value2 < 0) {
7398
+ return `an "incomplete" entry "${key}" must be a non-negative integer`;
7399
+ }
7400
+ }
7401
+ const lines = fields.lines;
7402
+ if (fields.includedLines > lines) {
7403
+ return 'an "incomplete" entry "includedLines" exceeds its "lines"';
7404
+ }
7405
+ const ranges = fields.omittedRanges;
7406
+ if (!Array.isArray(ranges)) return 'an "incomplete" entry has no "omittedRanges" array';
7407
+ let previousEnd = 0;
7408
+ let omitted = 0;
7409
+ for (const range of ranges) {
7410
+ if (!Array.isArray(range) || range.length !== 2) {
7411
+ return 'an "incomplete" entry "omittedRanges" must hold [from, to] pairs';
7412
+ }
7413
+ const [from, to] = range;
7414
+ if (typeof from !== "number" || typeof to !== "number" || !Number.isSafeInteger(from) || !Number.isSafeInteger(to)) {
7415
+ return 'an "incomplete" entry "omittedRanges" must hold integer pairs';
7416
+ }
7417
+ if (from < 1 || to < from || to > lines) {
7418
+ return `an "incomplete" entry records an omitted range ${from}-${to}, outside 1-${lines}`;
7419
+ }
7420
+ if (from <= previousEnd) {
7421
+ return 'an "incomplete" entry "omittedRanges" must be sorted and non-overlapping';
7422
+ }
7423
+ previousEnd = to;
7424
+ omitted += to - from + 1;
7425
+ }
7426
+ if (omitted !== fields.omittedLines) {
7427
+ return "`omittedLines` does not match the ranges it records";
7428
+ }
7429
+ }
7354
7430
  }
7355
7431
  if (!Array.isArray(candidate.files)) return 'missing "files" array';
7356
7432
  for (const entry of candidate.files) {
@@ -7464,11 +7540,57 @@ function validateSnapshot(configInput) {
7464
7540
  );
7465
7541
  }
7466
7542
  const manifestFileMap = /* @__PURE__ */ new Map();
7543
+ const manifestFilesByPath = /* @__PURE__ */ new Map();
7467
7544
  for (const file of manifest.files) {
7468
7545
  if (file && typeof file.relativePath === "string") {
7469
7546
  manifestFileMap.set(file.relativePath, file.hashSha256);
7547
+ manifestFilesByPath.set(file.relativePath, file);
7470
7548
  }
7471
7549
  }
7550
+ const incompleteRecords = manifest.incomplete ?? [];
7551
+ const incompleteness = /* @__PURE__ */ new Map();
7552
+ for (const record of incompleteRecords) {
7553
+ incompleteness.set(record.relativePath, record);
7554
+ const label = maskedPath(record.relativePath, config.secretRules);
7555
+ const file = manifestFilesByPath.get(record.relativePath);
7556
+ if (file === void 0) {
7557
+ drift.partIssues.push({
7558
+ part: "(manifest)",
7559
+ issue: `${label} is in incomplete[] but not in files[]`
7560
+ });
7561
+ continue;
7562
+ }
7563
+ if (file.part !== record.part) {
7564
+ drift.partIssues.push({
7565
+ part: "(manifest)",
7566
+ issue: `${label} is recorded in part ${String(record.part)} in incomplete[] and part ${String(file.part)} in files[]`
7567
+ });
7568
+ }
7569
+ if (file.truncationReason !== record.reason) {
7570
+ drift.partIssues.push({
7571
+ part: "(manifest)",
7572
+ issue: `${label} records truncationReason ${String(file.truncationReason)} in files[] and reason ${String(record.reason)} in incomplete[]`
7573
+ });
7574
+ }
7575
+ const recordedRanges = file.omittedRanges ?? [];
7576
+ const rangesAgree = recordedRanges.length === record.omittedRanges.length && recordedRanges.every(
7577
+ ([from, to], index) => record.omittedRanges[index][0] === from && record.omittedRanges[index][1] === to
7578
+ );
7579
+ if (!rangesAgree || file.includedLines !== record.includedLines || file.lines !== record.lines) {
7580
+ drift.partIssues.push({
7581
+ part: "(manifest)",
7582
+ issue: `${label} records different omission numbers in files[] and incomplete[]`
7583
+ });
7584
+ }
7585
+ }
7586
+ for (const file of manifest.files) {
7587
+ if (file.truncationReason === void 0) continue;
7588
+ if (incompleteness.has(file.relativePath)) continue;
7589
+ drift.partIssues.push({
7590
+ part: "(manifest)",
7591
+ issue: `${maskedPath(file.relativePath, config.secretRules)} records a truncationReason but is missing from incomplete[]`
7592
+ });
7593
+ }
7472
7594
  const skippedReasons = /* @__PURE__ */ new Map();
7473
7595
  for (const entry of manifest.skipped) {
7474
7596
  if (entry && typeof entry.path === "string" && typeof entry.reason === "string") {
@@ -7525,7 +7647,7 @@ function validateSnapshot(configInput) {
7525
7647
  // snapshot was reported as drifting.
7526
7648
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
7527
7649
  (directory) => path16.relative(config.cwd, path16.resolve(config.cwd, directory)).replace(/\\/g, "/")
7528
- ).filter((relative10) => relative10.length > 0 && !relative10.startsWith(".."))
7650
+ ).filter((relative11) => relative11.length > 0 && !relative11.startsWith(".."))
7529
7651
  });
7530
7652
  for (const diskFile of collection.files) {
7531
7653
  const snapshotHash = manifestFileMap.get(diskFile);
@@ -7981,8 +8103,8 @@ function validateSnapshot(configInput) {
7981
8103
  const target = match[1].split("#")[0];
7982
8104
  if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
7983
8105
  const resolved = path16.resolve(snapshotDir, "reports", target);
7984
- const relative10 = path16.relative(snapshotDir, resolved);
7985
- if (relative10.startsWith("..") || path16.isAbsolute(relative10) || !fs15.existsSync(resolved)) {
8106
+ const relative11 = path16.relative(snapshotDir, resolved);
8107
+ if (relative11.startsWith("..") || path16.isAbsolute(relative11) || !fs15.existsSync(resolved)) {
7986
8108
  drift.partIssues.push({
7987
8109
  part: key,
7988
8110
  issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
@@ -8177,14 +8299,14 @@ function writeCache(file, entry) {
8177
8299
  }
8178
8300
  }
8179
8301
  function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOUT_MS) {
8180
- return new Promise((resolve7) => {
8302
+ return new Promise((resolve8) => {
8181
8303
  let settled = false;
8182
8304
  let request = null;
8183
8305
  const finish = (value) => {
8184
8306
  if (settled) return;
8185
8307
  settled = true;
8186
8308
  clearTimeout(deadline);
8187
- resolve7(value);
8309
+ resolve8(value);
8188
8310
  };
8189
8311
  const deadline = setTimeout(() => {
8190
8312
  request?.destroy();
@@ -8272,23 +8394,23 @@ function describeMatcher(matcher) {
8272
8394
  function normalizeTarget(cwd, target) {
8273
8395
  const resolvedCwd = path16.resolve(cwd);
8274
8396
  const absolute = path16.resolve(resolvedCwd, target);
8275
- const relative10 = path16.relative(resolvedCwd, absolute);
8276
- if (relative10 === "" || relative10 === ".." || relative10.startsWith(`..${path16.sep}`) || path16.isAbsolute(relative10)) {
8397
+ const relative11 = path16.relative(resolvedCwd, absolute);
8398
+ if (relative11 === "" || relative11 === ".." || relative11.startsWith(`..${path16.sep}`) || path16.isAbsolute(relative11)) {
8277
8399
  return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
8278
8400
  }
8279
- return { relative: relative10.split(path16.sep).join("/"), outsideRoot: false };
8401
+ return { relative: relative11.split(path16.sep).join("/"), outsideRoot: false };
8280
8402
  }
8281
8403
  function findRuleMatch(rules, relativePath) {
8282
8404
  return rules.find(
8283
8405
  (rule) => matchRule(relativePath, rule.match)
8284
8406
  );
8285
8407
  }
8286
- function findRecordedAncestor(skipped, relative10, maskedPath2) {
8408
+ function findRecordedAncestor(skipped, relative11, maskedPath2) {
8287
8409
  let nearest;
8288
8410
  for (const record of skipped) {
8289
8411
  const ancestorPath = record.path;
8290
8412
  if (ancestorPath.length === 0) continue;
8291
- const isAncestor = relative10.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
8413
+ const isAncestor = relative11.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
8292
8414
  if (!isAncestor) continue;
8293
8415
  if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
8294
8416
  }
@@ -8304,8 +8426,8 @@ function readManifest2(config) {
8304
8426
  }
8305
8427
  function explainPath(config, target) {
8306
8428
  const normalized = normalizeTarget(config.cwd, target);
8307
- const relative10 = normalized.relative;
8308
- const maskedPath2 = findSecretInPath(relative10, config.secretRules)?.masked ?? relative10;
8429
+ const relative11 = normalized.relative;
8430
+ const maskedPath2 = findSecretInPath(relative11, config.secretRules)?.masked ?? relative11;
8309
8431
  if (normalized.outsideRoot) {
8310
8432
  return {
8311
8433
  path: maskedPath2,
@@ -8315,7 +8437,7 @@ function explainPath(config, target) {
8315
8437
  detail: "path resolves outside the configured repository root and was not inspected"
8316
8438
  };
8317
8439
  }
8318
- const absolute = path16.join(config.cwd, relative10);
8440
+ const absolute = path16.join(config.cwd, relative11);
8319
8441
  const result = {
8320
8442
  path: maskedPath2,
8321
8443
  exists: fs15.existsSync(absolute),
@@ -8333,11 +8455,11 @@ function explainPath(config, target) {
8333
8455
  // that is only missing because the walker dropped the tool's own output directory.
8334
8456
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
8335
8457
  (directory) => path16.relative(config.cwd, path16.resolve(config.cwd, directory)).replace(/\\/g, "/")
8336
- ).filter((relative11) => relative11.length > 0 && !relative11.startsWith(".."))
8458
+ ).filter((relative12) => relative12.length > 0 && !relative12.startsWith(".."))
8337
8459
  });
8338
- if (!collection.files.includes(relative10)) {
8460
+ if (!collection.files.includes(relative11)) {
8339
8461
  const record = collection.skipped.find(
8340
- (entry2) => entry2.path === relative10 || entry2.path === maskedPath2
8462
+ (entry2) => entry2.path === relative11 || entry2.path === maskedPath2
8341
8463
  );
8342
8464
  if (record) {
8343
8465
  result.reason = record.reason;
@@ -8346,7 +8468,7 @@ function explainPath(config, target) {
8346
8468
  result.reason = "missing";
8347
8469
  result.detail = "no such file or directory, relative to the configured cwd";
8348
8470
  } else {
8349
- const ancestor = findRecordedAncestor(collection.skipped, relative10, maskedPath2);
8471
+ const ancestor = findRecordedAncestor(collection.skipped, relative11, maskedPath2);
8350
8472
  if (ancestor) {
8351
8473
  result.reason = ancestor.reason;
8352
8474
  result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
@@ -8366,11 +8488,11 @@ function explainPath(config, target) {
8366
8488
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
8367
8489
  ...config.staged === true ? { staged: true } : {}
8368
8490
  });
8369
- inScope = scope.paths.has(relative10);
8491
+ inScope = scope.paths.has(relative11);
8370
8492
  if (!inScope && config.withDependents === true) {
8371
8493
  inScope = importsChangedFile(
8372
- relative10,
8373
- importsOfFile(relative10, absolute),
8494
+ relative11,
8495
+ importsOfFile(relative11, absolute),
8374
8496
  scope.paths,
8375
8497
  buildImportResolver(collection.files.map((file) => ({ relativePath: file })))
8376
8498
  );
@@ -8428,12 +8550,12 @@ function explainPath(config, target) {
8428
8550
  result.bytes = buffer.length;
8429
8551
  result.lines = countLines(text2);
8430
8552
  if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
8431
- const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative10);
8553
+ const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative11);
8432
8554
  result.secretCount = findings.length;
8433
8555
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
8434
8556
  let inclusionMode = "full";
8435
- if (config.skeleton === true && isSkeletonizable(relative10)) {
8436
- const skeleton = skeletonizeTypeScript(text2, relative10);
8557
+ if (config.skeleton === true && isSkeletonizable(relative11)) {
8558
+ const skeleton = skeletonizeTypeScript(text2, relative11);
8437
8559
  if (skeleton.collapsed > 0) inclusionMode = "signatures";
8438
8560
  }
8439
8561
  if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
@@ -8442,15 +8564,15 @@ function explainPath(config, target) {
8442
8564
  }
8443
8565
  result.inclusionMode = inclusionMode;
8444
8566
  }
8445
- result.layer = classifyLayer(relative10, config.layers);
8446
- result.kind = classifyKind(relative10, config.kinds);
8447
- result.language = detectLanguage(relative10);
8448
- const layerRule = findRuleMatch(config.layers, relative10);
8567
+ result.layer = classifyLayer(relative11, config.layers);
8568
+ result.kind = classifyKind(relative11, config.kinds);
8569
+ result.language = detectLanguage(relative11);
8570
+ const layerRule = findRuleMatch(config.layers, relative11);
8449
8571
  if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
8450
- const kindRule = findRuleMatch(config.kinds, relative10);
8572
+ const kindRule = findRuleMatch(config.kinds, relative11);
8451
8573
  if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
8452
8574
  const manifest = readManifest2(config);
8453
- const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative10) : void 0;
8575
+ const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative11) : void 0;
8454
8576
  result.part = entry?.part ?? null;
8455
8577
  return result;
8456
8578
  }
@@ -8499,19 +8621,19 @@ function side(manifest) {
8499
8621
  function shortDigest(value) {
8500
8622
  return value === null ? "not recorded" : `${value.slice(0, 12)}\u2026`;
8501
8623
  }
8502
- function describeLayerChanges(before, after) {
8624
+ function describeLayerChanges(before, after, secretRules) {
8503
8625
  const names = Array.from(/* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])).sort();
8504
8626
  const changes = [];
8505
8627
  for (const name of names) {
8506
8628
  const was = before[name] ?? 0;
8507
8629
  const now = after[name] ?? 0;
8508
8630
  if (was === now) continue;
8509
- const label = findSecretInPath(name)?.masked ?? name;
8631
+ const label = findSecretInPath(name, secretRules)?.masked ?? name;
8510
8632
  changes.push(`layer "${label}": ${was} file(s) \u2192 ${now} file(s)`);
8511
8633
  }
8512
8634
  return changes;
8513
8635
  }
8514
- function describePartChanges(before, after) {
8636
+ function describePartChanges(before, after, secretRules) {
8515
8637
  const index = (parts) => {
8516
8638
  const map = /* @__PURE__ */ new Map();
8517
8639
  for (const part of parts) {
@@ -8521,7 +8643,7 @@ function describePartChanges(before, after) {
8521
8643
  };
8522
8644
  const left = index(before);
8523
8645
  const right = index(after);
8524
- const label = (filename) => findSecretInPath(filename)?.masked ?? filename;
8646
+ const label = (filename) => findSecretInPath(filename, secretRules)?.masked ?? filename;
8525
8647
  const changes = [];
8526
8648
  for (const [filename, part] of right) {
8527
8649
  const previous = left.get(filename);
@@ -8549,7 +8671,15 @@ function describePartChanges(before, after) {
8549
8671
  }
8550
8672
  return changes;
8551
8673
  }
8552
- function describePayloadDiff(before, after, sourceFilesIdentical) {
8674
+ function maskLayerNames(layers, secretRules) {
8675
+ return Object.fromEntries(
8676
+ Object.entries(layers ?? {}).map(([name, count]) => [
8677
+ findSecretInPath(name, secretRules)?.masked ?? name,
8678
+ count
8679
+ ])
8680
+ );
8681
+ }
8682
+ function describePayloadDiff(before, after, sourceFilesIdentical, secretRules) {
8553
8683
  const generatorBefore = before.generator?.version ?? "unknown";
8554
8684
  const generatorAfter = after.generator?.version ?? "unknown";
8555
8685
  const digestBefore = typeof before.config?.digest === "string" ? before.config.digest : null;
@@ -8562,35 +8692,43 @@ function describePayloadDiff(before, after, sourceFilesIdentical) {
8562
8692
  const configurationDiffers = generatorDiffers || digestDiffers || schemaDiffers;
8563
8693
  const fingerprintDiffers = before.fingerprint !== after.fingerprint;
8564
8694
  const partsDiffer = before.counts.partsCount !== after.counts.partsCount;
8565
- const partChanges = describePartChanges(before.parts ?? [], after.parts ?? []);
8566
- const layerChanges = describeLayerChanges(before.layers ?? {}, after.layers ?? {});
8695
+ const partChanges = describePartChanges(before.parts ?? [], after.parts ?? [], secretRules);
8696
+ const layerChanges = describeLayerChanges(before.layers ?? {}, after.layers ?? {}, secretRules);
8567
8697
  const reasons = [];
8698
+ const codes = [];
8568
8699
  if (schemaDiffers) {
8700
+ codes.push("schema-version");
8569
8701
  reasons.push(
8570
8702
  `schema version ${schemaBefore} \u2192 ${schemaAfter} (the two manifests describe different formats)`
8571
8703
  );
8572
8704
  }
8573
8705
  if (digestDiffers) {
8706
+ codes.push("config-digest");
8574
8707
  reasons.push(
8575
8708
  `configuration digest ${shortDigest(digestBefore)} \u2192 ${shortDigest(digestAfter)} (budgets, preview thresholds, redaction rules and artifact selection all count)`
8576
8709
  );
8577
8710
  } else if (digestBefore === null || digestAfter === null) {
8578
8711
  const missing = digestBefore === null && digestAfter !== null ? "before" : digestAfter === null && digestBefore !== null ? "after" : "both";
8712
+ codes.push("config-digest-missing");
8579
8713
  reasons.push(
8580
8714
  `configuration digest not recorded on the ${missing} side (manifest written before 4.0.5); compared the content fingerprint and part count instead`
8581
8715
  );
8582
8716
  }
8583
8717
  if (generatorDiffers) {
8718
+ codes.push("generator");
8584
8719
  reasons.push(`generator ${generatorBefore} \u2192 ${generatorAfter}`);
8585
8720
  }
8586
8721
  if (fingerprintDiffers && (sourceFilesIdentical || configurationDiffers)) {
8722
+ codes.push("fingerprint");
8587
8723
  reasons.push(
8588
8724
  `content fingerprint ${shortDigest(before.fingerprint)} \u2192 ${shortDigest(after.fingerprint)}` + (sourceFilesIdentical ? " (same source files, packed or configured differently)" : "")
8589
8725
  );
8590
8726
  }
8591
8727
  if (partsDiffer) {
8728
+ codes.push("parts-count");
8592
8729
  reasons.push(`${before.counts.partsCount} part(s) \u2192 ${after.counts.partsCount} part(s)`);
8593
8730
  }
8731
+ for (let index = 0; index < layerChanges.length; index += 1) codes.push("layer-changed");
8594
8732
  reasons.push(...layerChanges);
8595
8733
  return {
8596
8734
  sourceFilesIdentical,
@@ -8602,8 +8740,12 @@ function describePayloadDiff(before, after, sourceFilesIdentical) {
8602
8740
  partsCount: { before: before.counts.partsCount, after: after.counts.partsCount },
8603
8741
  schemaVersion: { before: schemaBefore, after: schemaAfter },
8604
8742
  partsManifest: { differs: partChanges.length > 0, changes: partChanges },
8605
- layers: { before: { ...before.layers ?? {} }, after: { ...after.layers ?? {} } },
8606
- reasons
8743
+ // The layer maps are printed and serialized, so a layer named after a project token leaks the
8744
+ // token here even though every reason line above is masked. Found while testing the rules
8745
+ // parameter: masking the prose and not the data it describes is the same bug one layer down.
8746
+ layers: { before: maskLayerNames(before.layers, secretRules), after: maskLayerNames(after.layers, secretRules) },
8747
+ reasons,
8748
+ codes
8607
8749
  };
8608
8750
  }
8609
8751
  function hashMap(manifest) {
@@ -8642,10 +8784,10 @@ function comparableProblem(value) {
8642
8784
  function assertUsableManifest(value, label) {
8643
8785
  const problem = comparableProblem(value);
8644
8786
  if (problem) {
8645
- throw new Error(`The ${label} manifest is not a snapshot manifest this tool wrote: ${problem}.`);
8787
+ throw new Error(`The ${label} manifest is not a snapshot manifest: ${problem}.`);
8646
8788
  }
8647
8789
  }
8648
- function compareManifests(before, after) {
8790
+ function compareManifests(before, after, secretRules) {
8649
8791
  assertUsableManifest(before, "before");
8650
8792
  assertUsableManifest(after, "after");
8651
8793
  const left = hashMap(before);
@@ -8665,8 +8807,8 @@ function compareManifests(before, after) {
8665
8807
  }
8666
8808
  const sort = (values) => values.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
8667
8809
  const sourceFilesIdentical = added.length === 0 && removed.length === 0 && changed.length === 0;
8668
- const payload = describePayloadDiff(before, after, sourceFilesIdentical);
8669
- const mask = (values) => values.map((value) => findSecretInPath(value)?.masked ?? value);
8810
+ const payload = describePayloadDiff(before, after, sourceFilesIdentical, secretRules);
8811
+ const mask = (values) => values.map((value) => findSecretInPath(value, secretRules)?.masked ?? value);
8670
8812
  return {
8671
8813
  before: side(before),
8672
8814
  after: side(after),
@@ -8700,7 +8842,7 @@ function loadManifest(target) {
8700
8842
  const problem = describeManifestShapeProblem(parsed);
8701
8843
  if (problem) {
8702
8844
  throw new Error(
8703
- `${manifestPath} is not a usable snapshot manifest: ${problem}. Point diff at a manifest.json written by \`generate\` (or at the directory that holds it).`
8845
+ `${manifestPath} is not a snapshot manifest: ${problem}. Point diff at a manifest.json written by \`generate\` (or at the directory that holds it).`
8704
8846
  );
8705
8847
  }
8706
8848
  return parsed;
@@ -8838,7 +8980,7 @@ var DEFAULT_ANSWERS = {
8838
8980
  branch: "main",
8839
8981
  maxPartBytes: "300k",
8840
8982
  maxPartTokens: null,
8841
- largeFileBytes: "200k",
8983
+ largeFileBytes: "300k",
8842
8984
  maxMonolithBytes: null,
8843
8985
  discovery: "auto",
8844
8986
  skeleton: false,
@@ -8955,6 +9097,10 @@ function renderConfig(answers) {
8955
9097
  // Set true to drop the built-in rules above and keep only customPatterns.
8956
9098
  disableDefaultPatterns: false,
8957
9099
  },
9100
+ // The library spelling of the same list, accepted here too so a config file can
9101
+ // express what a caller passes in code: an array of { rule, pattern } or a bare
9102
+ // RegExp. Use \`secrets.customPatterns\` above unless you are porting code.
9103
+ // secretRules: [],
8958
9104
 
8959
9105
  // \u2500\u2500 Artifacts \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
8960
9106
  artifacts: {
@@ -9142,7 +9288,7 @@ function keyReader(input) {
9142
9288
  next() {
9143
9289
  const queued = queue.shift();
9144
9290
  if (queued) return Promise.resolve(queued);
9145
- return new Promise((resolve7) => waiters.push(resolve7));
9291
+ return new Promise((resolve8) => waiters.push(resolve8));
9146
9292
  },
9147
9293
  close() {
9148
9294
  input.off("keypress", onKey);
@@ -9571,7 +9717,18 @@ function updatePackageJson(cwd, notes) {
9571
9717
  writeFileOrExplain(packagePath, serializePackageJson(raw, parsed));
9572
9718
  return { scripts: added, dependency };
9573
9719
  }
9574
- var GITIGNORE_ENTRIES = ["/snapshot/", "/snapshot.tmp/"];
9720
+ function gitignoreEntriesFor(cwd, outDir, tmpDir) {
9721
+ const entries = [];
9722
+ for (const directory of [outDir, tmpDir]) {
9723
+ if (directory === null) continue;
9724
+ const relative11 = path16.relative(cwd, path16.resolve(cwd, directory)).replace(/\\/g, "/");
9725
+ if (relative11 === "" || relative11 === "." || relative11.startsWith("..") || path16.isAbsolute(relative11)) {
9726
+ continue;
9727
+ }
9728
+ entries.push(`/${relative11}/`);
9729
+ }
9730
+ return [...new Set(entries)];
9731
+ }
9575
9732
  function resolvePresetChoice(detectedName, presetName) {
9576
9733
  return {
9577
9734
  value: presetName,
@@ -9601,13 +9758,11 @@ async function runInit(options) {
9601
9758
  // what the run used is drift the next `validate` reports, and `setup` is the one command
9602
9759
  // that is supposed to leave a project in a consistent state.
9603
9760
  maxPartTokens: options.maxPartTokens ?? DEFAULT_ANSWERS.maxPartTokens,
9604
- largeFileBytes: options.largeFileBytes ?? // A threshold above the part budget is a configuration error (a file between the two
9605
- // cannot fit, so it is cut while the manifest calls it a preview). Writing the old fixed
9606
- // 200 KB beside `--max-part-tokens 32k` made the setup's own output fail its own validate.
9607
- Math.min(
9608
- parseByteSize(DEFAULT_ANSWERS.largeFileBytes) ?? effectiveBudgetBytes,
9609
- effectiveBudgetBytes
9610
- ),
9761
+ // Follows the budget unless the caller named one. A threshold above the part budget is a
9762
+ // config error (a file between the two cannot fit a part, so it is cut while the manifest
9763
+ // calls it a preview); a fixed 200 KB beside `--max-part-tokens 32k` made setup's own output
9764
+ // fail its own validate, and a fixed 200 KB under a 300 KB budget previewed files that fit.
9765
+ largeFileBytes: options.largeFileBytes ?? effectiveBudgetBytes,
9611
9766
  maxMonolithBytes: options.maxMonolithBytes ?? DEFAULT_ANSWERS.maxMonolithBytes,
9612
9767
  discovery: options.discovery ?? DEFAULT_ANSWERS.discovery,
9613
9768
  skeleton: options.skeleton ?? DEFAULT_ANSWERS.skeleton,
@@ -9866,7 +10021,10 @@ async function runInit(options) {
9866
10021
  }
9867
10022
  if (!reused) writeFileOrExplain(configPath, configText);
9868
10023
  const { scripts, dependency } = updatePackageJson(options.cwd, notes);
9869
- const ignore = appendGitignoreEntries(options.cwd, GITIGNORE_ENTRIES);
10024
+ const ignore = appendGitignoreEntries(
10025
+ options.cwd,
10026
+ gitignoreEntriesFor(options.cwd, answers.outDir, options.tmpDir ?? (reused ? null : "snapshot.tmp"))
10027
+ );
9870
10028
  if (ignore.note !== null) notes.push(ignore.note);
9871
10029
  return {
9872
10030
  configPath,
@@ -9884,10 +10042,10 @@ async function runInit(options) {
9884
10042
  };
9885
10043
  }
9886
10044
  function describeTarget(cwd) {
9887
- const relative10 = path16.relative(process.cwd(), cwd);
9888
- if (relative10 === "") return "this directory";
9889
- if (relative10.startsWith("..") || path16.isAbsolute(relative10)) return cwd;
9890
- return relative10;
10045
+ const relative11 = path16.relative(process.cwd(), cwd);
10046
+ if (relative11 === "") return "this directory";
10047
+ if (relative11.startsWith("..") || path16.isAbsolute(relative11)) return cwd;
10048
+ return relative11;
9891
10049
  }
9892
10050
  function firstRunMessage(reason, cwd) {
9893
10051
  const where = describeTarget(cwd);
@@ -9989,8 +10147,8 @@ function gitDirectory(cwd) {
9989
10147
  }
9990
10148
  }
9991
10149
  function isInside2(parent, child) {
9992
- const relative10 = path16.relative(parent, child);
9993
- return relative10 === "" || !relative10.startsWith("..") && !path16.isAbsolute(relative10);
10150
+ const relative11 = path16.relative(parent, child);
10151
+ return relative11 === "" || !relative11.startsWith("..") && !path16.isAbsolute(relative11);
9994
10152
  }
9995
10153
  function isRegisteredWorktree(gitDir, cwd) {
9996
10154
  try {
@@ -10104,7 +10262,20 @@ const { parentPort, workerData } = require("node:worker_threads");
10104
10262
  // so the run is the documented MCP run rather than the CLI run with one setting removed.
10105
10263
  const base = loaded.config ? { ...loaded.config, hooks: {} } : null;
10106
10264
  const config = mod.resolveConfig(base, workerData.cliOptions, workerData.cwd);
10107
- const manifest = mod.generateSnapshot(config);
10265
+ const manifest = mod.generateSnapshot(config, { dryRun: workerData.dryRun === true });
10266
+ const skipCounts = new Map();
10267
+ for (const record of manifest.skipped) {
10268
+ skipCounts.set(record.reason, (skipCounts.get(record.reason) || 0) + 1);
10269
+ }
10270
+ const skipReasons = Array.from(skipCounts.entries())
10271
+ .sort(function (a, b) {
10272
+ if (b[1] !== a[1]) return b[1] - a[1];
10273
+ return a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0;
10274
+ })
10275
+ .slice(0, 8)
10276
+ .map(function (entry) {
10277
+ return { reason: entry[0], count: entry[1] };
10278
+ });
10108
10279
  parentPort.postMessage({
10109
10280
  ok: true,
10110
10281
  summary: {
@@ -10113,7 +10284,11 @@ const { parentPort, workerData } = require("node:worker_threads");
10113
10284
  skippedCount: manifest.counts.skippedCount,
10114
10285
  partsCount: manifest.counts.partsCount,
10115
10286
  parts: manifest.parts.map((part) => ({ filename: part.filename, byteSize: part.byteSize })),
10287
+ totalSizeBytes: manifest.counts.totalSizeBytes,
10116
10288
  totalContentBytes: manifest.totals.totalContentBytes,
10289
+ preset: manifest.config.preset,
10290
+ layers: manifest.layers,
10291
+ skipReasons: skipReasons,
10117
10292
  warnings: manifest.warnings,
10118
10293
  },
10119
10294
  });
@@ -10125,15 +10300,15 @@ const { parentPort, workerData } = require("node:worker_threads");
10125
10300
  }
10126
10301
  })();
10127
10302
  `;
10128
- function generateInWorker(cwd, cliOptions) {
10129
- return new Promise((resolve7) => {
10303
+ function generateInWorker(cwd, cliOptions, options = {}) {
10304
+ return new Promise((resolve8) => {
10130
10305
  let settled = false;
10131
10306
  let worker = null;
10132
10307
  const finish = (result) => {
10133
10308
  if (settled) return;
10134
10309
  settled = true;
10135
10310
  if (worker !== null) void worker.terminate();
10136
- resolve7(result);
10311
+ resolve8(result);
10137
10312
  };
10138
10313
  const isCjs = typeof __dirname !== "undefined";
10139
10314
  const directory = isCjs ? __dirname : path16.dirname(fileURLToPath(import.meta.url));
@@ -10143,7 +10318,8 @@ function generateInWorker(cwd, cliOptions) {
10143
10318
  workerData: {
10144
10319
  entryUrl: workerEntry(directory, isCjs).url,
10145
10320
  cwd,
10146
- cliOptions
10321
+ cliOptions,
10322
+ dryRun: options.dryRun === true
10147
10323
  }
10148
10324
  });
10149
10325
  } catch (error) {
@@ -10328,16 +10504,29 @@ function retain(items, keep) {
10328
10504
  }
10329
10505
  items.length = write;
10330
10506
  }
10331
- function buildIndexes(files, tsconfigPaths) {
10507
+ function buildIndexes(files, tsconfigPaths, skippedSummaryImports = /* @__PURE__ */ new Map()) {
10332
10508
  const resolver = buildImportResolver(files, { tsconfig: tsconfigPaths });
10333
10509
  const importerCounts = /* @__PURE__ */ new Map();
10334
- const byFile = files.filter((file) => isSourceSummary(file.summary)).map((file) => {
10335
- const summary = file.summary;
10336
- return {
10337
- path: file.relativePath,
10338
- imports: summary.imports,
10339
- exports: summary.exports
10340
- };
10510
+ const byFile = files.flatMap((file) => {
10511
+ if (isSourceSummary(file.summary)) {
10512
+ return [
10513
+ {
10514
+ path: file.relativePath,
10515
+ imports: file.summary.imports,
10516
+ exports: file.summary.exports
10517
+ }
10518
+ ];
10519
+ }
10520
+ const imports = skippedSummaryImports.get(file.relativePath);
10521
+ if (imports === void 0) return [];
10522
+ return [
10523
+ {
10524
+ path: file.relativePath,
10525
+ imports,
10526
+ exports: [],
10527
+ exportsOmitted: true
10528
+ }
10529
+ ];
10341
10530
  });
10342
10531
  for (const entry of byFile) {
10343
10532
  for (const specifier of entry.imports) {
@@ -10457,6 +10646,9 @@ function resolveSafeOutputDirs(config) {
10457
10646
  return { outDir, tmpDir };
10458
10647
  }
10459
10648
  var IGNORABLE_ENTRIES = /* @__PURE__ */ new Set([".DS_Store"]);
10649
+ function isIgnorableEntry(entry) {
10650
+ return IGNORABLE_ENTRIES.has(entry.slice(entry.lastIndexOf("/") + 1));
10651
+ }
10460
10652
  var RUN_DIR_PREFIX = "run-";
10461
10653
  var STALE_RUN_MS = 60 * 60 * 1e3;
10462
10654
  function maskSummaryStrings(value, secretRules) {
@@ -10499,9 +10691,9 @@ function listEntries(dir) {
10499
10691
  return;
10500
10692
  }
10501
10693
  for (const child of children) {
10502
- const relative10 = prefix === "" ? child.name : `${prefix}/${child.name}`;
10503
- entries.push(relative10);
10504
- if (child.isDirectory()) walk(path16.join(absolute, child.name), relative10);
10694
+ const relative11 = prefix === "" ? child.name : `${prefix}/${child.name}`;
10695
+ entries.push(relative11);
10696
+ if (child.isDirectory()) walk(path16.join(absolute, child.name), relative11);
10505
10697
  }
10506
10698
  };
10507
10699
  walk(dir, "");
@@ -10512,7 +10704,7 @@ function markerInventory(dir, written) {
10512
10704
  const files = [];
10513
10705
  for (const entry of entries) {
10514
10706
  if (entry === OWNERSHIP_MARKER) continue;
10515
- if (IGNORABLE_ENTRIES.has(entry.slice(entry.lastIndexOf("/") + 1))) continue;
10707
+ if (isIgnorableEntry(entry)) continue;
10516
10708
  const full = path16.join(dir, ...entry.split("/"));
10517
10709
  let stats;
10518
10710
  try {
@@ -10801,7 +10993,7 @@ function assessSnapshotDirectory(dir) {
10801
10993
  }
10802
10994
  const entries = listEntries(dir);
10803
10995
  const foreignEntries = entries.filter(
10804
- (entry) => !recorded.has(entry) && !IGNORABLE_ENTRIES.has(entry)
10996
+ (entry) => !recorded.has(entry) && !isIgnorableEntry(entry)
10805
10997
  );
10806
10998
  if (foreignEntries.length > 0) {
10807
10999
  return { owned: false, problem: null, foreignEntries, marker: marker2 };
@@ -11297,7 +11489,7 @@ function generateSnapshot(configInput, options) {
11297
11489
  // output — but only at these exact paths, not at every directory that shares the name.
11298
11490
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
11299
11491
  (directory) => path16.relative(config.cwd, path16.resolve(config.cwd, directory)).replace(/\\/g, "/")
11300
- ).filter((relative10) => relative10.length > 0 && !relative10.startsWith("..")),
11492
+ ).filter((relative11) => relative11.length > 0 && !relative11.startsWith("..")),
11301
11493
  // A staged path can be absent from the working tree while its index blob exists. Discovery
11302
11494
  // lists the working tree, so those paths would never reach the scan at all.
11303
11495
  ...stagedPaths.size > 0 ? { extraPaths: [...stagedPaths] } : {}
@@ -11717,7 +11909,7 @@ function generateSnapshot(configInput, options) {
11717
11909
  },
11718
11910
  layers: layerCounts,
11719
11911
  kinds: kindCounts,
11720
- indexes: buildIndexes(files, tsconfigPathsFor(config.cwd)),
11912
+ indexes: buildIndexes(files, tsconfigPathsFor(config.cwd), skippedSummaryImports),
11721
11913
  parts: parts.map((part) => part.metadata),
11722
11914
  files: files.map((file) => {
11723
11915
  const { content: _content, ...rest } = file;
@@ -11759,11 +11951,9 @@ function generateSnapshot(configInput, options) {
11759
11951
  let projectTree = null;
11760
11952
  if (config.artifacts.projectTree) {
11761
11953
  projectTree = generateProjectTree(files.map((file) => file.relativePath));
11762
- const depthMarker = /\[tree truncated at (\d+) levels\]/.exec(projectTree);
11763
- if (depthMarker) {
11764
- manifest.warnings.push(
11765
- `reports/project-tree.md was truncated at the ${depthMarker[1]}-level depth cap: deeper directories are not listed there.`
11766
- );
11954
+ const truncations = treeTruncationWarnings(projectTree);
11955
+ if (truncations.length > 0) {
11956
+ manifest.warnings.push(...truncations);
11767
11957
  manifest.totals.warningCount = manifest.warnings.length;
11768
11958
  }
11769
11959
  }
@@ -11791,7 +11981,7 @@ function generateSnapshot(configInput, options) {
11791
11981
  if (config.includeMonolith) {
11792
11982
  const fullFiles = files.map((file) => {
11793
11983
  const content = fullContents.get(file.relativePath) ?? "";
11794
- return {
11984
+ const entry = {
11795
11985
  ...file,
11796
11986
  content,
11797
11987
  inclusionMode: "full",
@@ -11799,6 +11989,9 @@ function generateSnapshot(configInput, options) {
11799
11989
  includedBytes: Buffer.byteLength(content, "utf8"),
11800
11990
  includedLines: countLines(content)
11801
11991
  };
11992
+ delete entry.truncationReason;
11993
+ delete entry.omittedRanges;
11994
+ return entry;
11802
11995
  });
11803
11996
  const bodyBytes = fullFiles.reduce((total, file) => total + file.includedBytes, 0);
11804
11997
  const definitelyTooLarge = config.maxMonolithBytes !== null && bodyBytes > config.maxMonolithBytes;
@@ -12007,4 +12200,4 @@ async function generateSnapshotAsync(configInput, options) {
12007
12200
  return manifest;
12008
12201
  }
12009
12202
 
12010
- export { ARTIFACT_NAMES, CHECK_INTERVAL_MS, CONFIG_KEYS, DEFAULT_ANSWERS, DEFAULT_SECRET_PATTERNS, FAILURE_INTERVAL_MS, GENERATOR_NAME, GENERATOR_VERSION, HOOK_MARKER, LANGUAGE_PROFILES, MIN_MAX_PART_BYTES, MIN_MAX_PART_TOKENS, PACKAGE_LATEST_URL, PRESETS, PromptBack, PromptCancelled, REQUEST_TIMEOUT_MS, SCHEMA_VERSION, UP_TO_DATE_INTERVAL_MS, anchorForPath, appendGitignoreEntries, assertReplaceable, assertUsableConfigInput, buildImportResolver, bytesForTokens, cacheDirectory, cacheFilePath, checkForUpdate, classifyKind, classifyLayer, collectFiles, compareManifests, configDigest, countInvalidUtf8Bytes, countLines, decodeText, defaultIO, defineConfig, describeManifestShapeProblem, detectLanguage, detectPreset, displayPath, displayWidth, enforceBudget, escapeControls, estimateTokens, explainPath, fenceForContent, fenceForText, fetchLatestVersion, findConfigFile, findSecretInPath, firstRunMessage, formatNumber, formatTokens, formatUpdateNotice, generateInWorker, generateProjectTree, generateSarifReport, generateSnapshot, generateSnapshotAsync, getGitInfo, getPreset, gitignorePath, globToRegExp, hasPriorSnapshot, importsChangedFile, importsOfFile, importsOfText, installKind, installPreCommitHook, isBinaryBuffer, isBinaryExtension, isBinaryFile, isDiscoveryMode, isEffectivelyEmpty, isInteractive, isNewer, isResolvedConfig, isSensitivePath, isSkeletonizable, isTsxFileName, listPresetNames, loadConfigFile, loadConfigFileDetailed, loadManifest, lockPathFor, markResolvedConfig, matchRule, matchesExclude, normalizeResolvedConfig, parseByteSize, partitionFiles, planFirstRun, profileForPath, renderConfig, renderDiffText, renderExplainText, renumberParts, resolveChangedScope, resolveConfig, resolveSafeOutputDirs, resolveSpecifier, runInit, runWithStdoutCapture, scanAndRedactSecrets, shouldCheck, skeletonizeTypeScript, stripJsonComments, summarizeJson, summarizeMarkdown, summarizeTypeScriptSource, summarizeWithProfile, supportsTypeScriptImports, truncatePreview, truncateToBytes, tsconfigPathsFor, unknownPresetMessage, updateCommand, validateSnapshot, workerEntry, wrapLines };
12203
+ export { ARTIFACT_NAMES, CHECK_INTERVAL_MS, CONFIG_KEYS, DEFAULT_ANSWERS, DEFAULT_SECRET_PATTERNS, FAILURE_INTERVAL_MS, GENERATOR_NAME, GENERATOR_VERSION, HOOK_MARKER, LANGUAGE_PROFILES, MIN_MAX_PART_BYTES, MIN_MAX_PART_TOKENS, PACKAGE_LATEST_URL, PRESETS, PromptBack, PromptCancelled, REQUEST_TIMEOUT_MS, SCHEMA_VERSION, UP_TO_DATE_INTERVAL_MS, anchorForPath, appendGitignoreEntries, assertReplaceable, assertUsableConfigInput, buildImportResolver, bytesForTokens, cacheDirectory, cacheFilePath, checkForUpdate, classifyKind, classifyLayer, collectFiles, compareManifests, configDigest, countInvalidUtf8Bytes, countLines, decodeText, defaultIO, defineConfig, describeManifestShapeProblem, detectLanguage, detectPreset, displayPath, displayWidth, enforceBudget, escapeControls, estimateTokens, explainPath, fenceForContent, fenceForText, fetchLatestVersion, findConfigFile, findSecretInPath, firstRunMessage, formatNumber, formatTokens, formatUpdateNotice, generateInWorker, generateProjectTree, generateSarifReport, generateSnapshot, generateSnapshotAsync, getGitInfo, getPreset, gitignorePath, globToRegExp, hasPriorSnapshot, importsChangedFile, importsOfFile, importsOfText, installKind, installPreCommitHook, isBinaryBuffer, isBinaryExtension, isBinaryFile, isDiscoveryMode, isEffectivelyEmpty, isInteractive, isNewer, isResolvedConfig, isSensitivePath, isSkeletonizable, isTsxFileName, listPresetNames, loadConfigFile, loadConfigFileDetailed, loadManifest, lockPathFor, markResolvedConfig, matchRule, matchesExclude, normalizeResolvedConfig, parseByteSize, partitionFiles, planFirstRun, profileForPath, renderConfig, renderDiffText, renderExplainText, renumberParts, resolveChangedScope, resolveConfig, resolveSafeOutputDirs, resolveSpecifier, runInit, runWithStdoutCapture, scanAndRedactSecrets, shouldCheck, skeletonizeTypeScript, stripJsonComments, summarizeJson, summarizeMarkdown, summarizeTypeScriptSource, summarizeWithProfile, supportsTypeScriptImports, treeTruncationWarnings, truncatePreview, truncateToBytes, tsconfigPathsFor, unknownPresetMessage, updateCommand, validateSnapshot, workerEntry, wrapLines };