codebase-snapshot 0.9.15 → 0.9.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -1,19 +1,19 @@
1
1
  'use strict';
2
2
 
3
3
  var childProcess = require('child_process');
4
- var fs14 = require('fs');
4
+ var fs15 = require('fs');
5
5
  var path16 = require('path');
6
6
  var util = require('util');
7
7
  var crypto3 = require('crypto');
8
8
  var module$1 = require('module');
9
9
  var url = require('url');
10
- var ts = require('typescript');
10
+ var ts2 = require('typescript');
11
11
  var readline = require('readline');
12
+ var worker_threads = require('worker_threads');
12
13
  var async_hooks = require('async_hooks');
13
14
  var os = require('os');
14
15
  var http = require('http');
15
16
  var https = require('https');
16
- var worker_threads = require('worker_threads');
17
17
 
18
18
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
19
19
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -37,10 +37,10 @@ function _interopNamespace(e) {
37
37
  }
38
38
 
39
39
  var childProcess__namespace = /*#__PURE__*/_interopNamespace(childProcess);
40
- var fs14__namespace = /*#__PURE__*/_interopNamespace(fs14);
40
+ var fs15__namespace = /*#__PURE__*/_interopNamespace(fs15);
41
41
  var path16__namespace = /*#__PURE__*/_interopNamespace(path16);
42
42
  var crypto3__namespace = /*#__PURE__*/_interopNamespace(crypto3);
43
- var ts__default = /*#__PURE__*/_interopDefault(ts);
43
+ var ts2__default = /*#__PURE__*/_interopDefault(ts2);
44
44
  var readline__namespace = /*#__PURE__*/_interopNamespace(readline);
45
45
  var os__namespace = /*#__PURE__*/_interopNamespace(os);
46
46
  var http__namespace = /*#__PURE__*/_interopNamespace(http);
@@ -93,9 +93,9 @@ var SKIPPED_WALK_DIRS = /* @__PURE__ */ new Set([
93
93
  ]);
94
94
  function readSmallFile(fullPath) {
95
95
  try {
96
- const stats = fs14__namespace.statSync(fullPath);
96
+ const stats = fs15__namespace.statSync(fullPath);
97
97
  if (!stats.isFile() || stats.size > MANIFEST_MAX_BYTES) return null;
98
- return fs14__namespace.readFileSync(fullPath, "utf8");
98
+ return fs15__namespace.readFileSync(fullPath, "utf8");
99
99
  } catch {
100
100
  return null;
101
101
  }
@@ -161,7 +161,7 @@ function pnpmWorkspacePatterns(raw) {
161
161
  function childDirectories(cwd, parent) {
162
162
  let entries;
163
163
  try {
164
- entries = fs14__namespace.readdirSync(path16__namespace.join(cwd, parent), { withFileTypes: true });
164
+ entries = fs15__namespace.readdirSync(path16__namespace.join(cwd, parent), { withFileTypes: true });
165
165
  } catch {
166
166
  return [];
167
167
  }
@@ -196,10 +196,10 @@ function workspacePackageDirs(cwd, patterns) {
196
196
  function scanWorkspacePackages(cwd, patterns) {
197
197
  const files = /* @__PURE__ */ new Set();
198
198
  const dependencies = /* @__PURE__ */ new Set();
199
- for (const relative12 of workspacePackageDirs(cwd, patterns)) {
200
- const full = path16__namespace.join(cwd, relative12);
199
+ for (const relative14 of workspacePackageDirs(cwd, patterns)) {
200
+ const full = path16__namespace.join(cwd, relative14);
201
201
  try {
202
- for (const entry of fs14__namespace.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
202
+ for (const entry of fs15__namespace.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
203
203
  } catch {
204
204
  }
205
205
  const raw = readSmallFile(path16__namespace.join(full, "package.json"));
@@ -212,7 +212,7 @@ function scanWorkspacePackages(cwd, patterns) {
212
212
  var SNAPSHOT_MARKER = ".codebase-snapshot";
213
213
  function isToolOwnedDirectory(dir) {
214
214
  try {
215
- return fs14__namespace.statSync(dir).isDirectory() && fs14__namespace.existsSync(path16__namespace.join(dir, SNAPSHOT_MARKER));
215
+ return fs15__namespace.statSync(dir).isDirectory() && fs15__namespace.existsSync(path16__namespace.join(dir, SNAPSHOT_MARKER));
216
216
  } catch {
217
217
  return false;
218
218
  }
@@ -227,7 +227,7 @@ function countMarkdownFiles(cwd) {
227
227
  directoriesSeen += 1;
228
228
  let entries;
229
229
  try {
230
- entries = fs14__namespace.readdirSync(current.dir, { withFileTypes: true });
230
+ entries = fs15__namespace.readdirSync(current.dir, { withFileTypes: true });
231
231
  } catch {
232
232
  continue;
233
233
  }
@@ -249,7 +249,7 @@ function buildPresetContext(cwd) {
249
249
  const files = /* @__PURE__ */ new Set();
250
250
  const dirs = /* @__PURE__ */ new Set();
251
251
  try {
252
- for (const entry of fs14__namespace.readdirSync(cwd, { withFileTypes: true })) {
252
+ for (const entry of fs15__namespace.readdirSync(cwd, { withFileTypes: true })) {
253
253
  if (entry.isDirectory()) dirs.add(entry.name);
254
254
  else if (entry.isFile()) files.add(entry.name);
255
255
  }
@@ -1124,7 +1124,10 @@ var ASSIGN = String.raw`(?<![=!<>])[:=](?!=)`;
1124
1124
  var NOT_AFTER_QUOTE = String.raw`(?<!["'])`;
1125
1125
  var NOT_A_NAMESPACED_IDENTIFIER = String.raw`(?![a-z][a-z0-9]*(?:\.[a-z][a-z0-9-]*)+/)`;
1126
1126
  var QUOTED_CREDENTIAL_KEY = `["'](?!id[-_]token["'])[A-Za-z0-9_$-]{0,64}${STRONG_CREDENTIAL_NAME}["']`;
1127
- var QUOTED_VALUE = String.raw`((?:[^"'\\\n]|\\\\["'](?=[A-Za-z0-9_])|\\.){1,512})`;
1127
+ function quotedValueFor(delimiterGroup) {
1128
+ return "((?:(?!\\" + delimiterGroup + String.raw`)[^\\\n]|\\\\["'](?=[A-Za-z0-9_])|\\.){1,512})`;
1129
+ }
1130
+ var QUOTED_VALUE = quotedValueFor(1);
1128
1131
  var UNQUOTED_STRONG_NAME = `(?<!id[-_])${STRONG_CREDENTIAL_NAME}`;
1129
1132
  var CREDENTIAL_KEY_TAIL = new RegExp(`(?:${STRONG_CREDENTIAL_NAME})$`, "i");
1130
1133
  var DEFAULT_SECRET_PATTERNS = [
@@ -1278,7 +1281,7 @@ var DEFAULT_SECRET_PATTERNS = [
1278
1281
  // consumes the flag so the match is the credential alone.
1279
1282
  // - An Azure SAS link authenticates with `?sig=`; the signature *is* the credential.
1280
1283
  rule: "uri-credentials",
1281
- pattern: /\/\/[^\s:/@"'`;()<>,]{0,128}:[^\s:/@"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}|(?<=(?:^|[\s;|&(])--?u(?:ser)?[ \t=]{1,8})["']?[^\s"']{1,300}:[^\s"']{0,256}["']?|(?<=[?&])sig=[A-Za-z0-9%._=~-]{20,300}(?![A-Za-z0-9%._=~-])/
1284
+ pattern: /\/\/[^\s:/@"'`;()<>,]{0,128}:[^\s:/@"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}|(?<=(?:^|[\s;|&(])--?u(?:ser)?[ \t=]{1,8})["']?[A-Za-z0-9._~-][A-Za-z0-9._~-]{0,127}:[^\s"'%$()+]{1,256}["']?|(?<=[?&])sig=[A-Za-z0-9%._=~-]{20,300}(?![A-Za-z0-9%._=~-])/
1282
1285
  },
1283
1286
  {
1284
1287
  // The host tail stops at quotes, `;`, `)`, `<`, `>` and `,`: an unbounded
@@ -1390,7 +1393,7 @@ var DEFAULT_SECRET_PATTERNS = [
1390
1393
  // rendering of textual userinfo mixes cases, while the prose the earlier rules were
1391
1394
  // protecting (`Bearer authentication`) is a lowercase word.
1392
1395
  rule: "authorization-header",
1393
- pattern: /(?<=(?:Bearer|Basic)\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_.+/=-])/
1396
+ 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_.+/=-])/
1394
1397
  },
1395
1398
  {
1396
1399
  // Broader names than before (`apiKey`, `clientSecret`, `privateKey` were
@@ -1417,7 +1420,9 @@ var DEFAULT_SECRET_PATTERNS = [
1417
1420
  // between the braces to mask, and `isTemplateInterpolation` keeps such a value readable.
1418
1421
  rule: "interpolation-fallback-secret",
1419
1422
  pattern: new RegExp(
1420
- `(?:["']${STRONG_CREDENTIAL_NAME}["']|${NOT_AFTER_QUOTE}${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}["'\`]?\\$\\{[A-Za-z_][A-Za-z0-9_]*:?[-=?+]([^}"'\`\\r\\n]{2,512})\\}["'\`]?`,
1423
+ // The operator set deliberately omits `?`: `${VAR:?message}` is an error message in shell
1424
+ // and Compose, not a fallback value, and masking it hid the sentence a user is meant to read.
1425
+ `(?:["']${STRONG_CREDENTIAL_NAME}["']|${NOT_AFTER_QUOTE}${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}["'\`]?\\$\\{[A-Za-z_][A-Za-z0-9_]*:?[-=+]([^}"'\`\\r\\n]{2,512})\\}["'\`]?`,
1421
1426
  "i"
1422
1427
  ),
1423
1428
  valueGroup: 1
@@ -1466,19 +1471,15 @@ function compilePattern(rule, pattern, valueGroup) {
1466
1471
  if (pattern instanceof RegExp) {
1467
1472
  const flags = new Set(pattern.flags.replace(/[gy]/g, "").split(""));
1468
1473
  if (valueGroup !== void 0) flags.add("d");
1469
- return {
1470
- rule,
1471
- pattern: new RegExp(pattern.source, [...flags].join("")),
1472
- ...valueGroup === void 0 ? {} : { valueGroup }
1473
- };
1474
+ return checkedPattern(rule, new RegExp(pattern.source, [...flags].join("")), valueGroup);
1474
1475
  }
1475
1476
  if (typeof pattern === "string") {
1476
1477
  try {
1477
- return {
1478
+ return checkedPattern(
1478
1479
  rule,
1479
- pattern: new RegExp(pattern, valueGroup === void 0 ? "i" : "id"),
1480
- ...valueGroup === void 0 ? {} : { valueGroup }
1481
- };
1480
+ new RegExp(pattern, valueGroup === void 0 ? "i" : "id"),
1481
+ valueGroup
1482
+ );
1482
1483
  } catch (err) {
1483
1484
  throw new Error(
1484
1485
  `Invalid regular expression for secret rule "${rule}": ${err.message}`
@@ -1489,6 +1490,19 @@ function compilePattern(rule, pattern, valueGroup) {
1489
1490
  `Secret rule "${rule}" has a pattern that is neither a RegExp nor a string (received ${describeValue(pattern)}).`
1490
1491
  );
1491
1492
  }
1493
+ function checkedPattern(rule, compiled, valueGroup) {
1494
+ const stateless = new RegExp(compiled.source, compiled.flags.replace(/[gy]/g, ""));
1495
+ if (stateless.test("")) {
1496
+ throw new Error(
1497
+ `Secret rule "${rule}" can match the empty string. Every alternative must require at least one character, or the scan cannot advance past a match.`
1498
+ );
1499
+ }
1500
+ return {
1501
+ rule,
1502
+ pattern: compiled,
1503
+ ...valueGroup === void 0 ? {} : { valueGroup }
1504
+ };
1505
+ }
1492
1506
  function compileSecretRules(rules) {
1493
1507
  if (!Array.isArray(rules)) {
1494
1508
  throw new Error(
@@ -1545,6 +1559,193 @@ function toGlobal(rule) {
1545
1559
  }
1546
1560
  var LINE_BREAK = /(\r\n|\n|\r)/;
1547
1561
  var LINE_TERMINATOR = /\r\n|\n|\r/g;
1562
+ function isOpeningQuote(line, index) {
1563
+ const code = line.charCodeAt(index);
1564
+ if (code === 96) return true;
1565
+ if (code !== 34 && code !== 39) return false;
1566
+ return index === 0 || !/[A-Za-z0-9]/.test(line[index - 1]);
1567
+ }
1568
+ function quoteStates(line) {
1569
+ const states = new Uint8Array(line.length + 1);
1570
+ let quote = 0;
1571
+ for (let index = 0; index < line.length; index += 1) {
1572
+ states[index] = quote;
1573
+ const code = line.charCodeAt(index);
1574
+ if (quote === 0) {
1575
+ if (isOpeningQuote(line, index)) quote = code;
1576
+ } else if (code === 92) {
1577
+ if (index + 1 < line.length) {
1578
+ index += 1;
1579
+ states[index] = quote;
1580
+ }
1581
+ } else if (code === quote) {
1582
+ quote = 0;
1583
+ }
1584
+ }
1585
+ states[line.length] = quote;
1586
+ return states;
1587
+ }
1588
+ function quoteStateFor(line, context) {
1589
+ if (context.quoteAt === void 0) context.quoteAt = quoteStates(line);
1590
+ return context.quoteAt;
1591
+ }
1592
+ function quoteStateAfter(text2, quote, end = text2.length) {
1593
+ for (let index = 0; index < end; index += 1) {
1594
+ const code = text2.charCodeAt(index);
1595
+ if (quote === 0) {
1596
+ if (isOpeningQuote(text2, index)) quote = code;
1597
+ } else if (code === 92) {
1598
+ index += 1;
1599
+ } else if (code === quote) {
1600
+ quote = 0;
1601
+ }
1602
+ }
1603
+ return quote;
1604
+ }
1605
+ function commentStartFor(line, context) {
1606
+ if (context.commentStart !== void 0) return context.commentStart;
1607
+ const quotes = quoteStateFor(line, context);
1608
+ let start = line.length;
1609
+ for (let index = 0; index < line.length; index += 1) {
1610
+ if (line.charCodeAt(index) !== 35 || quotes[index] !== 0) continue;
1611
+ if (index === 0 || /\s/.test(line[index - 1])) {
1612
+ start = index;
1613
+ break;
1614
+ }
1615
+ }
1616
+ context.commentStart = start;
1617
+ return start;
1618
+ }
1619
+ function commandSeparatorsFor(line, context) {
1620
+ if (context.commandSeparators !== void 0) return context.commandSeparators;
1621
+ const quotes = quoteStateFor(line, context);
1622
+ const separators = [];
1623
+ for (let index = 0; index < line.length; index += 1) {
1624
+ if (quotes[index] !== 0) continue;
1625
+ const ch = line[index];
1626
+ const spaced = index > 0 && /\s/.test(line[index - 1]) || index + 1 < line.length && /\s/.test(line[index + 1]);
1627
+ if (ch === "&" || ch === "|") {
1628
+ if (line[index + 1] === ch) {
1629
+ const after = index + 2;
1630
+ const doubleSpaced = spaced || after >= line.length || /\s/.test(line[after]);
1631
+ if (doubleSpaced) separators.push(index);
1632
+ index += 1;
1633
+ } else if (spaced) {
1634
+ separators.push(index);
1635
+ }
1636
+ } else if ((ch === ";" || ch === ">" || ch === "<") && spaced) {
1637
+ separators.push(index);
1638
+ }
1639
+ }
1640
+ context.commandSeparators = separators;
1641
+ return separators;
1642
+ }
1643
+ function lineValueEnd(line, start, context) {
1644
+ const comment = commentStartFor(line, context);
1645
+ let end = comment > start ? comment : line.length;
1646
+ for (const separator of commandSeparatorsFor(line, context)) {
1647
+ if (separator > start && separator < end) {
1648
+ end = separator;
1649
+ break;
1650
+ }
1651
+ }
1652
+ while (end > start && /\s/.test(line[end - 1])) end -= 1;
1653
+ return end;
1654
+ }
1655
+ function hasStructuralQuote(line) {
1656
+ for (let index = 0; index < line.length; index += 1) {
1657
+ const ch = line[index];
1658
+ if (ch !== '"' && ch !== "'" && ch !== "`") continue;
1659
+ if (ch === "'" && index > 0 && /[A-Za-z0-9]/.test(line[index - 1])) continue;
1660
+ let backslashes = 0;
1661
+ for (let before2 = index - 1; before2 >= 0 && line[before2] === "\\"; before2 -= 1) backslashes += 1;
1662
+ if (backslashes % 2 === 1) continue;
1663
+ let before = index - 1;
1664
+ while (before >= 0 && (line[before] === " " || line[before] === " ")) before -= 1;
1665
+ if (before < 0 || "+,=:([{".includes(line[before])) return true;
1666
+ }
1667
+ return false;
1668
+ }
1669
+ function maskRawPemLine(line) {
1670
+ if (line.trim() === "") return line;
1671
+ const leading = /^[ \t]*(?:#|\/\/|;)?[ \t]*/.exec(line)?.[0] ?? "";
1672
+ let rest = line.slice(leading.length);
1673
+ const trailing = /[ \t]*(?:[,;\\+])?[ \t]*$/.exec(rest)?.[0] ?? "";
1674
+ rest = rest.slice(0, rest.length - trailing.length);
1675
+ return leading + (rest.length > 0 ? PEM_REDACTION_MARKER : "") + trailing;
1676
+ }
1677
+ function skeletonisePemLine(line, initialQuote) {
1678
+ const hasQuote = line.includes('"') || line.includes("'") || line.includes("`");
1679
+ const structural = initialQuote !== 0 || hasQuote && (hasStructuralQuote(line) || /-----BEGIN|-----END/.test(line));
1680
+ if (!structural) return { text: maskRawPemLine(line), quote: initialQuote };
1681
+ let out = "";
1682
+ let quote = initialQuote;
1683
+ let masking = false;
1684
+ for (let index = 0; index < line.length; index += 1) {
1685
+ const code = line.charCodeAt(index);
1686
+ if (quote === 0) {
1687
+ if (isOpeningQuote(line, index)) {
1688
+ quote = code;
1689
+ masking = false;
1690
+ }
1691
+ out += line[index];
1692
+ continue;
1693
+ }
1694
+ if (code === 92) {
1695
+ masking = false;
1696
+ out += line[index];
1697
+ if (index + 1 < line.length) {
1698
+ out += line[index + 1];
1699
+ index += 1;
1700
+ }
1701
+ continue;
1702
+ }
1703
+ if (code === quote) {
1704
+ masking = false;
1705
+ quote = 0;
1706
+ out += line[index];
1707
+ continue;
1708
+ }
1709
+ if (!masking) {
1710
+ out += PEM_REDACTION_MARKER;
1711
+ masking = true;
1712
+ }
1713
+ }
1714
+ return { text: out, quote };
1715
+ }
1716
+ function lineSpanAt(text2, start, end) {
1717
+ let lineStart = start;
1718
+ while (lineStart > 0 && text2[lineStart - 1] !== "\n" && text2[lineStart - 1] !== "\r") {
1719
+ lineStart -= 1;
1720
+ }
1721
+ let lineEnd = end;
1722
+ while (lineEnd < text2.length && text2[lineEnd] !== "\n" && text2[lineEnd] !== "\r") lineEnd += 1;
1723
+ if (lineEnd < text2.length) {
1724
+ lineEnd += text2[lineEnd] === "\r" && text2[lineEnd + 1] === "\n" ? 2 : 1;
1725
+ }
1726
+ return { start: lineStart, end: lineEnd };
1727
+ }
1728
+ function redactPemSpan(text2, matchStart, matchEnd) {
1729
+ const span = lineSpanAt(text2, matchStart, matchEnd);
1730
+ const segments = text2.slice(span.start, span.end).split(LINE_BREAK);
1731
+ let quote = quoteStateAfter(text2, 0, matchStart);
1732
+ let cursor = span.start;
1733
+ for (let index = 0; index < segments.length; index += 2) {
1734
+ const line = segments[index];
1735
+ const lineStart = cursor;
1736
+ const lineEnd = lineStart + line.length;
1737
+ cursor = lineEnd + (index + 1 < segments.length ? segments[index + 1].length : 0);
1738
+ const from = Math.max(lineStart, matchStart);
1739
+ const to = Math.min(lineEnd, matchEnd);
1740
+ if (from >= to) continue;
1741
+ const localFrom = from - lineStart;
1742
+ const localTo = to - lineStart;
1743
+ const result = skeletonisePemLine(line.slice(localFrom, localTo), quote);
1744
+ segments[index] = line.slice(0, localFrom) + result.text + line.slice(localTo);
1745
+ quote = result.quote;
1746
+ }
1747
+ return { replacement: segments.join(""), start: span.start, end: span.end };
1748
+ }
1548
1749
  var COMPILED_RULES = /* @__PURE__ */ new WeakMap();
1549
1750
  function compiledRuleFor(rule) {
1550
1751
  let compiled = COMPILED_RULES.get(rule);
@@ -1559,22 +1760,30 @@ function compiledRuleFor(rule) {
1559
1760
  return compiled;
1560
1761
  }
1561
1762
  function scanAndRedactSecrets(content, rules, filePath) {
1562
- const findings = [];
1763
+ const findingsByLine = /* @__PURE__ */ new Map();
1764
+ const recordFinding = (line, rulesForLine) => {
1765
+ let entry = findingsByLine.get(line);
1766
+ if (entry === void 0) {
1767
+ entry = /* @__PURE__ */ new Set();
1768
+ findingsByLine.set(line, entry);
1769
+ }
1770
+ for (const rule of rulesForLine) entry.add(rule);
1771
+ };
1563
1772
  let redacted = content;
1564
1773
  for (const blockPattern of [PEM_BLOCK_PATTERN, PEM_UNTERMINATED_PATTERN]) {
1565
1774
  blockPattern.lastIndex = 0;
1566
1775
  let match;
1567
1776
  while ((match = blockPattern.exec(redacted)) !== null) {
1568
1777
  if (match[0].length === 0) {
1569
- blockPattern.lastIndex += 1;
1778
+ blockPattern.lastIndex = advanceStringIndex(redacted, match.index, blockPattern.unicode);
1570
1779
  continue;
1571
1780
  }
1572
- const before = redacted.slice(0, match.index);
1573
- const line = (before.match(LINE_TERMINATOR) ?? []).length + 1;
1574
- const newlines = (match[0].match(LINE_TERMINATOR) ?? []).length;
1575
- findings.push({ rules: ["private-key-block"], line, path: filePath });
1576
- redacted = before + PEM_REDACTION_MARKER + "\n".repeat(newlines) + redacted.slice(match.index + match[0].length);
1577
- blockPattern.lastIndex = match.index + PEM_REDACTION_MARKER.length + newlines;
1781
+ const matchEnd = match.index + match[0].length;
1782
+ const line = (redacted.slice(0, match.index).match(LINE_TERMINATOR) ?? []).length + 1;
1783
+ const span = redactPemSpan(redacted, match.index, matchEnd);
1784
+ recordFinding(line, ["private-key-block"]);
1785
+ redacted = redacted.slice(0, span.start) + span.replacement + redacted.slice(span.end);
1786
+ blockPattern.lastIndex = span.start + span.replacement.length;
1578
1787
  }
1579
1788
  }
1580
1789
  const compiled = rules.map(compiledRuleFor);
@@ -1585,17 +1794,38 @@ function scanAndRedactSecrets(content, rules, filePath) {
1585
1794
  if (line.length > 0) {
1586
1795
  const spans = [];
1587
1796
  const matchedRules = /* @__PURE__ */ new Set();
1797
+ const context = {};
1588
1798
  for (const { rule, pattern, valueGroup } of compiled) {
1589
1799
  pattern.lastIndex = 0;
1590
1800
  let match;
1591
1801
  while ((match = pattern.exec(line)) !== null) {
1592
1802
  if (match[0].length === 0) {
1593
- pattern.lastIndex += 1;
1803
+ pattern.lastIndex = advanceStringIndex(line, match.index, pattern.unicode);
1594
1804
  continue;
1595
1805
  }
1596
1806
  const group = valueGroup === void 0 ? void 0 : match.indices?.[valueGroup];
1807
+ const candidate = group ? line.slice(group[0], group[1]) : line.slice(match.index, match.index + match[0].length);
1808
+ if (isPlaceholderValue(candidate)) continue;
1809
+ if (group && isUnquotedValue(line, group[0]) && isSourceCodeFile(filePath) && (quoteStateFor(line, context)[match.index] ?? 0) === 0) {
1810
+ continue;
1811
+ }
1812
+ if (group && /^\$[({A-Za-z_]/.test(line.slice(group[0], group[1])) && (isAssignmentFile(filePath) || isUnquotedValue(line, group[0]))) {
1813
+ continue;
1814
+ }
1815
+ if (rule === "credential-assignment-weak" && group) {
1816
+ let before = match.index - 1;
1817
+ while (before >= 0 && (line[before] === " " || line[before] === " ")) before -= 1;
1818
+ if (before >= 0 && (line[before] === "?" || line[before] === ":")) continue;
1819
+ const keyText = line.slice(match.index, group[0]).replace(/["'\s:=]+/g, " ").trim();
1820
+ if (/^(?:PASS|FAIL)$/i.test(keyText) && /^[A-Z]{2,}$/.test(line.slice(group[0], group[1]))) {
1821
+ continue;
1822
+ }
1823
+ }
1597
1824
  if (group && isSelfNamingConstant(line, group[0], group[1])) continue;
1598
- if (valueGroup !== void 0 && startsInsideStringLiteral(line, match.index, group?.[0])) {
1825
+ if (group && !isUnquotedValue(line, group[0]) && /["'`]\s*\+\s*|\s*\+\s*["'`]/.test(line.slice(group[0], group[1]))) {
1826
+ continue;
1827
+ }
1828
+ if (valueGroup !== void 0 && startsInsideStringLiteral(line, match.index, group?.[0], context, filePath)) {
1599
1829
  continue;
1600
1830
  }
1601
1831
  if (group && isUnquotedValue(line, group[0]) && isDeclaredBinding(line, match.index, filePath)) {
@@ -1621,7 +1851,12 @@ function scanAndRedactSecrets(content, rules, filePath) {
1621
1851
  if (wholeValue) {
1622
1852
  spans.push({
1623
1853
  start: group[0],
1624
- end: Math.max(group[1], tokenEnd(line, group[0])),
1854
+ // A passphrase contains spaces: `DB_PASSWORD=correct horse battery staple` used to
1855
+ // stop at the first one and emit the rest beside the marker. Stop at the end of
1856
+ // the value, a trailing comment, or a shell operator instead. The rule's own end
1857
+ // is not used: the colon form's value pattern includes the spaces before a
1858
+ // trailing `# comment`, and masking them welds the comment to the marker.
1859
+ end: lineValueEnd(line, group[0], context),
1625
1860
  rule
1626
1861
  });
1627
1862
  matchedRules.add(rule);
@@ -1634,14 +1869,153 @@ function scanAndRedactSecrets(content, rules, filePath) {
1634
1869
  matchedRules.add(rule);
1635
1870
  }
1636
1871
  }
1872
+ for (const span of concatenatedCredentialSpans(line)) {
1873
+ spans.push(span);
1874
+ matchedRules.add(span.rule);
1875
+ }
1637
1876
  if (spans.length > 0) {
1638
- findings.push({ rules: [...matchedRules], line: lineNumber, path: filePath });
1639
- segments[index] = applySpans(line, spans);
1877
+ const maskedLine = applySpans(line, spans);
1878
+ if (!quotesAreBalanced(line) || quotesAreBalanced(maskedLine)) {
1879
+ recordFinding(lineNumber, matchedRules);
1880
+ segments[index] = maskedLine;
1881
+ }
1640
1882
  }
1641
1883
  }
1642
1884
  if (index + 1 < segments.length) lineNumber += 1;
1643
1885
  }
1644
- return { redacted: segments.join(""), findings };
1886
+ let finalText = segments.join("");
1887
+ finalText = redactStructuredValues(finalText, filePath, recordFinding);
1888
+ finalText = redactDockerfileEnv(finalText, filePath, recordFinding);
1889
+ const findings = [...findingsByLine.entries()].sort(([left], [right]) => left - right).map(([line, rulesForLine]) => ({
1890
+ rules: [...rulesForLine],
1891
+ line,
1892
+ path: filePath
1893
+ }));
1894
+ return { redacted: finalText, findings };
1895
+ }
1896
+ function advanceStringIndex(text2, index, unicode) {
1897
+ if (!unicode) return index + 1;
1898
+ const first = text2.charCodeAt(index);
1899
+ if (first >= 55296 && first <= 56319) {
1900
+ const second = text2.charCodeAt(index + 1);
1901
+ if (second >= 56320 && second <= 57343) return index + 2;
1902
+ }
1903
+ return index + 1;
1904
+ }
1905
+ var STRUCTURED_FILE = /\.(?:json|jsonc|json5|ya?ml|toml|ini|conf|cfg|properties|env|tf|tfvars)$/i;
1906
+ var STRUCTURED_BASENAME = /^(?:\.env(?:\.[^/]*)?|docker-compose(?:\.[^/]*)?|compose(?:\.[^/]*)?)$/i;
1907
+ function isStructuredFile(filePath) {
1908
+ if (filePath === void 0) return false;
1909
+ const normalised = filePath.replace(/\\/g, "/");
1910
+ if (STRUCTURED_FILE.test(normalised)) return true;
1911
+ return STRUCTURED_BASENAME.test(normalised.slice(normalised.lastIndexOf("/") + 1));
1912
+ }
1913
+ function isDockerfile(filePath) {
1914
+ if (filePath === void 0) return false;
1915
+ const normalised = filePath.replace(/\\/g, "/");
1916
+ return /^(?:Dockerfile|[^/]*\.dockerfile)$/i.test(
1917
+ normalised.slice(normalised.lastIndexOf("/") + 1)
1918
+ );
1919
+ }
1920
+ function maskLineContent(line) {
1921
+ if (line.trim() === "") return line;
1922
+ const indent = /^[ \t]*/.exec(line)?.[0] ?? "";
1923
+ return `${indent}${REDACTION_MARKER}`;
1924
+ }
1925
+ function maskValueLine(line) {
1926
+ if (line.trim() === "") return line;
1927
+ const indent = /^[ \t]*/.exec(line)?.[0] ?? "";
1928
+ const content = line.slice(indent.length);
1929
+ const quoted = /^(["'`])(.*)\1([,;]?[ \t]*)$/.exec(content);
1930
+ if (quoted !== null) {
1931
+ return `${indent}${quoted[1]}${REDACTION_MARKER}${quoted[1]}${quoted[3] ?? ""}`;
1932
+ }
1933
+ return `${indent}${REDACTION_MARKER}`;
1934
+ }
1935
+ var STRUCTURED_KEY = /^([ \t]*)["']?([A-Za-z0-9_$.-]{1,128})["']?[ \t]*([:=])[ \t]*(.*)$/;
1936
+ var BLOCK_SCALAR = /^[|>][+-]?\d*[ \t]*(?:#.*)?$/;
1937
+ function redactStructuredValues(text2, filePath, recordFinding) {
1938
+ if (!isStructuredFile(filePath)) return text2;
1939
+ const segments = text2.split(LINE_BREAK);
1940
+ for (let index = 0; index < segments.length; index += 2) {
1941
+ const line = segments[index];
1942
+ if (line === void 0 || line.length === 0) continue;
1943
+ const match = STRUCTURED_KEY.exec(line);
1944
+ if (match === null) continue;
1945
+ const key = match[2] ?? "";
1946
+ if (!CREDENTIAL_KEY_TAIL.test(key)) continue;
1947
+ const baseIndent = (match[1] ?? "").length;
1948
+ const rest = (match[4] ?? "").trim();
1949
+ if (BLOCK_SCALAR.test(rest)) {
1950
+ let cursor2 = index + 2;
1951
+ let masked2 = false;
1952
+ while (cursor2 < segments.length) {
1953
+ const body = segments[cursor2] ?? "";
1954
+ if (body.trim() !== "") {
1955
+ const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
1956
+ if (indent <= baseIndent) break;
1957
+ segments[cursor2] = maskLineContent(body);
1958
+ masked2 = true;
1959
+ }
1960
+ cursor2 += 2;
1961
+ }
1962
+ if (masked2) recordFinding(index / 2 + 1, ["credential-block-scalar"]);
1963
+ continue;
1964
+ }
1965
+ if (rest !== "") continue;
1966
+ let cursor = index + 2;
1967
+ while (cursor < segments.length && (segments[cursor] ?? "").trim() === "") cursor += 2;
1968
+ const firstValue = segments[cursor];
1969
+ if (firstValue === void 0) continue;
1970
+ const valueIndent = (/^[ \t]*/.exec(firstValue)?.[0] ?? "").length;
1971
+ if (valueIndent <= baseIndent) continue;
1972
+ let masked = false;
1973
+ while (cursor < segments.length) {
1974
+ const body = segments[cursor] ?? "";
1975
+ if (body.trim() !== "") {
1976
+ const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
1977
+ if (indent < valueIndent) break;
1978
+ segments[cursor] = maskValueLine(body);
1979
+ masked = true;
1980
+ }
1981
+ cursor += 2;
1982
+ }
1983
+ if (masked) recordFinding(index / 2 + 1, ["credential-multiline-value"]);
1984
+ }
1985
+ return segments.join("");
1986
+ }
1987
+ var DOCKERFILE_ENV = /^([ \t]*ENV[ \t]+)([A-Za-z_][A-Za-z0-9_]*)([ \t]+)(\S.*)$/;
1988
+ function redactDockerfileEnv(text2, filePath, recordFinding) {
1989
+ if (!isDockerfile(filePath)) return text2;
1990
+ const segments = text2.split(LINE_BREAK);
1991
+ for (let index = 0; index < segments.length; index += 2) {
1992
+ const line = segments[index];
1993
+ if (line === void 0) continue;
1994
+ const match = DOCKERFILE_ENV.exec(line);
1995
+ if (match === null) continue;
1996
+ if (!CREDENTIAL_KEY_TAIL.test(match[2] ?? "")) continue;
1997
+ const value = match[4] ?? "";
1998
+ if (value.startsWith("=")) continue;
1999
+ segments[index] = `${match[1]}${match[2]}${match[3]}${REDACTION_MARKER}`;
2000
+ recordFinding(index / 2 + 1, ["dockerfile-env-secret"]);
2001
+ }
2002
+ return segments.join("");
2003
+ }
2004
+ var CONCATENATED_CREDENTIAL = new RegExp(
2005
+ "([A-Za-z0-9_$.-]{0,64}(?:password|passwd|passphrase|pwd|api[_-]?key|api[_-]?secret|access[_-]?key|secret[_-]?access[_-]?key|secret[_-]?key|client[_-]?secret[_-]?key|client[_-]?secret|private[_-]?key|access[_-]?token|refresh[_-]?token|auth[_-]?token|session[_-]?token|session[_-]?key|secret|token))\\s*=\\s*(?<=[=:]\\s{0,8})([\"'`])\\s*\\+\\s*([\"'`])((?:(?!\\3)[^\\\\\\n]|\\\\.){1,512})\\3",
2006
+ "gid"
2007
+ );
2008
+ function concatenatedCredentialSpans(line) {
2009
+ const spans = [];
2010
+ CONCATENATED_CREDENTIAL.lastIndex = 0;
2011
+ let match;
2012
+ while ((match = CONCATENATED_CREDENTIAL.exec(line)) !== null) {
2013
+ const group = match.indices?.[4];
2014
+ if (group !== void 0) {
2015
+ spans.push({ start: group[0], end: group[1], rule: "credential-concatenation" });
2016
+ }
2017
+ }
2018
+ return spans;
1645
2019
  }
1646
2020
  var TOKEN_CHARS_LEFT = /[A-Za-z0-9_+/-]/;
1647
2021
  var TOKEN_CHARS_RIGHT = /[A-Za-z0-9_+/=-]/;
@@ -1659,13 +2033,20 @@ function expandOverToken(line, start, end) {
1659
2033
  while (right < line.length && TOKEN_CHARS_RIGHT.test(line[right])) right += 1;
1660
2034
  return { start: left, end: right };
1661
2035
  }
1662
- function startsInsideStringLiteral(line, matchIndex, valueStart) {
1663
- let runStart = matchIndex;
1664
- while (runStart > 0 && /[A-Za-z0-9_-]/.test(line[runStart - 1])) runStart -= 1;
1665
- const before = runStart > 0 ? line[runStart - 1] : "";
1666
- if (before !== '"' && before !== "'" && before !== "`") return false;
2036
+ function startsInsideStringLiteral(line, matchIndex, valueStart, context, filePath) {
2037
+ const quote = quoteStateFor(line, context)[matchIndex] ?? 0;
2038
+ if (quote === 0) return false;
2039
+ if (quote === 96 && /\.(?:md|mdx)$/i.test(filePath ?? "")) return true;
1667
2040
  if (valueStart === void 0) return true;
1668
- return /["'`]/.test(line.slice(matchIndex, valueStart));
2041
+ for (let index = matchIndex; index < valueStart; index += 1) {
2042
+ const code = line.charCodeAt(index);
2043
+ if (code === 92) {
2044
+ index += 1;
2045
+ } else if (code === quote) {
2046
+ return true;
2047
+ }
2048
+ }
2049
+ return false;
1669
2050
  }
1670
2051
  function isTemplateInterpolation(line, start, end) {
1671
2052
  if (line[start] !== "$" || line[start + 1] !== "{" || line[end - 1] !== "}") {
@@ -1693,6 +2074,40 @@ function isSelfNamingConstant(line, start, end) {
1693
2074
  }
1694
2075
  return line.endsWith(value, index);
1695
2076
  }
2077
+ var SOURCE_CODE_FILE = /\.(?:[cm]?[jt]sx?)$/i;
2078
+ function isSourceCodeFile(filePath) {
2079
+ return filePath !== void 0 && SOURCE_CODE_FILE.test(filePath.replace(/\\/g, "/"));
2080
+ }
2081
+ var PLACEHOLDER_PATTERNS = [
2082
+ /^<[^>]*>?$/,
2083
+ /^\.{3,}$/,
2084
+ /^(?:x{4,}|X{4,}|\*{3,})$/,
2085
+ /^(?:replace|change)[-_ ]?me(?:[-_ ].*)?$/i,
2086
+ /^your[-_ ].*$/i,
2087
+ /^(?:example|sample)(?:[-_ ].*)?$/i
2088
+ ];
2089
+ function isPlaceholderValue(value) {
2090
+ const trimmed = value.trim().replace(/^["'`]+/, "").replace(/["'`]+$/, "");
2091
+ if (trimmed.length === 0) return false;
2092
+ if (PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(trimmed))) return true;
2093
+ return trimmed.includes("...") || /^<[^>]*$/.test(trimmed);
2094
+ }
2095
+ function quotesAreBalanced(text2) {
2096
+ let single = 0;
2097
+ let double = 0;
2098
+ let backtick = 0;
2099
+ for (let index = 0; index < text2.length; index += 1) {
2100
+ const char = text2[index];
2101
+ if (char === "\\") {
2102
+ index += 1;
2103
+ continue;
2104
+ }
2105
+ if (char === '"') double += 1;
2106
+ else if (char === "'") single += 1;
2107
+ else if (char === "`") backtick += 1;
2108
+ }
2109
+ return double % 2 === 0 && single % 2 === 0 && backtick % 2 === 0;
2110
+ }
1696
2111
  function assignmentAround(line, valueStart) {
1697
2112
  let index = valueStart;
1698
2113
  while (index > 0 && (line[index - 1] === " " || line[index - 1] === " ")) index -= 1;
@@ -1762,6 +2177,16 @@ function applySpans(line, spans) {
1762
2177
  return out;
1763
2178
  }
1764
2179
 
2180
+ // src/version.ts
2181
+ var GENERATOR_NAME = "codebase-snapshot";
2182
+ var GENERATOR_VERSION = "0.9.17";
2183
+ var SCHEMA_VERSION = "3.0.0";
2184
+ var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2185
+ function isOurGeneratorName(name) {
2186
+ if (typeof name !== "string") return false;
2187
+ return name === GENERATOR_NAME || LEGACY_GENERATOR_NAMES.includes(name);
2188
+ }
2189
+
1765
2190
  // src/scanner/files.ts
1766
2191
  function isDiscoveryMode(value) {
1767
2192
  return value === "auto" || value === "git" || value === "walk";
@@ -1771,7 +2196,7 @@ var PRESET_IGNORES = new Set(
1771
2196
  );
1772
2197
  function readLinkTarget(linkPath, fallback) {
1773
2198
  try {
1774
- return fs14__namespace.readlinkSync(linkPath);
2199
+ return fs15__namespace.readlinkSync(linkPath);
1775
2200
  } catch {
1776
2201
  return fallback;
1777
2202
  }
@@ -1786,8 +2211,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
1786
2211
  };
1787
2212
  }
1788
2213
  function isInside(root, candidate) {
1789
- const relative12 = path16__namespace.relative(root, candidate);
1790
- return relative12 === "" || !relative12.startsWith(`..${path16__namespace.sep}`) && relative12 !== ".." && !path16__namespace.isAbsolute(relative12);
2214
+ const relative14 = path16__namespace.relative(root, candidate);
2215
+ return relative14 === "" || !relative14.startsWith(`..${path16__namespace.sep}`) && relative14 !== ".." && !path16__namespace.isAbsolute(relative14);
1791
2216
  }
1792
2217
  var GIT_OUTPUT_LIMIT = 68157440;
1793
2218
  function getGitInfo(cwd, fallbackBranch = "main") {
@@ -1848,10 +2273,10 @@ var DEFAULT_IGNORED_FILES = [
1848
2273
  "bun.lockb",
1849
2274
  "composer.lock"
1850
2275
  ];
1851
- 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|\.vault-token|vault[-_]agent[-_]token|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;
1852
- var SENSITIVE_PATH = /(?:^|\/)\.(?:aws|ssh|gnupg)\/|(?:^|\/)\.docker\/config\.json$|(?:^|\/)\.kube\/config$/i;
2276
+ 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;
2277
+ var SENSITIVE_PATH = /(?:^|\/)\.(?:aws|ssh|gnupg)\/|(?:^|\/)\.docker\/config\.json$|(?:^|\/)\.kube\/config$|(?:^|\/)\.config\/gcloud\/|(?:^|\/)\.composer\/|(?:^|\/)\.terraform\/credentials\.tfrc\.json$/i;
1853
2278
  var SENSITIVE_EXT = /\.(?:pem|key|p12|pfx|jks|keystore|ppk|asc|kdbx|tfstate|tfvars)$/i;
1854
- var TEMPLATE_SUFFIX = /\.(?:example|sample|template|dist)(?=$|[.])/i;
2279
+ var TEMPLATE_SUFFIX = /^(.*)\.(?:example|sample|template|dist)(\.[A-Za-z0-9_-]+)?$/i;
1855
2280
  var BACKUP_SUFFIX = /(?:~|\.(?:bak|backup|old|orig|save|copy|swp|swo|tmp|part))$/i;
1856
2281
  function normaliseName(name) {
1857
2282
  let normalised = name.trim().replace(/[. ]+$/, "");
@@ -1867,12 +2292,16 @@ function isSensitivePath(relativePath) {
1867
2292
  const posixPath = relativePath.replace(/\\/g, "/");
1868
2293
  const raw = posixPath.split("/").pop() ?? posixPath;
1869
2294
  const base = normaliseName(raw);
1870
- if (TEMPLATE_SUFFIX.test(base)) {
1871
- const stripped = base.replace(new RegExp(TEMPLATE_SUFFIX.source, "gi"), "");
1872
- if (matchesSensitiveList(posixPath, stripped)) return false;
1873
- }
2295
+ if (templateOfCredentialFile(posixPath, base)) return false;
1874
2296
  return matchesSensitiveList(posixPath, base);
1875
2297
  }
2298
+ function templateOfCredentialFile(posixPath, base) {
2299
+ const match = TEMPLATE_SUFFIX.exec(base);
2300
+ if (match === null) return null;
2301
+ const stripped = `${match[1] ?? ""}${match[2] ?? ""}`;
2302
+ if (SENSITIVE_EXT.test(stripped)) return null;
2303
+ return matchesSensitiveList(posixPath, stripped) ? stripped : null;
2304
+ }
1876
2305
  var GLOBAL_PATTERNS = /* @__PURE__ */ new WeakMap();
1877
2306
  var GLOB_REGEX_CACHE = /* @__PURE__ */ new Map();
1878
2307
  var GITIGNORE_REGEX_CACHE = /* @__PURE__ */ new Map();
@@ -1904,7 +2333,7 @@ function findSecretInPath(relativePath, extraRules) {
1904
2333
  let match;
1905
2334
  while ((match = scan.exec(posixPath)) !== null) {
1906
2335
  if (match[0].length === 0) {
1907
- scan.lastIndex += 1;
2336
+ scan.lastIndex = advanceStringIndex(posixPath, match.index, scan.unicode);
1908
2337
  continue;
1909
2338
  }
1910
2339
  spans.push({ start: match.index, end: match.index + match[0].length });
@@ -1965,11 +2394,14 @@ function globBodyToRegExp(body, allowBraces) {
1965
2394
  if (char === "*") {
1966
2395
  if (body[i + 1] === "*") {
1967
2396
  i += 1;
1968
- if (body[i + 1] === "/") {
2397
+ const startsSegment = i - 2 < 0 || body[i - 2] === "/";
2398
+ if (startsSegment && body[i + 1] === "/") {
1969
2399
  i += 1;
1970
- out += "(?:.*/)?";
1971
- } else {
2400
+ out += "(?:[^/]+/)*";
2401
+ } else if (startsSegment && i + 1 === body.length) {
1972
2402
  out += ".*";
2403
+ } else {
2404
+ out += "[^/]*";
1973
2405
  }
1974
2406
  } else {
1975
2407
  out += "[^/]*";
@@ -2041,7 +2473,7 @@ function readGitignoreRules(dir) {
2041
2473
  const gitignorePath2 = path16__namespace.join(dir, ".gitignore");
2042
2474
  let raw;
2043
2475
  try {
2044
- raw = fs14__namespace.readFileSync(gitignorePath2, "utf8");
2476
+ raw = fs15__namespace.readFileSync(gitignorePath2, "utf8");
2045
2477
  } catch {
2046
2478
  return [];
2047
2479
  }
@@ -2214,11 +2646,50 @@ function listIgnoredPaths(cwd) {
2214
2646
  }
2215
2647
  function hasSnapshotMarker(target) {
2216
2648
  try {
2217
- return fs14__namespace.statSync(target).isDirectory() && fs14__namespace.existsSync(path16__namespace.join(target, ".codebase-snapshot"));
2649
+ return fs15__namespace.statSync(target).isDirectory() && fs15__namespace.existsSync(path16__namespace.join(target, ".codebase-snapshot"));
2218
2650
  } catch {
2219
2651
  return false;
2220
2652
  }
2221
2653
  }
2654
+ var IGNORABLE_DIRECTORY_ENTRIES = /* @__PURE__ */ new Set([".DS_Store"]);
2655
+ function isToolOwnedDirectory2(dir) {
2656
+ let raw;
2657
+ try {
2658
+ raw = fs15__namespace.readFileSync(path16__namespace.join(dir, ".codebase-snapshot"), "utf8");
2659
+ } catch {
2660
+ return false;
2661
+ }
2662
+ let parsed;
2663
+ try {
2664
+ parsed = JSON.parse(raw);
2665
+ } catch {
2666
+ return false;
2667
+ }
2668
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
2669
+ const marker2 = parsed;
2670
+ if (marker2.generator !== GENERATOR_NAME || marker2.state !== "complete" || typeof marker2.id !== "string" || !Array.isArray(marker2.files)) {
2671
+ return false;
2672
+ }
2673
+ const accounted = /* @__PURE__ */ new Set();
2674
+ for (const item of marker2.files) {
2675
+ if (!item || typeof item !== "object" || Array.isArray(item)) return false;
2676
+ const entry = item.path;
2677
+ if (typeof entry !== "string" || entry.length === 0) return false;
2678
+ const parts = entry.split("/");
2679
+ for (let depth = 1; depth <= parts.length; depth += 1) {
2680
+ accounted.add(parts.slice(0, depth).join("/"));
2681
+ }
2682
+ }
2683
+ let entries;
2684
+ try {
2685
+ entries = fs15__namespace.readdirSync(dir);
2686
+ } catch {
2687
+ return false;
2688
+ }
2689
+ return entries.every(
2690
+ (entry) => entry === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry) || accounted.has(entry)
2691
+ );
2692
+ }
2222
2693
  function makeToolOwnedDecider(cwd, toolOwnedPaths) {
2223
2694
  const markers = /* @__PURE__ */ new Map();
2224
2695
  const reservedPaths = new Set(toolOwnedPaths.filter((entry) => entry.length > 0));
@@ -2228,7 +2699,7 @@ function makeToolOwnedDecider(cwd, toolOwnedPaths) {
2228
2699
  const prefix = parts.slice(0, depth).join("/");
2229
2700
  let hasMarker = markers.get(prefix);
2230
2701
  if (hasMarker === void 0) {
2231
- hasMarker = fs14__namespace.existsSync(path16__namespace.join(cwd, prefix, ".codebase-snapshot"));
2702
+ hasMarker = isToolOwnedDirectory2(path16__namespace.join(cwd, prefix));
2232
2703
  markers.set(prefix, hasMarker);
2233
2704
  }
2234
2705
  if (hasMarker) return true;
@@ -2243,7 +2714,7 @@ function makeLinkProbe() {
2243
2714
  let known = cache.get(absolutePath);
2244
2715
  if (known === void 0) {
2245
2716
  try {
2246
- known = fs14__namespace.lstatSync(absolutePath).isSymbolicLink();
2717
+ known = fs15__namespace.lstatSync(absolutePath).isSymbolicLink();
2247
2718
  } catch {
2248
2719
  known = false;
2249
2720
  }
@@ -2256,7 +2727,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
2256
2727
  const isLink = makeLinkProbe();
2257
2728
  let rootReal = cwd;
2258
2729
  try {
2259
- rootReal = fs14__namespace.realpathSync(cwd);
2730
+ rootReal = fs15__namespace.realpathSync(cwd);
2260
2731
  } catch {
2261
2732
  }
2262
2733
  const reported = /* @__PURE__ */ new Set();
@@ -2284,7 +2755,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
2284
2755
  const rawTarget = readLinkTarget(absolute, absolute);
2285
2756
  let targetReal = null;
2286
2757
  try {
2287
- targetReal = fs14__namespace.realpathSync(absolute);
2758
+ targetReal = fs15__namespace.realpathSync(absolute);
2288
2759
  } catch {
2289
2760
  targetReal = null;
2290
2761
  }
@@ -2302,7 +2773,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
2302
2773
  }
2303
2774
  let stats = null;
2304
2775
  try {
2305
- stats = fs14__namespace.statSync(absolute);
2776
+ stats = fs15__namespace.statSync(absolute);
2306
2777
  } catch {
2307
2778
  stats = null;
2308
2779
  }
@@ -2390,7 +2861,7 @@ function collectFiles(cwd, options = {}) {
2390
2861
  "Discovery mode is `git`, but git could not list this directory's files. Run inside a working repository, or pass --discovery walk (or auto) to scan the tree directly."
2391
2862
  );
2392
2863
  }
2393
- if (fs14__namespace.existsSync(path16__namespace.join(cwd, ".git"))) {
2864
+ if (fs15__namespace.existsSync(path16__namespace.join(cwd, ".git"))) {
2394
2865
  throw new Error(
2395
2866
  "This directory is a git repository, but git could not list its files. A plain walk honours .gitignore files, but git also applies .git/info/exclude and your global excludes file, includes files that are tracked although a .gitignore now matches them, and treats a submodule as a single entry. Fix the repository (git status should work), run outside git, or pass --discovery walk to accept those differences."
2396
2867
  );
@@ -2400,6 +2871,15 @@ function collectFiles(cwd, options = {}) {
2400
2871
  for (const record of walked.skipped) skipped.push(record);
2401
2872
  }
2402
2873
  }
2874
+ const extraPaths = (options.extraPaths ?? []).map((entry) => entry.replace(/\\/g, "/"));
2875
+ if (extraPaths.length > 0) {
2876
+ const known = new Set(candidates);
2877
+ for (const extra of extraPaths) {
2878
+ if (extra.length === 0 || known.has(extra)) continue;
2879
+ known.add(extra);
2880
+ candidates.push(extra);
2881
+ }
2882
+ }
2403
2883
  const files = candidates.filter((file) => {
2404
2884
  if (isToolOwned(file)) return false;
2405
2885
  const ignored = defaultIgnoreReason(file, toolDirNames);
@@ -2449,7 +2929,7 @@ function collectFiles(cwd, options = {}) {
2449
2929
  }
2450
2930
  function rootRealFor(root) {
2451
2931
  try {
2452
- return fs14__namespace.realpathSync(root);
2932
+ return fs15__namespace.realpathSync(root);
2453
2933
  } catch {
2454
2934
  return root;
2455
2935
  }
@@ -2469,7 +2949,7 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
2469
2949
  ];
2470
2950
  let entries;
2471
2951
  try {
2472
- entries = fs14__namespace.readdirSync(current, { withFileTypes: true });
2952
+ entries = fs15__namespace.readdirSync(current, { withFileTypes: true });
2473
2953
  } catch {
2474
2954
  results.skipped.push({
2475
2955
  path: relativeToBase(current),
@@ -2525,14 +3005,14 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
2525
3005
  if (entry.isSymbolicLink()) {
2526
3006
  let targetReal;
2527
3007
  try {
2528
- targetReal = fs14__namespace.realpathSync(fullPath);
3008
+ targetReal = fs15__namespace.realpathSync(fullPath);
2529
3009
  } catch {
2530
3010
  results.skipped.push(brokenLinkRecord(fullPath, relPath, rootReal));
2531
3011
  continue;
2532
3012
  }
2533
3013
  let stats;
2534
3014
  try {
2535
- stats = fs14__namespace.statSync(fullPath);
3015
+ stats = fs15__namespace.statSync(fullPath);
2536
3016
  } catch {
2537
3017
  results.skipped.push({ path: relPath, reason: "read-error", detail: "unreadable symlink" });
2538
3018
  continue;
@@ -2562,6 +3042,15 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
2562
3042
  });
2563
3043
  continue;
2564
3044
  }
3045
+ const targetRelative = path16__namespace.relative(rootReal, targetReal).split(path16__namespace.sep).join("/");
3046
+ if (isSensitivePath(targetRelative)) {
3047
+ results.skipped.push({
3048
+ path: relPath,
3049
+ reason: "sensitive-file",
3050
+ detail: "link target is a credential-bearing file; not followed"
3051
+ });
3052
+ continue;
3053
+ }
2565
3054
  isDirectory = false;
2566
3055
  isFile = true;
2567
3056
  }
@@ -2610,12 +3099,19 @@ var CONFIG_FILENAMES = [
2610
3099
  function findConfigFile(cwd) {
2611
3100
  for (const filename of CONFIG_FILENAMES) {
2612
3101
  const fullPath = path16__namespace.join(cwd, filename);
2613
- if (fs14__namespace.existsSync(fullPath)) return fullPath;
3102
+ let stats = null;
3103
+ try {
3104
+ stats = fs15__namespace.statSync(fullPath);
3105
+ } catch {
3106
+ if (fs15__namespace.existsSync(fullPath)) return fullPath;
3107
+ continue;
3108
+ }
3109
+ if (stats.isFile()) return fullPath;
2614
3110
  }
2615
3111
  const pkgJsonPath = path16__namespace.join(cwd, "package.json");
2616
- if (!fs14__namespace.existsSync(pkgJsonPath)) return null;
3112
+ if (!fs15__namespace.existsSync(pkgJsonPath)) return null;
2617
3113
  try {
2618
- const parsed = JSON.parse(stripJsonComments(fs14__namespace.readFileSync(pkgJsonPath, "utf8")));
3114
+ const parsed = JSON.parse(stripJsonComments(fs15__namespace.readFileSync(pkgJsonPath, "utf8")));
2619
3115
  const snapshot = parsed?.snapshot;
2620
3116
  return typeof snapshot === "object" && snapshot !== null && !Array.isArray(snapshot) ? pkgJsonPath : null;
2621
3117
  } catch {
@@ -2876,17 +3372,34 @@ function readConfigExport(exported, file) {
2876
3372
  assertKnownConfigKeys(exported, file);
2877
3373
  return exported;
2878
3374
  }
2879
- var moduleConfigLoadToken = 0;
3375
+ var lastModuleConfig = null;
3376
+ function moduleConfigKey(fullPath) {
3377
+ try {
3378
+ return crypto3.createHash("sha256").update(fs15__namespace.readFileSync(fullPath)).digest("hex").slice(0, 24);
3379
+ } catch {
3380
+ try {
3381
+ const stats = fs15__namespace.statSync(fullPath);
3382
+ return `stat-${stats.mtimeMs}-${stats.size}`;
3383
+ } catch {
3384
+ return "unreadable";
3385
+ }
3386
+ }
3387
+ }
2880
3388
  async function importConfigModule(fullPath) {
3389
+ const key = moduleConfigKey(fullPath);
3390
+ if (lastModuleConfig !== null && lastModuleConfig.path === fullPath && lastModuleConfig.key === key) {
3391
+ return lastModuleConfig.exports;
3392
+ }
2881
3393
  try {
2882
3394
  const requireFromConfig = module$1.createRequire(fullPath);
2883
3395
  delete requireFromConfig.cache[requireFromConfig.resolve(fullPath)];
2884
3396
  } catch {
2885
3397
  }
2886
3398
  const url$1 = url.pathToFileURL(fullPath);
2887
- moduleConfigLoadToken += 1;
2888
- url$1.searchParams.set("codebaseSnapshotLoad", String(moduleConfigLoadToken));
2889
- return await import(url$1.href);
3399
+ url$1.searchParams.set("codebaseSnapshotLoad", key);
3400
+ const loaded = await import(url$1.href);
3401
+ lastModuleConfig = { path: fullPath, key, exports: loaded };
3402
+ return loaded;
2890
3403
  }
2891
3404
  function attachConfigDir(config, filePath) {
2892
3405
  if (typeof config === "object" && config !== null) {
@@ -2898,15 +3411,25 @@ function attachConfigDir(config, filePath) {
2898
3411
  }
2899
3412
  return config;
2900
3413
  }
2901
- async function loadConfigFileDetailed(cwd) {
3414
+ async function loadConfigFileDetailed(cwd, options = {}) {
2902
3415
  const warnings = [];
2903
3416
  const errors = [];
3417
+ const configDirectories = [];
2904
3418
  for (const filename of CONFIG_FILENAMES) {
2905
3419
  const fullPath = path16__namespace.join(cwd, filename);
2906
- if (!fs14__namespace.existsSync(fullPath)) continue;
3420
+ let candidateStats = null;
3421
+ try {
3422
+ candidateStats = fs15__namespace.statSync(fullPath);
3423
+ } catch {
3424
+ if (!fs15__namespace.existsSync(fullPath)) continue;
3425
+ }
3426
+ if (candidateStats !== null && !candidateStats.isFile()) {
3427
+ configDirectories.push(fullPath);
3428
+ continue;
3429
+ }
2907
3430
  if (filename.endsWith(".json") || filename === ".snapshotrc") {
2908
3431
  try {
2909
- const config = parseJsonish(fs14__namespace.readFileSync(fullPath, "utf8"), fullPath);
3432
+ const config = parseJsonish(fs15__namespace.readFileSync(fullPath, "utf8"), fullPath);
2910
3433
  if (config === null || typeof config !== "object" || Array.isArray(config)) {
2911
3434
  throw new Error(
2912
3435
  `${fullPath} does not hold a configuration object (received ${describeValue2(config)}).`
@@ -2922,6 +3445,12 @@ async function loadConfigFileDetailed(cwd) {
2922
3445
  continue;
2923
3446
  }
2924
3447
  }
3448
+ if (options.allowExecutableConfig === false) {
3449
+ const message = `${fullPath} was not loaded: it is an executable config, and this server does not run repository code. Export the same settings from snapshot.config.json instead.`;
3450
+ warnings.push(message);
3451
+ errors.push(message);
3452
+ continue;
3453
+ }
2925
3454
  if (filename.endsWith(".ts") && !supportsTypeScriptImports()) {
2926
3455
  warnings.push(
2927
3456
  `${fullPath} was ignored: loading a .ts config needs Node >= 22.6 (running ${process.versions.node}). Use snapshot.config.mjs, .cjs or .json instead.`
@@ -2941,9 +3470,9 @@ async function loadConfigFileDetailed(cwd) {
2941
3470
  }
2942
3471
  }
2943
3472
  const pkgJsonPath = path16__namespace.join(cwd, "package.json");
2944
- if (fs14__namespace.existsSync(pkgJsonPath)) {
3473
+ if (fs15__namespace.existsSync(pkgJsonPath)) {
2945
3474
  try {
2946
- const parsed = parseJsonish(fs14__namespace.readFileSync(pkgJsonPath, "utf8"), pkgJsonPath);
3475
+ const parsed = parseJsonish(fs15__namespace.readFileSync(pkgJsonPath, "utf8"), pkgJsonPath);
2947
3476
  const snapshotKey = parsed.snapshot;
2948
3477
  if (snapshotKey && typeof snapshotKey === "object" && !Array.isArray(snapshotKey)) {
2949
3478
  assertKnownConfigKeys(
@@ -2969,6 +3498,11 @@ async function loadConfigFileDetailed(cwd) {
2969
3498
  errors.push(message);
2970
3499
  }
2971
3500
  }
3501
+ if (configDirectories.length > 0) {
3502
+ warnings.push(
3503
+ `${configDirectories.join(", ")} ${configDirectories.length === 1 ? "is a directory" : "are directories"}, not a configuration file; no configuration was read from ${configDirectories.length === 1 ? "it" : "them"}.`
3504
+ );
3505
+ }
2972
3506
  return { config: null, file: null, warnings, errors };
2973
3507
  }
2974
3508
  var MIN_MAX_PART_BYTES = 4096;
@@ -3137,11 +3671,11 @@ function outputExcludePatterns(cwd, outDir, tmpDir) {
3137
3671
  const patterns = [];
3138
3672
  for (const dir of [outDir, tmpDir]) {
3139
3673
  const absolute = path16__namespace.resolve(cwd, dir);
3140
- const relative12 = path16__namespace.relative(cwd, absolute);
3141
- if (!relative12 || relative12 === ".." || relative12.startsWith(`..${path16__namespace.sep}`) || path16__namespace.isAbsolute(relative12)) {
3674
+ const relative14 = path16__namespace.relative(cwd, absolute);
3675
+ if (!relative14 || relative14 === ".." || relative14.startsWith(`..${path16__namespace.sep}`) || path16__namespace.isAbsolute(relative14)) {
3142
3676
  continue;
3143
3677
  }
3144
- patterns.push(`${relative12.replace(/\\/g, "/")}/**`);
3678
+ patterns.push(`${relative14.replace(/\\/g, "/")}/**`);
3145
3679
  }
3146
3680
  return patterns;
3147
3681
  }
@@ -3272,10 +3806,10 @@ function resolveCandidateCwd(userConfig, cliOptions, baseDir) {
3272
3806
  }
3273
3807
  const candidate = cliOptions?.cwd || userConfig?.cwd || baseDir || process.cwd();
3274
3808
  const resolved = path16__namespace.resolve(candidate);
3275
- if (!fs14__namespace.existsSync(resolved)) {
3809
+ if (!fs15__namespace.existsSync(resolved)) {
3276
3810
  throw new Error(`Working directory does not exist: ${resolved}`);
3277
3811
  }
3278
- if (!fs14__namespace.statSync(resolved).isDirectory()) {
3812
+ if (!fs15__namespace.statSync(resolved).isDirectory()) {
3279
3813
  throw new Error(`Working directory is not a directory: ${resolved}`);
3280
3814
  }
3281
3815
  return resolved;
@@ -3525,6 +4059,13 @@ function configDigest(config) {
3525
4059
  // moving `{ name: "api", match: "src/api/**" }` to `"src/v2/**"` produced the same
3526
4060
  // digest, so `validate` reported "valid and up to date" for a snapshot whose files
3527
4061
  // had all been reclassified — and per-layer budgets applied to different files.
4062
+ // A function matcher's `String()` is its source, not its closure: two functions with the same
4063
+ // body but different captured values digest identically. That cannot be fixed by hashing, so
4064
+ // the digest records that executable matchers are present and `validate` says the digest does
4065
+ // not cover their closure, instead of claiming a equality it cannot prove.
4066
+ executableMatchers: [...config.layers, ...config.kinds].some(
4067
+ (rule) => typeof rule.match === "function"
4068
+ ),
3528
4069
  layers: config.layers.map((layer2) => ({ name: layer2.name, match: String(layer2.match) })),
3529
4070
  kinds: config.kinds.map((kind) => ({ kind: kind.kind, match: String(kind.match) })),
3530
4071
  // How files are enumerated decides what is in the snapshot at all.
@@ -3553,7 +4094,18 @@ function gitPaths(cwd, args) {
3553
4094
  `Could not list changed files (git ${args.join(" ")}): ${reason}. A changed-files snapshot needs a git working tree and a ref that exists; run \`codebase-snapshot generate\` without --changed-since to scan everything.`
3554
4095
  );
3555
4096
  }
3556
- return output.split("\0").map((entry) => entry.trim().replace(/\\/g, "/")).filter((entry) => entry.length > 0);
4097
+ return output.split("\0").filter((entry) => entry.length > 0);
4098
+ }
4099
+ function readStagedBlob(cwd, relativePath) {
4100
+ try {
4101
+ return childProcess.execFileSync("git", ["cat-file", "blob", `:${relativePath}`], {
4102
+ cwd,
4103
+ stdio: ["ignore", "pipe", "pipe"],
4104
+ maxBuffer: 512 * 1024 * 1024
4105
+ });
4106
+ } catch {
4107
+ return null;
4108
+ }
3557
4109
  }
3558
4110
  function assertUsableRef(ref) {
3559
4111
  if (ref.startsWith("-")) {
@@ -3564,6 +4116,8 @@ function assertUsableRef(ref) {
3564
4116
  }
3565
4117
  function resolveChangedScope(cwd, request) {
3566
4118
  const paths = /* @__PURE__ */ new Set();
4119
+ const stagedPaths = /* @__PURE__ */ new Set();
4120
+ const deletedPaths = /* @__PURE__ */ new Set();
3567
4121
  const descriptions = [];
3568
4122
  if (request.changedSince !== void 0) {
3569
4123
  assertUsableRef(request.changedSince);
@@ -3572,7 +4126,17 @@ function resolveChangedScope(cwd, request) {
3572
4126
  "--name-only",
3573
4127
  "-z",
3574
4128
  "--relative",
3575
- request.changedSince,
4129
+ `${request.changedSince}...HEAD`,
4130
+ "--"
4131
+ ])) {
4132
+ paths.add(path22);
4133
+ }
4134
+ for (const path22 of gitPaths(cwd, [
4135
+ "diff",
4136
+ "--name-only",
4137
+ "-z",
4138
+ "--relative",
4139
+ "HEAD",
3576
4140
  "--"
3577
4141
  ])) {
3578
4142
  paths.add(path22);
@@ -3592,10 +4156,22 @@ function resolveChangedScope(cwd, request) {
3592
4156
  "--"
3593
4157
  ])) {
3594
4158
  paths.add(path22);
4159
+ stagedPaths.add(path22);
4160
+ }
4161
+ for (const path22 of gitPaths(cwd, [
4162
+ "diff",
4163
+ "--cached",
4164
+ "--name-only",
4165
+ "-z",
4166
+ "--relative",
4167
+ "--diff-filter=D",
4168
+ "--"
4169
+ ])) {
4170
+ deletedPaths.add(path22);
3595
4171
  }
3596
4172
  descriptions.push("staged");
3597
4173
  }
3598
- return { paths, detail: descriptions.join(" and ") };
4174
+ return { paths, stagedPaths, deletedPaths, detail: descriptions.join(" and ") };
3599
4175
  }
3600
4176
  var RELATIVE_SPECIFIER = /^\.{1,2}\//;
3601
4177
  var IMPORT_CANDIDATE_SUFFIXES = [
@@ -3626,34 +4202,88 @@ var PYTHON_EXTENSIONS = /* @__PURE__ */ new Set([".py", ".pyi"]);
3626
4202
  var RUBY_EXTENSIONS = /* @__PURE__ */ new Set([".rb", ".rake", ".gemspec"]);
3627
4203
  var C_EXTENSIONS = /* @__PURE__ */ new Set([".c", ".h", ".cc", ".cpp", ".cxx", ".hpp", ".hxx", ".m", ".mm"]);
3628
4204
  var PYTHON_SUFFIXES = [".py", ".pyi", "/__init__.py", "/__init__.pyi"];
3629
- function buildImportResolver(files) {
4205
+ var CASE_INSENSITIVE_FILESYSTEM = process.platform === "win32" || process.platform === "darwin";
4206
+ var TSCONFIG_CACHE = /* @__PURE__ */ new Map();
4207
+ function tsconfigPathsFor(cwd) {
4208
+ const configPath = path16__namespace.join(cwd, "tsconfig.json");
4209
+ let stats;
4210
+ try {
4211
+ stats = fs15__namespace.statSync(configPath);
4212
+ } catch (err) {
4213
+ if (err.code === "ENOENT") return null;
4214
+ return null;
4215
+ }
4216
+ const key = `${stats.mtimeMs}:${stats.size}`;
4217
+ const cached = TSCONFIG_CACHE.get(configPath);
4218
+ if (cached !== void 0 && cached.key === key) return cached.value;
4219
+ let value = null;
4220
+ try {
4221
+ const read = ts2__default.default.readConfigFile(configPath, ts2__default.default.sys.readFile);
4222
+ if (read.error === void 0) {
4223
+ const parsed = ts2__default.default.parseJsonConfigFileContent(read.config, ts2__default.default.sys, cwd, void 0, configPath);
4224
+ const options = parsed.options;
4225
+ const baseUrl = typeof options.baseUrl === "string" ? repositoryRelative(cwd, options.baseUrl) : null;
4226
+ const rules = [];
4227
+ if (options.paths !== void 0) {
4228
+ for (const [pattern, targets] of Object.entries(options.paths)) {
4229
+ if (!Array.isArray(targets)) continue;
4230
+ rules.push({
4231
+ pattern,
4232
+ targets: targets.map((target) => String(target).replace(/\\/g, "/"))
4233
+ });
4234
+ }
4235
+ }
4236
+ if (baseUrl !== null || rules.length > 0) value = { baseUrl, paths: rules };
4237
+ }
4238
+ } catch (err) {
4239
+ value = null;
4240
+ }
4241
+ TSCONFIG_CACHE.set(configPath, { key, value });
4242
+ return value;
4243
+ }
4244
+ function repositoryRelative(cwd, target) {
4245
+ const relative14 = path16__namespace.relative(cwd, target).replace(/\\/g, "/");
4246
+ return relative14.length === 0 || !relative14.startsWith("..") && !path16__namespace.isAbsolute(relative14) ? relative14 : null;
4247
+ }
4248
+ function rememberFirst(map, key, value) {
4249
+ if (!map.has(key)) map.set(key, value);
4250
+ }
4251
+ function buildImportResolver(files, options = {}) {
3630
4252
  const byPath = /* @__PURE__ */ new Map();
3631
4253
  const byPathFolded = /* @__PURE__ */ new Map();
3632
4254
  const byStem = /* @__PURE__ */ new Map();
3633
4255
  const byStemFolded = /* @__PURE__ */ new Map();
3634
- const remember = (map, key, value) => {
3635
- if (!map.has(key)) map.set(key, value);
3636
- };
3637
- for (const file of files) {
3638
- const relativePath = file.relativePath;
3639
- remember(byPath, relativePath, relativePath);
3640
- remember(byPathFolded, relativePath.toLowerCase(), relativePath);
4256
+ const register = (relativePath) => {
4257
+ rememberFirst(byPath, relativePath, relativePath);
4258
+ if (CASE_INSENSITIVE_FILESYSTEM) {
4259
+ rememberFirst(byPathFolded, relativePath.toLowerCase(), relativePath);
4260
+ }
3641
4261
  const extension = path16__namespace.posix.extname(relativePath);
3642
- if (!SOURCE_EXTENSIONS.has(extension)) continue;
4262
+ if (!SOURCE_EXTENSIONS.has(extension)) return;
3643
4263
  const stem = relativePath.slice(0, -extension.length);
3644
- remember(byStem, stem, relativePath);
3645
- remember(byStemFolded, stem.toLowerCase(), relativePath);
4264
+ rememberFirst(byStem, stem, relativePath);
4265
+ if (CASE_INSENSITIVE_FILESYSTEM) {
4266
+ rememberFirst(byStemFolded, stem.toLowerCase(), relativePath);
4267
+ }
3646
4268
  if (path16__namespace.posix.basename(stem) === "index") {
3647
4269
  const directory = path16__namespace.posix.dirname(stem);
3648
- remember(byStem, directory, relativePath);
3649
- remember(byStemFolded, directory.toLowerCase(), relativePath);
4270
+ rememberFirst(byStem, directory, relativePath);
4271
+ if (CASE_INSENSITIVE_FILESYSTEM) {
4272
+ rememberFirst(byStemFolded, directory.toLowerCase(), relativePath);
4273
+ }
4274
+ }
4275
+ };
4276
+ for (const file of files) register(file.relativePath);
4277
+ if (options.extraPaths !== void 0) {
4278
+ for (const extra of options.extraPaths) {
4279
+ if (!byPath.has(extra)) register(extra);
3650
4280
  }
3651
4281
  }
3652
- return { byPath, byPathFolded, byStem, byStemFolded };
4282
+ return { byPath, byPathFolded, byStem, byStemFolded, tsconfig: options.tsconfig ?? null };
3653
4283
  }
3654
4284
  function resolveSpecifier(fromFile, specifier, resolver) {
3655
4285
  const extension = path16__namespace.posix.extname(fromFile).toLowerCase();
3656
- const exact = (key) => resolver.byPath.get(key) ?? resolver.byPathFolded.get(key.toLowerCase()) ?? null;
4286
+ const exact = (key) => resolver.byPath.get(key) ?? (CASE_INSENSITIVE_FILESYSTEM ? resolver.byPathFolded.get(key.toLowerCase()) : void 0) ?? null;
3657
4287
  const firstOf = (candidates) => {
3658
4288
  for (const candidate of candidates) {
3659
4289
  const hit = exact(candidate);
@@ -3661,6 +4291,17 @@ function resolveSpecifier(fromFile, specifier, resolver) {
3661
4291
  }
3662
4292
  return null;
3663
4293
  };
4294
+ const lookupPath = (joined2) => {
4295
+ const direct = exact(joined2);
4296
+ if (direct) return direct;
4297
+ for (const suffix of IMPORT_CANDIDATE_SUFFIXES) {
4298
+ const hit = exact(`${joined2}${suffix}`);
4299
+ if (hit) return hit;
4300
+ }
4301
+ const stem = joined2.replace(/\.(?:js|mjs|cjs|jsx)$/, "");
4302
+ const byStem = (key) => resolver.byStem.get(key) ?? (CASE_INSENSITIVE_FILESYSTEM ? resolver.byStemFolded.get(key.toLowerCase()) : void 0) ?? null;
4303
+ return byStem(joined2) ?? byStem(stem);
4304
+ };
3664
4305
  if (PYTHON_EXTENSIONS.has(extension) && specifier.startsWith(".")) {
3665
4306
  const dots = /^\.+/.exec(specifier)?.[0].length ?? 0;
3666
4307
  const rest = specifier.slice(dots).replace(/\./g, "/");
@@ -3687,19 +4328,43 @@ function resolveSpecifier(fromFile, specifier, resolver) {
3687
4328
  );
3688
4329
  return firstOf([joined2, `${joined2}.dart`]);
3689
4330
  }
3690
- if (!RELATIVE_SPECIFIER.test(specifier)) return null;
4331
+ if (!RELATIVE_SPECIFIER.test(specifier)) {
4332
+ return resolveTsconfigSpecifier(specifier, resolver, lookupPath);
4333
+ }
3691
4334
  const joined = path16__namespace.posix.normalize(
3692
4335
  path16__namespace.posix.join(path16__namespace.posix.dirname(fromFile), specifier)
3693
4336
  );
3694
- const direct = exact(joined);
3695
- if (direct) return direct;
3696
- for (const suffix of IMPORT_CANDIDATE_SUFFIXES) {
3697
- const hit = exact(`${joined}${suffix}`);
3698
- if (hit) return hit;
4337
+ return lookupPath(joined);
4338
+ }
4339
+ function resolveTsconfigSpecifier(specifier, resolver, lookupPath) {
4340
+ const config = resolver.tsconfig;
4341
+ if (!config) return null;
4342
+ for (const rule of config.paths) {
4343
+ const star = rule.pattern.indexOf("*");
4344
+ let captured;
4345
+ if (star === -1) {
4346
+ captured = specifier === rule.pattern ? "" : null;
4347
+ } else {
4348
+ const prefix = rule.pattern.slice(0, star);
4349
+ const suffix = rule.pattern.slice(star + 1);
4350
+ if (specifier.length < prefix.length + suffix.length || !specifier.startsWith(prefix) || !specifier.endsWith(suffix)) {
4351
+ captured = null;
4352
+ } else {
4353
+ captured = specifier.slice(prefix.length, specifier.length - suffix.length);
4354
+ }
4355
+ }
4356
+ if (captured === null) continue;
4357
+ for (const target of rule.targets) {
4358
+ const substituted = target.split("*").join(captured);
4359
+ const base = config.baseUrl === null ? substituted : path16__namespace.posix.join(config.baseUrl, substituted);
4360
+ const hit = lookupPath(path16__namespace.posix.normalize(base));
4361
+ if (hit) return hit;
4362
+ }
4363
+ }
4364
+ if (config.baseUrl !== null) {
4365
+ return lookupPath(path16__namespace.posix.normalize(path16__namespace.posix.join(config.baseUrl, specifier)));
3699
4366
  }
3700
- const stem = joined.replace(/\.(?:js|mjs|cjs|jsx)$/, "");
3701
- const byStem = (key) => resolver.byStem.get(key) ?? resolver.byStemFolded.get(key.toLowerCase()) ?? null;
3702
- return byStem(joined) ?? byStem(stem);
4367
+ return null;
3703
4368
  }
3704
4369
  function importsChangedFile(importerPath, imports, changedPaths, resolver) {
3705
4370
  for (const specifier of imports) {
@@ -3717,16 +4382,73 @@ var ROUTE_HANDLER_NAMES = /* @__PURE__ */ new Set([
3717
4382
  "HEAD",
3718
4383
  "OPTIONS"
3719
4384
  ]);
4385
+ var ROUTE_RECEIVERS = /* @__PURE__ */ new Set(["app", "router", "server", "fastify", "api", "route"]);
4386
+ var ROUTE_REGISTRATION_VERBS = /* @__PURE__ */ new Set([
4387
+ "get",
4388
+ "post",
4389
+ "put",
4390
+ "delete",
4391
+ "patch",
4392
+ "head",
4393
+ "options"
4394
+ ]);
3720
4395
  function bindingNames(name, into) {
3721
- if (ts__default.default.isIdentifier(name)) {
4396
+ if (ts2__default.default.isIdentifier(name)) {
3722
4397
  into.push(name.text);
3723
4398
  return;
3724
4399
  }
3725
4400
  for (const element of name.elements) {
3726
- if (ts__default.default.isOmittedExpression(element)) continue;
4401
+ if (ts2__default.default.isOmittedExpression(element)) continue;
3727
4402
  bindingNames(element.name, into);
3728
4403
  }
3729
4404
  }
4405
+ function objectLiteralNames(node) {
4406
+ const names = [];
4407
+ for (const property of node.properties) {
4408
+ if (ts2__default.default.isShorthandPropertyAssignment(property)) {
4409
+ names.push(property.name.text);
4410
+ continue;
4411
+ }
4412
+ if (!ts2__default.default.isPropertyAssignment(property)) continue;
4413
+ const name = property.name;
4414
+ if (ts2__default.default.isIdentifier(name) || ts2__default.default.isStringLiteral(name) || ts2__default.default.isNumericLiteral(name)) {
4415
+ names.push(name.text);
4416
+ }
4417
+ }
4418
+ return names;
4419
+ }
4420
+ function cjsExportedNames(expression) {
4421
+ const left = expression.left;
4422
+ if (!ts2__default.default.isPropertyAccessExpression(left)) return null;
4423
+ const isModuleExports = left.name.text === "exports" && ts2__default.default.isIdentifier(left.expression) && left.expression.text === "module";
4424
+ if (isModuleExports) {
4425
+ const right = expression.right;
4426
+ if (ts2__default.default.isObjectLiteralExpression(right)) return objectLiteralNames(right);
4427
+ if (ts2__default.default.isIdentifier(right)) return [right.text];
4428
+ return [];
4429
+ }
4430
+ if (ts2__default.default.isIdentifier(left.expression) && left.expression.text === "exports") {
4431
+ return [left.name.text];
4432
+ }
4433
+ const parent = left.expression;
4434
+ if (ts2__default.default.isPropertyAccessExpression(parent) && parent.name.text === "exports" && ts2__default.default.isIdentifier(parent.expression) && parent.expression.text === "module") {
4435
+ return [left.name.text];
4436
+ }
4437
+ return null;
4438
+ }
4439
+ function countSyntacticErrors(fileName, content) {
4440
+ const result = ts2__default.default.transpileModule(content, {
4441
+ fileName,
4442
+ compilerOptions: {
4443
+ target: ts2__default.default.ScriptTarget.Latest,
4444
+ module: ts2__default.default.ModuleKind.ESNext
4445
+ },
4446
+ reportDiagnostics: true
4447
+ });
4448
+ return (result.diagnostics ?? []).filter(
4449
+ (diagnostic) => diagnostic.category === ts2__default.default.DiagnosticCategory.Error
4450
+ ).length;
4451
+ }
3730
4452
  function summarizeTypeScriptSource(relativePath, content) {
3731
4453
  const summary = {
3732
4454
  directives: [],
@@ -3744,19 +4466,20 @@ function summarizeTypeScriptSource(relativePath, content) {
3744
4466
  routeHandlers: []
3745
4467
  };
3746
4468
  const lowerPath = relativePath.toLowerCase();
3747
- const isJsx = lowerPath.endsWith(".tsx") || lowerPath.endsWith(".jsx");
3748
- const sourceFile = ts__default.default.createSourceFile(
4469
+ const scriptKind = /.tsx$/.test(lowerPath) ? ts2__default.default.ScriptKind.TSX : /.jsx$/.test(lowerPath) ? ts2__default.default.ScriptKind.JSX : /.(?:js|mjs|cjs)$/.test(lowerPath) ? ts2__default.default.ScriptKind.JS : ts2__default.default.ScriptKind.TS;
4470
+ const sourceFile = ts2__default.default.createSourceFile(
3749
4471
  relativePath,
3750
4472
  content,
3751
- ts__default.default.ScriptTarget.Latest,
4473
+ ts2__default.default.ScriptTarget.Latest,
3752
4474
  /* setParentNodes */
3753
4475
  false,
3754
- isJsx ? ts__default.default.ScriptKind.TSX : ts__default.default.ScriptKind.TS
4476
+ scriptKind
3755
4477
  );
3756
- const parseErrors = sourceFile.parseDiagnostics?.length ?? 0;
4478
+ const parsedDiagnostics = sourceFile.parseDiagnostics;
4479
+ const parseErrors = Array.isArray(parsedDiagnostics) ? parsedDiagnostics.filter((diagnostic) => diagnostic.category === ts2__default.default.DiagnosticCategory.Error).length : countSyntacticErrors(relativePath, content);
3757
4480
  if (parseErrors > 0) summary.parseErrors = parseErrors;
3758
4481
  for (const statement of sourceFile.statements) {
3759
- if (ts__default.default.isExpressionStatement(statement) && ts__default.default.isStringLiteral(statement.expression)) {
4482
+ if (ts2__default.default.isExpressionStatement(statement) && ts2__default.default.isStringLiteral(statement.expression)) {
3760
4483
  const text2 = statement.expression.text;
3761
4484
  if (text2 === "use client" || text2 === "use server") {
3762
4485
  summary.directives.push(text2);
@@ -3766,26 +4489,26 @@ function summarizeTypeScriptSource(relativePath, content) {
3766
4489
  break;
3767
4490
  }
3768
4491
  const isExported = (node) => {
3769
- const modifiers = ts__default.default.canHaveModifiers(node) ? ts__default.default.getModifiers(node) : void 0;
3770
- return Boolean(modifiers?.some((m) => m.kind === ts__default.default.SyntaxKind.ExportKeyword));
4492
+ const modifiers = ts2__default.default.canHaveModifiers(node) ? ts2__default.default.getModifiers(node) : void 0;
4493
+ return Boolean(modifiers?.some((m) => m.kind === ts2__default.default.SyntaxKind.ExportKeyword));
3771
4494
  };
3772
4495
  const isDefault = (node) => {
3773
- const modifiers = ts__default.default.canHaveModifiers(node) ? ts__default.default.getModifiers(node) : void 0;
3774
- return Boolean(modifiers?.some((m) => m.kind === ts__default.default.SyntaxKind.DefaultKeyword));
4496
+ const modifiers = ts2__default.default.canHaveModifiers(node) ? ts2__default.default.getModifiers(node) : void 0;
4497
+ return Boolean(modifiers?.some((m) => m.kind === ts2__default.default.SyntaxKind.DefaultKeyword));
3775
4498
  };
3776
4499
  const rendersJsx = (node) => {
3777
4500
  const pending = [node];
3778
4501
  while (pending.length > 0) {
3779
4502
  const current = pending.pop();
3780
- if (ts__default.default.isJsxElement(current) || ts__default.default.isJsxSelfClosingElement(current) || ts__default.default.isJsxFragment(current)) {
4503
+ if (ts2__default.default.isJsxElement(current) || ts2__default.default.isJsxSelfClosingElement(current) || ts2__default.default.isJsxFragment(current)) {
3781
4504
  return true;
3782
4505
  }
3783
- if (ts__default.default.isCallExpression(current)) {
4506
+ if (ts2__default.default.isCallExpression(current)) {
3784
4507
  const callee = current.expression;
3785
- const calleeName = ts__default.default.isIdentifier(callee) ? callee.text : ts__default.default.isPropertyAccessExpression(callee) ? callee.name.text : "";
4508
+ const calleeName = ts2__default.default.isIdentifier(callee) ? callee.text : ts2__default.default.isPropertyAccessExpression(callee) ? callee.name.text : "";
3786
4509
  if (calleeName === "createElement") return true;
3787
4510
  }
3788
- ts__default.default.forEachChild(current, (child) => {
4511
+ ts2__default.default.forEachChild(current, (child) => {
3789
4512
  pending.push(child);
3790
4513
  });
3791
4514
  }
@@ -3794,11 +4517,11 @@ function summarizeTypeScriptSource(relativePath, content) {
3794
4517
  const REACT_BASE_CLASS = /(?:^|\.)(?:PureComponent|Component)$/;
3795
4518
  const extendsReactBase = (node) => {
3796
4519
  const heritage = (node.heritageClauses ?? []).find(
3797
- (clause) => clause.token === ts__default.default.SyntaxKind.ExtendsKeyword
4520
+ (clause) => clause.token === ts2__default.default.SyntaxKind.ExtendsKeyword
3798
4521
  );
3799
4522
  const expression = heritage?.types[0]?.expression;
3800
4523
  if (!expression) return false;
3801
- const text2 = ts__default.default.isIdentifier(expression) ? expression.text : expression.getText(sourceFile);
4524
+ const text2 = ts2__default.default.isIdentifier(expression) ? expression.text : expression.getText(sourceFile);
3802
4525
  return REACT_BASE_CLASS.test(text2);
3803
4526
  };
3804
4527
  const recordFunctionLike = (name, exported, node) => {
@@ -3810,32 +4533,37 @@ function summarizeTypeScriptSource(relativePath, content) {
3810
4533
  if (/^use[A-Z0-9]/.test(name)) summary.hooks.push(name);
3811
4534
  if (/^[A-Z]/.test(name) && rendersJsx(node)) summary.reactComponents.push(name);
3812
4535
  };
4536
+ const cjsExports = [];
3813
4537
  const stack = [sourceFile];
3814
4538
  while (stack.length > 0) {
3815
4539
  const node = stack.pop();
3816
- if (ts__default.default.isImportDeclaration(node) && ts__default.default.isStringLiteral(node.moduleSpecifier)) {
4540
+ if (ts2__default.default.isImportDeclaration(node) && ts2__default.default.isStringLiteral(node.moduleSpecifier)) {
3817
4541
  summary.imports.push(node.moduleSpecifier.text);
3818
4542
  }
3819
- if (ts__default.default.isImportEqualsDeclaration(node) && ts__default.default.isExternalModuleReference(node.moduleReference) && node.moduleReference.expression !== void 0 && ts__default.default.isStringLiteral(node.moduleReference.expression)) {
4543
+ if (ts2__default.default.isImportEqualsDeclaration(node) && ts2__default.default.isExternalModuleReference(node.moduleReference) && node.moduleReference.expression !== void 0 && ts2__default.default.isStringLiteral(node.moduleReference.expression)) {
3820
4544
  summary.imports.push(node.moduleReference.expression.text);
3821
4545
  }
3822
- if (ts__default.default.isCallExpression(node) && node.arguments.length >= 1) {
4546
+ if (ts2__default.default.isCallExpression(node) && node.arguments.length >= 1) {
3823
4547
  const firstArgument = node.arguments[0];
3824
- if (firstArgument !== void 0 && ts__default.default.isStringLiteral(firstArgument)) {
3825
- const isDynamicImport = node.expression.kind === ts__default.default.SyntaxKind.ImportKeyword;
3826
- const isRequire = ts__default.default.isIdentifier(node.expression) && node.expression.text === "require";
4548
+ if (firstArgument !== void 0 && ts2__default.default.isStringLiteral(firstArgument)) {
4549
+ const isDynamicImport = node.expression.kind === ts2__default.default.SyntaxKind.ImportKeyword;
4550
+ const isRequire = ts2__default.default.isIdentifier(node.expression) && node.expression.text === "require";
3827
4551
  if (isDynamicImport || isRequire) summary.imports.push(firstArgument.text);
3828
4552
  }
4553
+ const callee = node.expression;
4554
+ if (ts2__default.default.isPropertyAccessExpression(callee) && ts2__default.default.isIdentifier(callee.expression) && ROUTE_RECEIVERS.has(callee.expression.text) && ROUTE_REGISTRATION_VERBS.has(callee.name.text.toLowerCase()) && firstArgument !== void 0 && ts2__default.default.isStringLiteral(firstArgument)) {
4555
+ summary.routeHandlers.push(callee.name.text.toUpperCase());
4556
+ }
3829
4557
  }
3830
- if (ts__default.default.isExportDeclaration(node)) {
3831
- if (node.moduleSpecifier && ts__default.default.isStringLiteral(node.moduleSpecifier)) {
4558
+ if (ts2__default.default.isExportDeclaration(node)) {
4559
+ if (node.moduleSpecifier && ts2__default.default.isStringLiteral(node.moduleSpecifier)) {
3832
4560
  summary.imports.push(node.moduleSpecifier.text);
3833
4561
  summary.reExports.push(node.moduleSpecifier.text);
3834
- if (node.exportClause && ts__default.default.isNamespaceExport(node.exportClause)) {
4562
+ if (node.exportClause && ts2__default.default.isNamespaceExport(node.exportClause)) {
3835
4563
  summary.exports.push(node.exportClause.name.text);
3836
4564
  }
3837
4565
  }
3838
- if (node.exportClause && ts__default.default.isNamedExports(node.exportClause)) {
4566
+ if (node.exportClause && ts2__default.default.isNamedExports(node.exportClause)) {
3839
4567
  for (const element of node.exportClause.elements) {
3840
4568
  const exported = element.name.text;
3841
4569
  summary.exports.push(exported);
@@ -3843,11 +4571,15 @@ function summarizeTypeScriptSource(relativePath, content) {
3843
4571
  }
3844
4572
  }
3845
4573
  }
3846
- if (ts__default.default.isExportAssignment(node)) {
4574
+ if (ts2__default.default.isExpressionStatement(node) && ts2__default.default.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === ts2__default.default.SyntaxKind.EqualsToken) {
4575
+ const cjsNames = cjsExportedNames(node.expression);
4576
+ if (cjsNames !== null) cjsExports.push(...cjsNames);
4577
+ }
4578
+ if (ts2__default.default.isExportAssignment(node)) {
3847
4579
  summary.exports.push("default");
3848
4580
  if (rendersJsx(node.expression)) summary.reactComponents.push("default");
3849
4581
  }
3850
- if (ts__default.default.isFunctionDeclaration(node)) {
4582
+ if (ts2__default.default.isFunctionDeclaration(node)) {
3851
4583
  const exported = isExported(node);
3852
4584
  if (node.name) {
3853
4585
  recordFunctionLike(node.name.text, exported, node);
@@ -3856,7 +4588,7 @@ function summarizeTypeScriptSource(relativePath, content) {
3856
4588
  summary.exports.push("default");
3857
4589
  }
3858
4590
  }
3859
- if (ts__default.default.isClassDeclaration(node)) {
4591
+ if (ts2__default.default.isClassDeclaration(node)) {
3860
4592
  if (node.name) {
3861
4593
  summary.classes.push(node.name.text);
3862
4594
  if (isExported(node)) summary.exports.push(node.name.text);
@@ -3868,19 +4600,19 @@ function summarizeTypeScriptSource(relativePath, content) {
3868
4600
  summary.exports.push("default");
3869
4601
  }
3870
4602
  }
3871
- if (ts__default.default.isInterfaceDeclaration(node)) {
4603
+ if (ts2__default.default.isInterfaceDeclaration(node)) {
3872
4604
  summary.interfaces.push(node.name.text);
3873
4605
  if (isExported(node)) summary.exports.push(node.name.text);
3874
4606
  }
3875
- if (ts__default.default.isTypeAliasDeclaration(node)) {
4607
+ if (ts2__default.default.isTypeAliasDeclaration(node)) {
3876
4608
  summary.types.push(node.name.text);
3877
4609
  if (isExported(node)) summary.exports.push(node.name.text);
3878
4610
  }
3879
- if (ts__default.default.isEnumDeclaration(node)) {
4611
+ if (ts2__default.default.isEnumDeclaration(node)) {
3880
4612
  summary.enums.push(node.name.text);
3881
4613
  if (isExported(node)) summary.exports.push(node.name.text);
3882
4614
  }
3883
- if (ts__default.default.isVariableStatement(node)) {
4615
+ if (ts2__default.default.isVariableStatement(node)) {
3884
4616
  const exported = isExported(node);
3885
4617
  for (const declaration of node.declarationList.declarations) {
3886
4618
  const bound = [];
@@ -3899,13 +4631,17 @@ function summarizeTypeScriptSource(relativePath, content) {
3899
4631
  }
3900
4632
  }
3901
4633
  const children = [];
3902
- ts__default.default.forEachChild(node, (child) => {
4634
+ ts2__default.default.forEachChild(node, (child) => {
3903
4635
  children.push(child);
3904
4636
  });
3905
4637
  for (let index = children.length - 1; index >= 0; index--) {
3906
4638
  stack.push(children[index]);
3907
4639
  }
3908
4640
  }
4641
+ if (cjsExports.length > 0) {
4642
+ summary.exportsKind = summary.exports.length > 0 ? "mixed" : "cjs";
4643
+ summary.exports.push(...cjsExports);
4644
+ }
3909
4645
  const dedupeSorted2 = (values) => Array.from(new Set(values)).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
3910
4646
  summary.directives = dedupeSorted2(summary.directives);
3911
4647
  summary.imports = dedupeSorted2(summary.imports);
@@ -4469,9 +5205,9 @@ var rubyProfile = {
4469
5205
  eachLine(content, (line) => {
4470
5206
  const trimmed = line.trim();
4471
5207
  if (!trimmed || trimmed.startsWith("#")) return;
4472
- const relative12 = REQUIRE_RELATIVE.exec(trimmed);
4473
- if (relative12) {
4474
- summary.imports.push(`./${relative12[1]}`);
5208
+ const relative14 = REQUIRE_RELATIVE.exec(trimmed);
5209
+ if (relative14) {
5210
+ summary.imports.push(`./${relative14[1]}`);
4475
5211
  return;
4476
5212
  }
4477
5213
  const required = REQUIRE.exec(trimmed);
@@ -4998,13 +5734,13 @@ function isBinaryFile(absolutePath) {
4998
5734
  if (isBinaryExtension(absolutePath)) return true;
4999
5735
  let fd;
5000
5736
  try {
5001
- fd = fs14__namespace.openSync(absolutePath, "r");
5737
+ fd = fs15__namespace.openSync(absolutePath, "r");
5002
5738
  const buffer = Buffer.alloc(CHUNK);
5003
5739
  let sample;
5004
5740
  let position = 0;
5005
5741
  while (position < BINARY_SCAN_BYTES) {
5006
5742
  const wanted = Math.min(CHUNK, BINARY_SCAN_BYTES - position);
5007
- const bytesRead = fs14__namespace.readSync(fd, buffer, 0, wanted, position);
5743
+ const bytesRead = fs15__namespace.readSync(fd, buffer, 0, wanted, position);
5008
5744
  if (bytesRead === 0) return false;
5009
5745
  const chunk = buffer.subarray(0, bytesRead);
5010
5746
  if (sample === void 0) {
@@ -5022,7 +5758,7 @@ function isBinaryFile(absolutePath) {
5022
5758
  } finally {
5023
5759
  if (fd !== void 0) {
5024
5760
  try {
5025
- fs14__namespace.closeSync(fd);
5761
+ fs15__namespace.closeSync(fd);
5026
5762
  } catch {
5027
5763
  }
5028
5764
  }
@@ -5044,9 +5780,9 @@ function importsOfText(relativePath, text2) {
5044
5780
  function importsOfFile(relativePath, absolutePath) {
5045
5781
  let buffer;
5046
5782
  try {
5047
- const stats = fs14__namespace.statSync(absolutePath);
5783
+ const stats = fs15__namespace.statSync(absolutePath);
5048
5784
  if (!stats.isFile() || stats.size > SUMMARY_MAX_SOURCE_BYTES) return [];
5049
- buffer = fs14__namespace.readFileSync(absolutePath);
5785
+ buffer = fs15__namespace.readFileSync(absolutePath);
5050
5786
  } catch {
5051
5787
  return [];
5052
5788
  }
@@ -5073,7 +5809,7 @@ function findStagingDirectory(config) {
5073
5809
  const tmpDir = path16__namespace.resolve(config.cwd, config.tmpDir);
5074
5810
  let entries;
5075
5811
  try {
5076
- entries = fs14__namespace.readdirSync(tmpDir);
5812
+ entries = fs15__namespace.readdirSync(tmpDir);
5077
5813
  } catch {
5078
5814
  return null;
5079
5815
  }
@@ -5086,8 +5822,8 @@ function describeMissingManifest(config, manifestPath) {
5086
5822
  const markerPath = path16__namespace.join(outDir, ".codebase-snapshot");
5087
5823
  let marker2 = null;
5088
5824
  try {
5089
- if (fs14__namespace.existsSync(markerPath)) {
5090
- const parsed = JSON.parse(fs14__namespace.readFileSync(markerPath, "utf8"));
5825
+ if (fs15__namespace.existsSync(markerPath)) {
5826
+ const parsed = JSON.parse(fs15__namespace.readFileSync(markerPath, "utf8"));
5091
5827
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
5092
5828
  marker2 = parsed;
5093
5829
  }
@@ -5124,11 +5860,11 @@ function sha256Hex(buffer) {
5124
5860
  function wouldNowBeIncluded(cwd, relativePath) {
5125
5861
  const absolutePath = path16__namespace.join(cwd, relativePath);
5126
5862
  try {
5127
- const stats = fs14__namespace.statSync(absolutePath);
5863
+ const stats = fs15__namespace.statSync(absolutePath);
5128
5864
  if (!stats.isFile()) return false;
5129
5865
  if (isBinaryExtension(absolutePath)) return false;
5130
5866
  if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) return false;
5131
- return !decodeText(fs14__namespace.readFileSync(absolutePath)).binary;
5867
+ return !decodeText(fs15__namespace.readFileSync(absolutePath)).binary;
5132
5868
  } catch {
5133
5869
  return false;
5134
5870
  }
@@ -5159,14 +5895,71 @@ function describeManifestShapeProblem(value) {
5159
5895
  if (!candidate.totals || typeof candidate.totals !== "object" || Array.isArray(candidate.totals)) {
5160
5896
  return 'missing "totals" object';
5161
5897
  }
5898
+ const currentSchema = candidate.schemaVersion === SCHEMA_VERSION;
5899
+ if (currentSchema) {
5900
+ const generator = candidate.generator;
5901
+ if (!generator || typeof generator !== "object" || Array.isArray(generator)) {
5902
+ return 'missing "generator" object';
5903
+ }
5904
+ const generatorFields = generator;
5905
+ if (!isOurGeneratorName(generatorFields.name)) {
5906
+ return "`generator.name` is not this generator";
5907
+ }
5908
+ if (typeof generatorFields.version !== "string" || generatorFields.version.trim() === "") {
5909
+ return "`generator.version` must be a non-empty string";
5910
+ }
5911
+ const git = candidate.git;
5912
+ if (!git || typeof git !== "object" || Array.isArray(git)) return 'missing "git" object';
5913
+ const gitFields = git;
5914
+ if (typeof gitFields.branch !== "string") return "`git.branch` must be a string";
5915
+ if (typeof gitFields.commit !== "string") return "`git.commit` must be a string";
5916
+ if (typeof gitFields.isDirty !== "boolean") return "`git.isDirty` must be a boolean";
5917
+ const config = candidate.config;
5918
+ if (!config || typeof config !== "object" || Array.isArray(config)) {
5919
+ return 'missing "config" object';
5920
+ }
5921
+ const budgets = candidate.budgets;
5922
+ if (!budgets || typeof budgets !== "object" || Array.isArray(budgets)) {
5923
+ return 'missing "budgets" object';
5924
+ }
5925
+ for (const key of ["maxPartBytes", "largeFileBytes"]) {
5926
+ const value2 = budgets[key];
5927
+ if (typeof value2 !== "number" || !Number.isSafeInteger(value2) || value2 < 0) {
5928
+ return `\`budgets.${key}\` must be a non-negative integer`;
5929
+ }
5930
+ }
5931
+ if (!candidate.indexes || typeof candidate.indexes !== "object" || Array.isArray(candidate.indexes)) {
5932
+ return 'missing "indexes" object';
5933
+ }
5934
+ if (!candidate.kinds || typeof candidate.kinds !== "object" || Array.isArray(candidate.kinds)) {
5935
+ return 'missing "kinds" object';
5936
+ }
5937
+ }
5162
5938
  if (!Array.isArray(candidate.files)) return 'missing "files" array';
5163
5939
  for (const entry of candidate.files) {
5164
5940
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
5165
5941
  return 'a "files" entry is not an object';
5166
5942
  }
5167
- if (typeof entry.relativePath !== "string") {
5943
+ const fields = entry;
5944
+ if (typeof fields.relativePath !== "string") {
5168
5945
  return 'a "files" entry has no "relativePath"';
5169
5946
  }
5947
+ if (!currentSchema) continue;
5948
+ if (typeof fields.part !== "string" || fields.part.length === 0) {
5949
+ return 'a "files" entry records no "part"';
5950
+ }
5951
+ if (typeof fields.hashSha256 !== "string" || !/^[0-9a-f]{64}$/.test(fields.hashSha256)) {
5952
+ return 'a "files" entry "hashSha256" must be a 64-character lowercase sha256 hex digest';
5953
+ }
5954
+ for (const key of ["sizeBytes", "lines"]) {
5955
+ const value2 = fields[key];
5956
+ if (typeof value2 !== "number" || !Number.isSafeInteger(value2) || value2 < 0) {
5957
+ return `a "files" entry "${key}" must be a non-negative integer`;
5958
+ }
5959
+ }
5960
+ if (!["full", "preview", "signatures"].includes(String(fields.inclusionMode))) {
5961
+ return 'a "files" entry has an unknown "inclusionMode"';
5962
+ }
5170
5963
  }
5171
5964
  if (!Array.isArray(candidate.skipped)) return 'missing "skipped" array';
5172
5965
  if (!Array.isArray(candidate.parts)) return 'missing "parts" array';
@@ -5174,13 +5967,28 @@ function describeManifestShapeProblem(value) {
5174
5967
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
5175
5968
  return 'a "parts" entry is not an object';
5176
5969
  }
5177
- const filename = entry.filename;
5970
+ const fields = entry;
5971
+ const filename = fields.filename;
5178
5972
  if (typeof filename !== "string" || filename.trim() === "") {
5179
5973
  return 'a "parts" entry has no "filename"';
5180
5974
  }
5181
5975
  if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path16__namespace.isAbsolute(filename)) {
5182
5976
  return 'a "parts" entry "filename" must be a bare filename inside parts/';
5183
5977
  }
5978
+ if (currentSchema) {
5979
+ if (typeof fields.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(fields.sha256)) {
5980
+ return 'a "parts" entry "sha256" must be a 64-character lowercase sha256 hex digest';
5981
+ }
5982
+ if (typeof fields.byteSize !== "number" || !Number.isSafeInteger(fields.byteSize) || fields.byteSize < 0) {
5983
+ return 'a "parts" entry "byteSize" must be a non-negative integer';
5984
+ }
5985
+ if (typeof fields.index !== "number" || !Number.isSafeInteger(fields.index) || fields.index < 1) {
5986
+ return 'a "parts" entry "index" must be a positive integer';
5987
+ }
5988
+ if (!Array.isArray(fields.includedFiles)) {
5989
+ return 'a "parts" entry has no "includedFiles" array';
5990
+ }
5991
+ }
5184
5992
  }
5185
5993
  if (!candidate.layers || typeof candidate.layers !== "object" || Array.isArray(candidate.layers)) {
5186
5994
  return 'missing "layers" object';
@@ -5191,7 +5999,7 @@ function validateSnapshot(configInput) {
5191
5999
  assertUsableConfigInput(configInput);
5192
6000
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput);
5193
6001
  const manifestPath = path16__namespace.resolve(config.cwd, config.outDir, "manifest.json");
5194
- if (!fs14__namespace.existsSync(manifestPath)) {
6002
+ if (!fs15__namespace.existsSync(manifestPath)) {
5195
6003
  return {
5196
6004
  valid: false,
5197
6005
  manifestPresent: false,
@@ -5202,7 +6010,7 @@ function validateSnapshot(configInput) {
5202
6010
  }
5203
6011
  let manifest;
5204
6012
  try {
5205
- manifest = JSON.parse(fs14__namespace.readFileSync(manifestPath, "utf8"));
6013
+ manifest = JSON.parse(fs15__namespace.readFileSync(manifestPath, "utf8"));
5206
6014
  } catch (err) {
5207
6015
  return {
5208
6016
  valid: false,
@@ -5225,6 +6033,19 @@ function validateSnapshot(configInput) {
5225
6033
  const drift = emptyDrift();
5226
6034
  const warnings = [];
5227
6035
  const snapshotDir = path16__namespace.resolve(config.cwd, config.outDir);
6036
+ const unreadableSkips = manifest.skipped.filter(
6037
+ (entry) => entry.reason === "missing" || entry.reason === "read-error"
6038
+ );
6039
+ if (unreadableSkips.length > 0) {
6040
+ warnings.push(
6041
+ `${unreadableSkips.length} path(s) could not be read when this snapshot was generated (see manifest.skipped[] with reason "missing" or "read-error"); they are not in the snapshot.`
6042
+ );
6043
+ }
6044
+ if ([...config.layers, ...config.kinds].some((rule) => typeof rule.match === "function")) {
6045
+ warnings.push(
6046
+ "The configuration uses executable (function) matchers; the recorded digest covers their source text, not the values they capture, so it cannot prove their classification is unchanged."
6047
+ );
6048
+ }
5228
6049
  const manifestFileMap = /* @__PURE__ */ new Map();
5229
6050
  for (const file of manifest.files) {
5230
6051
  if (file && typeof file.relativePath === "string") {
@@ -5287,7 +6108,7 @@ function validateSnapshot(configInput) {
5287
6108
  // snapshot was reported as drifting.
5288
6109
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
5289
6110
  (directory) => path16__namespace.relative(config.cwd, path16__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
5290
- ).filter((relative12) => relative12.length > 0 && !relative12.startsWith(".."))
6111
+ ).filter((relative14) => relative14.length > 0 && !relative14.startsWith(".."))
5291
6112
  });
5292
6113
  for (const diskFile of collection.files) {
5293
6114
  const snapshotHash = manifestFileMap.get(diskFile);
@@ -5312,7 +6133,7 @@ function validateSnapshot(configInput) {
5312
6133
  }
5313
6134
  let diskHash;
5314
6135
  try {
5315
- diskHash = sha256Hex(fs14__namespace.readFileSync(path16__namespace.join(config.cwd, diskFile)));
6136
+ diskHash = sha256Hex(fs15__namespace.readFileSync(path16__namespace.join(config.cwd, diskFile)));
5316
6137
  } catch (err) {
5317
6138
  if (err.code === "ENOENT") {
5318
6139
  drift.missingOnDisk.push(diskFile);
@@ -5336,7 +6157,7 @@ function validateSnapshot(configInput) {
5336
6157
  }
5337
6158
  let statFailure = null;
5338
6159
  try {
5339
- fs14__namespace.statSync(confined);
6160
+ fs15__namespace.statSync(confined);
5340
6161
  } catch (err) {
5341
6162
  statFailure = err;
5342
6163
  }
@@ -5371,7 +6192,7 @@ function validateSnapshot(configInput) {
5371
6192
  }
5372
6193
  let buffer;
5373
6194
  try {
5374
- buffer = fs14__namespace.readFileSync(partPath);
6195
+ buffer = fs15__namespace.readFileSync(partPath);
5375
6196
  } catch {
5376
6197
  drift.partIssues.push({ part: part.filename, issue: "missing from snapshot/parts" });
5377
6198
  continue;
@@ -5393,24 +6214,85 @@ function validateSnapshot(configInput) {
5393
6214
  });
5394
6215
  }
5395
6216
  }
5396
- const filesInParts = manifest.parts.reduce(
5397
- (total, part) => total + (typeof part?.fileCount === "number" ? part.fileCount : 0),
5398
- 0
5399
- );
5400
- if (filesInParts !== manifest.files.length) {
5401
- drift.partIssues.push({
5402
- part: "(totals)",
5403
- issue: `parts list ${filesInParts} file(s) but the manifest lists ${manifest.files.length}`
5404
- });
6217
+ const maskDriftPath = (value) => findSecretInPath(value, config.secretRules)?.masked ?? value;
6218
+ const includedByPart = /* @__PURE__ */ new Map();
6219
+ const partIndexes = /* @__PURE__ */ new Set();
6220
+ for (const part of manifest.parts) {
6221
+ if (includedByPart.has(part.filename)) {
6222
+ drift.partIssues.push({
6223
+ part: maskDriftPath(part.filename),
6224
+ issue: "appears more than once in parts[]"
6225
+ });
6226
+ }
6227
+ if (typeof part.index === "number") {
6228
+ if (partIndexes.has(part.index)) {
6229
+ drift.partIssues.push({
6230
+ part: maskDriftPath(part.filename),
6231
+ issue: `reuses part index ${part.index}`
6232
+ });
6233
+ }
6234
+ partIndexes.add(part.index);
6235
+ }
6236
+ const listed = /* @__PURE__ */ new Set();
6237
+ for (const included of part.includedFiles ?? []) {
6238
+ if (typeof included?.relativePath !== "string") continue;
6239
+ if (listed.has(included.relativePath)) {
6240
+ drift.partIssues.push({
6241
+ part: maskDriftPath(part.filename),
6242
+ issue: `lists ${maskDriftPath(included.relativePath)} twice`
6243
+ });
6244
+ }
6245
+ listed.add(included.relativePath);
6246
+ }
6247
+ includedByPart.set(part.filename, listed);
6248
+ if (typeof part.fileCount === "number" && part.fileCount !== listed.size) {
6249
+ drift.partIssues.push({
6250
+ part: maskDriftPath(part.filename),
6251
+ issue: `declares ${part.fileCount} file(s) but lists ${listed.size} in includedFiles`
6252
+ });
6253
+ }
5405
6254
  }
6255
+ const filePaths = /* @__PURE__ */ new Set();
5406
6256
  for (const file of manifest.files) {
5407
- if (file?.part && !partNames.has(file.part)) {
6257
+ if (filePaths.has(file.relativePath)) {
6258
+ drift.partIssues.push({
6259
+ part: "(files)",
6260
+ issue: `${maskDriftPath(file.relativePath)} appears more than once in files[]`
6261
+ });
6262
+ continue;
6263
+ }
6264
+ filePaths.add(file.relativePath);
6265
+ if (typeof file.part !== "string" || file.part.length === 0) {
6266
+ drift.partIssues.push({
6267
+ part: "(files)",
6268
+ issue: `${maskDriftPath(file.relativePath)} records no part`
6269
+ });
6270
+ continue;
6271
+ }
6272
+ if (!partNames.has(file.part)) {
6273
+ drift.partIssues.push({
6274
+ part: maskDriftPath(file.part),
6275
+ issue: `${maskDriftPath(file.relativePath)} points at a part that is not in the manifest`
6276
+ });
6277
+ continue;
6278
+ }
6279
+ if (!includedByPart.get(file.part)?.has(file.relativePath)) {
5408
6280
  drift.partIssues.push({
5409
- part: file.part,
5410
- issue: `${file.relativePath} points at a part that is not in the manifest`
6281
+ part: maskDriftPath(file.part),
6282
+ issue: `${maskDriftPath(file.relativePath)} is not listed in that part's includedFiles`
5411
6283
  });
5412
6284
  }
5413
6285
  }
6286
+ for (const [partName, listed] of includedByPart) {
6287
+ for (const relativePath of listed) {
6288
+ if (!filePaths.has(relativePath)) {
6289
+ drift.partIssues.push({
6290
+ part: maskDriftPath(partName),
6291
+ issue: `lists ${maskDriftPath(relativePath)}, which the manifest does not`
6292
+ });
6293
+ }
6294
+ }
6295
+ }
5414
6296
  const maskValue = (value) => findSecretInPath(value, config.secretRules)?.masked ?? value;
5415
6297
  const currentExcludes = config.excludePatterns.map(maskValue);
5416
6298
  const currentInclude = config.include.map(maskValue);
@@ -5566,6 +6448,13 @@ function validateSnapshot(configInput) {
5566
6448
  0
5567
6449
  );
5568
6450
  expectEqual("counts.totalFiles", counts.totalFiles, manifest.files.length);
6451
+ if (manifest.files.every((file) => typeof file?.lines === "number")) {
6452
+ expectEqual(
6453
+ "counts.totalLines",
6454
+ counts.totalLines,
6455
+ manifest.files.reduce((total, file) => total + file.lines, 0)
6456
+ );
6457
+ }
5569
6458
  expectEqual("counts.partsCount", counts.partsCount, manifest.parts.length);
5570
6459
  expectEqual("counts.skippedCount", counts.skippedCount, manifest.skipped.length);
5571
6460
  expectEqual("counts.totalSizeBytes", counts.totalSizeBytes, sumSourceBytes);
@@ -5589,6 +6478,37 @@ function validateSnapshot(configInput) {
5589
6478
  `totals.fullFiles + previewFiles (${totals.fullFiles} + ${totals.previewFiles}) != ${manifest.files.length} files`
5590
6479
  );
5591
6480
  }
6481
+ const recordedSettingsDigest = manifest.config && typeof manifest.config.digest === "string" ? manifest.config.digest : null;
6482
+ if (recordedSettingsDigest !== null && manifest.files.every((file) => typeof file?.hashSha256 === "string")) {
6483
+ const settingsLine = `settings:${recordedSettingsDigest}`;
6484
+ const currentDefinition = sha256Hex(
6485
+ Buffer.from(
6486
+ [
6487
+ ...manifest.files.map(
6488
+ (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}`
6489
+ ),
6490
+ settingsLine
6491
+ ].join("\n"),
6492
+ "utf8"
6493
+ )
6494
+ );
6495
+ const legacyDefinition = sha256Hex(
6496
+ Buffer.from(
6497
+ [
6498
+ ...manifest.files.map(
6499
+ (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
6500
+ ),
6501
+ settingsLine
6502
+ ].join("\n"),
6503
+ "utf8"
6504
+ )
6505
+ );
6506
+ if (manifest.fingerprint !== currentDefinition && manifest.fingerprint !== legacyDefinition) {
6507
+ totalsMismatches.push(
6508
+ "fingerprint: does not match the files and settings recorded in this manifest"
6509
+ );
6510
+ }
6511
+ }
5592
6512
  if (manifest.budgets && manifest.budgets.maxPartBytes !== config.maxPartBytes) {
5593
6513
  totalsMismatches.push(
5594
6514
  `budgets.maxPartBytes: manifest ${manifest.budgets.maxPartBytes} vs current ${config.maxPartBytes}`
@@ -5616,26 +6536,49 @@ function validateSnapshot(configInput) {
5616
6536
  drift.configMismatches.push(`manifest declared itself invalid: ${error}`);
5617
6537
  }
5618
6538
  }
5619
- for (const [key, artifact] of [
6539
+ const declaredArtifacts = [
6540
+ ["README.md", manifest.artifacts?.readme],
6541
+ ["reports/navigation.md", manifest.artifacts?.navigation],
6542
+ ["reports/project-tree.md", manifest.artifacts?.projectTree],
6543
+ ["reports/audit.md", manifest.artifacts?.audit],
5620
6544
  ["full-codebase.json", manifest.artifacts?.fullJson],
5621
6545
  ["full-codebase.md", manifest.artifacts?.fullMarkdown]
5622
- ]) {
6546
+ ];
6547
+ for (const [key, artifact] of declaredArtifacts) {
5623
6548
  if (!artifact) continue;
5624
- const artifactPath = path16__namespace.join(snapshotDir, key);
6549
+ const artifactPath = path16__namespace.join(snapshotDir, ...key.split("/"));
6550
+ let buffer;
5625
6551
  try {
5626
- const buffer = fs14__namespace.readFileSync(artifactPath);
5627
- if (sha256Hex(buffer) !== artifact.sha256 || buffer.length !== artifact.byteSize) {
5628
- drift.partIssues.push({ part: key, issue: "artifact does not match its recorded digest" });
5629
- }
6552
+ if (!fs15__namespace.statSync(artifactPath).isFile()) throw new Error("not a regular file");
6553
+ buffer = fs15__namespace.readFileSync(artifactPath);
5630
6554
  } catch {
5631
6555
  drift.partIssues.push({ part: key, issue: "declared artifact is missing" });
6556
+ continue;
6557
+ }
6558
+ if (sha256Hex(buffer) !== artifact.sha256 || buffer.length !== artifact.byteSize) {
6559
+ drift.partIssues.push({ part: key, issue: "artifact does not match its recorded digest" });
6560
+ continue;
6561
+ }
6562
+ if (key === "reports/navigation.md") {
6563
+ for (const match of buffer.toString("utf8").matchAll(/\]\(([^)\s]+)\)/g)) {
6564
+ const target = match[1].split("#")[0];
6565
+ if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
6566
+ const resolved = path16__namespace.resolve(snapshotDir, "reports", target);
6567
+ const relative14 = path16__namespace.relative(snapshotDir, resolved);
6568
+ if (relative14.startsWith("..") || path16__namespace.isAbsolute(relative14) || !fs15__namespace.existsSync(resolved)) {
6569
+ drift.partIssues.push({
6570
+ part: key,
6571
+ issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
6572
+ });
6573
+ }
6574
+ }
5632
6575
  }
5633
6576
  }
5634
6577
  const sarifArtifact = manifest.artifacts?.sarif;
5635
6578
  if (sarifArtifact) {
5636
6579
  const sarifKey = "reports/audit.sarif";
5637
6580
  try {
5638
- const buffer = fs14__namespace.readFileSync(path16__namespace.join(snapshotDir, "reports", "audit.sarif"));
6581
+ const buffer = fs15__namespace.readFileSync(path16__namespace.join(snapshotDir, "reports", "audit.sarif"));
5639
6582
  if (sha256Hex(buffer) !== sarifArtifact.sha256 || buffer.length !== sarifArtifact.byteSize) {
5640
6583
  drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
5641
6584
  }
@@ -5644,8 +6587,11 @@ function validateSnapshot(configInput) {
5644
6587
  }
5645
6588
  }
5646
6589
  if (manifest.git && manifest.git.branch && manifest.git.branch !== config.branch) {
6590
+ const maskBranch = (value) => findSecretInPath(value, config.secretRules)?.masked ?? value;
6591
+ const generatedOn = maskBranch(manifest.git.branch);
6592
+ const configuredAs = maskBranch(config.branch);
5647
6593
  warnings.push(
5648
- `Snapshot was generated on branch "${manifest.git.branch}" but the configured branch is "${config.branch}".`
6594
+ `Snapshot was generated on branch "${generatedOn}" but the configured branch is "${configuredAs}".`
5649
6595
  );
5650
6596
  }
5651
6597
  const errors = [];
@@ -5896,14 +6842,14 @@ function compareManifests(before, after) {
5896
6842
  function loadManifest(target) {
5897
6843
  let isDirectory;
5898
6844
  try {
5899
- isDirectory = fs14__namespace.statSync(target).isDirectory();
6845
+ isDirectory = fs15__namespace.statSync(target).isDirectory();
5900
6846
  } catch {
5901
6847
  throw new Error(`No snapshot found at ${target}: the path does not exist.`);
5902
6848
  }
5903
6849
  const manifestPath = isDirectory ? path16__namespace.join(target, "manifest.json") : target;
5904
6850
  let raw;
5905
6851
  try {
5906
- raw = fs14__namespace.readFileSync(manifestPath, "utf8");
6852
+ raw = fs15__namespace.readFileSync(manifestPath, "utf8");
5907
6853
  } catch {
5908
6854
  throw new Error(`Could not read a manifest at ${manifestPath}.`);
5909
6855
  }
@@ -5957,6 +6903,68 @@ function renderDiffText(diff) {
5957
6903
  }
5958
6904
  return lines.join("\n");
5959
6905
  }
6906
+ function hasCollapsibleBody(node) {
6907
+ if (!("body" in node)) return false;
6908
+ const body = node.body;
6909
+ return body !== void 0 && ts2__default.default.isBlock(body);
6910
+ }
6911
+ function scriptKindFor(fileName) {
6912
+ const lower = fileName.toLowerCase();
6913
+ if (lower.endsWith(".tsx")) return ts2__default.default.ScriptKind.TSX;
6914
+ if (lower.endsWith(".jsx")) return ts2__default.default.ScriptKind.JSX;
6915
+ if (lower.endsWith(".js") || lower.endsWith(".mjs") || lower.endsWith(".cjs")) {
6916
+ return ts2__default.default.ScriptKind.JS;
6917
+ }
6918
+ return ts2__default.default.ScriptKind.TS;
6919
+ }
6920
+ function skeletonizeTypeScript(source, fileName = "file.ts") {
6921
+ const sourceFile = ts2__default.default.createSourceFile(
6922
+ fileName,
6923
+ source,
6924
+ ts2__default.default.ScriptTarget.Latest,
6925
+ // `setParentNodes: false`. Nothing here reads `.parent` — the one `getStart` call is given the
6926
+ // source file explicitly, which is the reason that argument exists. Asking for parent pointers
6927
+ // makes the parser run a second full pass over every node in the file to set them, on top of
6928
+ // the summary parse this same file already pays for.
6929
+ false,
6930
+ scriptKindFor(fileName)
6931
+ );
6932
+ const spans = [];
6933
+ const visit = (node) => {
6934
+ if ((ts2__default.default.isFunctionDeclaration(node) || ts2__default.default.isMethodDeclaration(node) || ts2__default.default.isConstructorDeclaration(node) || ts2__default.default.isGetAccessorDeclaration(node) || ts2__default.default.isSetAccessorDeclaration(node) || ts2__default.default.isFunctionExpression(node) || ts2__default.default.isArrowFunction(node)) && hasCollapsibleBody(node)) {
6935
+ const body = node.body;
6936
+ if (body.statements.length > 0) {
6937
+ const start = body.getStart(sourceFile);
6938
+ const end = body.getEnd();
6939
+ if (end > start) spans.push({ start, end });
6940
+ }
6941
+ }
6942
+ ts2__default.default.forEachChild(node, visit);
6943
+ };
6944
+ visit(sourceFile);
6945
+ if (spans.length === 0) return { text: source, collapsed: 0 };
6946
+ const outermost = [];
6947
+ for (const span of spans.sort((a, b) => a.start - b.start || b.end - a.end)) {
6948
+ const last = outermost[outermost.length - 1];
6949
+ if (last && span.start < last.end) continue;
6950
+ outermost.push(span);
6951
+ }
6952
+ const chunks = [];
6953
+ let cursor = 0;
6954
+ for (const span of outermost) {
6955
+ chunks.push(source.slice(cursor, span.start), "{ /* ... */ }");
6956
+ cursor = span.end;
6957
+ }
6958
+ chunks.push(source.slice(cursor));
6959
+ return { text: chunks.join(""), collapsed: outermost.length };
6960
+ }
6961
+ function isSkeletonizable(filePath) {
6962
+ const lower = filePath.toLowerCase();
6963
+ if (lower.endsWith(".d.ts") || lower.endsWith(".d.mts") || lower.endsWith(".d.cts")) {
6964
+ return false;
6965
+ }
6966
+ return lower.endsWith(".ts") || lower.endsWith(".tsx") || lower.endsWith(".mts") || lower.endsWith(".cts") || lower.endsWith(".js") || lower.endsWith(".jsx") || lower.endsWith(".mjs") || lower.endsWith(".cjs");
6967
+ }
5960
6968
 
5961
6969
  // src/partitioner/preview.ts
5962
6970
  var LINE_ENDINGS = /\r\n|\r/g;
@@ -5979,9 +6987,9 @@ function truncateToBytes(content, maxBytes) {
5979
6987
  if (maxBytes <= 0) return { content: "", isTruncated: content.length > 0 };
5980
6988
  const buffer = Buffer.from(content, "utf8");
5981
6989
  if (buffer.length <= maxBytes) return { content, isTruncated: false };
5982
- let slice = buffer.subarray(0, maxBytes).toString("utf8");
5983
- while (slice.endsWith("\uFFFD")) slice = slice.slice(0, -1);
5984
- return { content: slice, isTruncated: true };
6990
+ let end = maxBytes;
6991
+ while (end > 0 && (buffer[end] & 192) === 128) end -= 1;
6992
+ return { content: buffer.subarray(0, end).toString("utf8"), isTruncated: true };
5985
6993
  }
5986
6994
  function truncatePreview(content, headLines, tailLines) {
5987
6995
  const normalised = normaliseLineEndings(content);
@@ -6117,23 +7125,23 @@ function describeMatcher(matcher) {
6117
7125
  function normalizeTarget(cwd, target) {
6118
7126
  const resolvedCwd = path16__namespace.resolve(cwd);
6119
7127
  const absolute = path16__namespace.resolve(resolvedCwd, target);
6120
- const relative12 = path16__namespace.relative(resolvedCwd, absolute);
6121
- if (relative12 === "" || relative12 === ".." || relative12.startsWith(`..${path16__namespace.sep}`) || path16__namespace.isAbsolute(relative12)) {
7128
+ const relative14 = path16__namespace.relative(resolvedCwd, absolute);
7129
+ if (relative14 === "" || relative14 === ".." || relative14.startsWith(`..${path16__namespace.sep}`) || path16__namespace.isAbsolute(relative14)) {
6122
7130
  return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
6123
7131
  }
6124
- return { relative: relative12.split(path16__namespace.sep).join("/"), outsideRoot: false };
7132
+ return { relative: relative14.split(path16__namespace.sep).join("/"), outsideRoot: false };
6125
7133
  }
6126
7134
  function findRuleMatch(rules, relativePath) {
6127
7135
  return rules.find(
6128
7136
  (rule) => matchRule(relativePath, rule.match)
6129
7137
  );
6130
7138
  }
6131
- function findRecordedAncestor(skipped, relative12, maskedPath2) {
7139
+ function findRecordedAncestor(skipped, relative14, maskedPath2) {
6132
7140
  let nearest;
6133
7141
  for (const record of skipped) {
6134
7142
  const ancestorPath = record.path;
6135
7143
  if (ancestorPath.length === 0) continue;
6136
- const isAncestor = relative12.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
7144
+ const isAncestor = relative14.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
6137
7145
  if (!isAncestor) continue;
6138
7146
  if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
6139
7147
  }
@@ -6142,15 +7150,15 @@ function findRecordedAncestor(skipped, relative12, maskedPath2) {
6142
7150
  function readManifest2(config) {
6143
7151
  const manifestPath = path16__namespace.resolve(config.cwd, config.outDir, "manifest.json");
6144
7152
  try {
6145
- return JSON.parse(fs14__namespace.readFileSync(manifestPath, "utf8"));
7153
+ return JSON.parse(fs15__namespace.readFileSync(manifestPath, "utf8"));
6146
7154
  } catch {
6147
7155
  return null;
6148
7156
  }
6149
7157
  }
6150
7158
  function explainPath(config, target) {
6151
7159
  const normalized = normalizeTarget(config.cwd, target);
6152
- const relative12 = normalized.relative;
6153
- const maskedPath2 = findSecretInPath(relative12, config.secretRules)?.masked ?? relative12;
7160
+ const relative14 = normalized.relative;
7161
+ const maskedPath2 = findSecretInPath(relative14, config.secretRules)?.masked ?? relative14;
6154
7162
  if (normalized.outsideRoot) {
6155
7163
  return {
6156
7164
  path: maskedPath2,
@@ -6160,10 +7168,10 @@ function explainPath(config, target) {
6160
7168
  detail: "path resolves outside the configured repository root and was not inspected"
6161
7169
  };
6162
7170
  }
6163
- const absolute = path16__namespace.join(config.cwd, relative12);
7171
+ const absolute = path16__namespace.join(config.cwd, relative14);
6164
7172
  const result = {
6165
7173
  path: maskedPath2,
6166
- exists: fs14__namespace.existsSync(absolute),
7174
+ exists: fs15__namespace.existsSync(absolute),
6167
7175
  included: false
6168
7176
  };
6169
7177
  const collection = collectFiles(config.cwd, {
@@ -6178,11 +7186,11 @@ function explainPath(config, target) {
6178
7186
  // that is only missing because the walker dropped the tool's own output directory.
6179
7187
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
6180
7188
  (directory) => path16__namespace.relative(config.cwd, path16__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
6181
- ).filter((relative13) => relative13.length > 0 && !relative13.startsWith(".."))
7189
+ ).filter((relative15) => relative15.length > 0 && !relative15.startsWith(".."))
6182
7190
  });
6183
- if (!collection.files.includes(relative12)) {
7191
+ if (!collection.files.includes(relative14)) {
6184
7192
  const record = collection.skipped.find(
6185
- (entry2) => entry2.path === relative12 || entry2.path === maskedPath2
7193
+ (entry2) => entry2.path === relative14 || entry2.path === maskedPath2
6186
7194
  );
6187
7195
  if (record) {
6188
7196
  result.reason = record.reason;
@@ -6191,7 +7199,7 @@ function explainPath(config, target) {
6191
7199
  result.reason = "missing";
6192
7200
  result.detail = "no such file or directory, relative to the configured cwd";
6193
7201
  } else {
6194
- const ancestor = findRecordedAncestor(collection.skipped, relative12, maskedPath2);
7202
+ const ancestor = findRecordedAncestor(collection.skipped, relative14, maskedPath2);
6195
7203
  if (ancestor) {
6196
7204
  result.reason = ancestor.reason;
6197
7205
  result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
@@ -6211,11 +7219,11 @@ function explainPath(config, target) {
6211
7219
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
6212
7220
  ...config.staged === true ? { staged: true } : {}
6213
7221
  });
6214
- inScope = scope.paths.has(relative12);
7222
+ inScope = scope.paths.has(relative14);
6215
7223
  if (!inScope && config.withDependents === true) {
6216
7224
  inScope = importsChangedFile(
6217
- relative12,
6218
- importsOfFile(relative12, absolute),
7225
+ relative14,
7226
+ importsOfFile(relative14, absolute),
6219
7227
  scope.paths,
6220
7228
  buildImportResolver(collection.files.map((file) => ({ relativePath: file })))
6221
7229
  );
@@ -6242,7 +7250,7 @@ function explainPath(config, target) {
6242
7250
  }
6243
7251
  let sizeOnDisk = null;
6244
7252
  try {
6245
- sizeOnDisk = fs14__namespace.statSync(absolute).size;
7253
+ sizeOnDisk = fs15__namespace.statSync(absolute).size;
6246
7254
  } catch {
6247
7255
  sizeOnDisk = null;
6248
7256
  }
@@ -6252,8 +7260,16 @@ function explainPath(config, target) {
6252
7260
  result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
6253
7261
  return result;
6254
7262
  }
6255
- if (fs14__namespace.existsSync(absolute) && fs14__namespace.statSync(absolute).isFile()) {
6256
- const buffer = fs14__namespace.readFileSync(absolute);
7263
+ if (fs15__namespace.existsSync(absolute) && fs15__namespace.statSync(absolute).isFile()) {
7264
+ let buffer;
7265
+ try {
7266
+ buffer = fs15__namespace.readFileSync(absolute);
7267
+ } catch (err) {
7268
+ result.included = false;
7269
+ result.reason = "read-error";
7270
+ result.detail = `${err.message} (explain could not read the file; generate records this as a skipped entry)`;
7271
+ return result;
7272
+ }
6257
7273
  const decoded = decodeText(buffer);
6258
7274
  if (decoded.binary) {
6259
7275
  result.included = false;
@@ -6265,21 +7281,30 @@ function explainPath(config, target) {
6265
7281
  result.bytes = buffer.length;
6266
7282
  result.lines = countLines(text2);
6267
7283
  if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
6268
- const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative12);
7284
+ const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative14);
6269
7285
  result.secretCount = findings.length;
6270
7286
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
7287
+ let inclusionMode = "full";
7288
+ if (config.skeleton === true && isSkeletonizable(relative14)) {
7289
+ const skeleton = skeletonizeTypeScript(text2, relative14);
7290
+ if (skeleton.collapsed > 0) inclusionMode = "signatures";
7291
+ }
7292
+ if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
7293
+ const preview = truncatePreview(text2, config.previewHeadLines, config.previewTailLines);
7294
+ inclusionMode = preview.isTruncated ? "preview" : "full";
7295
+ }
7296
+ result.inclusionMode = inclusionMode;
6271
7297
  }
6272
- result.layer = classifyLayer(relative12, config.layers);
6273
- result.kind = classifyKind(relative12, config.kinds);
6274
- result.language = detectLanguage(relative12);
6275
- const layerRule = findRuleMatch(config.layers, relative12);
7298
+ result.layer = classifyLayer(relative14, config.layers);
7299
+ result.kind = classifyKind(relative14, config.kinds);
7300
+ result.language = detectLanguage(relative14);
7301
+ const layerRule = findRuleMatch(config.layers, relative14);
6276
7302
  if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
6277
- const kindRule = findRuleMatch(config.kinds, relative12);
7303
+ const kindRule = findRuleMatch(config.kinds, relative14);
6278
7304
  if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
6279
7305
  const manifest = readManifest2(config);
6280
- const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative12) : void 0;
7306
+ const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative14) : void 0;
6281
7307
  result.part = entry?.part ?? null;
6282
- result.inclusionMode = entry?.inclusionMode;
6283
7308
  return result;
6284
7309
  }
6285
7310
  function renderExplainText(result) {
@@ -6488,18 +7513,70 @@ function summarizeMarkdown(content) {
6488
7513
  frontmatterKeys: Array.from(new Set(frontmatterKeys)).sort()
6489
7514
  };
6490
7515
  }
7516
+ function decodeGitignore(buffer) {
7517
+ const startsWith = (...bytes) => buffer.length >= bytes.length && bytes.every((byte, index) => buffer[index] === byte);
7518
+ if (startsWith(239, 187, 191)) {
7519
+ const body = buffer.subarray(3);
7520
+ const text3 = body.toString("utf8");
7521
+ if (!Buffer.from(text3, "utf8").equals(body)) return null;
7522
+ return { text: text3, bom: buffer.subarray(0, 3), encoding: "utf8" };
7523
+ }
7524
+ if (startsWith(255, 254)) {
7525
+ const body = buffer.subarray(2);
7526
+ if (body.length % 2 !== 0) return null;
7527
+ const text3 = body.toString("utf16le");
7528
+ if (!Buffer.from(text3, "utf16le").equals(body)) return null;
7529
+ return { text: text3, bom: buffer.subarray(0, 2), encoding: "utf16le" };
7530
+ }
7531
+ if (startsWith(254, 255)) {
7532
+ const body = buffer.subarray(2);
7533
+ if (body.length % 2 !== 0) return null;
7534
+ const swapped = Buffer.from(body);
7535
+ swapped.swap16();
7536
+ const text3 = swapped.toString("utf16le");
7537
+ if (!Buffer.from(text3, "utf16le").equals(swapped)) return null;
7538
+ return { text: text3, bom: buffer.subarray(0, 2), encoding: "utf16be" };
7539
+ }
7540
+ const text2 = buffer.toString("utf8");
7541
+ if (!Buffer.from(text2, "utf8").equals(buffer)) return null;
7542
+ return { text: text2, bom: Buffer.alloc(0), encoding: "utf8" };
7543
+ }
7544
+ function encodeGitignore(decoded, text2) {
7545
+ if (decoded.encoding === "utf8") {
7546
+ return Buffer.concat([decoded.bom, Buffer.from(text2, "utf8")]);
7547
+ }
7548
+ const littleEndian = Buffer.from(text2, "utf16le");
7549
+ if (decoded.encoding === "utf16le") return Buffer.concat([decoded.bom, littleEndian]);
7550
+ const bigEndian = Buffer.from(littleEndian);
7551
+ bigEndian.swap16();
7552
+ return Buffer.concat([decoded.bom, bigEndian]);
7553
+ }
7554
+ function canonicalIgnorePattern(line) {
7555
+ const trimmed = line.trim();
7556
+ if (trimmed.length === 0 || trimmed.startsWith("#")) return trimmed;
7557
+ const negated = trimmed.startsWith("!");
7558
+ const body = (negated ? trimmed.slice(1) : trimmed).replace(/^\/+/, "").replace(/\/+$/, "");
7559
+ return `${negated ? "!" : ""}${body}`;
7560
+ }
6491
7561
  function appendGitignoreEntries(cwd, entries) {
6492
7562
  const wanted = [...new Set(entries)].filter((entry) => entry.trim().length > 0);
6493
7563
  if (wanted.length === 0) return { added: [], note: null };
6494
7564
  const ignorePath = path16__namespace.join(cwd, ".gitignore");
6495
7565
  const manual = `Add ${wanted.map((entry) => `"${entry}"`).join(" and ")} to your .gitignore yourself.`;
6496
- let existing = "";
7566
+ let decoded = { text: "", bom: Buffer.alloc(0), encoding: "utf8" };
6497
7567
  try {
6498
- if (fs14__namespace.existsSync(ignorePath)) {
6499
- if (fs14__namespace.statSync(ignorePath).isDirectory()) {
7568
+ if (fs15__namespace.existsSync(ignorePath)) {
7569
+ if (fs15__namespace.statSync(ignorePath).isDirectory()) {
6500
7570
  return { added: [], note: `${ignorePath} is a directory, so it was not updated. ${manual}` };
6501
7571
  }
6502
- existing = fs14__namespace.readFileSync(ignorePath, "utf8");
7572
+ const read = decodeGitignore(fs15__namespace.readFileSync(ignorePath));
7573
+ if (read === null) {
7574
+ return {
7575
+ added: [],
7576
+ note: `${ignorePath} is not valid UTF-8, UTF-16LE or UTF-16BE text, so it was not updated. ` + manual
7577
+ };
7578
+ }
7579
+ decoded = read;
6503
7580
  }
6504
7581
  } catch (err) {
6505
7582
  return {
@@ -6507,13 +7584,17 @@ function appendGitignoreEntries(cwd, entries) {
6507
7584
  note: `${ignorePath} could not be read (${err.message}). ${manual}`
6508
7585
  };
6509
7586
  }
6510
- const present = new Set(existing.split(/\r?\n/).map((line) => line.trim()));
6511
- const added = wanted.filter((entry) => !present.has(entry));
7587
+ const existing = decoded.text;
7588
+ const present = new Set(existing.split(/\r?\n/).map(canonicalIgnorePattern));
7589
+ const added = wanted.filter((entry) => !present.has(canonicalIgnorePattern(entry)));
6512
7590
  if (added.length === 0) return { added: [], note: null };
6513
- const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : "\n";
7591
+ const newline = existing.includes("\r\n") ? "\r\n" : "\n";
7592
+ const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : newline;
6514
7593
  try {
6515
- fs14__namespace.writeFileSync(ignorePath, `${existing}${prefix}${added.join("\n")}
6516
- `, "utf8");
7594
+ fs15__namespace.writeFileSync(
7595
+ ignorePath,
7596
+ encodeGitignore(decoded, `${existing}${prefix}${added.join(newline)}${newline}`)
7597
+ );
6517
7598
  } catch (err) {
6518
7599
  return { added: [], note: `${err.message}. ${manual}` };
6519
7600
  }
@@ -6523,15 +7604,6 @@ function gitignorePath(cwd, filePath) {
6523
7604
  return path16__namespace.relative(cwd, filePath).split(path16__namespace.sep).join("/");
6524
7605
  }
6525
7606
 
6526
- // src/version.ts
6527
- var GENERATOR_NAME = "codebase-snapshot";
6528
- var GENERATOR_VERSION = "0.9.15";
6529
- var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
6530
- function isOurGeneratorName(name) {
6531
- if (typeof name !== "string") return false;
6532
- return name === GENERATOR_NAME || LEGACY_GENERATOR_NAMES.includes(name);
6533
- }
6534
-
6535
7607
  // src/wizard/config-template.ts
6536
7608
  var DEFAULT_ANSWERS = {
6537
7609
  maxPartBytes: "300k",
@@ -6836,7 +7908,7 @@ function keyReader(input) {
6836
7908
  next() {
6837
7909
  const queued = queue.shift();
6838
7910
  if (queued) return Promise.resolve(queued);
6839
- return new Promise((resolve10) => waiters.push(resolve10));
7911
+ return new Promise((resolve11) => waiters.push(resolve11));
6840
7912
  },
6841
7913
  close() {
6842
7914
  input.off("keypress", onKey);
@@ -7062,7 +8134,7 @@ function parsePackageJson(raw) {
7062
8134
  }
7063
8135
  function readPackageJson(cwd) {
7064
8136
  try {
7065
- return parsePackageJson(fs14__namespace.readFileSync(path16__namespace.join(cwd, "package.json"), "utf8"));
8137
+ return parsePackageJson(fs15__namespace.readFileSync(path16__namespace.join(cwd, "package.json"), "utf8"));
7066
8138
  } catch {
7067
8139
  return null;
7068
8140
  }
@@ -7099,7 +8171,7 @@ function artifactAnswers(options) {
7099
8171
  }
7100
8172
  function topLevelDirs(cwd) {
7101
8173
  try {
7102
- return fs14__namespace.readdirSync(cwd, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules").map((entry) => entry.name).sort();
8174
+ return fs15__namespace.readdirSync(cwd, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules").map((entry) => entry.name).sort();
7103
8175
  } catch {
7104
8176
  return [];
7105
8177
  }
@@ -7112,10 +8184,38 @@ function describeJsonValue(value) {
7112
8184
  }
7113
8185
  function writeFileOrExplain(target, content) {
7114
8186
  try {
7115
- fs14__namespace.writeFileSync(target, content, "utf8");
8187
+ let stats = null;
8188
+ try {
8189
+ stats = fs15__namespace.lstatSync(target);
8190
+ } catch {
8191
+ stats = null;
8192
+ }
8193
+ if (stats !== null && stats.isSymbolicLink()) {
8194
+ throw new Error(
8195
+ `Cannot write ${target}: it is a symbolic link, and writing through it would modify whatever it points at.`
8196
+ );
8197
+ }
8198
+ if (stats !== null && !stats.isFile()) {
8199
+ throw new Error(
8200
+ `Cannot write ${target}: ${stats.isDirectory() ? "it is a directory" : "it is not a regular file"}.`
8201
+ );
8202
+ }
8203
+ const temporary = `${target}.tmp-${process.pid}-${Date.now()}`;
8204
+ fs15__namespace.writeFileSync(temporary, content, { encoding: "utf8", flag: "wx" });
8205
+ try {
8206
+ fs15__namespace.renameSync(temporary, target);
8207
+ } catch (err) {
8208
+ try {
8209
+ fs15__namespace.unlinkSync(temporary);
8210
+ } catch {
8211
+ }
8212
+ throw err;
8213
+ }
7116
8214
  } catch (err) {
8215
+ const message = err.message;
8216
+ if (message.startsWith(`Cannot write ${target}:`)) throw err;
7117
8217
  const code = err.code;
7118
- const reason = code === "EACCES" || code === "EPERM" || code === "EROFS" ? `permission denied (${code})` : code === "EISDIR" ? "it is a directory" : `${err.message}`;
8218
+ const reason = code === "EACCES" || code === "EPERM" || code === "EROFS" ? `permission denied (${code})` : code === "EISDIR" ? "it is a directory" : message;
7119
8219
  throw new Error(`Cannot write ${target}: ${reason}`);
7120
8220
  }
7121
8221
  }
@@ -7159,14 +8259,14 @@ function updatePackageJson(cwd, notes) {
7159
8259
  scripts: [],
7160
8260
  dependency: { name: GENERATOR_NAME, range: null, added: false }
7161
8261
  };
7162
- if (!fs14__namespace.existsSync(packagePath)) {
8262
+ if (!fs15__namespace.existsSync(packagePath)) {
7163
8263
  notes.push("No package.json found, so npm scripts and the devDependency were not added.");
7164
8264
  return unchanged;
7165
8265
  }
7166
8266
  let raw;
7167
8267
  let parsed;
7168
8268
  try {
7169
- raw = fs14__namespace.readFileSync(packagePath, "utf8");
8269
+ raw = fs15__namespace.readFileSync(packagePath, "utf8");
7170
8270
  parsed = parsePackageJson(raw);
7171
8271
  } catch {
7172
8272
  notes.push("Could not parse package.json; npm scripts and the devDependency were not added.");
@@ -7237,7 +8337,7 @@ function updatePackageJson(cwd, notes) {
7237
8337
  writeFileOrExplain(packagePath, serializePackageJson(raw, parsed));
7238
8338
  return { scripts: added, dependency };
7239
8339
  }
7240
- var GITIGNORE_ENTRIES = ["snapshot/", "snapshot.tmp/"];
8340
+ var GITIGNORE_ENTRIES = ["/snapshot/", "/snapshot.tmp/"];
7241
8341
  function resolvePresetChoice(detectedName, presetName) {
7242
8342
  return {
7243
8343
  value: presetName,
@@ -7475,7 +8575,7 @@ async function runInit(options) {
7475
8575
  const configText = renderConfig(answers);
7476
8576
  const preferredName = chooseConfigFileName(options.cwd);
7477
8577
  const presentConfigs = CONFIG_CANDIDATES.filter(
7478
- (name) => fs14__namespace.existsSync(path16__namespace.join(options.cwd, name))
8578
+ (name) => fs15__namespace.existsSync(path16__namespace.join(options.cwd, name))
7479
8579
  );
7480
8580
  const present = presentConfigs[0] ?? null;
7481
8581
  if (presentConfigs.length > 1) {
@@ -7518,7 +8618,7 @@ async function runInit(options) {
7518
8618
  'package.json already defines a "snapshot" config. Remove that key, or re-run with --force to write a config file that takes precedence over it.'
7519
8619
  );
7520
8620
  }
7521
- if (fs14__namespace.existsSync(configPath) && !options.force && !reused) {
8621
+ if (fs15__namespace.existsSync(configPath) && !options.force && !reused) {
7522
8622
  throw new Error(`${configName} already exists. Re-run with --force to replace it.`);
7523
8623
  }
7524
8624
  if (!reused) writeFileOrExplain(configPath, configText);
@@ -7541,10 +8641,10 @@ async function runInit(options) {
7541
8641
  };
7542
8642
  }
7543
8643
  function describeTarget(cwd) {
7544
- const relative12 = path16__namespace.relative(process.cwd(), cwd);
7545
- if (relative12 === "") return "this directory";
7546
- if (relative12.startsWith("..") || path16__namespace.isAbsolute(relative12)) return cwd;
7547
- return relative12;
8644
+ const relative14 = path16__namespace.relative(process.cwd(), cwd);
8645
+ if (relative14 === "") return "this directory";
8646
+ if (relative14.startsWith("..") || path16__namespace.isAbsolute(relative14)) return cwd;
8647
+ return relative14;
7548
8648
  }
7549
8649
  function firstRunMessage(reason, cwd) {
7550
8650
  const where = describeTarget(cwd);
@@ -7567,7 +8667,7 @@ function planFirstRun(facts) {
7567
8667
  var NOT_CONTENT = /* @__PURE__ */ new Set([".git", ".hg", ".svn", ".bzr", ".DS_Store", "Thumbs.db"]);
7568
8668
  function isEffectivelyEmpty(cwd) {
7569
8669
  try {
7570
- return fs14__namespace.readdirSync(cwd).every((entry) => NOT_CONTENT.has(entry));
8670
+ return fs15__namespace.readdirSync(cwd).every((entry) => NOT_CONTENT.has(entry));
7571
8671
  } catch {
7572
8672
  return false;
7573
8673
  }
@@ -7575,7 +8675,7 @@ function isEffectivelyEmpty(cwd) {
7575
8675
  function hasPriorSnapshot(cwd, outDir) {
7576
8676
  let parsed;
7577
8677
  try {
7578
- parsed = JSON.parse(fs14__namespace.readFileSync(path16__namespace.join(cwd, outDir, ".codebase-snapshot"), "utf8"));
8678
+ parsed = JSON.parse(fs15__namespace.readFileSync(path16__namespace.join(cwd, outDir, ".codebase-snapshot"), "utf8"));
7579
8679
  } catch {
7580
8680
  return false;
7581
8681
  }
@@ -7603,104 +8703,42 @@ function installStdoutRouter() {
7603
8703
  if (hookStdoutScope.getStore() === true) return realStderr(...args);
7604
8704
  const capture = captureScope.getStore();
7605
8705
  if (capture !== void 0) {
7606
- capture.write(asText(args[0]));
7607
- const callback = callbackIn(args.slice(1));
7608
- if (callback) callback(null);
7609
- return true;
7610
- }
7611
- return realStdout(...args);
7612
- });
7613
- process.stdout.write = router;
7614
- }
7615
- installs += 1;
7616
- let released = false;
7617
- return () => {
7618
- if (released) return;
7619
- released = true;
7620
- installs -= 1;
7621
- if (installs === 0) {
7622
- if (process.stdout.write === router && underlying !== null) {
7623
- process.stdout.write = underlying;
7624
- }
7625
- underlying = null;
7626
- router = null;
7627
- }
7628
- };
7629
- }
7630
- async function runWithStdoutCapture(fn) {
7631
- let text2 = "";
7632
- const release = installStdoutRouter();
7633
- try {
7634
- const value = await captureScope.run(
7635
- { write: (chunk) => void (text2 += chunk) },
7636
- fn
7637
- );
7638
- return { value, text: text2 };
7639
- } finally {
7640
- release();
7641
- }
7642
- }
7643
- function hasCollapsibleBody(node) {
7644
- if (!("body" in node)) return false;
7645
- const body = node.body;
7646
- return body !== void 0 && ts__default.default.isBlock(body);
7647
- }
7648
- function scriptKindFor(fileName) {
7649
- const lower = fileName.toLowerCase();
7650
- if (lower.endsWith(".tsx")) return ts__default.default.ScriptKind.TSX;
7651
- if (lower.endsWith(".jsx")) return ts__default.default.ScriptKind.JSX;
7652
- if (lower.endsWith(".js") || lower.endsWith(".mjs") || lower.endsWith(".cjs")) {
7653
- return ts__default.default.ScriptKind.JS;
7654
- }
7655
- return ts__default.default.ScriptKind.TS;
7656
- }
7657
- function skeletonizeTypeScript(source, fileName = "file.ts") {
7658
- const sourceFile = ts__default.default.createSourceFile(
7659
- fileName,
7660
- source,
7661
- ts__default.default.ScriptTarget.Latest,
7662
- // `setParentNodes: false`. Nothing here reads `.parent` — the one `getStart` call is given the
7663
- // source file explicitly, which is the reason that argument exists. Asking for parent pointers
7664
- // makes the parser run a second full pass over every node in the file to set them, on top of
7665
- // the summary parse this same file already pays for.
7666
- false,
7667
- scriptKindFor(fileName)
7668
- );
7669
- const spans = [];
7670
- const visit = (node) => {
7671
- if ((ts__default.default.isFunctionDeclaration(node) || ts__default.default.isMethodDeclaration(node) || ts__default.default.isConstructorDeclaration(node) || ts__default.default.isGetAccessorDeclaration(node) || ts__default.default.isSetAccessorDeclaration(node) || ts__default.default.isFunctionExpression(node) || ts__default.default.isArrowFunction(node)) && hasCollapsibleBody(node)) {
7672
- const body = node.body;
7673
- if (body.statements.length > 0) {
7674
- const start = body.getStart(sourceFile);
7675
- const end = body.getEnd();
7676
- if (end > start) spans.push({ start, end });
8706
+ capture.write(asText(args[0]));
8707
+ const callback = callbackIn(args.slice(1));
8708
+ if (callback) callback(null);
8709
+ return true;
8710
+ }
8711
+ return realStdout(...args);
8712
+ });
8713
+ process.stdout.write = router;
8714
+ }
8715
+ installs += 1;
8716
+ let released = false;
8717
+ return () => {
8718
+ if (released) return;
8719
+ released = true;
8720
+ installs -= 1;
8721
+ if (installs === 0) {
8722
+ if (process.stdout.write === router && underlying !== null) {
8723
+ process.stdout.write = underlying;
7677
8724
  }
8725
+ underlying = null;
8726
+ router = null;
7678
8727
  }
7679
- ts__default.default.forEachChild(node, visit);
7680
8728
  };
7681
- visit(sourceFile);
7682
- if (spans.length === 0) return { text: source, collapsed: 0 };
7683
- const outermost = [];
7684
- for (const span of spans.sort((a, b) => a.start - b.start || b.end - a.end)) {
7685
- const last = outermost[outermost.length - 1];
7686
- if (last && span.start < last.end) continue;
7687
- outermost.push(span);
7688
- }
7689
- const chunks = [];
7690
- let cursor = 0;
7691
- for (const span of outermost) {
7692
- chunks.push(source.slice(cursor, span.start), "{ /* ... */ }");
7693
- cursor = span.end;
7694
- }
7695
- chunks.push(source.slice(cursor));
7696
- return { text: chunks.join(""), collapsed: outermost.length };
7697
8729
  }
7698
- function isSkeletonizable(filePath) {
7699
- const lower = filePath.toLowerCase();
7700
- if (lower.endsWith(".d.ts") || lower.endsWith(".d.mts") || lower.endsWith(".d.cts")) {
7701
- return false;
8730
+ async function runWithStdoutCapture(fn) {
8731
+ let text2 = "";
8732
+ const release = installStdoutRouter();
8733
+ try {
8734
+ const value = await captureScope.run(
8735
+ { write: (chunk) => void (text2 += chunk) },
8736
+ fn
8737
+ );
8738
+ return { value, text: text2 };
8739
+ } finally {
8740
+ release();
7702
8741
  }
7703
- return lower.endsWith(".ts") || lower.endsWith(".tsx") || lower.endsWith(".mts") || lower.endsWith(".cts") || lower.endsWith(".js") || lower.endsWith(".jsx") || lower.endsWith(".mjs") || lower.endsWith(".cjs");
7704
8742
  }
7705
8743
 
7706
8744
  // src/generator/audit.ts
@@ -7713,8 +8751,9 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
7713
8751
  `**Generated:** ${manifest.generatedAt} `,
7714
8752
  `**Git Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""}) `,
7715
8753
  `**Total Files:** ${formatNumber(manifest.counts.totalFiles)} `,
7716
- `**Total Lines:** ${formatNumber(manifest.counts.totalLines)} `,
7717
- `**Total Size:** ${(manifest.counts.totalSizeBytes / (1024 * 1024)).toFixed(2)} MB `,
8754
+ `**Source Lines:** ${formatNumber(manifest.counts.totalLines)} `,
8755
+ `**Emitted Lines:** ${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)} `,
8756
+ `**Total Size:** ${(manifest.counts.totalSizeBytes / (1024 * 1024)).toFixed(2)} MiB `,
7718
8757
  // This counts the bytes that were *emitted* after redaction, not the bytes
7719
8758
  // that were masked: calling it "redacted bytes" made a repository with zero
7720
8759
  // secrets report a non-zero redacted-byte figure directly above "no secrets
@@ -7754,9 +8793,19 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
7754
8793
  const parseIssues = manifest.files.filter(
7755
8794
  (file) => file.summary !== void 0 && typeof file.summary === "object" && "parseErrors" in file.summary && typeof file.summary.parseErrors === "number" && file.summary.parseErrors > 0
7756
8795
  );
8796
+ const unparsedPreviews = manifest.files.filter(
8797
+ (file) => file.summary === void 0 && (file.isPreviewTruncated === true || file.isLarge === true)
8798
+ ).length;
7757
8799
  lines.push("## 2. Parse & AST Diagnostics", "");
7758
8800
  if (parseIssues.length === 0) {
7759
- lines.push("\u2705 Every parsed file produced a complete structural summary.", "");
8801
+ if (unparsedPreviews > 0) {
8802
+ lines.push(
8803
+ `\u2705 No parse errors among the files that were parsed; ${formatNumber(unparsedPreviews)} file(s) were previewed or too large to parse and produced no structural summary.`,
8804
+ ""
8805
+ );
8806
+ } else {
8807
+ lines.push("\u2705 Every parsed file produced a complete structural summary.", "");
8808
+ }
7760
8809
  } else {
7761
8810
  lines.push(
7762
8811
  `${parseIssues.length} file(s) produced an incomplete summary:`,
@@ -7983,19 +9032,19 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
7983
9032
  for (const sections of greedyGroups(prepared, budget)) groups.push({ sections, budget });
7984
9033
  }
7985
9034
  if (groups.length === 0) return [];
7986
- const measurements = /* @__PURE__ */ new Map();
9035
+ const assemblies = /* @__PURE__ */ new Map();
7987
9036
  const widthOf = (total) => Math.max(3, String(total).length);
7988
- const measure = (group, index, total) => {
7989
- const cached = measurements.get(group);
9037
+ const assemble = (group, index, total) => {
7990
9038
  const width = widthOf(total);
9039
+ const cached = assemblies.get(group);
7991
9040
  if (cached !== void 0 && cached.index === index && cached.width === width) {
7992
- return cached.size;
9041
+ return cached.value;
7993
9042
  }
7994
- const { content } = assembleGroup(group, index, total, contentFingerprint);
7995
- const size2 = Buffer.byteLength(content, "utf8");
7996
- measurements.set(group, { index, width, size: size2 });
7997
- return size2;
9043
+ const value = assembleGroup(group, index, total, contentFingerprint);
9044
+ assemblies.set(group, { index, width, value });
9045
+ return value;
7998
9046
  };
9047
+ const measure = (group, index, total) => Buffer.byteLength(assemble(group, index, total).content, "utf8");
7999
9048
  for (let pass = 0; pass < MAX_SPLIT_PASSES; pass++) {
8000
9049
  const total = groups.length;
8001
9050
  let oversized = -1;
@@ -8006,16 +9055,16 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
8006
9055
  break;
8007
9056
  }
8008
9057
  }
8009
- if (oversized === -1) return renderGroups(groups, contentFingerprint);
9058
+ if (oversized === -1) return renderGroups(groups, contentFingerprint, assemble);
8010
9059
  const group = groups[oversized];
8011
9060
  if (group.sections.length > 1) {
8012
9061
  const moved = group.sections.pop();
8013
9062
  groups.splice(oversized + 1, 0, { sections: [moved], budget: group.budget });
8014
- measurements.delete(group);
9063
+ assemblies.delete(group);
8015
9064
  continue;
8016
9065
  }
8017
9066
  const [section] = group.sections;
8018
- if (section === void 0) return renderGroups(groups, contentFingerprint);
9067
+ if (section === void 0) return renderGroups(groups, contentFingerprint, assemble);
8019
9068
  const overflow = measure(group, oversized, total) - group.budget;
8020
9069
  const currentContent = section.file.content ?? "";
8021
9070
  const shrinkTo = Math.max(
@@ -8032,10 +9081,10 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
8032
9081
  applyTruncatedContent(section.file, shrunk.content);
8033
9082
  section.text = renderFileSection(section.file);
8034
9083
  section.byteSize = Buffer.byteLength(section.text, "utf8");
8035
- measurements.delete(group);
9084
+ assemblies.delete(group);
8036
9085
  continue;
8037
9086
  }
8038
- const rendered = renderGroups(groups, contentFingerprint);
9087
+ const rendered = renderGroups(groups, contentFingerprint, assemble);
8039
9088
  const marker2 = TRUNCATION_MARKER;
8040
9089
  assertBudgetHoldsMarker(group.budget);
8041
9090
  const target = Math.max(
@@ -8049,7 +9098,7 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
8049
9098
  );
8050
9099
  return rendered;
8051
9100
  }
8052
- return renderGroups(groups, contentFingerprint).flatMap(
9101
+ return renderGroups(groups, contentFingerprint, assemble).flatMap(
8053
9102
  (part) => enforceBudget([part], part.metadata.budgetBytes)
8054
9103
  );
8055
9104
  }
@@ -8223,8 +9272,8 @@ function assembleGroup(group, index, total, contentFingerprint) {
8223
9272
  for (const section of group.sections) {
8224
9273
  section.file.part = filename;
8225
9274
  }
8226
- const layerCounts = {};
8227
- const kindCounts = {};
9275
+ const layerCounts = /* @__PURE__ */ Object.create(null);
9276
+ const kindCounts = /* @__PURE__ */ Object.create(null);
8228
9277
  for (const section of group.sections) {
8229
9278
  layerCounts[section.file.layer] = (layerCounts[section.file.layer] || 0) + 1;
8230
9279
  kindCounts[section.file.kind] = (kindCounts[section.file.kind] || 0) + 1;
@@ -8259,15 +9308,10 @@ function assembleGroup(group, index, total, contentFingerprint) {
8259
9308
  const estimatedTokens = estimateTokens(assembled);
8260
9309
  return { filename, content: insertTokenLine(assembled, estimatedTokens), estimatedTokens };
8261
9310
  }
8262
- function renderGroups(groups, contentFingerprint) {
9311
+ function renderGroups(groups, contentFingerprint, assemble = (group, index, total) => assembleGroup(group, index, total, contentFingerprint)) {
8263
9312
  const total = groups.length;
8264
9313
  return groups.map((group, index) => {
8265
- const { filename, content, estimatedTokens } = assembleGroup(
8266
- group,
8267
- index,
8268
- total,
8269
- contentFingerprint
8270
- );
9314
+ const { filename, content, estimatedTokens } = assemble(group, index, total);
8271
9315
  const byteSize = Buffer.byteLength(content, "utf8");
8272
9316
  const sha256 = crypto3__namespace.createHash("sha256").update(content).digest("hex");
8273
9317
  const layersCovered = Array.from(new Set(group.sections.map((s) => s.file.layer))).sort();
@@ -8484,9 +9528,10 @@ function generateReadme(manifest, artifacts) {
8484
9528
  `- **Schema Version:** \`${manifest.schemaVersion}\``,
8485
9529
  `- **Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""})`,
8486
9530
  `- **Total Tracked Files:** \`${manifest.counts.totalFiles}\``,
8487
- `- **Total Code Lines:** \`${formatNumber(manifest.counts.totalLines)}\``,
8488
- `- **Total Size:** \`${(manifest.counts.totalSizeBytes / (1024 * 1024)).toFixed(2)} MB\``,
8489
- `- **Emitted Content:** \`${(manifest.totals.totalContentBytes / (1024 * 1024)).toFixed(2)} MB\``,
9531
+ `- **Source Lines:** \`${formatNumber(manifest.counts.totalLines)}\``,
9532
+ `- **Emitted Lines:** \`${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)}\``,
9533
+ `- **Total Size:** \`${(manifest.counts.totalSizeBytes / (1024 * 1024)).toFixed(2)} MiB\``,
9534
+ `- **Emitted Content:** \`${(manifest.totals.totalContentBytes / (1024 * 1024)).toFixed(2)} MiB\``,
8490
9535
  `- **Part Count:** \`${manifest.counts.partsCount}\` (budget \`${(manifest.budgets.maxPartBytes / 1024).toFixed(0)} KB\` per part)`,
8491
9536
  `- **Generator:** \`${manifest.generator.name}@${manifest.generator.version}\``,
8492
9537
  "",
@@ -8672,23 +9717,24 @@ function shouldCheck(argv, env) {
8672
9717
  for (const skip of ["mcp", "describe", "skill", "--version", "-v", "--help", "-h"]) {
8673
9718
  if (args.includes(skip)) return false;
8674
9719
  }
9720
+ let format = null;
8675
9721
  for (let index = 0; index < args.length; index += 1) {
8676
9722
  const argument = args[index];
9723
+ if (argument === "--") break;
8677
9724
  if (argument === "--format") {
8678
- if (args[index + 1] === "json") return false;
8679
- break;
8680
- }
8681
- if (argument.startsWith("--format=")) {
8682
- if (argument.slice("--format=".length) === "json") return false;
8683
- break;
9725
+ format = args[index + 1] ?? null;
9726
+ index += 1;
9727
+ continue;
8684
9728
  }
9729
+ if (argument.startsWith("--format=")) format = argument.slice("--format=".length);
8685
9730
  }
9731
+ if (format === "json") return false;
8686
9732
  return true;
8687
9733
  }
8688
9734
  function readCache(file) {
8689
9735
  let raw;
8690
9736
  try {
8691
- raw = fs14__namespace.readFileSync(file, "utf8");
9737
+ raw = fs15__namespace.readFileSync(file, "utf8");
8692
9738
  } catch {
8693
9739
  return null;
8694
9740
  }
@@ -8705,21 +9751,21 @@ function readCache(file) {
8705
9751
  }
8706
9752
  function writeCache(file, entry) {
8707
9753
  try {
8708
- fs14__namespace.mkdirSync(path16__namespace.dirname(file), { recursive: true });
8709
- fs14__namespace.writeFileSync(file, `${JSON.stringify(entry)}
9754
+ fs15__namespace.mkdirSync(path16__namespace.dirname(file), { recursive: true });
9755
+ fs15__namespace.writeFileSync(file, `${JSON.stringify(entry)}
8710
9756
  `, "utf8");
8711
9757
  } catch {
8712
9758
  }
8713
9759
  }
8714
9760
  function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOUT_MS) {
8715
- return new Promise((resolve10) => {
9761
+ return new Promise((resolve11) => {
8716
9762
  let settled = false;
8717
9763
  let request = null;
8718
9764
  const finish = (value) => {
8719
9765
  if (settled) return;
8720
9766
  settled = true;
8721
9767
  clearTimeout(deadline);
8722
- resolve10(value);
9768
+ resolve11(value);
8723
9769
  };
8724
9770
  const deadline = setTimeout(() => {
8725
9771
  request?.destroy();
@@ -8814,9 +9860,17 @@ set -e
8814
9860
  SNAPSHOT_DIR="${dir}"
8815
9861
 
8816
9862
  if [ ! -f "$SNAPSHOT_DIR/manifest.json" ]; then
8817
- echo "${GENERATOR_NAME}: no snapshot in $SNAPSHOT_DIR, skipping the staleness check." >&2
8818
- echo " Run \\"npx ${GENERATOR_NAME} generate\\" to create one." >&2
8819
- exit 0
9863
+ # Fail closed. A missing snapshot used to exit 0 with a reassuring message, so deleting or
9864
+ # renaming the output directory disabled the gate while every commit still succeeded \u2014 the one
9865
+ # failure mode a commit gate must not have. The opt-out is explicit and documented.
9866
+ if [ "\${CODEBASE_SNAPSHOT_ALLOW_MISSING:-}" = "1" ]; then
9867
+ echo "${GENERATOR_NAME}: no snapshot in $SNAPSHOT_DIR; skipping the check (CODEBASE_SNAPSHOT_ALLOW_MISSING=1)." >&2
9868
+ exit 0
9869
+ fi
9870
+ echo "${GENERATOR_NAME}: refusing the commit: no snapshot in $SNAPSHOT_DIR." >&2
9871
+ echo " Run \\"npx ${GENERATOR_NAME} generate\\", stage it, and commit again." >&2
9872
+ echo " To disable this gate, set CODEBASE_SNAPSHOT_ALLOW_MISSING=1." >&2
9873
+ exit 1
8820
9874
  fi
8821
9875
 
8822
9876
  if ! npx --no-install ${GENERATOR_NAME} validate >/dev/null 2>&1; then
@@ -8831,26 +9885,69 @@ function gitDirectory(cwd) {
8831
9885
  const dotGit = path16__namespace.join(cwd, ".git");
8832
9886
  let stats;
8833
9887
  try {
8834
- stats = fs14__namespace.statSync(dotGit);
9888
+ stats = fs15__namespace.statSync(dotGit);
8835
9889
  } catch {
8836
9890
  return null;
8837
9891
  }
8838
9892
  if (stats.isDirectory()) return dotGit;
8839
9893
  if (!stats.isFile()) return null;
8840
9894
  try {
8841
- const contents = fs14__namespace.readFileSync(dotGit, "utf8");
9895
+ const contents = fs15__namespace.readFileSync(dotGit, "utf8");
8842
9896
  const match = /^gitdir:\s*(.+)$/m.exec(contents);
8843
9897
  if (!match) return null;
8844
9898
  const target = match[1];
8845
9899
  const resolved = path16__namespace.isAbsolute(target.trim()) ? target.trim() : path16__namespace.join(cwd, target.trim());
8846
- return fs14__namespace.statSync(resolved).isDirectory() ? resolved : null;
9900
+ if (!fs15__namespace.statSync(resolved).isDirectory()) return null;
9901
+ if (isInside2(path16__namespace.resolve(cwd), path16__namespace.resolve(resolved))) return resolved;
9902
+ return isRegisteredWorktree(path16__namespace.resolve(resolved), cwd) ? resolved : null;
9903
+ } catch {
9904
+ return null;
9905
+ }
9906
+ }
9907
+ function isInside2(parent, child) {
9908
+ const relative14 = path16__namespace.relative(parent, child);
9909
+ return relative14 === "" || !relative14.startsWith("..") && !path16__namespace.isAbsolute(relative14);
9910
+ }
9911
+ function isRegisteredWorktree(gitDir, cwd) {
9912
+ try {
9913
+ const back = fs15__namespace.readFileSync(path16__namespace.join(gitDir, "gitdir"), "utf8").trim();
9914
+ return path16__namespace.resolve(gitDir, back) === path16__namespace.join(path16__namespace.resolve(cwd), ".git");
9915
+ } catch {
9916
+ return false;
9917
+ }
9918
+ }
9919
+ function gitOutput(cwd, args) {
9920
+ try {
9921
+ const output = childProcess__namespace.execFileSync("git", args, {
9922
+ cwd,
9923
+ encoding: "utf8",
9924
+ stdio: ["ignore", "pipe", "ignore"]
9925
+ });
9926
+ const trimmed = output.trim();
9927
+ return trimmed.length > 0 ? trimmed : null;
8847
9928
  } catch {
8848
9929
  return null;
8849
9930
  }
8850
9931
  }
9932
+ function configuredHooksDirectory(cwd) {
9933
+ const hooks = gitOutput(cwd, ["rev-parse", "--git-path", "hooks"]);
9934
+ if (hooks === null) return null;
9935
+ const resolved = path16__namespace.resolve(cwd, hooks);
9936
+ const common = gitOutput(cwd, ["rev-parse", "--git-common-dir"]);
9937
+ const commonDir = common === null ? null : path16__namespace.resolve(cwd, common);
9938
+ if (isInside2(path16__namespace.resolve(cwd), resolved)) return { dir: resolved };
9939
+ if (commonDir !== null && isInside2(commonDir, resolved)) return { dir: resolved };
9940
+ return {
9941
+ 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.`
9942
+ };
9943
+ }
8851
9944
  function installPreCommitHook(cwd, outDir = "snapshot") {
8852
- const gitDir = gitDirectory(cwd);
8853
- if (gitDir === null) {
9945
+ const configured = configuredHooksDirectory(cwd);
9946
+ if (configured !== null && "refusal" in configured) {
9947
+ return { path: null, written: false, notes: [configured.refusal] };
9948
+ }
9949
+ const gitDir = configured === null ? gitDirectory(cwd) : null;
9950
+ if (configured === null && gitDir === null) {
8854
9951
  return {
8855
9952
  path: null,
8856
9953
  written: false,
@@ -8859,10 +9956,10 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
8859
9956
  ]
8860
9957
  };
8861
9958
  }
8862
- const hooksDir = path16__namespace.join(gitDir, "hooks");
9959
+ const hooksDir = configured === null ? path16__namespace.join(gitDir, "hooks") : configured.dir;
8863
9960
  const hookPath = path16__namespace.join(hooksDir, "pre-commit");
8864
9961
  try {
8865
- fs14__namespace.mkdirSync(hooksDir, { recursive: true });
9962
+ fs15__namespace.mkdirSync(hooksDir, { recursive: true });
8866
9963
  } catch (err) {
8867
9964
  return {
8868
9965
  path: hookPath,
@@ -8872,7 +9969,7 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
8872
9969
  }
8873
9970
  let existing = null;
8874
9971
  try {
8875
- existing = fs14__namespace.readFileSync(hookPath, "utf8");
9972
+ existing = fs15__namespace.readFileSync(hookPath, "utf8");
8876
9973
  } catch {
8877
9974
  existing = null;
8878
9975
  }
@@ -8887,8 +9984,8 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
8887
9984
  };
8888
9985
  }
8889
9986
  try {
8890
- fs14__namespace.writeFileSync(hookPath, hookScript(outDir), "utf8");
8891
- fs14__namespace.chmodSync(hookPath, 493);
9987
+ fs15__namespace.writeFileSync(hookPath, hookScript(outDir), "utf8");
9988
+ fs15__namespace.chmodSync(hookPath, 493);
8892
9989
  } catch (err) {
8893
9990
  return {
8894
9991
  path: hookPath,
@@ -8945,14 +10042,14 @@ const { parentPort, workerData } = require("node:worker_threads");
8945
10042
  })();
8946
10043
  `;
8947
10044
  function generateInWorker(cwd, cliOptions) {
8948
- return new Promise((resolve10) => {
10045
+ return new Promise((resolve11) => {
8949
10046
  let settled = false;
8950
10047
  let worker = null;
8951
10048
  const finish = (result) => {
8952
10049
  if (settled) return;
8953
10050
  settled = true;
8954
10051
  if (worker !== null) void worker.terminate();
8955
- resolve10(result);
10052
+ resolve11(result);
8956
10053
  };
8957
10054
  const isCjs = typeof __dirname !== "undefined";
8958
10055
  const directory = isCjs ? __dirname : path16__namespace.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href))));
@@ -8985,7 +10082,6 @@ function generateInWorker(cwd, cliOptions) {
8985
10082
  }
8986
10083
 
8987
10084
  // src/index.ts
8988
- var SCHEMA_VERSION = "3.0.0";
8989
10085
  var SUMMARY_MAX_SOURCE_BYTES2 = SUMMARY_MAX_SOURCE_BYTES;
8990
10086
  var FILE_DERIVATIONS = /* @__PURE__ */ new Map();
8991
10087
  var FILE_DERIVATION_LIMIT_BYTES = 64 * 1024 * 1024;
@@ -8993,12 +10089,21 @@ var fileDerivationBytes = 0;
8993
10089
  function takeDerivation(path22, hash, settings) {
8994
10090
  const cached = FILE_DERIVATIONS.get(path22);
8995
10091
  if (cached === void 0 || cached.hash !== hash || cached.settings !== settings) return void 0;
10092
+ FILE_DERIVATIONS.delete(path22);
10093
+ FILE_DERIVATIONS.set(path22, cached);
8996
10094
  return cached;
8997
10095
  }
8998
10096
  function rememberDerivation(path22, hash, settings, derivation) {
8999
10097
  const bodyBytes = derivation.finalContent === derivation.redacted ? derivation.redacted.length : derivation.redacted.length + derivation.finalContent.length;
9000
10098
  const bytes = bodyBytes * 2 + 512;
9001
10099
  if (bytes > FILE_DERIVATION_LIMIT_BYTES / 4) return;
10100
+ const previous = FILE_DERIVATIONS.get(path22);
10101
+ if (previous !== void 0) {
10102
+ FILE_DERIVATIONS.delete(path22);
10103
+ fileDerivationBytes -= previous.bytes;
10104
+ } else {
10105
+ FILE_DERIVATIONS.delete(path22);
10106
+ }
9002
10107
  while (fileDerivationBytes + bytes > FILE_DERIVATION_LIMIT_BYTES) {
9003
10108
  const oldest = FILE_DERIVATIONS.keys().next();
9004
10109
  if (oldest.done === true) break;
@@ -9019,11 +10124,12 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
9019
10124
  const lineCount = countLines(rawContent);
9020
10125
  const { redacted, findings } = scanAndRedactSecrets(rawContent, config.secretRules, relativePath);
9021
10126
  const isLarge = sizeBytes > config.largeFileBytes;
10127
+ const oversizeForSummary = Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES2;
9022
10128
  let finalContent = redacted;
9023
10129
  let isPreviewTruncated = false;
9024
10130
  let includedLines = lineCount;
9025
10131
  let inclusionMode = "full";
9026
- if (config.skeleton === true && isSkeletonizable(relativePath)) {
10132
+ if (config.skeleton === true && isSkeletonizable(relativePath) && !oversizeForSummary) {
9027
10133
  const skeleton = skeletonizeTypeScript(redacted, relativePath);
9028
10134
  if (skeleton.collapsed > 0) {
9029
10135
  finalContent = skeleton.text;
@@ -9043,7 +10149,7 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
9043
10149
  let summarySkip = null;
9044
10150
  let summaryWarning = null;
9045
10151
  let dependentImports = null;
9046
- if (Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES2) {
10152
+ if (oversizeForSummary) {
9047
10153
  summarySkip = "oversize";
9048
10154
  dependentImports = [];
9049
10155
  } else if (isPreviewTruncated && hasStructuralSummary(relativePath)) {
@@ -9130,8 +10236,8 @@ function retain(items, keep) {
9130
10236
  }
9131
10237
  items.length = write;
9132
10238
  }
9133
- function buildIndexes(files) {
9134
- const resolver = buildImportResolver(files);
10239
+ function buildIndexes(files, tsconfigPaths) {
10240
+ const resolver = buildImportResolver(files, { tsconfig: tsconfigPaths });
9135
10241
  const importerCounts = /* @__PURE__ */ new Map();
9136
10242
  const byFile = files.filter((file) => isSourceSummary(file.summary)).map((file) => {
9137
10243
  const summary = file.summary;
@@ -9274,20 +10380,20 @@ function listEntries(dir) {
9274
10380
  const walk = (absolute, prefix) => {
9275
10381
  let children;
9276
10382
  try {
9277
- children = fs14__namespace.readdirSync(absolute, { withFileTypes: true });
10383
+ children = fs15__namespace.readdirSync(absolute, { withFileTypes: true });
9278
10384
  } catch {
9279
10385
  return;
9280
10386
  }
9281
10387
  for (const child of children) {
9282
- const relative12 = prefix === "" ? child.name : `${prefix}/${child.name}`;
9283
- entries.push(relative12);
9284
- if (child.isDirectory()) walk(path16__namespace.join(absolute, child.name), relative12);
10388
+ const relative14 = prefix === "" ? child.name : `${prefix}/${child.name}`;
10389
+ entries.push(relative14);
10390
+ if (child.isDirectory()) walk(path16__namespace.join(absolute, child.name), relative14);
9285
10391
  }
9286
10392
  };
9287
10393
  walk(dir, "");
9288
10394
  return entries.sort();
9289
10395
  }
9290
- function markerInventory(dir) {
10396
+ function markerInventory(dir, written) {
9291
10397
  const entries = listEntries(dir);
9292
10398
  const files = [];
9293
10399
  for (const entry of entries) {
@@ -9296,14 +10402,19 @@ function markerInventory(dir) {
9296
10402
  const full = path16__namespace.join(dir, ...entry.split("/"));
9297
10403
  let stats;
9298
10404
  try {
9299
- stats = fs14__namespace.lstatSync(full);
10405
+ stats = fs15__namespace.lstatSync(full);
9300
10406
  } catch {
9301
10407
  continue;
9302
10408
  }
9303
10409
  if (!stats.isFile()) continue;
10410
+ const recorded = written?.get(entry);
10411
+ if (recorded !== void 0 && recorded.digest.bytes === stats.size && recorded.mtimeMs === stats.mtimeMs) {
10412
+ files.push(recorded.digest);
10413
+ continue;
10414
+ }
9304
10415
  let digest;
9305
10416
  try {
9306
- digest = sha256Hex2(fs14__namespace.readFileSync(full));
10417
+ digest = sha256Hex2(fs15__namespace.readFileSync(full));
9307
10418
  } catch {
9308
10419
  continue;
9309
10420
  }
@@ -9311,8 +10422,8 @@ function markerInventory(dir) {
9311
10422
  }
9312
10423
  return { entries, files };
9313
10424
  }
9314
- function markerPayload(dir, state, id, createdAt) {
9315
- const { entries, files } = markerInventory(dir);
10425
+ function markerPayload(dir, state, id, createdAt, written) {
10426
+ const { entries, files } = markerInventory(dir, written);
9316
10427
  const marker2 = {
9317
10428
  generator: GENERATOR_NAME,
9318
10429
  version: GENERATOR_VERSION,
@@ -9325,13 +10436,13 @@ function markerPayload(dir, state, id, createdAt) {
9325
10436
  files
9326
10437
  };
9327
10438
  const manifestPath = path16__namespace.join(dir, "manifest.json");
9328
- if (fs14__namespace.existsSync(manifestPath)) {
9329
- marker2.manifestSha256 = sha256Hex2(fs14__namespace.readFileSync(manifestPath));
10439
+ if (fs15__namespace.existsSync(manifestPath)) {
10440
+ marker2.manifestSha256 = sha256Hex2(fs15__namespace.readFileSync(manifestPath));
9330
10441
  }
9331
10442
  return marker2;
9332
10443
  }
9333
10444
  function writeOwnershipMarker(dir, marker2) {
9334
- fs14__namespace.writeFileSync(
10445
+ fs15__namespace.writeFileSync(
9335
10446
  path16__namespace.join(dir, OWNERSHIP_MARKER),
9336
10447
  `${JSON.stringify(marker2, null, 2)}
9337
10448
  `,
@@ -9345,12 +10456,12 @@ function markerBelongsTo(dir, id) {
9345
10456
  }
9346
10457
  function readOwnershipMarker(dir) {
9347
10458
  const markerPath = path16__namespace.join(dir, OWNERSHIP_MARKER);
9348
- if (!fs14__namespace.existsSync(markerPath)) {
10459
+ if (!fs15__namespace.existsSync(markerPath)) {
9349
10460
  return { marker: null, problem: "it holds no .codebase-snapshot marker" };
9350
10461
  }
9351
10462
  let raw;
9352
10463
  try {
9353
- raw = fs14__namespace.readFileSync(markerPath, "utf8");
10464
+ raw = fs15__namespace.readFileSync(markerPath, "utf8");
9354
10465
  } catch {
9355
10466
  return { marker: null, problem: "its .codebase-snapshot marker could not be read" };
9356
10467
  }
@@ -9453,7 +10564,7 @@ function verifyMarkerInventory(dir, entries, files) {
9453
10564
  const full = path16__namespace.join(dir, ...entry.split("/"));
9454
10565
  let stats;
9455
10566
  try {
9456
- stats = fs14__namespace.lstatSync(full);
10567
+ stats = fs15__namespace.lstatSync(full);
9457
10568
  } catch {
9458
10569
  return `its .codebase-snapshot inventory lists ${entry}, which cannot be read`;
9459
10570
  }
@@ -9478,7 +10589,7 @@ function verifyMarkerInventory(dir, entries, files) {
9478
10589
  }
9479
10590
  let digest;
9480
10591
  try {
9481
- digest = sha256Hex2(fs14__namespace.readFileSync(full));
10592
+ digest = sha256Hex2(fs15__namespace.readFileSync(full));
9482
10593
  } catch {
9483
10594
  return `its .codebase-snapshot inventory cannot verify ${entry}: the file could not be read`;
9484
10595
  }
@@ -9500,11 +10611,11 @@ function assessSnapshotDirectory(dir) {
9500
10611
  };
9501
10612
  }
9502
10613
  const manifestPath = path16__namespace.join(dir, "manifest.json");
9503
- const hasManifest = fs14__namespace.existsSync(manifestPath);
10614
+ const hasManifest = fs15__namespace.existsSync(manifestPath);
9504
10615
  if (hasManifest) {
9505
10616
  let raw;
9506
10617
  try {
9507
- raw = fs14__namespace.readFileSync(manifestPath, "utf8");
10618
+ raw = fs15__namespace.readFileSync(manifestPath, "utf8");
9508
10619
  } catch {
9509
10620
  return {
9510
10621
  owned: false,
@@ -9599,7 +10710,7 @@ function containsNoFiles(dir) {
9599
10710
  const current = pending.pop();
9600
10711
  let entries;
9601
10712
  try {
9602
- entries = fs14__namespace.readdirSync(current, { withFileTypes: true });
10713
+ entries = fs15__namespace.readdirSync(current, { withFileTypes: true });
9603
10714
  } catch {
9604
10715
  return false;
9605
10716
  }
@@ -9614,13 +10725,13 @@ function containsNoFiles(dir) {
9614
10725
  return true;
9615
10726
  }
9616
10727
  function assertReplaceable(target, label, secretRules) {
9617
- if (!fs14__namespace.existsSync(target)) return;
9618
- if (!fs14__namespace.statSync(target).isDirectory()) {
10728
+ if (!fs15__namespace.existsSync(target)) return;
10729
+ if (!fs15__namespace.statSync(target).isDirectory()) {
9619
10730
  throw new Error(
9620
10731
  `Refusing to write into ${label} ${target}: it exists but is not a directory.`
9621
10732
  );
9622
10733
  }
9623
- const entries = fs14__namespace.readdirSync(target);
10734
+ const entries = fs15__namespace.readdirSync(target);
9624
10735
  if (entries.length === 0) return;
9625
10736
  if (entries.every((name) => IGNORABLE_ENTRIES.has(name))) return;
9626
10737
  if (containsNoFiles(target)) return;
@@ -9640,18 +10751,18 @@ function assertReplaceable(target, label, secretRules) {
9640
10751
  );
9641
10752
  }
9642
10753
  function assertStagingRootUsable(tmpDir, secretRules) {
9643
- if (!fs14__namespace.existsSync(tmpDir)) return;
9644
- if (!fs14__namespace.statSync(tmpDir).isDirectory()) {
10754
+ if (!fs15__namespace.existsSync(tmpDir)) return;
10755
+ if (!fs15__namespace.statSync(tmpDir).isDirectory()) {
9645
10756
  throw new Error(`Refusing to write into tmpDir ${tmpDir}: it exists but is not a directory.`);
9646
10757
  }
9647
- const entries = fs14__namespace.readdirSync(tmpDir);
10758
+ const entries = fs15__namespace.readdirSync(tmpDir);
9648
10759
  if (entries.length === 0) return;
9649
10760
  const foreign = entries.filter((name) => {
9650
10761
  const full = path16__namespace.join(tmpDir, name);
9651
10762
  if (!name.startsWith(RUN_DIR_PREFIX)) return true;
9652
10763
  let stats;
9653
10764
  try {
9654
- stats = fs14__namespace.statSync(full);
10765
+ stats = fs15__namespace.statSync(full);
9655
10766
  } catch {
9656
10767
  return true;
9657
10768
  }
@@ -9659,7 +10770,7 @@ function assertStagingRootUsable(tmpDir, secretRules) {
9659
10770
  const { marker: marker2 } = readOwnershipMarker(full);
9660
10771
  if (marker2) return false;
9661
10772
  try {
9662
- return fs14__namespace.readdirSync(full).length > 0;
10773
+ return fs15__namespace.readdirSync(full).length > 0;
9663
10774
  } catch {
9664
10775
  return true;
9665
10776
  }
@@ -9674,7 +10785,7 @@ function assertStagingRootUsable(tmpDir, secretRules) {
9674
10785
  function cleanStaleRunDirs(tmpDir) {
9675
10786
  let entries;
9676
10787
  try {
9677
- entries = fs14__namespace.readdirSync(tmpDir);
10788
+ entries = fs15__namespace.readdirSync(tmpDir);
9678
10789
  } catch {
9679
10790
  return;
9680
10791
  }
@@ -9688,58 +10799,101 @@ function cleanStaleRunDirs(tmpDir) {
9688
10799
  const abandoned = typeof marker2.pid === "number" && !isProcessAlive(marker2.pid);
9689
10800
  if (aged || abandoned) {
9690
10801
  try {
9691
- fs14__namespace.rmSync(full, { recursive: true, force: true });
10802
+ fs15__namespace.rmSync(full, { recursive: true, force: true });
9692
10803
  } catch {
9693
10804
  }
9694
10805
  }
9695
10806
  continue;
9696
10807
  }
9697
10808
  try {
9698
- if (fs14__namespace.readdirSync(full).length === 0) fs14__namespace.rmSync(full, { recursive: true, force: true });
10809
+ if (fs15__namespace.readdirSync(full).length === 0) fs15__namespace.rmSync(full, { recursive: true, force: true });
9699
10810
  } catch {
9700
10811
  }
9701
10812
  }
9702
10813
  }
9703
10814
  function removeIfEmpty(dir) {
9704
10815
  try {
9705
- if (fs14__namespace.readdirSync(dir).length === 0) fs14__namespace.rmSync(dir, { recursive: true, force: true });
10816
+ if (fs15__namespace.readdirSync(dir).length === 0) fs15__namespace.rmSync(dir, { recursive: true, force: true });
9706
10817
  } catch {
9707
10818
  }
9708
10819
  }
9709
10820
  function ensureParentDirectory(target, label) {
9710
10821
  const parent = path16__namespace.dirname(target);
9711
- if (fs14__namespace.existsSync(parent) && !fs14__namespace.statSync(parent).isDirectory()) {
10822
+ if (fs15__namespace.existsSync(parent) && !fs15__namespace.statSync(parent).isDirectory()) {
9712
10823
  throw new Error(
9713
10824
  `Refusing to create ${label} ${target}: ${parent} exists but is not a directory.`
9714
10825
  );
9715
10826
  }
9716
10827
  try {
9717
- fs14__namespace.mkdirSync(parent, { recursive: true });
10828
+ fs15__namespace.mkdirSync(parent, { recursive: true });
9718
10829
  } catch (err) {
9719
10830
  throw new Error(
9720
10831
  `Refusing to create ${label} ${target}: its parent ${parent} could not be created (${err.message}).`
9721
10832
  );
9722
10833
  }
9723
10834
  }
10835
+ var LOCK_HEARTBEAT_MS = 5e3;
10836
+ var LOCK_STALE_HEARTBEAT_MS = 12e4;
10837
+ var LOCK_HEARTBEAT_SOURCE = `
10838
+ const { parentPort, workerData } = require("node:worker_threads");
10839
+ const fs = require("node:fs");
10840
+ const { lockPath, intervalMs } = workerData;
10841
+ const timer = setInterval(() => {
10842
+ try {
10843
+ const now = new Date();
10844
+ fs.utimesSync(lockPath, now, now);
10845
+ } catch (err) {
10846
+ // The lock was reclaimed or removed; nothing left to keep alive.
10847
+ }
10848
+ }, intervalMs);
10849
+ timer.unref();
10850
+ if (parentPort) {
10851
+ parentPort.on("message", (message) => {
10852
+ if (message === "stop") {
10853
+ clearInterval(timer);
10854
+ process.exit(0);
10855
+ }
10856
+ });
10857
+ }
10858
+ `;
10859
+ function startLockHeartbeat(lockPath) {
10860
+ try {
10861
+ const worker = new worker_threads.Worker(LOCK_HEARTBEAT_SOURCE, {
10862
+ eval: true,
10863
+ workerData: { lockPath, intervalMs: LOCK_HEARTBEAT_MS }
10864
+ });
10865
+ worker.unref();
10866
+ return () => {
10867
+ void worker.terminate().catch(() => void 0);
10868
+ };
10869
+ } catch {
10870
+ return () => void 0;
10871
+ }
10872
+ }
9724
10873
  function acquireRunLock(stagingRoot) {
9725
10874
  const lockPath = lockPathFor(stagingRoot);
9726
10875
  const payload = `${JSON.stringify({
9727
10876
  pid: process.pid,
9728
10877
  stagingRoot,
10878
+ host: os__namespace.hostname(),
10879
+ runId: crypto3__namespace.randomUUID(),
10880
+ heartbeatMs: LOCK_HEARTBEAT_MS,
9729
10881
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
9730
10882
  })}
9731
10883
  `;
9732
10884
  for (let attempt = 0; attempt < 2; attempt += 1) {
9733
10885
  try {
9734
- const handle = fs14__namespace.openSync(lockPath, "wx");
10886
+ const handle = fs15__namespace.openSync(lockPath, "wx");
9735
10887
  try {
9736
- fs14__namespace.writeSync(handle, payload);
10888
+ fs15__namespace.writeSync(handle, payload);
9737
10889
  } finally {
9738
- fs14__namespace.closeSync(handle);
10890
+ fs15__namespace.closeSync(handle);
9739
10891
  }
10892
+ const stopHeartbeat = startLockHeartbeat(lockPath);
9740
10893
  return () => {
10894
+ stopHeartbeat();
9741
10895
  try {
9742
- fs14__namespace.rmSync(lockPath, { force: true });
10896
+ fs15__namespace.rmSync(lockPath, { force: true });
9743
10897
  } catch {
9744
10898
  }
9745
10899
  };
@@ -9747,7 +10901,7 @@ function acquireRunLock(stagingRoot) {
9747
10901
  if (err.code !== "EEXIST") throw err;
9748
10902
  if (attempt === 0 && reclaimStaleLock(lockPath)) continue;
9749
10903
  throw new Error(
9750
- `Another generate run is already using the staging directory ${stagingRoot}. Wait for it to finish, or delete ${lockPath} if no other run is active.`
10904
+ `Another generate run is already using the staging directory ${stagingRoot} (lock ${lockPath}, heartbeat ${Math.round(lockHeartbeatAgeMs(lockPath) / 1e3)}s old). Wait for it to finish, or delete the lock if no other run is active.`
9751
10905
  );
9752
10906
  }
9753
10907
  }
@@ -9764,7 +10918,7 @@ function canonicalLockTarget(targetPath2) {
9764
10918
  const tail = [];
9765
10919
  for (; ; ) {
9766
10920
  try {
9767
- return path16__namespace.join(fs14__namespace.realpathSync(existing), ...tail);
10921
+ return path16__namespace.join(fs15__namespace.realpathSync(existing), ...tail);
9768
10922
  } catch {
9769
10923
  const parent = path16__namespace.dirname(existing);
9770
10924
  if (parent === existing) return resolved;
@@ -9776,10 +10930,17 @@ function canonicalLockTarget(targetPath2) {
9776
10930
  function lockPathFor(stagingRoot) {
9777
10931
  return path16__namespace.join(os__namespace.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
9778
10932
  }
10933
+ function lockHeartbeatAgeMs(lockPath) {
10934
+ try {
10935
+ return Date.now() - fs15__namespace.statSync(lockPath).mtimeMs;
10936
+ } catch {
10937
+ return Number.POSITIVE_INFINITY;
10938
+ }
10939
+ }
9779
10940
  function lockOwnerIsGone(lockPath) {
9780
10941
  let raw;
9781
10942
  try {
9782
- raw = fs14__namespace.readFileSync(lockPath, "utf8");
10943
+ raw = fs15__namespace.readFileSync(lockPath, "utf8");
9783
10944
  } catch {
9784
10945
  return false;
9785
10946
  }
@@ -9792,96 +10953,120 @@ function lockOwnerIsGone(lockPath) {
9792
10953
  if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return lockFileIsAncient(lockPath);
9793
10954
  try {
9794
10955
  process.kill(pid, 0);
9795
- return false;
10956
+ return lockFileIsAncient(lockPath);
9796
10957
  } catch (err) {
9797
- return err.code === "ESRCH";
10958
+ if (err.code !== "ESRCH") return lockFileIsAncient(lockPath);
10959
+ return true;
9798
10960
  }
9799
10961
  }
9800
10962
  function reclaimStaleLock(lockPath) {
9801
10963
  let before;
9802
10964
  try {
9803
- before = fs14__namespace.statSync(lockPath);
10965
+ before = fs15__namespace.statSync(lockPath);
9804
10966
  } catch {
9805
10967
  return true;
9806
10968
  }
9807
10969
  if (!lockOwnerIsGone(lockPath)) return false;
9808
10970
  try {
9809
- const current = fs14__namespace.statSync(lockPath);
10971
+ const current = fs15__namespace.statSync(lockPath);
9810
10972
  const sameFile = current.ino === before.ino && current.birthtimeMs === before.birthtimeMs && current.mtimeMs === before.mtimeMs;
9811
10973
  if (!sameFile) return false;
9812
- fs14__namespace.rmSync(lockPath, { force: true });
10974
+ fs15__namespace.rmSync(lockPath, { force: true });
9813
10975
  return true;
9814
10976
  } catch {
9815
10977
  return false;
9816
10978
  }
9817
10979
  }
9818
10980
  function lockFileIsAncient(lockPath) {
9819
- try {
9820
- return Date.now() - fs14__namespace.statSync(lockPath).mtimeMs > STALE_RUN_MS;
9821
- } catch {
9822
- return false;
9823
- }
10981
+ return lockHeartbeatAgeMs(lockPath) > LOCK_STALE_HEARTBEAT_MS;
9824
10982
  }
9825
10983
  function writeManifestAtomically(manifestPath, manifest) {
9826
10984
  const tempPath = `${manifestPath}.${process.pid}.tmp`;
9827
- fs14__namespace.writeFileSync(tempPath, JSON.stringify(manifest, null, 2), "utf8");
10985
+ fs15__namespace.writeFileSync(tempPath, JSON.stringify(manifest, null, 2), "utf8");
9828
10986
  try {
9829
- fs14__namespace.renameSync(tempPath, manifestPath);
10987
+ fs15__namespace.renameSync(tempPath, manifestPath);
9830
10988
  } catch (err) {
9831
10989
  try {
9832
- fs14__namespace.rmSync(tempPath, { force: true });
10990
+ fs15__namespace.rmSync(tempPath, { force: true });
9833
10991
  } catch {
9834
10992
  }
9835
10993
  throw err;
9836
10994
  }
9837
10995
  }
9838
- function swapIntoPlace(stagingDir, outDir) {
10996
+ function swapIntoPlace(stagingDir, outDir, beforeSwap) {
9839
10997
  ensureParentDirectory(outDir, "outDir");
9840
10998
  const deadline = Date.now() + 3e3;
9841
- for (let attempt = 0; ; attempt += 1) {
10999
+ let delay = 25;
11000
+ for (; ; ) {
9842
11001
  try {
9843
- swapOnce(stagingDir, outDir);
11002
+ swapOnce(stagingDir, outDir, beforeSwap);
9844
11003
  return;
9845
11004
  } catch (err) {
9846
11005
  const code = err.code;
9847
- const racy = code === "ENOENT" || code === "ENOTEMPTY" || code === "EEXIST" || code === "EPERM";
9848
- if (!racy || attempt >= 10 || Date.now() > deadline) throw err;
9849
- sleepSync(50);
11006
+ const retryable = code === "ENOENT" || code === "ENOTEMPTY" || code === "EEXIST" || code === "EPERM";
11007
+ const remaining = deadline - Date.now();
11008
+ if (!retryable || remaining <= 0) throw err;
11009
+ sleepSync(Math.min(delay, remaining));
11010
+ delay = Math.min(delay * 2, 400);
9850
11011
  }
9851
11012
  }
9852
11013
  }
9853
- function swapOnce(stagingDir, outDir) {
11014
+ function recoverInterruptedPublish(outDir) {
11015
+ if (fs15__namespace.existsSync(outDir)) return;
11016
+ const parent = path16__namespace.dirname(outDir);
11017
+ const base = path16__namespace.basename(outDir);
11018
+ let backups;
11019
+ try {
11020
+ backups = fs15__namespace.readdirSync(parent).filter((name) => name.startsWith(`${base}.backup-`));
11021
+ } catch {
11022
+ return;
11023
+ }
11024
+ if (backups.length !== 1) return;
11025
+ const backupDir = path16__namespace.join(parent, backups[0]);
11026
+ const { marker: marker2, problem } = readOwnershipMarker(backupDir);
11027
+ if (problem !== null || marker2 === null || marker2.state !== "complete") return;
11028
+ try {
11029
+ fs15__namespace.renameSync(backupDir, outDir);
11030
+ process.stderr.write(
11031
+ `\u26A0 Recovered ${outDir} from ${backupDir}, left by an interrupted run. That snapshot is the one from before the interrupted run.
11032
+ `
11033
+ );
11034
+ } catch {
11035
+ }
11036
+ }
11037
+ function swapOnce(stagingDir, outDir, beforeSwap) {
9854
11038
  const backupDir = `${outDir}.backup-${process.pid}-${Date.now()}`;
9855
- const hadPrevious = fs14__namespace.existsSync(outDir);
9856
- if (hadPrevious) fs14__namespace.renameSync(outDir, backupDir);
11039
+ const hadPrevious = fs15__namespace.existsSync(outDir);
11040
+ if (hadPrevious) beforeSwap?.();
11041
+ if (hadPrevious) fs15__namespace.renameSync(outDir, backupDir);
9857
11042
  try {
9858
11043
  try {
9859
- fs14__namespace.renameSync(stagingDir, outDir);
11044
+ fs15__namespace.renameSync(stagingDir, outDir);
9860
11045
  } catch (err) {
9861
11046
  if (err.code !== "EXDEV") throw err;
9862
11047
  const partialDir = `${outDir}.partial-${process.pid}-${Date.now()}`;
9863
11048
  try {
9864
- fs14__namespace.cpSync(stagingDir, partialDir, { recursive: true });
9865
- fs14__namespace.renameSync(partialDir, outDir);
9866
- fs14__namespace.rmSync(stagingDir, { recursive: true, force: true });
11049
+ fs15__namespace.cpSync(stagingDir, partialDir, { recursive: true });
11050
+ fs15__namespace.renameSync(partialDir, outDir);
11051
+ fs15__namespace.rmSync(stagingDir, { recursive: true, force: true });
9867
11052
  } catch (copyErr) {
9868
11053
  try {
9869
- fs14__namespace.rmSync(partialDir, { recursive: true, force: true });
11054
+ fs15__namespace.rmSync(partialDir, { recursive: true, force: true });
9870
11055
  } catch {
9871
11056
  }
9872
11057
  throw copyErr;
9873
11058
  }
9874
11059
  }
9875
11060
  } catch (err) {
9876
- if (hadPrevious && fs14__namespace.existsSync(backupDir)) {
9877
- if (fs14__namespace.existsSync(outDir)) fs14__namespace.rmSync(outDir, { recursive: true, force: true });
9878
- fs14__namespace.renameSync(backupDir, outDir);
11061
+ if (hadPrevious && fs15__namespace.existsSync(backupDir)) {
11062
+ if (fs15__namespace.existsSync(outDir)) fs15__namespace.rmSync(outDir, { recursive: true, force: true });
11063
+ fs15__namespace.renameSync(backupDir, outDir);
9879
11064
  }
9880
11065
  throw err;
9881
11066
  }
9882
11067
  if (hadPrevious) {
9883
11068
  try {
9884
- fs14__namespace.rmSync(backupDir, { recursive: true, force: true });
11069
+ fs15__namespace.rmSync(backupDir, { recursive: true, force: true });
9885
11070
  } catch (err) {
9886
11071
  process.stderr.write(
9887
11072
  `\u26A0 The previous snapshot could not be removed from ${backupDir} (${err.message}). The new snapshot is in place; delete that directory by hand when convenient.
@@ -9958,6 +11143,13 @@ function generateSnapshot(configInput, options) {
9958
11143
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput ?? null);
9959
11144
  const dryRun = options?.dryRun ?? false;
9960
11145
  const gitInfo = getGitInfo(config.cwd, config.branch);
11146
+ const changedScope = config.changedSince !== void 0 || config.staged === true ? resolveChangedScope(config.cwd, {
11147
+ ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
11148
+ ...config.staged === true ? { staged: true } : {}
11149
+ }) : null;
11150
+ const changedPaths = changedScope === null ? null : new Set(changedScope.paths);
11151
+ const stagedPaths = changedScope?.stagedPaths ?? /* @__PURE__ */ new Set();
11152
+ const stagedDeletedPaths = changedScope?.deletedPaths ?? /* @__PURE__ */ new Set();
9961
11153
  const collection = collectFiles(config.cwd, {
9962
11154
  includePatterns: config.include,
9963
11155
  excludePatterns: [...config.excludePatterns, ...config.presetExclude],
@@ -9969,13 +11161,11 @@ function generateSnapshot(configInput, options) {
9969
11161
  // output — but only at these exact paths, not at every directory that shares the name.
9970
11162
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
9971
11163
  (directory) => path16__namespace.relative(config.cwd, path16__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
9972
- ).filter((relative12) => relative12.length > 0 && !relative12.startsWith(".."))
11164
+ ).filter((relative14) => relative14.length > 0 && !relative14.startsWith("..")),
11165
+ // A staged path can be absent from the working tree while its index blob exists. Discovery
11166
+ // lists the working tree, so those paths would never reach the scan at all.
11167
+ ...stagedPaths.size > 0 ? { extraPaths: [...stagedPaths] } : {}
9973
11168
  });
9974
- const changedScope = config.changedSince !== void 0 || config.staged === true ? resolveChangedScope(config.cwd, {
9975
- ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
9976
- ...config.staged === true ? { staged: true } : {}
9977
- }) : null;
9978
- const changedPaths = changedScope === null ? null : new Set(changedScope.paths);
9979
11169
  const unchangedPaths = [];
9980
11170
  const candidateFiles = changedPaths !== null && config.withDependents !== true ? collection.files.filter((relativePath) => {
9981
11171
  if (changedPaths.has(relativePath)) return true;
@@ -9997,45 +11187,92 @@ function generateSnapshot(configInput, options) {
9997
11187
  const oversizeSummaryPaths = [];
9998
11188
  const previewSummaryPaths = [];
9999
11189
  const skippedSummaryImports = /* @__PURE__ */ new Map();
10000
- const layerCounts = {};
10001
- const kindCounts = {};
11190
+ const layerCounts = /* @__PURE__ */ Object.create(null);
11191
+ const kindCounts = /* @__PURE__ */ Object.create(null);
10002
11192
  let totalLines = 0;
10003
11193
  let totalSizeBytes = 0;
10004
11194
  let largeFileCount = 0;
10005
11195
  for (const relativePath of candidateFiles) {
10006
11196
  const absolutePath = path16__namespace.join(config.cwd, relativePath);
10007
- let stats;
10008
- try {
10009
- stats = fs14__namespace.statSync(absolutePath);
10010
- if (!stats.isFile()) {
10011
- const nestedRepository = stats.isDirectory() && fs14__namespace.existsSync(path16__namespace.join(absolutePath, ".git"));
10012
- skipped.push(
10013
- nestedRepository ? {
11197
+ const fromIndex = stagedPaths.has(relativePath);
11198
+ let buffer;
11199
+ let sizeBytes;
11200
+ if (fromIndex && stagedDeletedPaths.has(relativePath)) {
11201
+ skipped.push({
11202
+ path: relativePath,
11203
+ reason: "deleted",
11204
+ detail: "staged for deletion; it is not part of the next commit"
11205
+ });
11206
+ continue;
11207
+ }
11208
+ if (fromIndex) {
11209
+ const staged = readStagedBlob(config.cwd, relativePath);
11210
+ if (staged === null) {
11211
+ skipped.push({
11212
+ path: relativePath,
11213
+ reason: "deleted",
11214
+ detail: "staged path has no blob in the index; it is not part of the next commit"
11215
+ });
11216
+ continue;
11217
+ }
11218
+ if (isBinaryExtension(absolutePath)) {
11219
+ skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${staged.length} B` });
11220
+ continue;
11221
+ }
11222
+ buffer = staged;
11223
+ sizeBytes = staged.length;
11224
+ } else {
11225
+ let stats;
11226
+ try {
11227
+ stats = fs15__namespace.statSync(absolutePath);
11228
+ if (!stats.isFile()) {
11229
+ const nestedRepository = stats.isDirectory() && fs15__namespace.existsSync(path16__namespace.join(absolutePath, ".git"));
11230
+ skipped.push(
11231
+ nestedRepository ? {
11232
+ path: relativePath,
11233
+ reason: "nested-repository",
11234
+ detail: "a directory belonging to another repository (nested checkout or submodule); its contents are not scanned"
11235
+ } : { path: relativePath, reason: "not-file" }
11236
+ );
11237
+ continue;
11238
+ }
11239
+ } catch (err) {
11240
+ const code = err.code;
11241
+ if (code === "ENOENT" || code === "ENOTDIR") {
11242
+ skipped.push({
10014
11243
  path: relativePath,
10015
- reason: "nested-repository",
10016
- detail: "a directory belonging to another repository (nested checkout or submodule); its contents are not scanned"
10017
- } : { path: relativePath, reason: "not-file" }
10018
- );
11244
+ reason: "missing",
11245
+ detail: "tracked but absent from disk (deleted without staging)"
11246
+ });
11247
+ } else {
11248
+ skipped.push({
11249
+ path: relativePath,
11250
+ reason: "read-error",
11251
+ detail: String(err.message).replace(/\s+/g, " ")
11252
+ });
11253
+ }
10019
11254
  continue;
10020
11255
  }
10021
- } catch {
10022
- skipped.push({ path: relativePath, reason: "read-error" });
10023
- continue;
10024
- }
10025
- if (isBinaryExtension(absolutePath)) {
10026
- skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${stats.size} B` });
10027
- continue;
10028
- }
10029
- if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) {
10030
- skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${stats.size} B` });
10031
- continue;
10032
- }
10033
- let buffer;
10034
- try {
10035
- buffer = fs14__namespace.readFileSync(absolutePath);
10036
- } catch {
10037
- skipped.push({ path: relativePath, reason: "read-error" });
10038
- continue;
11256
+ if (isBinaryExtension(absolutePath)) {
11257
+ skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${stats.size} B` });
11258
+ continue;
11259
+ }
11260
+ if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) {
11261
+ skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${stats.size} B` });
11262
+ continue;
11263
+ }
11264
+ try {
11265
+ buffer = fs15__namespace.readFileSync(absolutePath);
11266
+ } catch (err) {
11267
+ const code = err.code;
11268
+ skipped.push({
11269
+ path: relativePath,
11270
+ reason: code === "ENOENT" || code === "ENOTDIR" ? "missing" : "read-error",
11271
+ detail: String(err.message).replace(/\s+/g, " ")
11272
+ });
11273
+ continue;
11274
+ }
11275
+ sizeBytes = stats.size;
10039
11276
  }
10040
11277
  let decoded;
10041
11278
  try {
@@ -10044,7 +11281,7 @@ function generateSnapshot(configInput, options) {
10044
11281
  skipped.push({
10045
11282
  path: relativePath,
10046
11283
  reason: "read-error",
10047
- detail: `Size: ${stats.size} B; could not be decoded: ${err.message}`.replace(
11284
+ detail: `Size: ${sizeBytes} B; could not be decoded: ${err.message}`.replace(
10048
11285
  /\s+/g,
10049
11286
  " "
10050
11287
  )
@@ -10055,13 +11292,13 @@ function generateSnapshot(configInput, options) {
10055
11292
  skipped.push({
10056
11293
  path: relativePath,
10057
11294
  reason: "binary",
10058
- detail: `Size: ${stats.size} B; ${decoded.binaryReason ?? "binary content"}`
11295
+ detail: `Size: ${sizeBytes} B; ${decoded.binaryReason ?? "binary content"}`
10059
11296
  });
10060
11297
  continue;
10061
11298
  }
10062
11299
  const hashSha256 = sha256Hex2(buffer);
10063
11300
  const rawContent = decoded.text;
10064
- totalSizeBytes += stats.size;
11301
+ totalSizeBytes += sizeBytes;
10065
11302
  if (decoded.encoding !== "utf-8") {
10066
11303
  encodingNotes.push({
10067
11304
  path: relativePath,
@@ -10075,7 +11312,7 @@ function generateSnapshot(configInput, options) {
10075
11312
  bump(layerCounts, layer2);
10076
11313
  bump(kindCounts, kind);
10077
11314
  const derivation = takeDerivation(absolutePath, hashSha256, derivationKey) ?? (() => {
10078
- const fresh = deriveFile(relativePath, rawContent, stats.size, config);
11315
+ const fresh = deriveFile(relativePath, rawContent, sizeBytes, config);
10079
11316
  rememberDerivation(absolutePath, hashSha256, derivationKey, fresh);
10080
11317
  return fresh;
10081
11318
  })();
@@ -10096,7 +11333,7 @@ function generateSnapshot(configInput, options) {
10096
11333
  }
10097
11334
  files.push({
10098
11335
  relativePath,
10099
- sizeBytes: stats.size,
11336
+ sizeBytes,
10100
11337
  lines: lineCount,
10101
11338
  hashSha256,
10102
11339
  part: "",
@@ -10117,7 +11354,10 @@ function generateSnapshot(configInput, options) {
10117
11354
  }
10118
11355
  if (changedScope !== null && changedPaths !== null && config.withDependents === true) {
10119
11356
  const keep = new Set(changedPaths);
10120
- const resolver = buildImportResolver(files);
11357
+ const resolver = buildImportResolver(files, {
11358
+ extraPaths: changedPaths,
11359
+ tsconfig: tsconfigPathsFor(config.cwd)
11360
+ });
10121
11361
  for (const file of files) {
10122
11362
  const fileImports = isSourceSummary(file.summary) ? file.summary.imports : skippedSummaryImports.get(file.relativePath) ?? [];
10123
11363
  if (fileImports.length === 0) continue;
@@ -10211,7 +11451,7 @@ function generateSnapshot(configInput, options) {
10211
11451
  const fingerprint = sha256Hex2(
10212
11452
  [
10213
11453
  ...files.map(
10214
- (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
11454
+ (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}`
10215
11455
  ),
10216
11456
  `settings:${configDigest(config)}`
10217
11457
  ].join("\n")
@@ -10298,6 +11538,8 @@ function generateSnapshot(configInput, options) {
10298
11538
  skippedFiles: skipped.length,
10299
11539
  totalSourceBytes: totalSizeBytes,
10300
11540
  totalContentBytes,
11541
+ sourceLines: totalLines,
11542
+ emittedLines: files.reduce((total, file) => total + file.includedLines, 0),
10301
11543
  // The parts are what a model is handed, so the estimate is over the parts rather than
10302
11544
  // over the sources: previews and the byte budget both shrink the number.
10303
11545
  estimatedTokens: parts.reduce((total, part) => total + part.metadata.estimatedTokens, 0),
@@ -10316,7 +11558,7 @@ function generateSnapshot(configInput, options) {
10316
11558
  },
10317
11559
  layers: layerCounts,
10318
11560
  kinds: kindCounts,
10319
- indexes: buildIndexes(files),
11561
+ indexes: buildIndexes(files, tsconfigPathsFor(config.cwd)),
10320
11562
  parts: parts.map((part) => part.metadata),
10321
11563
  files: files.map((file) => {
10322
11564
  const { content: _content, ...rest } = file;
@@ -10333,6 +11575,23 @@ function generateSnapshot(configInput, options) {
10333
11575
  );
10334
11576
  manifest.totals.warningCount = manifest.warnings.length;
10335
11577
  }
11578
+ if (files.some((file) => file.isPreviewTruncated) && config.largeFileBytes <= config.maxPartBytes) {
11579
+ manifest.warnings.push(
11580
+ `${files.filter((file) => file.isPreviewTruncated).length} file(s) were previewed because largeFileBytes (${config.largeFileBytes} B) is not above maxPartBytes (${config.maxPartBytes} B). Raise largeFileBytes if a whole file is wanted.`
11581
+ );
11582
+ manifest.totals.warningCount = manifest.warnings.length;
11583
+ }
11584
+ if (config.maxPartTokens !== void 0) {
11585
+ const overTokenBudget = parts.filter(
11586
+ (part) => part.metadata.estimatedTokens > (config.maxPartTokens ?? 0)
11587
+ );
11588
+ if (overTokenBudget.length > 0) {
11589
+ manifest.warnings.push(
11590
+ `${overTokenBudget.length} part(s) exceed the estimated token ceiling of ${config.maxPartTokens}: the partitioner enforces the equivalent byte budget (tokens \xD7 4), and estimatedTokens is an estimate, not a hard bound.`
11591
+ );
11592
+ manifest.totals.warningCount = manifest.warnings.length;
11593
+ }
11594
+ }
10336
11595
  if (secretFindings.length > 0 && !config.artifacts.audit) {
10337
11596
  manifest.warnings.push(
10338
11597
  `${secretFindings.length} line(s) contain redacted values; reports/audit.md is disabled, so the per-line detail was not written.`
@@ -10361,6 +11620,18 @@ function generateSnapshot(configInput, options) {
10361
11620
  sha256: sha256Hex2(sarifText)
10362
11621
  };
10363
11622
  }
11623
+ const artifacts = config.artifacts;
11624
+ const artifactRecord = (text2) => ({
11625
+ byteSize: Buffer.byteLength(text2, "utf8"),
11626
+ sha256: sha256Hex2(text2)
11627
+ });
11628
+ const navigationText = artifacts.navigation ? generateNavigation(manifest) : null;
11629
+ if (navigationText !== null) manifest.artifacts.navigation = artifactRecord(navigationText);
11630
+ const auditText = artifacts.audit ? generateAuditReport(manifest, secretFindings, config.secretRules) : null;
11631
+ if (auditText !== null) manifest.artifacts.audit = artifactRecord(auditText);
11632
+ const readmeText = artifacts.readme ? generateReadme(manifest, artifacts) : null;
11633
+ if (readmeText !== null) manifest.artifacts.readme = artifactRecord(readmeText);
11634
+ if (projectTree !== null) manifest.artifacts.projectTree = artifactRecord(projectTree);
10364
11635
  let monolithJson = null;
10365
11636
  let monolithMarkdown = null;
10366
11637
  if (config.includeMonolith) {
@@ -10375,26 +11646,33 @@ function generateSnapshot(configInput, options) {
10375
11646
  includedLines: countLines(content)
10376
11647
  };
10377
11648
  });
10378
- const markdown = generateMonolithMarkdown(manifest, fullFiles);
10379
- const markdownBytes = Buffer.byteLength(markdown, "utf8");
10380
- if (!config.maxMonolithBytes || markdownBytes <= config.maxMonolithBytes) {
11649
+ const bodyBytes = fullFiles.reduce((total, file) => total + file.includedBytes, 0);
11650
+ const definitelyTooLarge = config.maxMonolithBytes !== null && bodyBytes > config.maxMonolithBytes;
11651
+ if (definitelyTooLarge) {
11652
+ const reason = `their bodies total ${bodyBytes} B, which already exceeds maxMonolithBytes ${config.maxMonolithBytes ?? 0} B`;
11653
+ manifest.warnings.push(`full-codebase.md skipped: ${reason}`);
11654
+ manifest.warnings.push(`full-codebase.json skipped: ${reason}`);
11655
+ }
11656
+ const markdown = definitelyTooLarge ? null : generateMonolithMarkdown(manifest, fullFiles);
11657
+ const markdownBytes = markdown === null ? 0 : Buffer.byteLength(markdown, "utf8");
11658
+ if (markdown !== null && (!config.maxMonolithBytes || markdownBytes <= config.maxMonolithBytes)) {
10381
11659
  monolithMarkdown = markdown;
10382
11660
  manifest.artifacts.fullMarkdown = {
10383
11661
  byteSize: markdownBytes,
10384
11662
  sha256: sha256Hex2(markdown)
10385
11663
  };
10386
- } else {
11664
+ } else if (!definitelyTooLarge) {
10387
11665
  manifest.warnings.push(
10388
11666
  `full-codebase.md skipped: ${markdownBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
10389
11667
  );
10390
11668
  }
10391
11669
  manifest.totals.warningCount = manifest.warnings.length;
10392
- const json = generateMonolithJson(manifest, fullFiles);
10393
- const jsonBytes = Buffer.byteLength(json, "utf8");
10394
- if (!config.maxMonolithBytes || jsonBytes <= config.maxMonolithBytes) {
11670
+ const json = definitelyTooLarge ? null : generateMonolithJson(manifest, fullFiles);
11671
+ const jsonBytes = json === null ? 0 : Buffer.byteLength(json, "utf8");
11672
+ if (json !== null && (!config.maxMonolithBytes || jsonBytes <= config.maxMonolithBytes)) {
10395
11673
  monolithJson = json;
10396
11674
  manifest.artifacts.fullJson = { byteSize: jsonBytes, sha256: sha256Hex2(json) };
10397
- } else {
11675
+ } else if (!definitelyTooLarge) {
10398
11676
  manifest.warnings.push(
10399
11677
  `full-codebase.json skipped: ${jsonBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
10400
11678
  );
@@ -10402,26 +11680,34 @@ function generateSnapshot(configInput, options) {
10402
11680
  manifest.totals.warningCount = manifest.warnings.length;
10403
11681
  }
10404
11682
  const { outDir, tmpDir } = resolveSafeOutputDirs(config);
10405
- const { artifacts } = config;
10406
11683
  assertReplaceable(outDir, "outDir", config.secretRules);
10407
11684
  assertStagingRootUsable(tmpDir, config.secretRules);
10408
11685
  if (dryRun) {
10409
11686
  return manifest;
10410
11687
  }
10411
11688
  const lockKeys = Array.from(/* @__PURE__ */ new Set([tmpDir, outDir])).sort();
10412
- const releases = lockKeys.map((key) => acquireRunLock(key));
11689
+ const releases = [];
11690
+ try {
11691
+ for (const key of lockKeys) releases.push(acquireRunLock(key));
11692
+ } catch (error) {
11693
+ for (const release of [...releases].reverse()) release();
11694
+ throw error;
11695
+ }
10413
11696
  const releaseLock = () => {
10414
11697
  for (const release of [...releases].reverse()) release();
10415
11698
  };
11699
+ recoverInterruptedPublish(outDir);
11700
+ assertReplaceable(outDir, "outDir", config.secretRules);
10416
11701
  let stagingDir = null;
11702
+ let releaseDeferred = false;
10417
11703
  try {
10418
11704
  ensureParentDirectory(outDir, "outDir");
10419
- fs14__namespace.mkdirSync(tmpDir, { recursive: true });
11705
+ fs15__namespace.mkdirSync(tmpDir, { recursive: true });
10420
11706
  cleanStaleRunDirs(tmpDir);
10421
11707
  const snapshotId = crypto3__namespace.randomUUID();
10422
11708
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
10423
11709
  stagingDir = path16__namespace.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
10424
- fs14__namespace.mkdirSync(stagingDir);
11710
+ fs15__namespace.mkdirSync(stagingDir);
10425
11711
  writeOwnershipMarker(stagingDir, {
10426
11712
  generator: GENERATOR_NAME,
10427
11713
  version: GENERATOR_VERSION,
@@ -10433,45 +11719,66 @@ function generateSnapshot(configInput, options) {
10433
11719
  });
10434
11720
  const partsDir = path16__namespace.join(stagingDir, "parts");
10435
11721
  const reportsDir = path16__namespace.join(stagingDir, "reports");
10436
- if (artifacts.parts) fs14__namespace.mkdirSync(partsDir, { recursive: true });
11722
+ if (artifacts.parts) fs15__namespace.mkdirSync(partsDir, { recursive: true });
10437
11723
  if (artifacts.navigation || artifacts.projectTree || artifacts.audit || config.sarif === true) {
10438
- fs14__namespace.mkdirSync(reportsDir, { recursive: true });
10439
- }
11724
+ fs15__namespace.mkdirSync(reportsDir, { recursive: true });
11725
+ }
11726
+ const writtenArtifacts = /* @__PURE__ */ new Map();
11727
+ const writeArtifact = (targetDir, relativeEntry, data) => {
11728
+ const full = path16__namespace.join(targetDir, ...relativeEntry.split("/"));
11729
+ fs15__namespace.writeFileSync(full, data, "utf8");
11730
+ const stats = fs15__namespace.statSync(full);
11731
+ writtenArtifacts.set(relativeEntry, {
11732
+ digest: { path: relativeEntry, bytes: stats.size, sha256: sha256Hex2(data) },
11733
+ mtimeMs: stats.mtimeMs
11734
+ });
11735
+ };
11736
+ const recordArtifact = (targetDir, relativeEntry) => {
11737
+ const full = path16__namespace.join(targetDir, ...relativeEntry.split("/"));
11738
+ const stats = fs15__namespace.statSync(full);
11739
+ writtenArtifacts.set(relativeEntry, {
11740
+ digest: {
11741
+ path: relativeEntry,
11742
+ bytes: stats.size,
11743
+ sha256: sha256Hex2(fs15__namespace.readFileSync(full))
11744
+ },
11745
+ mtimeMs: stats.mtimeMs
11746
+ });
11747
+ };
10440
11748
  if (artifacts.parts) {
10441
11749
  for (const part of parts) {
10442
- fs14__namespace.writeFileSync(path16__namespace.join(partsDir, part.filename), part.markdown, "utf8");
11750
+ writeArtifact(partsDir, part.filename, part.markdown);
10443
11751
  }
10444
11752
  }
10445
11753
  if (projectTree !== null) {
10446
- fs14__namespace.writeFileSync(path16__namespace.join(reportsDir, "project-tree.md"), projectTree, "utf8");
11754
+ writeArtifact(reportsDir, "project-tree.md", projectTree);
10447
11755
  }
10448
- if (artifacts.navigation) {
10449
- fs14__namespace.writeFileSync(path16__namespace.join(reportsDir, "navigation.md"), generateNavigation(manifest), "utf8");
11756
+ if (navigationText !== null) {
11757
+ writeArtifact(reportsDir, "navigation.md", navigationText);
10450
11758
  }
10451
- if (artifacts.audit) {
10452
- fs14__namespace.writeFileSync(
10453
- path16__namespace.join(reportsDir, "audit.md"),
10454
- generateAuditReport(manifest, secretFindings, config.secretRules),
10455
- "utf8"
10456
- );
11759
+ if (auditText !== null) {
11760
+ writeArtifact(reportsDir, "audit.md", auditText);
10457
11761
  }
10458
11762
  if (sarifText !== null) {
10459
- fs14__namespace.writeFileSync(path16__namespace.join(reportsDir, "audit.sarif"), sarifText, "utf8");
11763
+ writeArtifact(reportsDir, "audit.sarif", sarifText);
10460
11764
  }
10461
- if (artifacts.readme) {
10462
- fs14__namespace.writeFileSync(path16__namespace.join(stagingDir, "README.md"), generateReadme(manifest, artifacts), "utf8");
11765
+ if (readmeText !== null) {
11766
+ writeArtifact(stagingDir, "README.md", readmeText);
10463
11767
  }
10464
11768
  if (artifacts.manifest) {
10465
- fs14__namespace.writeFileSync(path16__namespace.join(stagingDir, "manifest.json"), JSON.stringify(manifest, null, 2), "utf8");
11769
+ writeArtifact(stagingDir, "manifest.json", JSON.stringify(manifest, null, 2));
10466
11770
  }
10467
11771
  if (monolithJson !== null) {
10468
- fs14__namespace.writeFileSync(path16__namespace.join(stagingDir, "full-codebase.json"), monolithJson, "utf8");
11772
+ writeArtifact(stagingDir, "full-codebase.json", monolithJson);
10469
11773
  }
10470
11774
  if (monolithMarkdown !== null) {
10471
- fs14__namespace.writeFileSync(path16__namespace.join(stagingDir, "full-codebase.md"), monolithMarkdown, "utf8");
11775
+ writeArtifact(stagingDir, "full-codebase.md", monolithMarkdown);
10472
11776
  }
10473
- writeOwnershipMarker(stagingDir, markerPayload(stagingDir, "complete", snapshotId, createdAt));
10474
- swapIntoPlace(stagingDir, outDir);
11777
+ writeOwnershipMarker(
11778
+ stagingDir,
11779
+ markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts)
11780
+ );
11781
+ swapIntoPlace(stagingDir, outDir, () => assertReplaceable(outDir, "outDir", config.secretRules));
10475
11782
  stagingDir = null;
10476
11783
  const warningsBeforeHook = manifest.warnings.length;
10477
11784
  const pendingHook = runAfterGenerate(config, manifest);
@@ -10479,8 +11786,12 @@ function generateSnapshot(configInput, options) {
10479
11786
  if (!markerBelongsTo(outDir, snapshotId)) return;
10480
11787
  if (artifacts.manifest && manifest.warnings.length !== warningsBeforeHook) {
10481
11788
  writeManifestAtomically(path16__namespace.join(outDir, "manifest.json"), manifest);
11789
+ recordArtifact(outDir, "manifest.json");
10482
11790
  }
10483
- writeOwnershipMarker(outDir, markerPayload(outDir, "complete", snapshotId, createdAt));
11791
+ writeOwnershipMarker(
11792
+ outDir,
11793
+ markerPayload(outDir, "complete", snapshotId, createdAt, writtenArtifacts)
11794
+ );
10484
11795
  };
10485
11796
  if (config.hooks.afterGenerate) shipHookState();
10486
11797
  if (pendingHook) {
@@ -10507,19 +11818,26 @@ function generateSnapshot(configInput, options) {
10507
11818
  if (pendingHooks.get(outDir) === tracked) pendingHooks.delete(outDir);
10508
11819
  });
10509
11820
  pendingHooks.set(outDir, tracked);
11821
+ releaseDeferred = true;
11822
+ void tracked.finally(() => {
11823
+ removeIfEmpty(tmpDir);
11824
+ releaseLock();
11825
+ });
10510
11826
  }
10511
11827
  return manifest;
10512
11828
  } catch (err) {
10513
11829
  if (stagingDir !== null) {
10514
11830
  try {
10515
- fs14__namespace.rmSync(stagingDir, { recursive: true, force: true });
11831
+ fs15__namespace.rmSync(stagingDir, { recursive: true, force: true });
10516
11832
  } catch {
10517
11833
  }
10518
11834
  }
10519
11835
  throw err;
10520
11836
  } finally {
10521
- removeIfEmpty(tmpDir);
10522
- releaseLock();
11837
+ if (!releaseDeferred) {
11838
+ removeIfEmpty(tmpDir);
11839
+ releaseLock();
11840
+ }
10523
11841
  }
10524
11842
  }
10525
11843
  var pendingHooks = /* @__PURE__ */ new Map();
@@ -10633,12 +11951,12 @@ function foldForComparison(value) {
10633
11951
  function canonicalPath(value) {
10634
11952
  const absolute = path16__namespace.resolve(value);
10635
11953
  try {
10636
- return fs14__namespace.realpathSync(absolute);
11954
+ return fs15__namespace.realpathSync(absolute);
10637
11955
  } catch {
10638
11956
  return absolute;
10639
11957
  }
10640
11958
  }
10641
- function isInside2(parent, child) {
11959
+ function isInside3(parent, child) {
10642
11960
  const foldedParent = foldForComparison(parent);
10643
11961
  const foldedChild = foldForComparison(child);
10644
11962
  return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path16__namespace.sep}`);
@@ -10646,7 +11964,7 @@ function isInside2(parent, child) {
10646
11964
  function resolveThroughExistingAncestor(target) {
10647
11965
  let existing = target;
10648
11966
  const missing = [];
10649
- while (!fs14__namespace.existsSync(existing)) {
11967
+ while (!fs15__namespace.existsSync(existing)) {
10650
11968
  missing.unshift(path16__namespace.basename(existing));
10651
11969
  const parent = path16__namespace.dirname(existing);
10652
11970
  if (parent === existing) break;
@@ -10663,7 +11981,7 @@ function resolveRoot(requested, context) {
10663
11981
  const absolute = path16__namespace.resolve(context.cwd, wanted);
10664
11982
  let stats;
10665
11983
  try {
10666
- stats = fs14__namespace.statSync(absolute);
11984
+ stats = fs15__namespace.statSync(absolute);
10667
11985
  } catch {
10668
11986
  return { ok: false, message: `"${wanted}" does not exist, so it cannot be a repository root.` };
10669
11987
  }
@@ -10672,7 +11990,7 @@ function resolveRoot(requested, context) {
10672
11990
  }
10673
11991
  const resolved = canonicalPath(absolute);
10674
11992
  for (const allowed of context.roots) {
10675
- if (isInside2(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
11993
+ if (isInside3(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
10676
11994
  }
10677
11995
  const shown = context.roots.join(", ");
10678
11996
  return {
@@ -10680,8 +11998,8 @@ function resolveRoot(requested, context) {
10680
11998
  message: `"${wanted}" resolves outside the directories this server may read (${shown}). The server reads the directory it was started for; restart it with --cwd <directory> to serve a different repository.`
10681
11999
  };
10682
12000
  }
10683
- async function openWorkspace(root, overrides = {}, allowedRoots) {
10684
- const loaded = await loadConfigFileDetailed(root);
12001
+ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
12002
+ const loaded = await loadConfigFileDetailed(root, options);
10685
12003
  if (loaded.errors.length > 0) {
10686
12004
  return {
10687
12005
  ok: false,
@@ -10716,7 +12034,7 @@ async function openWorkspace(root, overrides = {}, allowedRoots) {
10716
12034
  const requested = overrides.outDir.trim();
10717
12035
  const permitted = allowedRoots !== void 0 && allowedRoots.length > 0 ? allowedRoots : [root];
10718
12036
  const resolved = resolveThroughExistingAncestor(path16__namespace.resolve(root, requested));
10719
- if (!permitted.some((allowed) => isInside2(canonicalPath(allowed), resolved))) {
12037
+ if (!permitted.some((allowed) => isInside3(canonicalPath(allowed), resolved))) {
10720
12038
  const shown = permitted.map((allowed) => canonicalPath(allowed)).join(", ");
10721
12039
  return {
10722
12040
  ok: false,
@@ -10745,6 +12063,7 @@ async function openWorkspace(root, overrides = {}, allowedRoots) {
10745
12063
  return { ok: false, message: error instanceof Error ? error.message : String(error) };
10746
12064
  }
10747
12065
  }
12066
+ var MANIFEST_CACHE_LIMIT = 8;
10748
12067
  var manifestCache = /* @__PURE__ */ new Map();
10749
12068
  function manifestPathFor(workspace) {
10750
12069
  return path16__namespace.resolve(workspace.root, workspace.config.outDir, "manifest.json");
@@ -10753,8 +12072,20 @@ function partPathFor(workspace, filename) {
10753
12072
  if (filename.length === 0 || filename.includes("\0")) return null;
10754
12073
  const partsDir = path16__namespace.resolve(workspace.root, workspace.config.outDir, "parts");
10755
12074
  const resolved = path16__namespace.resolve(partsDir, filename);
10756
- const relative12 = path16__namespace.relative(partsDir, resolved);
10757
- if (relative12.length === 0 || relative12.includes(path16__namespace.sep) || relative12.includes("/") || relative12.includes("\\") || path16__namespace.isAbsolute(relative12)) {
12075
+ const relative14 = path16__namespace.relative(partsDir, resolved);
12076
+ if (relative14.length === 0 || relative14.includes(path16__namespace.sep) || relative14.includes("/") || relative14.includes("\\") || path16__namespace.isAbsolute(relative14)) {
12077
+ return null;
12078
+ }
12079
+ let stats;
12080
+ try {
12081
+ stats = fs15__namespace.lstatSync(resolved);
12082
+ } catch {
12083
+ return null;
12084
+ }
12085
+ if (!stats.isFile()) return null;
12086
+ try {
12087
+ if (path16__namespace.dirname(fs15__namespace.realpathSync(resolved)) !== fs15__namespace.realpathSync(partsDir)) return null;
12088
+ } catch {
10758
12089
  return null;
10759
12090
  }
10760
12091
  return resolved;
@@ -10764,7 +12095,7 @@ function readManifest3(workspace) {
10764
12095
  const shown = path16__namespace.relative(workspace.root, file).split(path16__namespace.sep).join("/") || file;
10765
12096
  let stats;
10766
12097
  try {
10767
- stats = fs14__namespace.statSync(file);
12098
+ stats = fs15__namespace.statSync(file);
10768
12099
  } catch {
10769
12100
  return {
10770
12101
  ok: false,
@@ -10773,12 +12104,12 @@ function readManifest3(workspace) {
10773
12104
  };
10774
12105
  }
10775
12106
  const cached = manifestCache.get(file);
10776
- if (cached && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size) {
12107
+ if (cached && cached.mtimeMs === stats.mtimeMs && cached.ctimeMs === stats.ctimeMs && cached.size === stats.size) {
10777
12108
  return { ok: true, manifest: cached.manifest, file };
10778
12109
  }
10779
12110
  let raw;
10780
12111
  try {
10781
- raw = fs14__namespace.readFileSync(file, "utf8");
12112
+ raw = fs15__namespace.readFileSync(file, "utf8");
10782
12113
  } catch (error) {
10783
12114
  return {
10784
12115
  ok: false,
@@ -10797,7 +12128,18 @@ function readManifest3(workspace) {
10797
12128
  return { ok: false, missing: false, message: `${shown} is not a snapshot manifest: ${problem}` };
10798
12129
  }
10799
12130
  const manifest = parsed;
10800
- manifestCache.set(file, { mtimeMs: stats.mtimeMs, size: stats.size, manifest });
12131
+ manifestCache.delete(file);
12132
+ manifestCache.set(file, {
12133
+ mtimeMs: stats.mtimeMs,
12134
+ ctimeMs: stats.ctimeMs,
12135
+ size: stats.size,
12136
+ manifest
12137
+ });
12138
+ while (manifestCache.size > MANIFEST_CACHE_LIMIT) {
12139
+ const oldest = manifestCache.keys().next().value;
12140
+ if (oldest === void 0) break;
12141
+ manifestCache.delete(oldest);
12142
+ }
10801
12143
  return { ok: true, manifest, file };
10802
12144
  }
10803
12145
  function forgetManifest(file) {
@@ -10900,11 +12242,11 @@ function toRelativePath(root, value) {
10900
12242
  if (cleaned.length === 0 || cleaned.includes("\0")) return null;
10901
12243
  const resolvedRoot = path16__namespace.resolve(root);
10902
12244
  const absolute = path16__namespace.resolve(resolvedRoot, cleaned);
10903
- const relative12 = path16__namespace.relative(resolvedRoot, absolute);
10904
- if (relative12 === "" || relative12 === ".." || relative12.startsWith(`..${path16__namespace.sep}`) || path16__namespace.isAbsolute(relative12)) {
12245
+ const relative14 = path16__namespace.relative(resolvedRoot, absolute);
12246
+ if (relative14 === "" || relative14 === ".." || relative14.startsWith(`..${path16__namespace.sep}`) || path16__namespace.isAbsolute(relative14)) {
10905
12247
  return null;
10906
12248
  }
10907
- return relative12.split(path16__namespace.sep).join("/");
12249
+ return relative14.split(path16__namespace.sep).join("/");
10908
12250
  }
10909
12251
  function symbolsOf(entry) {
10910
12252
  const summary = entry.summary;
@@ -10945,7 +12287,9 @@ function symbolsOf(entry) {
10945
12287
  async function prepare(args, context, overrides = {}) {
10946
12288
  const rootOutcome = resolveRoot(args.root, context);
10947
12289
  if (!rootOutcome.ok) return { ok: false, outcome: failure(rootOutcome.message) };
10948
- const opened = await openWorkspace(rootOutcome.root, overrides, context.roots);
12290
+ const opened = await openWorkspace(rootOutcome.root, overrides, context.roots, {
12291
+ allowExecutableConfig: false
12292
+ });
10949
12293
  if (!opened.ok) return { ok: false, outcome: failure(opened.message) };
10950
12294
  return { ok: true, workspace: opened.workspace };
10951
12295
  }
@@ -11301,10 +12645,12 @@ var locateTool = {
11301
12645
  else if (wants("kind") && entry.kind.toLowerCase().includes(needle)) add(entry, "kind");
11302
12646
  }
11303
12647
  if (wants("route")) {
12648
+ const matchedPaths = new Set(matches.map((match) => match.path));
11304
12649
  for (const route of manifest.indexes.routes) {
11305
12650
  const method = route.methods.find((name) => name.toLowerCase().includes(needle));
11306
12651
  if (!route.path.toLowerCase().includes(needle) && method === void 0) continue;
11307
- if (matches.some((match) => match.path === route.path)) continue;
12652
+ if (matchedPaths.has(route.path)) continue;
12653
+ matchedPaths.add(route.path);
11308
12654
  matches.push({
11309
12655
  path: route.path,
11310
12656
  part: route.part,
@@ -11497,7 +12843,9 @@ var readTool = {
11497
12843
  fromLine: { type: "integer" },
11498
12844
  returnedLines: { type: "integer" },
11499
12845
  totalLines: { type: "integer" },
11500
- nextFromLine: { type: "integer" }
12846
+ nextFromLine: { type: "integer" },
12847
+ pageable: { type: "boolean" },
12848
+ reason: { type: "string" }
11501
12849
  }
11502
12850
  },
11503
12851
  annotations: READ_ONLY,
@@ -11536,7 +12884,7 @@ var readTool = {
11536
12884
  }
11537
12885
  let partText;
11538
12886
  try {
11539
- partText = fs14__namespace.readFileSync(partPath, "utf8");
12887
+ partText = fs15__namespace.readFileSync(partPath, "utf8");
11540
12888
  } catch {
11541
12889
  return failure(
11542
12890
  `${entry.part} could not be read, so the snapshot is damaged. Run snapshot_generate to rebuild it.`
@@ -11553,15 +12901,20 @@ var readTool = {
11553
12901
  const window = windowText(section.body, fromLine, lineCount);
11554
12902
  let body = window.text;
11555
12903
  let truncatedByBytes = false;
12904
+ let clippedInsideLine = false;
11556
12905
  if (Buffer.byteLength(body, "utf8") > MAX_RESULT_BYTES) {
11557
12906
  const clipped = truncateToBytes(body, MAX_RESULT_BYTES);
11558
- body = clipped.content;
11559
- const lastBreak = body.lastIndexOf("\n");
11560
- body = lastBreak > 0 ? body.slice(0, lastBreak) : body;
12907
+ const lastBreak = clipped.content.lastIndexOf("\n");
12908
+ if (lastBreak > 0) {
12909
+ body = clipped.content.slice(0, lastBreak);
12910
+ } else {
12911
+ body = clipped.content;
12912
+ clippedInsideLine = true;
12913
+ }
11561
12914
  truncatedByBytes = true;
11562
12915
  }
11563
12916
  const returnedLines = body.length === 0 ? 0 : body.split("\n").length;
11564
- const moreRemain = !window.pastEnd && (window.truncated || truncatedByBytes);
12917
+ const moreRemain = !clippedInsideLine && !window.pastEnd && (window.truncated || truncatedByBytes);
11565
12918
  const header = [
11566
12919
  `${entry.relativePath} \u2014 ${entry.part}, ${entry.layer}/${entry.kind}, ${entry.language}`,
11567
12920
  // The line range is the answer to "where am I in this file", and it is computed from the
@@ -11575,12 +12928,17 @@ var readTool = {
11575
12928
  ] : section.inclusion === "signatures" ? [
11576
12929
  "Signatures: function and method bodies were replaced with `{ /* ... */ }` when the snapshot was generated."
11577
12930
  ] : [],
11578
- window.totalLines === 0 ? "This file is empty." : window.pastEnd ? `This file has ${window.totalLines} line(s); fromLine=${window.fromLine} is past its end.` : `Lines ${window.fromLine}\u2013${window.fromLine + returnedLines - 1} of ${window.totalLines}.`
12931
+ window.totalLines === 0 ? "This file is empty." : window.pastEnd ? `This file has ${window.totalLines} line(s); fromLine=${window.fromLine} is past its end.` : clippedInsideLine ? `Line ${window.fromLine} of ${window.totalLines}: this line is longer than one result can carry, so this page ends mid-line.` : `Lines ${window.fromLine}\u2013${window.fromLine + returnedLines - 1} of ${window.totalLines}.`
11579
12932
  ];
11580
12933
  const lines = [...header, "", body];
11581
12934
  if (moreRemain) {
11582
12935
  const next = window.fromLine + returnedLines;
11583
12936
  lines.push("", `Truncated. Call snapshot_read with fromLine=${next} for the rest.`);
12937
+ } else if (clippedInsideLine) {
12938
+ lines.push(
12939
+ "",
12940
+ "Truncated. The remainder of this line is not reachable through snapshot_read; read the file from disk to see it."
12941
+ );
11584
12942
  }
11585
12943
  return {
11586
12944
  text: lines.join("\n"),
@@ -11594,7 +12952,9 @@ var readTool = {
11594
12952
  fromLine: window.fromLine,
11595
12953
  returnedLines,
11596
12954
  totalLines: window.totalLines,
11597
- truncated: moreRemain,
12955
+ truncated: moreRemain || clippedInsideLine,
12956
+ pageable: !clippedInsideLine,
12957
+ ...clippedInsideLine ? { reason: "line exceeds the result limit; its remainder is not reachable by fromLine" } : {},
11598
12958
  nextFromLine: moreRemain ? window.fromLine + returnedLines : null,
11599
12959
  sha256: entry.hashSha256
11600
12960
  }
@@ -11752,6 +13112,13 @@ var ERROR_CODES = {
11752
13112
  * invent a partial one.
11753
13113
  */
11754
13114
  resourceTooLarge: -32e3,
13115
+ /**
13116
+ * The server is at its concurrency limit.
13117
+ *
13118
+ * Implementation-defined range, like `resourceTooLarge`. A typed error rather than silent
13119
+ * queueing or a dropped request: the caller can retry, and knows why.
13120
+ */
13121
+ overloaded: -32001,
11755
13122
  unsupportedProtocolVersion: -32022
11756
13123
  };
11757
13124
  var METHOD3 = {
@@ -11884,13 +13251,14 @@ var COMMAND_OPTION_SCOPE = {
11884
13251
  "with-dependents",
11885
13252
  "cwd",
11886
13253
  "out-dir",
11887
- "max-part-bytes",
13254
+ // `--large-file-bytes` changes the inclusion mode `explain` reports, so it belongs here.
13255
+ // `--max-part-bytes`, `--max-monolith-bytes`, `--include-monolith`, `--skip-artifacts` and
13256
+ // `--only-artifacts` were accepted and never read: a per-file answer cannot depend on how the
13257
+ // whole snapshot is partitioned, and none of them changes whether this file is included.
13258
+ // Removed rather than implemented, because a flag that parses and does nothing is the defect
13259
+ // this table exists to prevent.
11888
13260
  "large-file-bytes",
11889
- "max-monolith-bytes",
11890
- "include-monolith",
11891
13261
  "include-sensitive-files",
11892
- "skip-artifacts",
11893
- "only-artifacts",
11894
13262
  "no-config",
11895
13263
  "discovery",
11896
13264
  "no-update-check",
@@ -12238,7 +13606,7 @@ function buildAgentContract() {
12238
13606
  type: "string",
12239
13607
  default: "unset",
12240
13608
  appliesTo: optionAppliesTo("max-part-tokens"),
12241
- summary: "Ceiling on a part expressed in tokens. Narrows --max-part-bytes instead of replacing it; the manifest records both units. Minimum 1024."
13609
+ summary: "Ceiling on a part expressed in tokens. Converted to bytes at 4 bytes/token and enforced as that byte ceiling \u2014 the estimate in manifest.parts[].estimatedTokens is not a hard bound, and a warning names any part whose estimate exceeds it. Minimum 1024."
12242
13610
  },
12243
13611
  {
12244
13612
  flag: "--large-file-bytes",
@@ -12273,7 +13641,7 @@ function buildAgentContract() {
12273
13641
  type: "string",
12274
13642
  default: "auto",
12275
13643
  appliesTo: optionAppliesTo("discovery"),
12276
- summary: "How files are discovered: auto (git when usable), git (require git), walk (read the root .gitignore directly; the escape hatch for a .git that cannot be listed)."
13644
+ summary: "How files are discovered: auto (git when usable), git (require git), walk (read .gitignore files directly, including nested ones; the escape hatch for a .git that cannot be listed)."
12277
13645
  },
12278
13646
  {
12279
13647
  flag: "--skip-artifacts",
@@ -12294,7 +13662,7 @@ function buildAgentContract() {
12294
13662
  type: "boolean",
12295
13663
  default: false,
12296
13664
  appliesTo: optionAppliesTo("skeleton"),
12297
- summary: 'Replace function and method bodies with `{ /* ... */ }` in TypeScript/TSX files, keeping signatures and comments. The part records inclusionMode "signatures" for each file it touched.'
13665
+ summary: 'Replace function and method bodies with `{ /* ... */ }` in JS, JSX, TS and TSX files (including .mjs/.cjs; .d.ts files have nothing to collapse), keeping signatures and comments. The part records inclusionMode "signatures" for each file it touched.'
12298
13666
  },
12299
13667
  {
12300
13668
  flag: "--sarif",
@@ -12408,7 +13776,7 @@ function buildAgentContract() {
12408
13776
  type: "boolean",
12409
13777
  default: false,
12410
13778
  appliesTo: optionAppliesTo("autopilot"),
12411
- summary: "Set the project up without asking, then generate: detect the preset, write the config and .gitignore, add the npm scripts and devDependency, install with the project's own package manager, generate. Never overwrites an existing config, and never prompts. Refuses an empty directory (exit 1); contradicts --no-config (exit 2)."
13779
+ summary: "Set the project up without asking, then generate: detect the preset, write the config and .gitignore, add the npm scripts and devDependency, install with the project's own package manager, generate. Autopilot chooses the preset and takes no --preset/--include/--exclude/--install-hook: those belong to `setup` or `init`. Never overwrites an existing config, and never prompts. Refuses an empty directory (exit 1); contradicts --no-config (exit 2)."
12412
13780
  },
12413
13781
  {
12414
13782
  flag: "--install",
@@ -12748,11 +14116,11 @@ function targetPath(cwd, target) {
12748
14116
  }
12749
14117
  }
12750
14118
  function assertWritableInsideRepository(cwd, filePath) {
12751
- const root = fs14__namespace.realpathSync(cwd);
14119
+ const root = fs15__namespace.realpathSync(cwd);
12752
14120
  const shown = path16__namespace.relative(root, filePath) || filePath;
12753
14121
  let stat = null;
12754
14122
  try {
12755
- stat = fs14__namespace.lstatSync(filePath);
14123
+ stat = fs15__namespace.lstatSync(filePath);
12756
14124
  } catch {
12757
14125
  stat = null;
12758
14126
  }
@@ -12768,13 +14136,13 @@ function assertWritableInsideRepository(cwd, filePath) {
12768
14136
  }
12769
14137
  let existing = filePath;
12770
14138
  const missing = [];
12771
- while (!fs14__namespace.existsSync(existing)) {
14139
+ while (!fs15__namespace.existsSync(existing)) {
12772
14140
  missing.unshift(path16__namespace.basename(existing));
12773
14141
  const parent = path16__namespace.dirname(existing);
12774
14142
  if (parent === existing) break;
12775
14143
  existing = parent;
12776
14144
  }
12777
- const realAncestor = fs14__namespace.realpathSync(existing);
14145
+ const realAncestor = fs15__namespace.realpathSync(existing);
12778
14146
  const resolved = missing.length === 0 ? realAncestor : path16__namespace.join(realAncestor, ...missing);
12779
14147
  if (resolved !== root && !resolved.startsWith(`${root}${path16__namespace.sep}`)) {
12780
14148
  throw new Error(
@@ -12783,17 +14151,17 @@ function assertWritableInsideRepository(cwd, filePath) {
12783
14151
  }
12784
14152
  }
12785
14153
  function writeIfChanged(target, filePath, content) {
12786
- const existing = fs14__namespace.existsSync(filePath) ? fs14__namespace.readFileSync(filePath, "utf8") : null;
14154
+ const existing = fs15__namespace.existsSync(filePath) ? fs15__namespace.readFileSync(filePath, "utf8") : null;
12787
14155
  if (existing === content) return { target, path: filePath, action: "unchanged" };
12788
- fs14__namespace.mkdirSync(path16__namespace.dirname(filePath), { recursive: true });
12789
- fs14__namespace.writeFileSync(filePath, content, "utf8");
14156
+ fs15__namespace.mkdirSync(path16__namespace.dirname(filePath), { recursive: true });
14157
+ fs15__namespace.writeFileSync(filePath, content, "utf8");
12790
14158
  return { target, path: filePath, action: existing === null ? "created" : "updated" };
12791
14159
  }
12792
14160
  function legacyAgentsNote(cwd) {
12793
14161
  const filePath = path16__namespace.join(cwd, "AGENTS.md");
12794
14162
  try {
12795
- if (!fs14__namespace.existsSync(filePath)) return null;
12796
- if (!fs14__namespace.readFileSync(filePath, "utf8").includes(LEGACY_AGENTS_MARKER)) return null;
14163
+ if (!fs15__namespace.existsSync(filePath)) return null;
14164
+ if (!fs15__namespace.readFileSync(filePath, "utf8").includes(LEGACY_AGENTS_MARKER)) return null;
12797
14165
  } catch {
12798
14166
  return null;
12799
14167
  }
@@ -12805,7 +14173,7 @@ function installSkill(cwd, target = "all") {
12805
14173
  const notes = [];
12806
14174
  const wanted = target === "all" ? ["claude", "cursor"] : [target];
12807
14175
  for (const item of wanted) assertWritableInsideRepository(cwd, targetPath(cwd, item));
12808
- const createsSomething = wanted.some((item) => !fs14__namespace.existsSync(targetPath(cwd, item)));
14176
+ const createsSomething = wanted.some((item) => !fs15__namespace.existsSync(targetPath(cwd, item)));
12809
14177
  if (createsSomething) {
12810
14178
  assertWritableInsideRepository(cwd, path16__namespace.join(cwd, ".gitignore"));
12811
14179
  }
@@ -12962,13 +14330,13 @@ function formatBytes2(bytes) {
12962
14330
  async function workspaceFor(context) {
12963
14331
  const root = resolveRoot(void 0, context);
12964
14332
  if (!root.ok) return { error: root.message };
12965
- const opened = await openWorkspace(root.root);
14333
+ const opened = await openWorkspace(root.root, {}, void 0, { allowExecutableConfig: false });
12966
14334
  if (!opened.ok) return { error: opened.message };
12967
14335
  return opened.workspace;
12968
14336
  }
12969
14337
  function readFileIfPresent(file) {
12970
14338
  try {
12971
- return fs14__namespace.readFileSync(file, "utf8");
14339
+ return fs15__namespace.readFileSync(file, "utf8");
12972
14340
  } catch {
12973
14341
  return null;
12974
14342
  }
@@ -13086,7 +14454,7 @@ function buildResourceProvider() {
13086
14454
  if (partPath === null) return null;
13087
14455
  let partBytes;
13088
14456
  try {
13089
- partBytes = fs14__namespace.statSync(partPath).size;
14457
+ partBytes = fs15__namespace.statSync(partPath).size;
13090
14458
  } catch {
13091
14459
  return null;
13092
14460
  }
@@ -13502,11 +14870,11 @@ var MAX_LINE_BYTES = 32 * 1024 * 1024;
13502
14870
  function createWriter(output) {
13503
14871
  return {
13504
14872
  write(value) {
13505
- return new Promise((resolve10, reject) => {
14873
+ return new Promise((resolve11, reject) => {
13506
14874
  output.write(`${JSON.stringify(value)}
13507
14875
  `, (error) => {
13508
14876
  if (error) reject(error);
13509
- else resolve10();
14877
+ else resolve11();
13510
14878
  });
13511
14879
  });
13512
14880
  }
@@ -13639,11 +15007,12 @@ async function runStdioServer(options) {
13639
15007
  });
13640
15008
  return writeChain;
13641
15009
  };
15010
+ const MAX_IN_FLIGHT = 4;
13642
15011
  let inFlight = 0;
13643
15012
  let inputEnded = false;
13644
15013
  let resolveDone = () => void 0;
13645
- const finished = new Promise((resolve10) => {
13646
- resolveDone = resolve10;
15014
+ const finished = new Promise((resolve11) => {
15015
+ resolveDone = resolve11;
13647
15016
  });
13648
15017
  const finishIfIdle = () => {
13649
15018
  if (inputEnded && inFlight === 0) resolveDone(0);
@@ -13659,9 +15028,31 @@ async function runStdioServer(options) {
13659
15028
  const response = await server.handle(message);
13660
15029
  if (response) await send(response);
13661
15030
  };
15031
+ const rejectOverloaded = (line) => {
15032
+ let id = null;
15033
+ try {
15034
+ const parsed = JSON.parse(line);
15035
+ if (!isJsonObject(parsed)) return;
15036
+ if (typeof parsed.id === "string" || typeof parsed.id === "number") id = parsed.id;
15037
+ else return;
15038
+ } catch {
15039
+ return;
15040
+ }
15041
+ void send(
15042
+ errorResponse(
15043
+ id,
15044
+ ERROR_CODES.overloaded,
15045
+ `The server is already handling ${MAX_IN_FLIGHT} requests; retry this one when it is free.`
15046
+ )
15047
+ );
15048
+ };
13662
15049
  const stopReading = createLineReader(process.stdin, {
13663
15050
  onOverflow: (bytes) => log(`mcp: discarded an oversized message (${bytes} bytes)`),
13664
15051
  onLine: (line) => {
15052
+ if (inFlight >= MAX_IN_FLIGHT) {
15053
+ rejectOverloaded(line);
15054
+ return;
15055
+ }
13665
15056
  inFlight += 1;
13666
15057
  void handleLine(line).finally(() => {
13667
15058
  inFlight -= 1;
@@ -13926,10 +15317,10 @@ function parseCliArgs(argv) {
13926
15317
  }
13927
15318
  if (values.cwd !== void 0) {
13928
15319
  const target = String(values.cwd);
13929
- if (!fs14__namespace.existsSync(target)) {
15320
+ if (!fs15__namespace.existsSync(target)) {
13930
15321
  throw new UsageError(`--cwd directory does not exist: ${target}`);
13931
15322
  }
13932
- if (!fs14__namespace.statSync(target).isDirectory()) {
15323
+ if (!fs15__namespace.statSync(target).isDirectory()) {
13933
15324
  throw new UsageError(`--cwd is not a directory: ${target}`);
13934
15325
  }
13935
15326
  }
@@ -14033,7 +15424,9 @@ function parseCliArgs(argv) {
14033
15424
  )
14034
15425
  )
14035
15426
  );
14036
- const hint = ignored.some((flag) => ["--preset", "--include", "--exclude"].includes(flag)) ? " To scope a run, set include/excludePatterns/preset in snapshot.config.ts (or run `codebase-snapshot init` to generate one)." : "";
15427
+ const setupOnly = ["--preset", "--include", "--exclude", "--install-hook"];
15428
+ const autopilotChose = values.autopilot === true && ignored.some((flag) => setupOnly.includes(flag));
15429
+ const hint = autopilotChose ? " --autopilot chooses the preset and takes none of these: name them with `setup` (or `init`) instead." : ignored.some((flag) => ["--preset", "--include", "--exclude"].includes(flag)) ? " To scope a run, set include/excludePatterns/preset in snapshot.config.ts (or run `codebase-snapshot init` to generate one)." : "";
14037
15430
  throw new UsageError(
14038
15431
  `${ignored.join(", ")} ${ignored.length === 1 ? "does" : "do"} not apply to \`${command}\` and ${ignored.length === 1 ? "was" : "were"} not applied. ${ignored.length === 1 ? "It is" : "They are"} accepted by: ${owners.join(", ")}.${hint}`
14039
15432
  );
@@ -14155,8 +15548,8 @@ function splitList(value) {
14155
15548
  }
14156
15549
  function displayOutPath(cwd, outDir, ...segments) {
14157
15550
  const absolute = path16__namespace.resolve(cwd, outDir, ...segments);
14158
- const relative12 = path16__namespace.relative(cwd, absolute);
14159
- if (relative12 && !relative12.startsWith("..") && !path16__namespace.isAbsolute(relative12)) return relative12;
15551
+ const relative14 = path16__namespace.relative(cwd, absolute);
15552
+ if (relative14 && !relative14.startsWith("..") && !path16__namespace.isAbsolute(relative14)) return relative14;
14160
15553
  return absolute;
14161
15554
  }
14162
15555
  function nextStepHint(cwd, scriptsAddedNow) {
@@ -14164,7 +15557,7 @@ function nextStepHint(cwd, scriptsAddedNow) {
14164
15557
  if (!hasScript) {
14165
15558
  try {
14166
15559
  const parsed = JSON.parse(
14167
- stripJsonComments2(fs14__namespace.readFileSync(path16__namespace.join(cwd, "package.json"), "utf8"))
15560
+ stripJsonComments2(fs15__namespace.readFileSync(path16__namespace.join(cwd, "package.json"), "utf8"))
14168
15561
  );
14169
15562
  hasScript = typeof parsed.scripts?.snapshot === "string";
14170
15563
  } catch {
@@ -14173,7 +15566,7 @@ function nextStepHint(cwd, scriptsAddedNow) {
14173
15566
  }
14174
15567
  if (!hasScript) return `npx ${GENERATOR_NAME} generate`;
14175
15568
  const bin = path16__namespace.join(cwd, "node_modules", ".bin", "codebase-snapshot");
14176
- const installed = fs14__namespace.existsSync(bin) || fs14__namespace.existsSync(`${bin}.cmd`);
15569
+ const installed = fs15__namespace.existsSync(bin) || fs15__namespace.existsSync(`${bin}.cmd`);
14177
15570
  return installed ? "npm run snapshot" : "npm install && npm run snapshot";
14178
15571
  }
14179
15572
  function presetSummary(init) {
@@ -14230,16 +15623,25 @@ async function runInitCommand(invocation) {
14230
15623
  }
14231
15624
  }
14232
15625
  function detectPackageManager(cwd) {
14233
- const has = (name) => fs14__namespace.existsSync(path16__namespace.join(cwd, name));
15626
+ const has = (name) => fs15__namespace.existsSync(path16__namespace.join(cwd, name));
14234
15627
  if (has("bun.lockb") || has("bun.lock")) return { name: "bun", command: "bun", args: ["install"] };
14235
15628
  if (has("pnpm-lock.yaml")) return { name: "pnpm", command: "pnpm", args: ["install"] };
14236
15629
  if (has("yarn.lock")) return { name: "yarn", command: "yarn", args: ["install"] };
14237
15630
  return { name: "npm", command: "npm", args: ["install"] };
14238
15631
  }
15632
+ var INHERITED_NPM_SETTINGS = /* @__PURE__ */ new Set([
15633
+ "npm_config_registry",
15634
+ "npm_config_proxy",
15635
+ "npm_config_https_proxy",
15636
+ "npm_config_noproxy",
15637
+ "npm_config_cafile",
15638
+ "npm_config_ca",
15639
+ "npm_config_strict_ssl"
15640
+ ]);
14239
15641
  function cleanInstallEnv(env = process.env) {
14240
15642
  const cleaned = {};
14241
15643
  for (const [key, value] of Object.entries(env)) {
14242
- if (/^npm_config_/i.test(key)) continue;
15644
+ if (/^npm_config_/i.test(key) && !INHERITED_NPM_SETTINGS.has(key.toLowerCase())) continue;
14243
15645
  if (key === "npm_lifecycle_event" || key === "npm_lifecycle_script") continue;
14244
15646
  cleaned[key] = value;
14245
15647
  }
@@ -14663,12 +16065,12 @@ ${USAGE}
14663
16065
  }
14664
16066
  if (invocation.command === "report") {
14665
16067
  const manifestPath = path16__namespace.resolve(resolved.cwd, resolved.outDir, "manifest.json");
14666
- if (!fs14__namespace.existsSync(manifestPath)) {
16068
+ if (!fs15__namespace.existsSync(manifestPath)) {
14667
16069
  return fail(invocation.format, `Manifest not found at ${manifestPath}. Run generate first.`);
14668
16070
  }
14669
16071
  let manifest;
14670
16072
  try {
14671
- manifest = JSON.parse(fs14__namespace.readFileSync(manifestPath, "utf8"));
16073
+ manifest = JSON.parse(fs15__namespace.readFileSync(manifestPath, "utf8"));
14672
16074
  } catch (err) {
14673
16075
  return fail(invocation.format, `Could not read ${manifestPath}: ${err.message}`);
14674
16076
  }
@@ -14844,8 +16246,8 @@ function comparablePath(value) {
14844
16246
  return process.platform === "win32" ? absolute.toLowerCase() : absolute;
14845
16247
  }
14846
16248
  function isSameOrInside(parent, candidate) {
14847
- const relative12 = path16__namespace.relative(parent, candidate);
14848
- return relative12 === "" || relative12 !== ".." && !relative12.startsWith(`..${path16__namespace.sep}`) && !path16__namespace.isAbsolute(relative12);
16249
+ const relative14 = path16__namespace.relative(parent, candidate);
16250
+ return relative14 === "" || relative14 !== ".." && !relative14.startsWith(`..${path16__namespace.sep}`) && !path16__namespace.isAbsolute(relative14);
14849
16251
  }
14850
16252
  function isGeneratedWatchPath(candidate, paths) {
14851
16253
  const absolute = comparablePath(path16__namespace.resolve(paths.cwd, candidate));
@@ -14960,7 +16362,7 @@ async function runWatchLoop(invocation, resolved, options) {
14960
16362
  info("\u{1F440} Watching for changes. Press Ctrl+C to stop.");
14961
16363
  let watcher;
14962
16364
  try {
14963
- watcher = fs14__namespace.watch(resolved.cwd, { recursive: true }, (_event, filename) => {
16365
+ watcher = fs15__namespace.watch(resolved.cwd, { recursive: true }, (_event, filename) => {
14964
16366
  const decision = decideWatchEvent(
14965
16367
  state,
14966
16368
  {
@@ -14990,12 +16392,12 @@ async function runWatchLoop(invocation, resolved, options) {
14990
16392
  info(`\u26A0 Watch error: ${err.message}`);
14991
16393
  info(" The watcher may have missed changes. Restart with Ctrl+C if they stop arriving.");
14992
16394
  });
14993
- await new Promise((resolve10) => {
16395
+ await new Promise((resolve11) => {
14994
16396
  const stop = () => {
14995
16397
  stopped = true;
14996
16398
  if (timer) clearTimeout(timer);
14997
16399
  watcher.close();
14998
- resolve10();
16400
+ resolve11();
14999
16401
  };
15000
16402
  process.once("SIGINT", stop);
15001
16403
  process.once("SIGTERM", stop);