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/bin.js CHANGED
@@ -2,12 +2,12 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { spawnSync } from "child_process";
5
- import * as fs19 from "fs";
5
+ import * as fs20 from "fs";
6
6
  import * as path21 from "path";
7
7
  import { parseArgs } from "util";
8
8
 
9
9
  // src/diff.ts
10
- import * as fs7 from "fs";
10
+ import * as fs8 from "fs";
11
11
  import * as path7 from "path";
12
12
 
13
13
  // src/scanner/files.ts
@@ -167,8 +167,8 @@ function workspacePackageDirs(cwd, patterns) {
167
167
  function scanWorkspacePackages(cwd, patterns) {
168
168
  const files = /* @__PURE__ */ new Set();
169
169
  const dependencies = /* @__PURE__ */ new Set();
170
- for (const relative12 of workspacePackageDirs(cwd, patterns)) {
171
- const full = path.join(cwd, relative12);
170
+ for (const relative14 of workspacePackageDirs(cwd, patterns)) {
171
+ const full = path.join(cwd, relative14);
172
172
  try {
173
173
  for (const entry of fs.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
174
174
  } catch {
@@ -1095,7 +1095,10 @@ var ASSIGN = String.raw`(?<![=!<>])[:=](?!=)`;
1095
1095
  var NOT_AFTER_QUOTE = String.raw`(?<!["'])`;
1096
1096
  var NOT_A_NAMESPACED_IDENTIFIER = String.raw`(?![a-z][a-z0-9]*(?:\.[a-z][a-z0-9-]*)+/)`;
1097
1097
  var QUOTED_CREDENTIAL_KEY = `["'](?!id[-_]token["'])[A-Za-z0-9_$-]{0,64}${STRONG_CREDENTIAL_NAME}["']`;
1098
- var QUOTED_VALUE = String.raw`((?:[^"'\\\n]|\\\\["'](?=[A-Za-z0-9_])|\\.){1,512})`;
1098
+ function quotedValueFor(delimiterGroup) {
1099
+ return "((?:(?!\\" + delimiterGroup + String.raw`)[^\\\n]|\\\\["'](?=[A-Za-z0-9_])|\\.){1,512})`;
1100
+ }
1101
+ var QUOTED_VALUE = quotedValueFor(1);
1099
1102
  var UNQUOTED_STRONG_NAME = `(?<!id[-_])${STRONG_CREDENTIAL_NAME}`;
1100
1103
  var CREDENTIAL_KEY_TAIL = new RegExp(`(?:${STRONG_CREDENTIAL_NAME})$`, "i");
1101
1104
  var DEFAULT_SECRET_PATTERNS = [
@@ -1249,7 +1252,7 @@ var DEFAULT_SECRET_PATTERNS = [
1249
1252
  // consumes the flag so the match is the credential alone.
1250
1253
  // - An Azure SAS link authenticates with `?sig=`; the signature *is* the credential.
1251
1254
  rule: "uri-credentials",
1252
- 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%._=~-])/
1255
+ 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%._=~-])/
1253
1256
  },
1254
1257
  {
1255
1258
  // The host tail stops at quotes, `;`, `)`, `<`, `>` and `,`: an unbounded
@@ -1361,7 +1364,7 @@ var DEFAULT_SECRET_PATTERNS = [
1361
1364
  // rendering of textual userinfo mixes cases, while the prose the earlier rules were
1362
1365
  // protecting (`Bearer authentication`) is a lowercase word.
1363
1366
  rule: "authorization-header",
1364
- 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_.+/=-])/
1367
+ 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_.+/=-])/
1365
1368
  },
1366
1369
  {
1367
1370
  // Broader names than before (`apiKey`, `clientSecret`, `privateKey` were
@@ -1388,7 +1391,9 @@ var DEFAULT_SECRET_PATTERNS = [
1388
1391
  // between the braces to mask, and `isTemplateInterpolation` keeps such a value readable.
1389
1392
  rule: "interpolation-fallback-secret",
1390
1393
  pattern: new RegExp(
1391
- `(?:["']${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})\\}["'\`]?`,
1394
+ // The operator set deliberately omits `?`: `${VAR:?message}` is an error message in shell
1395
+ // and Compose, not a fallback value, and masking it hid the sentence a user is meant to read.
1396
+ `(?:["']${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})\\}["'\`]?`,
1392
1397
  "i"
1393
1398
  ),
1394
1399
  valueGroup: 1
@@ -1437,19 +1442,15 @@ function compilePattern(rule, pattern, valueGroup) {
1437
1442
  if (pattern instanceof RegExp) {
1438
1443
  const flags = new Set(pattern.flags.replace(/[gy]/g, "").split(""));
1439
1444
  if (valueGroup !== void 0) flags.add("d");
1440
- return {
1441
- rule,
1442
- pattern: new RegExp(pattern.source, [...flags].join("")),
1443
- ...valueGroup === void 0 ? {} : { valueGroup }
1444
- };
1445
+ return checkedPattern(rule, new RegExp(pattern.source, [...flags].join("")), valueGroup);
1445
1446
  }
1446
1447
  if (typeof pattern === "string") {
1447
1448
  try {
1448
- return {
1449
+ return checkedPattern(
1449
1450
  rule,
1450
- pattern: new RegExp(pattern, valueGroup === void 0 ? "i" : "id"),
1451
- ...valueGroup === void 0 ? {} : { valueGroup }
1452
- };
1451
+ new RegExp(pattern, valueGroup === void 0 ? "i" : "id"),
1452
+ valueGroup
1453
+ );
1453
1454
  } catch (err) {
1454
1455
  throw new Error(
1455
1456
  `Invalid regular expression for secret rule "${rule}": ${err.message}`
@@ -1460,6 +1461,19 @@ function compilePattern(rule, pattern, valueGroup) {
1460
1461
  `Secret rule "${rule}" has a pattern that is neither a RegExp nor a string (received ${describeValue(pattern)}).`
1461
1462
  );
1462
1463
  }
1464
+ function checkedPattern(rule, compiled, valueGroup) {
1465
+ const stateless = new RegExp(compiled.source, compiled.flags.replace(/[gy]/g, ""));
1466
+ if (stateless.test("")) {
1467
+ throw new Error(
1468
+ `Secret rule "${rule}" can match the empty string. Every alternative must require at least one character, or the scan cannot advance past a match.`
1469
+ );
1470
+ }
1471
+ return {
1472
+ rule,
1473
+ pattern: compiled,
1474
+ ...valueGroup === void 0 ? {} : { valueGroup }
1475
+ };
1476
+ }
1463
1477
  function compileSecretRules(rules) {
1464
1478
  if (!Array.isArray(rules)) {
1465
1479
  throw new Error(
@@ -1516,6 +1530,193 @@ function toGlobal(rule) {
1516
1530
  }
1517
1531
  var LINE_BREAK = /(\r\n|\n|\r)/;
1518
1532
  var LINE_TERMINATOR = /\r\n|\n|\r/g;
1533
+ function isOpeningQuote(line, index) {
1534
+ const code = line.charCodeAt(index);
1535
+ if (code === 96) return true;
1536
+ if (code !== 34 && code !== 39) return false;
1537
+ return index === 0 || !/[A-Za-z0-9]/.test(line[index - 1]);
1538
+ }
1539
+ function quoteStates(line) {
1540
+ const states = new Uint8Array(line.length + 1);
1541
+ let quote = 0;
1542
+ for (let index = 0; index < line.length; index += 1) {
1543
+ states[index] = quote;
1544
+ const code = line.charCodeAt(index);
1545
+ if (quote === 0) {
1546
+ if (isOpeningQuote(line, index)) quote = code;
1547
+ } else if (code === 92) {
1548
+ if (index + 1 < line.length) {
1549
+ index += 1;
1550
+ states[index] = quote;
1551
+ }
1552
+ } else if (code === quote) {
1553
+ quote = 0;
1554
+ }
1555
+ }
1556
+ states[line.length] = quote;
1557
+ return states;
1558
+ }
1559
+ function quoteStateFor(line, context) {
1560
+ if (context.quoteAt === void 0) context.quoteAt = quoteStates(line);
1561
+ return context.quoteAt;
1562
+ }
1563
+ function quoteStateAfter(text2, quote, end = text2.length) {
1564
+ for (let index = 0; index < end; index += 1) {
1565
+ const code = text2.charCodeAt(index);
1566
+ if (quote === 0) {
1567
+ if (isOpeningQuote(text2, index)) quote = code;
1568
+ } else if (code === 92) {
1569
+ index += 1;
1570
+ } else if (code === quote) {
1571
+ quote = 0;
1572
+ }
1573
+ }
1574
+ return quote;
1575
+ }
1576
+ function commentStartFor(line, context) {
1577
+ if (context.commentStart !== void 0) return context.commentStart;
1578
+ const quotes = quoteStateFor(line, context);
1579
+ let start = line.length;
1580
+ for (let index = 0; index < line.length; index += 1) {
1581
+ if (line.charCodeAt(index) !== 35 || quotes[index] !== 0) continue;
1582
+ if (index === 0 || /\s/.test(line[index - 1])) {
1583
+ start = index;
1584
+ break;
1585
+ }
1586
+ }
1587
+ context.commentStart = start;
1588
+ return start;
1589
+ }
1590
+ function commandSeparatorsFor(line, context) {
1591
+ if (context.commandSeparators !== void 0) return context.commandSeparators;
1592
+ const quotes = quoteStateFor(line, context);
1593
+ const separators = [];
1594
+ for (let index = 0; index < line.length; index += 1) {
1595
+ if (quotes[index] !== 0) continue;
1596
+ const ch = line[index];
1597
+ const spaced = index > 0 && /\s/.test(line[index - 1]) || index + 1 < line.length && /\s/.test(line[index + 1]);
1598
+ if (ch === "&" || ch === "|") {
1599
+ if (line[index + 1] === ch) {
1600
+ const after = index + 2;
1601
+ const doubleSpaced = spaced || after >= line.length || /\s/.test(line[after]);
1602
+ if (doubleSpaced) separators.push(index);
1603
+ index += 1;
1604
+ } else if (spaced) {
1605
+ separators.push(index);
1606
+ }
1607
+ } else if ((ch === ";" || ch === ">" || ch === "<") && spaced) {
1608
+ separators.push(index);
1609
+ }
1610
+ }
1611
+ context.commandSeparators = separators;
1612
+ return separators;
1613
+ }
1614
+ function lineValueEnd(line, start, context) {
1615
+ const comment = commentStartFor(line, context);
1616
+ let end = comment > start ? comment : line.length;
1617
+ for (const separator of commandSeparatorsFor(line, context)) {
1618
+ if (separator > start && separator < end) {
1619
+ end = separator;
1620
+ break;
1621
+ }
1622
+ }
1623
+ while (end > start && /\s/.test(line[end - 1])) end -= 1;
1624
+ return end;
1625
+ }
1626
+ function hasStructuralQuote(line) {
1627
+ for (let index = 0; index < line.length; index += 1) {
1628
+ const ch = line[index];
1629
+ if (ch !== '"' && ch !== "'" && ch !== "`") continue;
1630
+ if (ch === "'" && index > 0 && /[A-Za-z0-9]/.test(line[index - 1])) continue;
1631
+ let backslashes = 0;
1632
+ for (let before2 = index - 1; before2 >= 0 && line[before2] === "\\"; before2 -= 1) backslashes += 1;
1633
+ if (backslashes % 2 === 1) continue;
1634
+ let before = index - 1;
1635
+ while (before >= 0 && (line[before] === " " || line[before] === " ")) before -= 1;
1636
+ if (before < 0 || "+,=:([{".includes(line[before])) return true;
1637
+ }
1638
+ return false;
1639
+ }
1640
+ function maskRawPemLine(line) {
1641
+ if (line.trim() === "") return line;
1642
+ const leading = /^[ \t]*(?:#|\/\/|;)?[ \t]*/.exec(line)?.[0] ?? "";
1643
+ let rest = line.slice(leading.length);
1644
+ const trailing = /[ \t]*(?:[,;\\+])?[ \t]*$/.exec(rest)?.[0] ?? "";
1645
+ rest = rest.slice(0, rest.length - trailing.length);
1646
+ return leading + (rest.length > 0 ? PEM_REDACTION_MARKER : "") + trailing;
1647
+ }
1648
+ function skeletonisePemLine(line, initialQuote) {
1649
+ const hasQuote = line.includes('"') || line.includes("'") || line.includes("`");
1650
+ const structural = initialQuote !== 0 || hasQuote && (hasStructuralQuote(line) || /-----BEGIN|-----END/.test(line));
1651
+ if (!structural) return { text: maskRawPemLine(line), quote: initialQuote };
1652
+ let out = "";
1653
+ let quote = initialQuote;
1654
+ let masking = false;
1655
+ for (let index = 0; index < line.length; index += 1) {
1656
+ const code = line.charCodeAt(index);
1657
+ if (quote === 0) {
1658
+ if (isOpeningQuote(line, index)) {
1659
+ quote = code;
1660
+ masking = false;
1661
+ }
1662
+ out += line[index];
1663
+ continue;
1664
+ }
1665
+ if (code === 92) {
1666
+ masking = false;
1667
+ out += line[index];
1668
+ if (index + 1 < line.length) {
1669
+ out += line[index + 1];
1670
+ index += 1;
1671
+ }
1672
+ continue;
1673
+ }
1674
+ if (code === quote) {
1675
+ masking = false;
1676
+ quote = 0;
1677
+ out += line[index];
1678
+ continue;
1679
+ }
1680
+ if (!masking) {
1681
+ out += PEM_REDACTION_MARKER;
1682
+ masking = true;
1683
+ }
1684
+ }
1685
+ return { text: out, quote };
1686
+ }
1687
+ function lineSpanAt(text2, start, end) {
1688
+ let lineStart = start;
1689
+ while (lineStart > 0 && text2[lineStart - 1] !== "\n" && text2[lineStart - 1] !== "\r") {
1690
+ lineStart -= 1;
1691
+ }
1692
+ let lineEnd = end;
1693
+ while (lineEnd < text2.length && text2[lineEnd] !== "\n" && text2[lineEnd] !== "\r") lineEnd += 1;
1694
+ if (lineEnd < text2.length) {
1695
+ lineEnd += text2[lineEnd] === "\r" && text2[lineEnd + 1] === "\n" ? 2 : 1;
1696
+ }
1697
+ return { start: lineStart, end: lineEnd };
1698
+ }
1699
+ function redactPemSpan(text2, matchStart, matchEnd) {
1700
+ const span = lineSpanAt(text2, matchStart, matchEnd);
1701
+ const segments = text2.slice(span.start, span.end).split(LINE_BREAK);
1702
+ let quote = quoteStateAfter(text2, 0, matchStart);
1703
+ let cursor = span.start;
1704
+ for (let index = 0; index < segments.length; index += 2) {
1705
+ const line = segments[index];
1706
+ const lineStart = cursor;
1707
+ const lineEnd = lineStart + line.length;
1708
+ cursor = lineEnd + (index + 1 < segments.length ? segments[index + 1].length : 0);
1709
+ const from = Math.max(lineStart, matchStart);
1710
+ const to = Math.min(lineEnd, matchEnd);
1711
+ if (from >= to) continue;
1712
+ const localFrom = from - lineStart;
1713
+ const localTo = to - lineStart;
1714
+ const result = skeletonisePemLine(line.slice(localFrom, localTo), quote);
1715
+ segments[index] = line.slice(0, localFrom) + result.text + line.slice(localTo);
1716
+ quote = result.quote;
1717
+ }
1718
+ return { replacement: segments.join(""), start: span.start, end: span.end };
1719
+ }
1519
1720
  var COMPILED_RULES = /* @__PURE__ */ new WeakMap();
1520
1721
  function compiledRuleFor(rule) {
1521
1722
  let compiled = COMPILED_RULES.get(rule);
@@ -1530,22 +1731,30 @@ function compiledRuleFor(rule) {
1530
1731
  return compiled;
1531
1732
  }
1532
1733
  function scanAndRedactSecrets(content, rules, filePath) {
1533
- const findings = [];
1734
+ const findingsByLine = /* @__PURE__ */ new Map();
1735
+ const recordFinding = (line, rulesForLine) => {
1736
+ let entry = findingsByLine.get(line);
1737
+ if (entry === void 0) {
1738
+ entry = /* @__PURE__ */ new Set();
1739
+ findingsByLine.set(line, entry);
1740
+ }
1741
+ for (const rule of rulesForLine) entry.add(rule);
1742
+ };
1534
1743
  let redacted = content;
1535
1744
  for (const blockPattern of [PEM_BLOCK_PATTERN, PEM_UNTERMINATED_PATTERN]) {
1536
1745
  blockPattern.lastIndex = 0;
1537
1746
  let match;
1538
1747
  while ((match = blockPattern.exec(redacted)) !== null) {
1539
1748
  if (match[0].length === 0) {
1540
- blockPattern.lastIndex += 1;
1749
+ blockPattern.lastIndex = advanceStringIndex(redacted, match.index, blockPattern.unicode);
1541
1750
  continue;
1542
1751
  }
1543
- const before = redacted.slice(0, match.index);
1544
- const line = (before.match(LINE_TERMINATOR) ?? []).length + 1;
1545
- const newlines = (match[0].match(LINE_TERMINATOR) ?? []).length;
1546
- findings.push({ rules: ["private-key-block"], line, path: filePath });
1547
- redacted = before + PEM_REDACTION_MARKER + "\n".repeat(newlines) + redacted.slice(match.index + match[0].length);
1548
- blockPattern.lastIndex = match.index + PEM_REDACTION_MARKER.length + newlines;
1752
+ const matchEnd = match.index + match[0].length;
1753
+ const line = (redacted.slice(0, match.index).match(LINE_TERMINATOR) ?? []).length + 1;
1754
+ const span = redactPemSpan(redacted, match.index, matchEnd);
1755
+ recordFinding(line, ["private-key-block"]);
1756
+ redacted = redacted.slice(0, span.start) + span.replacement + redacted.slice(span.end);
1757
+ blockPattern.lastIndex = span.start + span.replacement.length;
1549
1758
  }
1550
1759
  }
1551
1760
  const compiled = rules.map(compiledRuleFor);
@@ -1556,17 +1765,38 @@ function scanAndRedactSecrets(content, rules, filePath) {
1556
1765
  if (line.length > 0) {
1557
1766
  const spans = [];
1558
1767
  const matchedRules = /* @__PURE__ */ new Set();
1768
+ const context = {};
1559
1769
  for (const { rule, pattern, valueGroup } of compiled) {
1560
1770
  pattern.lastIndex = 0;
1561
1771
  let match;
1562
1772
  while ((match = pattern.exec(line)) !== null) {
1563
1773
  if (match[0].length === 0) {
1564
- pattern.lastIndex += 1;
1774
+ pattern.lastIndex = advanceStringIndex(line, match.index, pattern.unicode);
1565
1775
  continue;
1566
1776
  }
1567
1777
  const group = valueGroup === void 0 ? void 0 : match.indices?.[valueGroup];
1778
+ const candidate = group ? line.slice(group[0], group[1]) : line.slice(match.index, match.index + match[0].length);
1779
+ if (isPlaceholderValue(candidate)) continue;
1780
+ if (group && isUnquotedValue(line, group[0]) && isSourceCodeFile(filePath) && (quoteStateFor(line, context)[match.index] ?? 0) === 0) {
1781
+ continue;
1782
+ }
1783
+ if (group && /^\$[({A-Za-z_]/.test(line.slice(group[0], group[1])) && (isAssignmentFile(filePath) || isUnquotedValue(line, group[0]))) {
1784
+ continue;
1785
+ }
1786
+ if (rule === "credential-assignment-weak" && group) {
1787
+ let before = match.index - 1;
1788
+ while (before >= 0 && (line[before] === " " || line[before] === " ")) before -= 1;
1789
+ if (before >= 0 && (line[before] === "?" || line[before] === ":")) continue;
1790
+ const keyText = line.slice(match.index, group[0]).replace(/["'\s:=]+/g, " ").trim();
1791
+ if (/^(?:PASS|FAIL)$/i.test(keyText) && /^[A-Z]{2,}$/.test(line.slice(group[0], group[1]))) {
1792
+ continue;
1793
+ }
1794
+ }
1568
1795
  if (group && isSelfNamingConstant(line, group[0], group[1])) continue;
1569
- if (valueGroup !== void 0 && startsInsideStringLiteral(line, match.index, group?.[0])) {
1796
+ if (group && !isUnquotedValue(line, group[0]) && /["'`]\s*\+\s*|\s*\+\s*["'`]/.test(line.slice(group[0], group[1]))) {
1797
+ continue;
1798
+ }
1799
+ if (valueGroup !== void 0 && startsInsideStringLiteral(line, match.index, group?.[0], context, filePath)) {
1570
1800
  continue;
1571
1801
  }
1572
1802
  if (group && isUnquotedValue(line, group[0]) && isDeclaredBinding(line, match.index, filePath)) {
@@ -1592,7 +1822,12 @@ function scanAndRedactSecrets(content, rules, filePath) {
1592
1822
  if (wholeValue) {
1593
1823
  spans.push({
1594
1824
  start: group[0],
1595
- end: Math.max(group[1], tokenEnd(line, group[0])),
1825
+ // A passphrase contains spaces: `DB_PASSWORD=correct horse battery staple` used to
1826
+ // stop at the first one and emit the rest beside the marker. Stop at the end of
1827
+ // the value, a trailing comment, or a shell operator instead. The rule's own end
1828
+ // is not used: the colon form's value pattern includes the spaces before a
1829
+ // trailing `# comment`, and masking them welds the comment to the marker.
1830
+ end: lineValueEnd(line, group[0], context),
1596
1831
  rule
1597
1832
  });
1598
1833
  matchedRules.add(rule);
@@ -1605,14 +1840,153 @@ function scanAndRedactSecrets(content, rules, filePath) {
1605
1840
  matchedRules.add(rule);
1606
1841
  }
1607
1842
  }
1843
+ for (const span of concatenatedCredentialSpans(line)) {
1844
+ spans.push(span);
1845
+ matchedRules.add(span.rule);
1846
+ }
1608
1847
  if (spans.length > 0) {
1609
- findings.push({ rules: [...matchedRules], line: lineNumber, path: filePath });
1610
- segments[index] = applySpans(line, spans);
1848
+ const maskedLine = applySpans(line, spans);
1849
+ if (!quotesAreBalanced(line) || quotesAreBalanced(maskedLine)) {
1850
+ recordFinding(lineNumber, matchedRules);
1851
+ segments[index] = maskedLine;
1852
+ }
1611
1853
  }
1612
1854
  }
1613
1855
  if (index + 1 < segments.length) lineNumber += 1;
1614
1856
  }
1615
- return { redacted: segments.join(""), findings };
1857
+ let finalText = segments.join("");
1858
+ finalText = redactStructuredValues(finalText, filePath, recordFinding);
1859
+ finalText = redactDockerfileEnv(finalText, filePath, recordFinding);
1860
+ const findings = [...findingsByLine.entries()].sort(([left], [right]) => left - right).map(([line, rulesForLine]) => ({
1861
+ rules: [...rulesForLine],
1862
+ line,
1863
+ path: filePath
1864
+ }));
1865
+ return { redacted: finalText, findings };
1866
+ }
1867
+ function advanceStringIndex(text2, index, unicode) {
1868
+ if (!unicode) return index + 1;
1869
+ const first = text2.charCodeAt(index);
1870
+ if (first >= 55296 && first <= 56319) {
1871
+ const second = text2.charCodeAt(index + 1);
1872
+ if (second >= 56320 && second <= 57343) return index + 2;
1873
+ }
1874
+ return index + 1;
1875
+ }
1876
+ var STRUCTURED_FILE = /\.(?:json|jsonc|json5|ya?ml|toml|ini|conf|cfg|properties|env|tf|tfvars)$/i;
1877
+ var STRUCTURED_BASENAME = /^(?:\.env(?:\.[^/]*)?|docker-compose(?:\.[^/]*)?|compose(?:\.[^/]*)?)$/i;
1878
+ function isStructuredFile(filePath) {
1879
+ if (filePath === void 0) return false;
1880
+ const normalised = filePath.replace(/\\/g, "/");
1881
+ if (STRUCTURED_FILE.test(normalised)) return true;
1882
+ return STRUCTURED_BASENAME.test(normalised.slice(normalised.lastIndexOf("/") + 1));
1883
+ }
1884
+ function isDockerfile(filePath) {
1885
+ if (filePath === void 0) return false;
1886
+ const normalised = filePath.replace(/\\/g, "/");
1887
+ return /^(?:Dockerfile|[^/]*\.dockerfile)$/i.test(
1888
+ normalised.slice(normalised.lastIndexOf("/") + 1)
1889
+ );
1890
+ }
1891
+ function maskLineContent(line) {
1892
+ if (line.trim() === "") return line;
1893
+ const indent = /^[ \t]*/.exec(line)?.[0] ?? "";
1894
+ return `${indent}${REDACTION_MARKER}`;
1895
+ }
1896
+ function maskValueLine(line) {
1897
+ if (line.trim() === "") return line;
1898
+ const indent = /^[ \t]*/.exec(line)?.[0] ?? "";
1899
+ const content = line.slice(indent.length);
1900
+ const quoted = /^(["'`])(.*)\1([,;]?[ \t]*)$/.exec(content);
1901
+ if (quoted !== null) {
1902
+ return `${indent}${quoted[1]}${REDACTION_MARKER}${quoted[1]}${quoted[3] ?? ""}`;
1903
+ }
1904
+ return `${indent}${REDACTION_MARKER}`;
1905
+ }
1906
+ var STRUCTURED_KEY = /^([ \t]*)["']?([A-Za-z0-9_$.-]{1,128})["']?[ \t]*([:=])[ \t]*(.*)$/;
1907
+ var BLOCK_SCALAR = /^[|>][+-]?\d*[ \t]*(?:#.*)?$/;
1908
+ function redactStructuredValues(text2, filePath, recordFinding) {
1909
+ if (!isStructuredFile(filePath)) return text2;
1910
+ const segments = text2.split(LINE_BREAK);
1911
+ for (let index = 0; index < segments.length; index += 2) {
1912
+ const line = segments[index];
1913
+ if (line === void 0 || line.length === 0) continue;
1914
+ const match = STRUCTURED_KEY.exec(line);
1915
+ if (match === null) continue;
1916
+ const key = match[2] ?? "";
1917
+ if (!CREDENTIAL_KEY_TAIL.test(key)) continue;
1918
+ const baseIndent = (match[1] ?? "").length;
1919
+ const rest = (match[4] ?? "").trim();
1920
+ if (BLOCK_SCALAR.test(rest)) {
1921
+ let cursor2 = index + 2;
1922
+ let masked2 = false;
1923
+ while (cursor2 < segments.length) {
1924
+ const body = segments[cursor2] ?? "";
1925
+ if (body.trim() !== "") {
1926
+ const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
1927
+ if (indent <= baseIndent) break;
1928
+ segments[cursor2] = maskLineContent(body);
1929
+ masked2 = true;
1930
+ }
1931
+ cursor2 += 2;
1932
+ }
1933
+ if (masked2) recordFinding(index / 2 + 1, ["credential-block-scalar"]);
1934
+ continue;
1935
+ }
1936
+ if (rest !== "") continue;
1937
+ let cursor = index + 2;
1938
+ while (cursor < segments.length && (segments[cursor] ?? "").trim() === "") cursor += 2;
1939
+ const firstValue = segments[cursor];
1940
+ if (firstValue === void 0) continue;
1941
+ const valueIndent = (/^[ \t]*/.exec(firstValue)?.[0] ?? "").length;
1942
+ if (valueIndent <= baseIndent) continue;
1943
+ let masked = false;
1944
+ while (cursor < segments.length) {
1945
+ const body = segments[cursor] ?? "";
1946
+ if (body.trim() !== "") {
1947
+ const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
1948
+ if (indent < valueIndent) break;
1949
+ segments[cursor] = maskValueLine(body);
1950
+ masked = true;
1951
+ }
1952
+ cursor += 2;
1953
+ }
1954
+ if (masked) recordFinding(index / 2 + 1, ["credential-multiline-value"]);
1955
+ }
1956
+ return segments.join("");
1957
+ }
1958
+ var DOCKERFILE_ENV = /^([ \t]*ENV[ \t]+)([A-Za-z_][A-Za-z0-9_]*)([ \t]+)(\S.*)$/;
1959
+ function redactDockerfileEnv(text2, filePath, recordFinding) {
1960
+ if (!isDockerfile(filePath)) return text2;
1961
+ const segments = text2.split(LINE_BREAK);
1962
+ for (let index = 0; index < segments.length; index += 2) {
1963
+ const line = segments[index];
1964
+ if (line === void 0) continue;
1965
+ const match = DOCKERFILE_ENV.exec(line);
1966
+ if (match === null) continue;
1967
+ if (!CREDENTIAL_KEY_TAIL.test(match[2] ?? "")) continue;
1968
+ const value = match[4] ?? "";
1969
+ if (value.startsWith("=")) continue;
1970
+ segments[index] = `${match[1]}${match[2]}${match[3]}${REDACTION_MARKER}`;
1971
+ recordFinding(index / 2 + 1, ["dockerfile-env-secret"]);
1972
+ }
1973
+ return segments.join("");
1974
+ }
1975
+ var CONCATENATED_CREDENTIAL = new RegExp(
1976
+ "([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",
1977
+ "gid"
1978
+ );
1979
+ function concatenatedCredentialSpans(line) {
1980
+ const spans = [];
1981
+ CONCATENATED_CREDENTIAL.lastIndex = 0;
1982
+ let match;
1983
+ while ((match = CONCATENATED_CREDENTIAL.exec(line)) !== null) {
1984
+ const group = match.indices?.[4];
1985
+ if (group !== void 0) {
1986
+ spans.push({ start: group[0], end: group[1], rule: "credential-concatenation" });
1987
+ }
1988
+ }
1989
+ return spans;
1616
1990
  }
1617
1991
  var TOKEN_CHARS_LEFT = /[A-Za-z0-9_+/-]/;
1618
1992
  var TOKEN_CHARS_RIGHT = /[A-Za-z0-9_+/=-]/;
@@ -1630,13 +2004,20 @@ function expandOverToken(line, start, end) {
1630
2004
  while (right < line.length && TOKEN_CHARS_RIGHT.test(line[right])) right += 1;
1631
2005
  return { start: left, end: right };
1632
2006
  }
1633
- function startsInsideStringLiteral(line, matchIndex, valueStart) {
1634
- let runStart = matchIndex;
1635
- while (runStart > 0 && /[A-Za-z0-9_-]/.test(line[runStart - 1])) runStart -= 1;
1636
- const before = runStart > 0 ? line[runStart - 1] : "";
1637
- if (before !== '"' && before !== "'" && before !== "`") return false;
2007
+ function startsInsideStringLiteral(line, matchIndex, valueStart, context, filePath) {
2008
+ const quote = quoteStateFor(line, context)[matchIndex] ?? 0;
2009
+ if (quote === 0) return false;
2010
+ if (quote === 96 && /\.(?:md|mdx)$/i.test(filePath ?? "")) return true;
1638
2011
  if (valueStart === void 0) return true;
1639
- return /["'`]/.test(line.slice(matchIndex, valueStart));
2012
+ for (let index = matchIndex; index < valueStart; index += 1) {
2013
+ const code = line.charCodeAt(index);
2014
+ if (code === 92) {
2015
+ index += 1;
2016
+ } else if (code === quote) {
2017
+ return true;
2018
+ }
2019
+ }
2020
+ return false;
1640
2021
  }
1641
2022
  function isTemplateInterpolation(line, start, end) {
1642
2023
  if (line[start] !== "$" || line[start + 1] !== "{" || line[end - 1] !== "}") {
@@ -1664,6 +2045,40 @@ function isSelfNamingConstant(line, start, end) {
1664
2045
  }
1665
2046
  return line.endsWith(value, index);
1666
2047
  }
2048
+ var SOURCE_CODE_FILE = /\.(?:[cm]?[jt]sx?)$/i;
2049
+ function isSourceCodeFile(filePath) {
2050
+ return filePath !== void 0 && SOURCE_CODE_FILE.test(filePath.replace(/\\/g, "/"));
2051
+ }
2052
+ var PLACEHOLDER_PATTERNS = [
2053
+ /^<[^>]*>?$/,
2054
+ /^\.{3,}$/,
2055
+ /^(?:x{4,}|X{4,}|\*{3,})$/,
2056
+ /^(?:replace|change)[-_ ]?me(?:[-_ ].*)?$/i,
2057
+ /^your[-_ ].*$/i,
2058
+ /^(?:example|sample)(?:[-_ ].*)?$/i
2059
+ ];
2060
+ function isPlaceholderValue(value) {
2061
+ const trimmed = value.trim().replace(/^["'`]+/, "").replace(/["'`]+$/, "");
2062
+ if (trimmed.length === 0) return false;
2063
+ if (PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(trimmed))) return true;
2064
+ return trimmed.includes("...") || /^<[^>]*$/.test(trimmed);
2065
+ }
2066
+ function quotesAreBalanced(text2) {
2067
+ let single = 0;
2068
+ let double = 0;
2069
+ let backtick = 0;
2070
+ for (let index = 0; index < text2.length; index += 1) {
2071
+ const char = text2[index];
2072
+ if (char === "\\") {
2073
+ index += 1;
2074
+ continue;
2075
+ }
2076
+ if (char === '"') double += 1;
2077
+ else if (char === "'") single += 1;
2078
+ else if (char === "`") backtick += 1;
2079
+ }
2080
+ return double % 2 === 0 && single % 2 === 0 && backtick % 2 === 0;
2081
+ }
1667
2082
  function assignmentAround(line, valueStart) {
1668
2083
  let index = valueStart;
1669
2084
  while (index > 0 && (line[index - 1] === " " || line[index - 1] === " ")) index -= 1;
@@ -1733,6 +2148,16 @@ function applySpans(line, spans) {
1733
2148
  return out;
1734
2149
  }
1735
2150
 
2151
+ // src/version.ts
2152
+ var GENERATOR_NAME = "codebase-snapshot";
2153
+ var GENERATOR_VERSION = "0.9.17";
2154
+ var SCHEMA_VERSION = "3.0.0";
2155
+ var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2156
+ function isOurGeneratorName(name) {
2157
+ if (typeof name !== "string") return false;
2158
+ return name === GENERATOR_NAME || LEGACY_GENERATOR_NAMES.includes(name);
2159
+ }
2160
+
1736
2161
  // src/scanner/files.ts
1737
2162
  function isDiscoveryMode(value) {
1738
2163
  return value === "auto" || value === "git" || value === "walk";
@@ -1757,8 +2182,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
1757
2182
  };
1758
2183
  }
1759
2184
  function isInside(root, candidate) {
1760
- const relative12 = path2.relative(root, candidate);
1761
- return relative12 === "" || !relative12.startsWith(`..${path2.sep}`) && relative12 !== ".." && !path2.isAbsolute(relative12);
2185
+ const relative14 = path2.relative(root, candidate);
2186
+ return relative14 === "" || !relative14.startsWith(`..${path2.sep}`) && relative14 !== ".." && !path2.isAbsolute(relative14);
1762
2187
  }
1763
2188
  var GIT_OUTPUT_LIMIT = 68157440;
1764
2189
  function getGitInfo(cwd, fallbackBranch = "main") {
@@ -1819,10 +2244,10 @@ var DEFAULT_IGNORED_FILES = [
1819
2244
  "bun.lockb",
1820
2245
  "composer.lock"
1821
2246
  ];
1822
- 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;
1823
- var SENSITIVE_PATH = /(?:^|\/)\.(?:aws|ssh|gnupg)\/|(?:^|\/)\.docker\/config\.json$|(?:^|\/)\.kube\/config$/i;
2247
+ 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;
2248
+ var SENSITIVE_PATH = /(?:^|\/)\.(?:aws|ssh|gnupg)\/|(?:^|\/)\.docker\/config\.json$|(?:^|\/)\.kube\/config$|(?:^|\/)\.config\/gcloud\/|(?:^|\/)\.composer\/|(?:^|\/)\.terraform\/credentials\.tfrc\.json$/i;
1824
2249
  var SENSITIVE_EXT = /\.(?:pem|key|p12|pfx|jks|keystore|ppk|asc|kdbx|tfstate|tfvars)$/i;
1825
- var TEMPLATE_SUFFIX = /\.(?:example|sample|template|dist)(?=$|[.])/i;
2250
+ var TEMPLATE_SUFFIX = /^(.*)\.(?:example|sample|template|dist)(\.[A-Za-z0-9_-]+)?$/i;
1826
2251
  var BACKUP_SUFFIX = /(?:~|\.(?:bak|backup|old|orig|save|copy|swp|swo|tmp|part))$/i;
1827
2252
  function normaliseName(name) {
1828
2253
  let normalised = name.trim().replace(/[. ]+$/, "");
@@ -1838,12 +2263,16 @@ function isSensitivePath(relativePath) {
1838
2263
  const posixPath = relativePath.replace(/\\/g, "/");
1839
2264
  const raw = posixPath.split("/").pop() ?? posixPath;
1840
2265
  const base = normaliseName(raw);
1841
- if (TEMPLATE_SUFFIX.test(base)) {
1842
- const stripped = base.replace(new RegExp(TEMPLATE_SUFFIX.source, "gi"), "");
1843
- if (matchesSensitiveList(posixPath, stripped)) return false;
1844
- }
2266
+ if (templateOfCredentialFile(posixPath, base)) return false;
1845
2267
  return matchesSensitiveList(posixPath, base);
1846
2268
  }
2269
+ function templateOfCredentialFile(posixPath, base) {
2270
+ const match = TEMPLATE_SUFFIX.exec(base);
2271
+ if (match === null) return null;
2272
+ const stripped = `${match[1] ?? ""}${match[2] ?? ""}`;
2273
+ if (SENSITIVE_EXT.test(stripped)) return null;
2274
+ return matchesSensitiveList(posixPath, stripped) ? stripped : null;
2275
+ }
1847
2276
  var GLOBAL_PATTERNS = /* @__PURE__ */ new WeakMap();
1848
2277
  var GLOB_REGEX_CACHE = /* @__PURE__ */ new Map();
1849
2278
  var GITIGNORE_REGEX_CACHE = /* @__PURE__ */ new Map();
@@ -1875,7 +2304,7 @@ function findSecretInPath(relativePath, extraRules) {
1875
2304
  let match;
1876
2305
  while ((match = scan.exec(posixPath)) !== null) {
1877
2306
  if (match[0].length === 0) {
1878
- scan.lastIndex += 1;
2307
+ scan.lastIndex = advanceStringIndex(posixPath, match.index, scan.unicode);
1879
2308
  continue;
1880
2309
  }
1881
2310
  spans.push({ start: match.index, end: match.index + match[0].length });
@@ -1936,11 +2365,14 @@ function globBodyToRegExp(body, allowBraces) {
1936
2365
  if (char === "*") {
1937
2366
  if (body[i + 1] === "*") {
1938
2367
  i += 1;
1939
- if (body[i + 1] === "/") {
2368
+ const startsSegment = i - 2 < 0 || body[i - 2] === "/";
2369
+ if (startsSegment && body[i + 1] === "/") {
1940
2370
  i += 1;
1941
- out += "(?:.*/)?";
1942
- } else {
2371
+ out += "(?:[^/]+/)*";
2372
+ } else if (startsSegment && i + 1 === body.length) {
1943
2373
  out += ".*";
2374
+ } else {
2375
+ out += "[^/]*";
1944
2376
  }
1945
2377
  } else {
1946
2378
  out += "[^/]*";
@@ -2190,6 +2622,45 @@ function hasSnapshotMarker(target) {
2190
2622
  return false;
2191
2623
  }
2192
2624
  }
2625
+ var IGNORABLE_DIRECTORY_ENTRIES = /* @__PURE__ */ new Set([".DS_Store"]);
2626
+ function isToolOwnedDirectory2(dir) {
2627
+ let raw;
2628
+ try {
2629
+ raw = fs2.readFileSync(path2.join(dir, ".codebase-snapshot"), "utf8");
2630
+ } catch {
2631
+ return false;
2632
+ }
2633
+ let parsed;
2634
+ try {
2635
+ parsed = JSON.parse(raw);
2636
+ } catch {
2637
+ return false;
2638
+ }
2639
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
2640
+ const marker2 = parsed;
2641
+ if (marker2.generator !== GENERATOR_NAME || marker2.state !== "complete" || typeof marker2.id !== "string" || !Array.isArray(marker2.files)) {
2642
+ return false;
2643
+ }
2644
+ const accounted = /* @__PURE__ */ new Set();
2645
+ for (const item of marker2.files) {
2646
+ if (!item || typeof item !== "object" || Array.isArray(item)) return false;
2647
+ const entry = item.path;
2648
+ if (typeof entry !== "string" || entry.length === 0) return false;
2649
+ const parts = entry.split("/");
2650
+ for (let depth = 1; depth <= parts.length; depth += 1) {
2651
+ accounted.add(parts.slice(0, depth).join("/"));
2652
+ }
2653
+ }
2654
+ let entries;
2655
+ try {
2656
+ entries = fs2.readdirSync(dir);
2657
+ } catch {
2658
+ return false;
2659
+ }
2660
+ return entries.every(
2661
+ (entry) => entry === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry) || accounted.has(entry)
2662
+ );
2663
+ }
2193
2664
  function makeToolOwnedDecider(cwd, toolOwnedPaths) {
2194
2665
  const markers = /* @__PURE__ */ new Map();
2195
2666
  const reservedPaths = new Set(toolOwnedPaths.filter((entry) => entry.length > 0));
@@ -2199,7 +2670,7 @@ function makeToolOwnedDecider(cwd, toolOwnedPaths) {
2199
2670
  const prefix = parts.slice(0, depth).join("/");
2200
2671
  let hasMarker = markers.get(prefix);
2201
2672
  if (hasMarker === void 0) {
2202
- hasMarker = fs2.existsSync(path2.join(cwd, prefix, ".codebase-snapshot"));
2673
+ hasMarker = isToolOwnedDirectory2(path2.join(cwd, prefix));
2203
2674
  markers.set(prefix, hasMarker);
2204
2675
  }
2205
2676
  if (hasMarker) return true;
@@ -2371,6 +2842,15 @@ function collectFiles(cwd, options = {}) {
2371
2842
  for (const record of walked.skipped) skipped.push(record);
2372
2843
  }
2373
2844
  }
2845
+ const extraPaths = (options.extraPaths ?? []).map((entry) => entry.replace(/\\/g, "/"));
2846
+ if (extraPaths.length > 0) {
2847
+ const known = new Set(candidates);
2848
+ for (const extra of extraPaths) {
2849
+ if (extra.length === 0 || known.has(extra)) continue;
2850
+ known.add(extra);
2851
+ candidates.push(extra);
2852
+ }
2853
+ }
2374
2854
  const files = candidates.filter((file) => {
2375
2855
  if (isToolOwned(file)) return false;
2376
2856
  const ignored = defaultIgnoreReason(file, toolDirNames);
@@ -2533,6 +3013,15 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
2533
3013
  });
2534
3014
  continue;
2535
3015
  }
3016
+ const targetRelative = path2.relative(rootReal, targetReal).split(path2.sep).join("/");
3017
+ if (isSensitivePath(targetRelative)) {
3018
+ results.skipped.push({
3019
+ path: relPath,
3020
+ reason: "sensitive-file",
3021
+ detail: "link target is a credential-bearing file; not followed"
3022
+ });
3023
+ continue;
3024
+ }
2536
3025
  isDirectory = false;
2537
3026
  isFile = true;
2538
3027
  }
@@ -2547,7 +3036,7 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
2547
3036
 
2548
3037
  // src/validator/validate.ts
2549
3038
  import * as crypto from "crypto";
2550
- import * as fs6 from "fs";
3039
+ import * as fs7 from "fs";
2551
3040
  import * as path6 from "path";
2552
3041
 
2553
3042
  // src/config.ts
@@ -2593,7 +3082,14 @@ var CONFIG_FILENAMES = [
2593
3082
  function findConfigFile(cwd) {
2594
3083
  for (const filename of CONFIG_FILENAMES) {
2595
3084
  const fullPath = path3.join(cwd, filename);
2596
- if (fs3.existsSync(fullPath)) return fullPath;
3085
+ let stats = null;
3086
+ try {
3087
+ stats = fs3.statSync(fullPath);
3088
+ } catch {
3089
+ if (fs3.existsSync(fullPath)) return fullPath;
3090
+ continue;
3091
+ }
3092
+ if (stats.isFile()) return fullPath;
2597
3093
  }
2598
3094
  const pkgJsonPath = path3.join(cwd, "package.json");
2599
3095
  if (!fs3.existsSync(pkgJsonPath)) return null;
@@ -2859,17 +3355,34 @@ function readConfigExport(exported, file) {
2859
3355
  assertKnownConfigKeys(exported, file);
2860
3356
  return exported;
2861
3357
  }
2862
- var moduleConfigLoadToken = 0;
3358
+ var lastModuleConfig = null;
3359
+ function moduleConfigKey(fullPath) {
3360
+ try {
3361
+ return createHash("sha256").update(fs3.readFileSync(fullPath)).digest("hex").slice(0, 24);
3362
+ } catch {
3363
+ try {
3364
+ const stats = fs3.statSync(fullPath);
3365
+ return `stat-${stats.mtimeMs}-${stats.size}`;
3366
+ } catch {
3367
+ return "unreadable";
3368
+ }
3369
+ }
3370
+ }
2863
3371
  async function importConfigModule(fullPath) {
3372
+ const key = moduleConfigKey(fullPath);
3373
+ if (lastModuleConfig !== null && lastModuleConfig.path === fullPath && lastModuleConfig.key === key) {
3374
+ return lastModuleConfig.exports;
3375
+ }
2864
3376
  try {
2865
3377
  const requireFromConfig = createRequire(fullPath);
2866
3378
  delete requireFromConfig.cache[requireFromConfig.resolve(fullPath)];
2867
3379
  } catch {
2868
3380
  }
2869
3381
  const url = pathToFileURL(fullPath);
2870
- moduleConfigLoadToken += 1;
2871
- url.searchParams.set("codebaseSnapshotLoad", String(moduleConfigLoadToken));
2872
- return await import(url.href);
3382
+ url.searchParams.set("codebaseSnapshotLoad", key);
3383
+ const loaded = await import(url.href);
3384
+ lastModuleConfig = { path: fullPath, key, exports: loaded };
3385
+ return loaded;
2873
3386
  }
2874
3387
  function attachConfigDir(config, filePath) {
2875
3388
  if (typeof config === "object" && config !== null) {
@@ -2881,12 +3394,22 @@ function attachConfigDir(config, filePath) {
2881
3394
  }
2882
3395
  return config;
2883
3396
  }
2884
- async function loadConfigFileDetailed(cwd) {
3397
+ async function loadConfigFileDetailed(cwd, options = {}) {
2885
3398
  const warnings = [];
2886
3399
  const errors = [];
3400
+ const configDirectories = [];
2887
3401
  for (const filename of CONFIG_FILENAMES) {
2888
3402
  const fullPath = path3.join(cwd, filename);
2889
- if (!fs3.existsSync(fullPath)) continue;
3403
+ let candidateStats = null;
3404
+ try {
3405
+ candidateStats = fs3.statSync(fullPath);
3406
+ } catch {
3407
+ if (!fs3.existsSync(fullPath)) continue;
3408
+ }
3409
+ if (candidateStats !== null && !candidateStats.isFile()) {
3410
+ configDirectories.push(fullPath);
3411
+ continue;
3412
+ }
2890
3413
  if (filename.endsWith(".json") || filename === ".snapshotrc") {
2891
3414
  try {
2892
3415
  const config = parseJsonish(fs3.readFileSync(fullPath, "utf8"), fullPath);
@@ -2905,6 +3428,12 @@ async function loadConfigFileDetailed(cwd) {
2905
3428
  continue;
2906
3429
  }
2907
3430
  }
3431
+ if (options.allowExecutableConfig === false) {
3432
+ 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.`;
3433
+ warnings.push(message);
3434
+ errors.push(message);
3435
+ continue;
3436
+ }
2908
3437
  if (filename.endsWith(".ts") && !supportsTypeScriptImports()) {
2909
3438
  warnings.push(
2910
3439
  `${fullPath} was ignored: loading a .ts config needs Node >= 22.6 (running ${process.versions.node}). Use snapshot.config.mjs, .cjs or .json instead.`
@@ -2952,6 +3481,11 @@ async function loadConfigFileDetailed(cwd) {
2952
3481
  errors.push(message);
2953
3482
  }
2954
3483
  }
3484
+ if (configDirectories.length > 0) {
3485
+ warnings.push(
3486
+ `${configDirectories.join(", ")} ${configDirectories.length === 1 ? "is a directory" : "are directories"}, not a configuration file; no configuration was read from ${configDirectories.length === 1 ? "it" : "them"}.`
3487
+ );
3488
+ }
2955
3489
  return { config: null, file: null, warnings, errors };
2956
3490
  }
2957
3491
  var MIN_MAX_PART_BYTES = 4096;
@@ -3120,11 +3654,11 @@ function outputExcludePatterns(cwd, outDir, tmpDir) {
3120
3654
  const patterns = [];
3121
3655
  for (const dir of [outDir, tmpDir]) {
3122
3656
  const absolute = path3.resolve(cwd, dir);
3123
- const relative12 = path3.relative(cwd, absolute);
3124
- if (!relative12 || relative12 === ".." || relative12.startsWith(`..${path3.sep}`) || path3.isAbsolute(relative12)) {
3657
+ const relative14 = path3.relative(cwd, absolute);
3658
+ if (!relative14 || relative14 === ".." || relative14.startsWith(`..${path3.sep}`) || path3.isAbsolute(relative14)) {
3125
3659
  continue;
3126
3660
  }
3127
- patterns.push(`${relative12.replace(/\\/g, "/")}/**`);
3661
+ patterns.push(`${relative14.replace(/\\/g, "/")}/**`);
3128
3662
  }
3129
3663
  return patterns;
3130
3664
  }
@@ -3508,6 +4042,13 @@ function configDigest(config) {
3508
4042
  // moving `{ name: "api", match: "src/api/**" }` to `"src/v2/**"` produced the same
3509
4043
  // digest, so `validate` reported "valid and up to date" for a snapshot whose files
3510
4044
  // had all been reclassified — and per-layer budgets applied to different files.
4045
+ // A function matcher's `String()` is its source, not its closure: two functions with the same
4046
+ // body but different captured values digest identically. That cannot be fixed by hashing, so
4047
+ // the digest records that executable matchers are present and `validate` says the digest does
4048
+ // not cover their closure, instead of claiming a equality it cannot prove.
4049
+ executableMatchers: [...config.layers, ...config.kinds].some(
4050
+ (rule) => typeof rule.match === "function"
4051
+ ),
3511
4052
  layers: config.layers.map((layer2) => ({ name: layer2.name, match: String(layer2.match) })),
3512
4053
  kinds: config.kinds.map((kind) => ({ kind: kind.kind, match: String(kind.match) })),
3513
4054
  // How files are enumerated decides what is in the snapshot at all.
@@ -3539,7 +4080,18 @@ function gitPaths(cwd, args) {
3539
4080
  `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.`
3540
4081
  );
3541
4082
  }
3542
- return output.split("\0").map((entry) => entry.trim().replace(/\\/g, "/")).filter((entry) => entry.length > 0);
4083
+ return output.split("\0").filter((entry) => entry.length > 0);
4084
+ }
4085
+ function readStagedBlob(cwd, relativePath) {
4086
+ try {
4087
+ return execFileSync2("git", ["cat-file", "blob", `:${relativePath}`], {
4088
+ cwd,
4089
+ stdio: ["ignore", "pipe", "pipe"],
4090
+ maxBuffer: 512 * 1024 * 1024
4091
+ });
4092
+ } catch {
4093
+ return null;
4094
+ }
3543
4095
  }
3544
4096
  function assertUsableRef(ref) {
3545
4097
  if (ref.startsWith("-")) {
@@ -3550,6 +4102,8 @@ function assertUsableRef(ref) {
3550
4102
  }
3551
4103
  function resolveChangedScope(cwd, request) {
3552
4104
  const paths = /* @__PURE__ */ new Set();
4105
+ const stagedPaths = /* @__PURE__ */ new Set();
4106
+ const deletedPaths = /* @__PURE__ */ new Set();
3553
4107
  const descriptions = [];
3554
4108
  if (request.changedSince !== void 0) {
3555
4109
  assertUsableRef(request.changedSince);
@@ -3558,7 +4112,17 @@ function resolveChangedScope(cwd, request) {
3558
4112
  "--name-only",
3559
4113
  "-z",
3560
4114
  "--relative",
3561
- request.changedSince,
4115
+ `${request.changedSince}...HEAD`,
4116
+ "--"
4117
+ ])) {
4118
+ paths.add(path22);
4119
+ }
4120
+ for (const path22 of gitPaths(cwd, [
4121
+ "diff",
4122
+ "--name-only",
4123
+ "-z",
4124
+ "--relative",
4125
+ "HEAD",
3562
4126
  "--"
3563
4127
  ])) {
3564
4128
  paths.add(path22);
@@ -3578,14 +4142,28 @@ function resolveChangedScope(cwd, request) {
3578
4142
  "--"
3579
4143
  ])) {
3580
4144
  paths.add(path22);
4145
+ stagedPaths.add(path22);
4146
+ }
4147
+ for (const path22 of gitPaths(cwd, [
4148
+ "diff",
4149
+ "--cached",
4150
+ "--name-only",
4151
+ "-z",
4152
+ "--relative",
4153
+ "--diff-filter=D",
4154
+ "--"
4155
+ ])) {
4156
+ deletedPaths.add(path22);
3581
4157
  }
3582
4158
  descriptions.push("staged");
3583
4159
  }
3584
- return { paths, detail: descriptions.join(" and ") };
4160
+ return { paths, stagedPaths, deletedPaths, detail: descriptions.join(" and ") };
3585
4161
  }
3586
4162
 
3587
4163
  // src/scanner/dependents.ts
4164
+ import * as fs4 from "fs";
3588
4165
  import * as path4 from "path";
4166
+ import ts from "typescript";
3589
4167
  var RELATIVE_SPECIFIER = /^\.{1,2}\//;
3590
4168
  var IMPORT_CANDIDATE_SUFFIXES = [
3591
4169
  ".ts",
@@ -3615,34 +4193,88 @@ var PYTHON_EXTENSIONS = /* @__PURE__ */ new Set([".py", ".pyi"]);
3615
4193
  var RUBY_EXTENSIONS = /* @__PURE__ */ new Set([".rb", ".rake", ".gemspec"]);
3616
4194
  var C_EXTENSIONS = /* @__PURE__ */ new Set([".c", ".h", ".cc", ".cpp", ".cxx", ".hpp", ".hxx", ".m", ".mm"]);
3617
4195
  var PYTHON_SUFFIXES = [".py", ".pyi", "/__init__.py", "/__init__.pyi"];
3618
- function buildImportResolver(files) {
4196
+ var CASE_INSENSITIVE_FILESYSTEM = process.platform === "win32" || process.platform === "darwin";
4197
+ var TSCONFIG_CACHE = /* @__PURE__ */ new Map();
4198
+ function tsconfigPathsFor(cwd) {
4199
+ const configPath = path4.join(cwd, "tsconfig.json");
4200
+ let stats;
4201
+ try {
4202
+ stats = fs4.statSync(configPath);
4203
+ } catch (err) {
4204
+ if (err.code === "ENOENT") return null;
4205
+ return null;
4206
+ }
4207
+ const key = `${stats.mtimeMs}:${stats.size}`;
4208
+ const cached = TSCONFIG_CACHE.get(configPath);
4209
+ if (cached !== void 0 && cached.key === key) return cached.value;
4210
+ let value = null;
4211
+ try {
4212
+ const read = ts.readConfigFile(configPath, ts.sys.readFile);
4213
+ if (read.error === void 0) {
4214
+ const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, cwd, void 0, configPath);
4215
+ const options = parsed.options;
4216
+ const baseUrl = typeof options.baseUrl === "string" ? repositoryRelative(cwd, options.baseUrl) : null;
4217
+ const rules = [];
4218
+ if (options.paths !== void 0) {
4219
+ for (const [pattern, targets] of Object.entries(options.paths)) {
4220
+ if (!Array.isArray(targets)) continue;
4221
+ rules.push({
4222
+ pattern,
4223
+ targets: targets.map((target) => String(target).replace(/\\/g, "/"))
4224
+ });
4225
+ }
4226
+ }
4227
+ if (baseUrl !== null || rules.length > 0) value = { baseUrl, paths: rules };
4228
+ }
4229
+ } catch (err) {
4230
+ value = null;
4231
+ }
4232
+ TSCONFIG_CACHE.set(configPath, { key, value });
4233
+ return value;
4234
+ }
4235
+ function repositoryRelative(cwd, target) {
4236
+ const relative14 = path4.relative(cwd, target).replace(/\\/g, "/");
4237
+ return relative14.length === 0 || !relative14.startsWith("..") && !path4.isAbsolute(relative14) ? relative14 : null;
4238
+ }
4239
+ function rememberFirst(map, key, value) {
4240
+ if (!map.has(key)) map.set(key, value);
4241
+ }
4242
+ function buildImportResolver(files, options = {}) {
3619
4243
  const byPath = /* @__PURE__ */ new Map();
3620
4244
  const byPathFolded = /* @__PURE__ */ new Map();
3621
4245
  const byStem = /* @__PURE__ */ new Map();
3622
4246
  const byStemFolded = /* @__PURE__ */ new Map();
3623
- const remember = (map, key, value) => {
3624
- if (!map.has(key)) map.set(key, value);
3625
- };
3626
- for (const file of files) {
3627
- const relativePath = file.relativePath;
3628
- remember(byPath, relativePath, relativePath);
3629
- remember(byPathFolded, relativePath.toLowerCase(), relativePath);
4247
+ const register = (relativePath) => {
4248
+ rememberFirst(byPath, relativePath, relativePath);
4249
+ if (CASE_INSENSITIVE_FILESYSTEM) {
4250
+ rememberFirst(byPathFolded, relativePath.toLowerCase(), relativePath);
4251
+ }
3630
4252
  const extension = path4.posix.extname(relativePath);
3631
- if (!SOURCE_EXTENSIONS.has(extension)) continue;
4253
+ if (!SOURCE_EXTENSIONS.has(extension)) return;
3632
4254
  const stem = relativePath.slice(0, -extension.length);
3633
- remember(byStem, stem, relativePath);
3634
- remember(byStemFolded, stem.toLowerCase(), relativePath);
4255
+ rememberFirst(byStem, stem, relativePath);
4256
+ if (CASE_INSENSITIVE_FILESYSTEM) {
4257
+ rememberFirst(byStemFolded, stem.toLowerCase(), relativePath);
4258
+ }
3635
4259
  if (path4.posix.basename(stem) === "index") {
3636
4260
  const directory = path4.posix.dirname(stem);
3637
- remember(byStem, directory, relativePath);
3638
- remember(byStemFolded, directory.toLowerCase(), relativePath);
4261
+ rememberFirst(byStem, directory, relativePath);
4262
+ if (CASE_INSENSITIVE_FILESYSTEM) {
4263
+ rememberFirst(byStemFolded, directory.toLowerCase(), relativePath);
4264
+ }
4265
+ }
4266
+ };
4267
+ for (const file of files) register(file.relativePath);
4268
+ if (options.extraPaths !== void 0) {
4269
+ for (const extra of options.extraPaths) {
4270
+ if (!byPath.has(extra)) register(extra);
3639
4271
  }
3640
4272
  }
3641
- return { byPath, byPathFolded, byStem, byStemFolded };
4273
+ return { byPath, byPathFolded, byStem, byStemFolded, tsconfig: options.tsconfig ?? null };
3642
4274
  }
3643
4275
  function resolveSpecifier(fromFile, specifier, resolver) {
3644
4276
  const extension = path4.posix.extname(fromFile).toLowerCase();
3645
- const exact = (key) => resolver.byPath.get(key) ?? resolver.byPathFolded.get(key.toLowerCase()) ?? null;
4277
+ const exact = (key) => resolver.byPath.get(key) ?? (CASE_INSENSITIVE_FILESYSTEM ? resolver.byPathFolded.get(key.toLowerCase()) : void 0) ?? null;
3646
4278
  const firstOf = (candidates) => {
3647
4279
  for (const candidate of candidates) {
3648
4280
  const hit = exact(candidate);
@@ -3650,6 +4282,17 @@ function resolveSpecifier(fromFile, specifier, resolver) {
3650
4282
  }
3651
4283
  return null;
3652
4284
  };
4285
+ const lookupPath = (joined2) => {
4286
+ const direct = exact(joined2);
4287
+ if (direct) return direct;
4288
+ for (const suffix of IMPORT_CANDIDATE_SUFFIXES) {
4289
+ const hit = exact(`${joined2}${suffix}`);
4290
+ if (hit) return hit;
4291
+ }
4292
+ const stem = joined2.replace(/\.(?:js|mjs|cjs|jsx)$/, "");
4293
+ const byStem = (key) => resolver.byStem.get(key) ?? (CASE_INSENSITIVE_FILESYSTEM ? resolver.byStemFolded.get(key.toLowerCase()) : void 0) ?? null;
4294
+ return byStem(joined2) ?? byStem(stem);
4295
+ };
3653
4296
  if (PYTHON_EXTENSIONS.has(extension) && specifier.startsWith(".")) {
3654
4297
  const dots = /^\.+/.exec(specifier)?.[0].length ?? 0;
3655
4298
  const rest = specifier.slice(dots).replace(/\./g, "/");
@@ -3676,19 +4319,43 @@ function resolveSpecifier(fromFile, specifier, resolver) {
3676
4319
  );
3677
4320
  return firstOf([joined2, `${joined2}.dart`]);
3678
4321
  }
3679
- if (!RELATIVE_SPECIFIER.test(specifier)) return null;
4322
+ if (!RELATIVE_SPECIFIER.test(specifier)) {
4323
+ return resolveTsconfigSpecifier(specifier, resolver, lookupPath);
4324
+ }
3680
4325
  const joined = path4.posix.normalize(
3681
4326
  path4.posix.join(path4.posix.dirname(fromFile), specifier)
3682
4327
  );
3683
- const direct = exact(joined);
3684
- if (direct) return direct;
3685
- for (const suffix of IMPORT_CANDIDATE_SUFFIXES) {
3686
- const hit = exact(`${joined}${suffix}`);
3687
- if (hit) return hit;
4328
+ return lookupPath(joined);
4329
+ }
4330
+ function resolveTsconfigSpecifier(specifier, resolver, lookupPath) {
4331
+ const config = resolver.tsconfig;
4332
+ if (!config) return null;
4333
+ for (const rule of config.paths) {
4334
+ const star = rule.pattern.indexOf("*");
4335
+ let captured;
4336
+ if (star === -1) {
4337
+ captured = specifier === rule.pattern ? "" : null;
4338
+ } else {
4339
+ const prefix = rule.pattern.slice(0, star);
4340
+ const suffix = rule.pattern.slice(star + 1);
4341
+ if (specifier.length < prefix.length + suffix.length || !specifier.startsWith(prefix) || !specifier.endsWith(suffix)) {
4342
+ captured = null;
4343
+ } else {
4344
+ captured = specifier.slice(prefix.length, specifier.length - suffix.length);
4345
+ }
4346
+ }
4347
+ if (captured === null) continue;
4348
+ for (const target of rule.targets) {
4349
+ const substituted = target.split("*").join(captured);
4350
+ const base = config.baseUrl === null ? substituted : path4.posix.join(config.baseUrl, substituted);
4351
+ const hit = lookupPath(path4.posix.normalize(base));
4352
+ if (hit) return hit;
4353
+ }
3688
4354
  }
3689
- const stem = joined.replace(/\.(?:js|mjs|cjs|jsx)$/, "");
3690
- const byStem = (key) => resolver.byStem.get(key) ?? resolver.byStemFolded.get(key.toLowerCase()) ?? null;
3691
- return byStem(joined) ?? byStem(stem);
4355
+ if (config.baseUrl !== null) {
4356
+ return lookupPath(path4.posix.normalize(path4.posix.join(config.baseUrl, specifier)));
4357
+ }
4358
+ return null;
3692
4359
  }
3693
4360
  function importsChangedFile(importerPath, imports, changedPaths, resolver) {
3694
4361
  for (const specifier of imports) {
@@ -3699,10 +4366,10 @@ function importsChangedFile(importerPath, imports, changedPaths, resolver) {
3699
4366
  }
3700
4367
 
3701
4368
  // src/ast/imports.ts
3702
- import * as fs5 from "fs";
4369
+ import * as fs6 from "fs";
3703
4370
 
3704
4371
  // src/ast/ts-parser.ts
3705
- import ts from "typescript";
4372
+ import ts2 from "typescript";
3706
4373
  var ROUTE_HANDLER_NAMES = /* @__PURE__ */ new Set([
3707
4374
  "GET",
3708
4375
  "POST",
@@ -3712,15 +4379,72 @@ var ROUTE_HANDLER_NAMES = /* @__PURE__ */ new Set([
3712
4379
  "HEAD",
3713
4380
  "OPTIONS"
3714
4381
  ]);
4382
+ var ROUTE_RECEIVERS = /* @__PURE__ */ new Set(["app", "router", "server", "fastify", "api", "route"]);
4383
+ var ROUTE_REGISTRATION_VERBS = /* @__PURE__ */ new Set([
4384
+ "get",
4385
+ "post",
4386
+ "put",
4387
+ "delete",
4388
+ "patch",
4389
+ "head",
4390
+ "options"
4391
+ ]);
3715
4392
  function bindingNames(name, into) {
3716
- if (ts.isIdentifier(name)) {
4393
+ if (ts2.isIdentifier(name)) {
3717
4394
  into.push(name.text);
3718
4395
  return;
3719
4396
  }
3720
- for (const element of name.elements) {
3721
- if (ts.isOmittedExpression(element)) continue;
3722
- bindingNames(element.name, into);
4397
+ for (const element of name.elements) {
4398
+ if (ts2.isOmittedExpression(element)) continue;
4399
+ bindingNames(element.name, into);
4400
+ }
4401
+ }
4402
+ function objectLiteralNames(node) {
4403
+ const names = [];
4404
+ for (const property of node.properties) {
4405
+ if (ts2.isShorthandPropertyAssignment(property)) {
4406
+ names.push(property.name.text);
4407
+ continue;
4408
+ }
4409
+ if (!ts2.isPropertyAssignment(property)) continue;
4410
+ const name = property.name;
4411
+ if (ts2.isIdentifier(name) || ts2.isStringLiteral(name) || ts2.isNumericLiteral(name)) {
4412
+ names.push(name.text);
4413
+ }
4414
+ }
4415
+ return names;
4416
+ }
4417
+ function cjsExportedNames(expression) {
4418
+ const left = expression.left;
4419
+ if (!ts2.isPropertyAccessExpression(left)) return null;
4420
+ const isModuleExports = left.name.text === "exports" && ts2.isIdentifier(left.expression) && left.expression.text === "module";
4421
+ if (isModuleExports) {
4422
+ const right = expression.right;
4423
+ if (ts2.isObjectLiteralExpression(right)) return objectLiteralNames(right);
4424
+ if (ts2.isIdentifier(right)) return [right.text];
4425
+ return [];
4426
+ }
4427
+ if (ts2.isIdentifier(left.expression) && left.expression.text === "exports") {
4428
+ return [left.name.text];
3723
4429
  }
4430
+ const parent = left.expression;
4431
+ if (ts2.isPropertyAccessExpression(parent) && parent.name.text === "exports" && ts2.isIdentifier(parent.expression) && parent.expression.text === "module") {
4432
+ return [left.name.text];
4433
+ }
4434
+ return null;
4435
+ }
4436
+ function countSyntacticErrors(fileName, content) {
4437
+ const result = ts2.transpileModule(content, {
4438
+ fileName,
4439
+ compilerOptions: {
4440
+ target: ts2.ScriptTarget.Latest,
4441
+ module: ts2.ModuleKind.ESNext
4442
+ },
4443
+ reportDiagnostics: true
4444
+ });
4445
+ return (result.diagnostics ?? []).filter(
4446
+ (diagnostic) => diagnostic.category === ts2.DiagnosticCategory.Error
4447
+ ).length;
3724
4448
  }
3725
4449
  function summarizeTypeScriptSource(relativePath, content) {
3726
4450
  const summary = {
@@ -3739,19 +4463,20 @@ function summarizeTypeScriptSource(relativePath, content) {
3739
4463
  routeHandlers: []
3740
4464
  };
3741
4465
  const lowerPath = relativePath.toLowerCase();
3742
- const isJsx = lowerPath.endsWith(".tsx") || lowerPath.endsWith(".jsx");
3743
- const sourceFile = ts.createSourceFile(
4466
+ const scriptKind = /.tsx$/.test(lowerPath) ? ts2.ScriptKind.TSX : /.jsx$/.test(lowerPath) ? ts2.ScriptKind.JSX : /.(?:js|mjs|cjs)$/.test(lowerPath) ? ts2.ScriptKind.JS : ts2.ScriptKind.TS;
4467
+ const sourceFile = ts2.createSourceFile(
3744
4468
  relativePath,
3745
4469
  content,
3746
- ts.ScriptTarget.Latest,
4470
+ ts2.ScriptTarget.Latest,
3747
4471
  /* setParentNodes */
3748
4472
  false,
3749
- isJsx ? ts.ScriptKind.TSX : ts.ScriptKind.TS
4473
+ scriptKind
3750
4474
  );
3751
- const parseErrors = sourceFile.parseDiagnostics?.length ?? 0;
4475
+ const parsedDiagnostics = sourceFile.parseDiagnostics;
4476
+ const parseErrors = Array.isArray(parsedDiagnostics) ? parsedDiagnostics.filter((diagnostic) => diagnostic.category === ts2.DiagnosticCategory.Error).length : countSyntacticErrors(relativePath, content);
3752
4477
  if (parseErrors > 0) summary.parseErrors = parseErrors;
3753
4478
  for (const statement of sourceFile.statements) {
3754
- if (ts.isExpressionStatement(statement) && ts.isStringLiteral(statement.expression)) {
4479
+ if (ts2.isExpressionStatement(statement) && ts2.isStringLiteral(statement.expression)) {
3755
4480
  const text2 = statement.expression.text;
3756
4481
  if (text2 === "use client" || text2 === "use server") {
3757
4482
  summary.directives.push(text2);
@@ -3761,26 +4486,26 @@ function summarizeTypeScriptSource(relativePath, content) {
3761
4486
  break;
3762
4487
  }
3763
4488
  const isExported = (node) => {
3764
- const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : void 0;
3765
- return Boolean(modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword));
4489
+ const modifiers = ts2.canHaveModifiers(node) ? ts2.getModifiers(node) : void 0;
4490
+ return Boolean(modifiers?.some((m) => m.kind === ts2.SyntaxKind.ExportKeyword));
3766
4491
  };
3767
4492
  const isDefault = (node) => {
3768
- const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : void 0;
3769
- return Boolean(modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword));
4493
+ const modifiers = ts2.canHaveModifiers(node) ? ts2.getModifiers(node) : void 0;
4494
+ return Boolean(modifiers?.some((m) => m.kind === ts2.SyntaxKind.DefaultKeyword));
3770
4495
  };
3771
4496
  const rendersJsx = (node) => {
3772
4497
  const pending = [node];
3773
4498
  while (pending.length > 0) {
3774
4499
  const current = pending.pop();
3775
- if (ts.isJsxElement(current) || ts.isJsxSelfClosingElement(current) || ts.isJsxFragment(current)) {
4500
+ if (ts2.isJsxElement(current) || ts2.isJsxSelfClosingElement(current) || ts2.isJsxFragment(current)) {
3776
4501
  return true;
3777
4502
  }
3778
- if (ts.isCallExpression(current)) {
4503
+ if (ts2.isCallExpression(current)) {
3779
4504
  const callee = current.expression;
3780
- const calleeName = ts.isIdentifier(callee) ? callee.text : ts.isPropertyAccessExpression(callee) ? callee.name.text : "";
4505
+ const calleeName = ts2.isIdentifier(callee) ? callee.text : ts2.isPropertyAccessExpression(callee) ? callee.name.text : "";
3781
4506
  if (calleeName === "createElement") return true;
3782
4507
  }
3783
- ts.forEachChild(current, (child) => {
4508
+ ts2.forEachChild(current, (child) => {
3784
4509
  pending.push(child);
3785
4510
  });
3786
4511
  }
@@ -3789,11 +4514,11 @@ function summarizeTypeScriptSource(relativePath, content) {
3789
4514
  const REACT_BASE_CLASS = /(?:^|\.)(?:PureComponent|Component)$/;
3790
4515
  const extendsReactBase = (node) => {
3791
4516
  const heritage = (node.heritageClauses ?? []).find(
3792
- (clause) => clause.token === ts.SyntaxKind.ExtendsKeyword
4517
+ (clause) => clause.token === ts2.SyntaxKind.ExtendsKeyword
3793
4518
  );
3794
4519
  const expression = heritage?.types[0]?.expression;
3795
4520
  if (!expression) return false;
3796
- const text2 = ts.isIdentifier(expression) ? expression.text : expression.getText(sourceFile);
4521
+ const text2 = ts2.isIdentifier(expression) ? expression.text : expression.getText(sourceFile);
3797
4522
  return REACT_BASE_CLASS.test(text2);
3798
4523
  };
3799
4524
  const recordFunctionLike = (name, exported, node) => {
@@ -3805,32 +4530,37 @@ function summarizeTypeScriptSource(relativePath, content) {
3805
4530
  if (/^use[A-Z0-9]/.test(name)) summary.hooks.push(name);
3806
4531
  if (/^[A-Z]/.test(name) && rendersJsx(node)) summary.reactComponents.push(name);
3807
4532
  };
4533
+ const cjsExports = [];
3808
4534
  const stack = [sourceFile];
3809
4535
  while (stack.length > 0) {
3810
4536
  const node = stack.pop();
3811
- if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
4537
+ if (ts2.isImportDeclaration(node) && ts2.isStringLiteral(node.moduleSpecifier)) {
3812
4538
  summary.imports.push(node.moduleSpecifier.text);
3813
4539
  }
3814
- if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference) && node.moduleReference.expression !== void 0 && ts.isStringLiteral(node.moduleReference.expression)) {
4540
+ if (ts2.isImportEqualsDeclaration(node) && ts2.isExternalModuleReference(node.moduleReference) && node.moduleReference.expression !== void 0 && ts2.isStringLiteral(node.moduleReference.expression)) {
3815
4541
  summary.imports.push(node.moduleReference.expression.text);
3816
4542
  }
3817
- if (ts.isCallExpression(node) && node.arguments.length >= 1) {
4543
+ if (ts2.isCallExpression(node) && node.arguments.length >= 1) {
3818
4544
  const firstArgument = node.arguments[0];
3819
- if (firstArgument !== void 0 && ts.isStringLiteral(firstArgument)) {
3820
- const isDynamicImport = node.expression.kind === ts.SyntaxKind.ImportKeyword;
3821
- const isRequire = ts.isIdentifier(node.expression) && node.expression.text === "require";
4545
+ if (firstArgument !== void 0 && ts2.isStringLiteral(firstArgument)) {
4546
+ const isDynamicImport = node.expression.kind === ts2.SyntaxKind.ImportKeyword;
4547
+ const isRequire = ts2.isIdentifier(node.expression) && node.expression.text === "require";
3822
4548
  if (isDynamicImport || isRequire) summary.imports.push(firstArgument.text);
3823
4549
  }
4550
+ const callee = node.expression;
4551
+ if (ts2.isPropertyAccessExpression(callee) && ts2.isIdentifier(callee.expression) && ROUTE_RECEIVERS.has(callee.expression.text) && ROUTE_REGISTRATION_VERBS.has(callee.name.text.toLowerCase()) && firstArgument !== void 0 && ts2.isStringLiteral(firstArgument)) {
4552
+ summary.routeHandlers.push(callee.name.text.toUpperCase());
4553
+ }
3824
4554
  }
3825
- if (ts.isExportDeclaration(node)) {
3826
- if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {
4555
+ if (ts2.isExportDeclaration(node)) {
4556
+ if (node.moduleSpecifier && ts2.isStringLiteral(node.moduleSpecifier)) {
3827
4557
  summary.imports.push(node.moduleSpecifier.text);
3828
4558
  summary.reExports.push(node.moduleSpecifier.text);
3829
- if (node.exportClause && ts.isNamespaceExport(node.exportClause)) {
4559
+ if (node.exportClause && ts2.isNamespaceExport(node.exportClause)) {
3830
4560
  summary.exports.push(node.exportClause.name.text);
3831
4561
  }
3832
4562
  }
3833
- if (node.exportClause && ts.isNamedExports(node.exportClause)) {
4563
+ if (node.exportClause && ts2.isNamedExports(node.exportClause)) {
3834
4564
  for (const element of node.exportClause.elements) {
3835
4565
  const exported = element.name.text;
3836
4566
  summary.exports.push(exported);
@@ -3838,11 +4568,15 @@ function summarizeTypeScriptSource(relativePath, content) {
3838
4568
  }
3839
4569
  }
3840
4570
  }
3841
- if (ts.isExportAssignment(node)) {
4571
+ if (ts2.isExpressionStatement(node) && ts2.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === ts2.SyntaxKind.EqualsToken) {
4572
+ const cjsNames = cjsExportedNames(node.expression);
4573
+ if (cjsNames !== null) cjsExports.push(...cjsNames);
4574
+ }
4575
+ if (ts2.isExportAssignment(node)) {
3842
4576
  summary.exports.push("default");
3843
4577
  if (rendersJsx(node.expression)) summary.reactComponents.push("default");
3844
4578
  }
3845
- if (ts.isFunctionDeclaration(node)) {
4579
+ if (ts2.isFunctionDeclaration(node)) {
3846
4580
  const exported = isExported(node);
3847
4581
  if (node.name) {
3848
4582
  recordFunctionLike(node.name.text, exported, node);
@@ -3851,7 +4585,7 @@ function summarizeTypeScriptSource(relativePath, content) {
3851
4585
  summary.exports.push("default");
3852
4586
  }
3853
4587
  }
3854
- if (ts.isClassDeclaration(node)) {
4588
+ if (ts2.isClassDeclaration(node)) {
3855
4589
  if (node.name) {
3856
4590
  summary.classes.push(node.name.text);
3857
4591
  if (isExported(node)) summary.exports.push(node.name.text);
@@ -3863,19 +4597,19 @@ function summarizeTypeScriptSource(relativePath, content) {
3863
4597
  summary.exports.push("default");
3864
4598
  }
3865
4599
  }
3866
- if (ts.isInterfaceDeclaration(node)) {
4600
+ if (ts2.isInterfaceDeclaration(node)) {
3867
4601
  summary.interfaces.push(node.name.text);
3868
4602
  if (isExported(node)) summary.exports.push(node.name.text);
3869
4603
  }
3870
- if (ts.isTypeAliasDeclaration(node)) {
4604
+ if (ts2.isTypeAliasDeclaration(node)) {
3871
4605
  summary.types.push(node.name.text);
3872
4606
  if (isExported(node)) summary.exports.push(node.name.text);
3873
4607
  }
3874
- if (ts.isEnumDeclaration(node)) {
4608
+ if (ts2.isEnumDeclaration(node)) {
3875
4609
  summary.enums.push(node.name.text);
3876
4610
  if (isExported(node)) summary.exports.push(node.name.text);
3877
4611
  }
3878
- if (ts.isVariableStatement(node)) {
4612
+ if (ts2.isVariableStatement(node)) {
3879
4613
  const exported = isExported(node);
3880
4614
  for (const declaration of node.declarationList.declarations) {
3881
4615
  const bound = [];
@@ -3894,13 +4628,17 @@ function summarizeTypeScriptSource(relativePath, content) {
3894
4628
  }
3895
4629
  }
3896
4630
  const children = [];
3897
- ts.forEachChild(node, (child) => {
4631
+ ts2.forEachChild(node, (child) => {
3898
4632
  children.push(child);
3899
4633
  });
3900
4634
  for (let index = children.length - 1; index >= 0; index--) {
3901
4635
  stack.push(children[index]);
3902
4636
  }
3903
4637
  }
4638
+ if (cjsExports.length > 0) {
4639
+ summary.exportsKind = summary.exports.length > 0 ? "mixed" : "cjs";
4640
+ summary.exports.push(...cjsExports);
4641
+ }
3904
4642
  const dedupeSorted2 = (values) => Array.from(new Set(values)).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
3905
4643
  summary.directives = dedupeSorted2(summary.directives);
3906
4644
  summary.imports = dedupeSorted2(summary.imports);
@@ -4464,9 +5202,9 @@ var rubyProfile = {
4464
5202
  eachLine(content, (line) => {
4465
5203
  const trimmed = line.trim();
4466
5204
  if (!trimmed || trimmed.startsWith("#")) return;
4467
- const relative12 = REQUIRE_RELATIVE.exec(trimmed);
4468
- if (relative12) {
4469
- summary.imports.push(`./${relative12[1]}`);
5205
+ const relative14 = REQUIRE_RELATIVE.exec(trimmed);
5206
+ if (relative14) {
5207
+ summary.imports.push(`./${relative14[1]}`);
4470
5208
  return;
4471
5209
  }
4472
5210
  const required = REQUIRE.exec(trimmed);
@@ -4785,7 +5523,7 @@ function summarizeWithProfile(path22, content) {
4785
5523
  }
4786
5524
 
4787
5525
  // src/scanner/binary.ts
4788
- import * as fs4 from "fs";
5526
+ import * as fs5 from "fs";
4789
5527
  import * as path5 from "path";
4790
5528
  var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
4791
5529
  ".png",
@@ -4997,13 +5735,13 @@ function isBinaryFile(absolutePath) {
4997
5735
  if (isBinaryExtension(absolutePath)) return true;
4998
5736
  let fd;
4999
5737
  try {
5000
- fd = fs4.openSync(absolutePath, "r");
5738
+ fd = fs5.openSync(absolutePath, "r");
5001
5739
  const buffer = Buffer.alloc(CHUNK);
5002
5740
  let sample;
5003
5741
  let position = 0;
5004
5742
  while (position < BINARY_SCAN_BYTES) {
5005
5743
  const wanted = Math.min(CHUNK, BINARY_SCAN_BYTES - position);
5006
- const bytesRead = fs4.readSync(fd, buffer, 0, wanted, position);
5744
+ const bytesRead = fs5.readSync(fd, buffer, 0, wanted, position);
5007
5745
  if (bytesRead === 0) return false;
5008
5746
  const chunk = buffer.subarray(0, bytesRead);
5009
5747
  if (sample === void 0) {
@@ -5021,7 +5759,7 @@ function isBinaryFile(absolutePath) {
5021
5759
  } finally {
5022
5760
  if (fd !== void 0) {
5023
5761
  try {
5024
- fs4.closeSync(fd);
5762
+ fs5.closeSync(fd);
5025
5763
  } catch {
5026
5764
  }
5027
5765
  }
@@ -5043,9 +5781,9 @@ function importsOfText(relativePath, text2) {
5043
5781
  function importsOfFile(relativePath, absolutePath) {
5044
5782
  let buffer;
5045
5783
  try {
5046
- const stats = fs5.statSync(absolutePath);
5784
+ const stats = fs6.statSync(absolutePath);
5047
5785
  if (!stats.isFile() || stats.size > SUMMARY_MAX_SOURCE_BYTES) return [];
5048
- buffer = fs5.readFileSync(absolutePath);
5786
+ buffer = fs6.readFileSync(absolutePath);
5049
5787
  } catch {
5050
5788
  return [];
5051
5789
  }
@@ -5072,7 +5810,7 @@ function findStagingDirectory(config) {
5072
5810
  const tmpDir = path6.resolve(config.cwd, config.tmpDir);
5073
5811
  let entries;
5074
5812
  try {
5075
- entries = fs6.readdirSync(tmpDir);
5813
+ entries = fs7.readdirSync(tmpDir);
5076
5814
  } catch {
5077
5815
  return null;
5078
5816
  }
@@ -5085,8 +5823,8 @@ function describeMissingManifest(config, manifestPath) {
5085
5823
  const markerPath = path6.join(outDir, ".codebase-snapshot");
5086
5824
  let marker2 = null;
5087
5825
  try {
5088
- if (fs6.existsSync(markerPath)) {
5089
- const parsed = JSON.parse(fs6.readFileSync(markerPath, "utf8"));
5826
+ if (fs7.existsSync(markerPath)) {
5827
+ const parsed = JSON.parse(fs7.readFileSync(markerPath, "utf8"));
5090
5828
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
5091
5829
  marker2 = parsed;
5092
5830
  }
@@ -5123,11 +5861,11 @@ function sha256Hex(buffer) {
5123
5861
  function wouldNowBeIncluded(cwd, relativePath) {
5124
5862
  const absolutePath = path6.join(cwd, relativePath);
5125
5863
  try {
5126
- const stats = fs6.statSync(absolutePath);
5864
+ const stats = fs7.statSync(absolutePath);
5127
5865
  if (!stats.isFile()) return false;
5128
5866
  if (isBinaryExtension(absolutePath)) return false;
5129
5867
  if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) return false;
5130
- return !decodeText(fs6.readFileSync(absolutePath)).binary;
5868
+ return !decodeText(fs7.readFileSync(absolutePath)).binary;
5131
5869
  } catch {
5132
5870
  return false;
5133
5871
  }
@@ -5158,14 +5896,71 @@ function describeManifestShapeProblem(value) {
5158
5896
  if (!candidate.totals || typeof candidate.totals !== "object" || Array.isArray(candidate.totals)) {
5159
5897
  return 'missing "totals" object';
5160
5898
  }
5899
+ const currentSchema = candidate.schemaVersion === SCHEMA_VERSION;
5900
+ if (currentSchema) {
5901
+ const generator = candidate.generator;
5902
+ if (!generator || typeof generator !== "object" || Array.isArray(generator)) {
5903
+ return 'missing "generator" object';
5904
+ }
5905
+ const generatorFields = generator;
5906
+ if (!isOurGeneratorName(generatorFields.name)) {
5907
+ return "`generator.name` is not this generator";
5908
+ }
5909
+ if (typeof generatorFields.version !== "string" || generatorFields.version.trim() === "") {
5910
+ return "`generator.version` must be a non-empty string";
5911
+ }
5912
+ const git = candidate.git;
5913
+ if (!git || typeof git !== "object" || Array.isArray(git)) return 'missing "git" object';
5914
+ const gitFields = git;
5915
+ if (typeof gitFields.branch !== "string") return "`git.branch` must be a string";
5916
+ if (typeof gitFields.commit !== "string") return "`git.commit` must be a string";
5917
+ if (typeof gitFields.isDirty !== "boolean") return "`git.isDirty` must be a boolean";
5918
+ const config = candidate.config;
5919
+ if (!config || typeof config !== "object" || Array.isArray(config)) {
5920
+ return 'missing "config" object';
5921
+ }
5922
+ const budgets = candidate.budgets;
5923
+ if (!budgets || typeof budgets !== "object" || Array.isArray(budgets)) {
5924
+ return 'missing "budgets" object';
5925
+ }
5926
+ for (const key of ["maxPartBytes", "largeFileBytes"]) {
5927
+ const value2 = budgets[key];
5928
+ if (typeof value2 !== "number" || !Number.isSafeInteger(value2) || value2 < 0) {
5929
+ return `\`budgets.${key}\` must be a non-negative integer`;
5930
+ }
5931
+ }
5932
+ if (!candidate.indexes || typeof candidate.indexes !== "object" || Array.isArray(candidate.indexes)) {
5933
+ return 'missing "indexes" object';
5934
+ }
5935
+ if (!candidate.kinds || typeof candidate.kinds !== "object" || Array.isArray(candidate.kinds)) {
5936
+ return 'missing "kinds" object';
5937
+ }
5938
+ }
5161
5939
  if (!Array.isArray(candidate.files)) return 'missing "files" array';
5162
5940
  for (const entry of candidate.files) {
5163
5941
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
5164
5942
  return 'a "files" entry is not an object';
5165
5943
  }
5166
- if (typeof entry.relativePath !== "string") {
5944
+ const fields = entry;
5945
+ if (typeof fields.relativePath !== "string") {
5167
5946
  return 'a "files" entry has no "relativePath"';
5168
5947
  }
5948
+ if (!currentSchema) continue;
5949
+ if (typeof fields.part !== "string" || fields.part.length === 0) {
5950
+ return 'a "files" entry records no "part"';
5951
+ }
5952
+ if (typeof fields.hashSha256 !== "string" || !/^[0-9a-f]{64}$/.test(fields.hashSha256)) {
5953
+ return 'a "files" entry "hashSha256" must be a 64-character lowercase sha256 hex digest';
5954
+ }
5955
+ for (const key of ["sizeBytes", "lines"]) {
5956
+ const value2 = fields[key];
5957
+ if (typeof value2 !== "number" || !Number.isSafeInteger(value2) || value2 < 0) {
5958
+ return `a "files" entry "${key}" must be a non-negative integer`;
5959
+ }
5960
+ }
5961
+ if (!["full", "preview", "signatures"].includes(String(fields.inclusionMode))) {
5962
+ return 'a "files" entry has an unknown "inclusionMode"';
5963
+ }
5169
5964
  }
5170
5965
  if (!Array.isArray(candidate.skipped)) return 'missing "skipped" array';
5171
5966
  if (!Array.isArray(candidate.parts)) return 'missing "parts" array';
@@ -5173,13 +5968,28 @@ function describeManifestShapeProblem(value) {
5173
5968
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
5174
5969
  return 'a "parts" entry is not an object';
5175
5970
  }
5176
- const filename = entry.filename;
5971
+ const fields = entry;
5972
+ const filename = fields.filename;
5177
5973
  if (typeof filename !== "string" || filename.trim() === "") {
5178
5974
  return 'a "parts" entry has no "filename"';
5179
5975
  }
5180
5976
  if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path6.isAbsolute(filename)) {
5181
5977
  return 'a "parts" entry "filename" must be a bare filename inside parts/';
5182
5978
  }
5979
+ if (currentSchema) {
5980
+ if (typeof fields.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(fields.sha256)) {
5981
+ return 'a "parts" entry "sha256" must be a 64-character lowercase sha256 hex digest';
5982
+ }
5983
+ if (typeof fields.byteSize !== "number" || !Number.isSafeInteger(fields.byteSize) || fields.byteSize < 0) {
5984
+ return 'a "parts" entry "byteSize" must be a non-negative integer';
5985
+ }
5986
+ if (typeof fields.index !== "number" || !Number.isSafeInteger(fields.index) || fields.index < 1) {
5987
+ return 'a "parts" entry "index" must be a positive integer';
5988
+ }
5989
+ if (!Array.isArray(fields.includedFiles)) {
5990
+ return 'a "parts" entry has no "includedFiles" array';
5991
+ }
5992
+ }
5183
5993
  }
5184
5994
  if (!candidate.layers || typeof candidate.layers !== "object" || Array.isArray(candidate.layers)) {
5185
5995
  return 'missing "layers" object';
@@ -5190,7 +6000,7 @@ function validateSnapshot(configInput) {
5190
6000
  assertUsableConfigInput(configInput);
5191
6001
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput);
5192
6002
  const manifestPath = path6.resolve(config.cwd, config.outDir, "manifest.json");
5193
- if (!fs6.existsSync(manifestPath)) {
6003
+ if (!fs7.existsSync(manifestPath)) {
5194
6004
  return {
5195
6005
  valid: false,
5196
6006
  manifestPresent: false,
@@ -5201,7 +6011,7 @@ function validateSnapshot(configInput) {
5201
6011
  }
5202
6012
  let manifest;
5203
6013
  try {
5204
- manifest = JSON.parse(fs6.readFileSync(manifestPath, "utf8"));
6014
+ manifest = JSON.parse(fs7.readFileSync(manifestPath, "utf8"));
5205
6015
  } catch (err) {
5206
6016
  return {
5207
6017
  valid: false,
@@ -5224,6 +6034,19 @@ function validateSnapshot(configInput) {
5224
6034
  const drift = emptyDrift();
5225
6035
  const warnings = [];
5226
6036
  const snapshotDir = path6.resolve(config.cwd, config.outDir);
6037
+ const unreadableSkips = manifest.skipped.filter(
6038
+ (entry) => entry.reason === "missing" || entry.reason === "read-error"
6039
+ );
6040
+ if (unreadableSkips.length > 0) {
6041
+ warnings.push(
6042
+ `${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.`
6043
+ );
6044
+ }
6045
+ if ([...config.layers, ...config.kinds].some((rule) => typeof rule.match === "function")) {
6046
+ warnings.push(
6047
+ "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."
6048
+ );
6049
+ }
5227
6050
  const manifestFileMap = /* @__PURE__ */ new Map();
5228
6051
  for (const file of manifest.files) {
5229
6052
  if (file && typeof file.relativePath === "string") {
@@ -5286,7 +6109,7 @@ function validateSnapshot(configInput) {
5286
6109
  // snapshot was reported as drifting.
5287
6110
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
5288
6111
  (directory) => path6.relative(config.cwd, path6.resolve(config.cwd, directory)).replace(/\\/g, "/")
5289
- ).filter((relative12) => relative12.length > 0 && !relative12.startsWith(".."))
6112
+ ).filter((relative14) => relative14.length > 0 && !relative14.startsWith(".."))
5290
6113
  });
5291
6114
  for (const diskFile of collection.files) {
5292
6115
  const snapshotHash = manifestFileMap.get(diskFile);
@@ -5311,7 +6134,7 @@ function validateSnapshot(configInput) {
5311
6134
  }
5312
6135
  let diskHash;
5313
6136
  try {
5314
- diskHash = sha256Hex(fs6.readFileSync(path6.join(config.cwd, diskFile)));
6137
+ diskHash = sha256Hex(fs7.readFileSync(path6.join(config.cwd, diskFile)));
5315
6138
  } catch (err) {
5316
6139
  if (err.code === "ENOENT") {
5317
6140
  drift.missingOnDisk.push(diskFile);
@@ -5335,7 +6158,7 @@ function validateSnapshot(configInput) {
5335
6158
  }
5336
6159
  let statFailure = null;
5337
6160
  try {
5338
- fs6.statSync(confined);
6161
+ fs7.statSync(confined);
5339
6162
  } catch (err) {
5340
6163
  statFailure = err;
5341
6164
  }
@@ -5370,7 +6193,7 @@ function validateSnapshot(configInput) {
5370
6193
  }
5371
6194
  let buffer;
5372
6195
  try {
5373
- buffer = fs6.readFileSync(partPath);
6196
+ buffer = fs7.readFileSync(partPath);
5374
6197
  } catch {
5375
6198
  drift.partIssues.push({ part: part.filename, issue: "missing from snapshot/parts" });
5376
6199
  continue;
@@ -5392,24 +6215,85 @@ function validateSnapshot(configInput) {
5392
6215
  });
5393
6216
  }
5394
6217
  }
5395
- const filesInParts = manifest.parts.reduce(
5396
- (total, part) => total + (typeof part?.fileCount === "number" ? part.fileCount : 0),
5397
- 0
5398
- );
5399
- if (filesInParts !== manifest.files.length) {
5400
- drift.partIssues.push({
5401
- part: "(totals)",
5402
- issue: `parts list ${filesInParts} file(s) but the manifest lists ${manifest.files.length}`
5403
- });
6218
+ const maskDriftPath = (value) => findSecretInPath(value, config.secretRules)?.masked ?? value;
6219
+ const includedByPart = /* @__PURE__ */ new Map();
6220
+ const partIndexes = /* @__PURE__ */ new Set();
6221
+ for (const part of manifest.parts) {
6222
+ if (includedByPart.has(part.filename)) {
6223
+ drift.partIssues.push({
6224
+ part: maskDriftPath(part.filename),
6225
+ issue: "appears more than once in parts[]"
6226
+ });
6227
+ }
6228
+ if (typeof part.index === "number") {
6229
+ if (partIndexes.has(part.index)) {
6230
+ drift.partIssues.push({
6231
+ part: maskDriftPath(part.filename),
6232
+ issue: `reuses part index ${part.index}`
6233
+ });
6234
+ }
6235
+ partIndexes.add(part.index);
6236
+ }
6237
+ const listed = /* @__PURE__ */ new Set();
6238
+ for (const included of part.includedFiles ?? []) {
6239
+ if (typeof included?.relativePath !== "string") continue;
6240
+ if (listed.has(included.relativePath)) {
6241
+ drift.partIssues.push({
6242
+ part: maskDriftPath(part.filename),
6243
+ issue: `lists ${maskDriftPath(included.relativePath)} twice`
6244
+ });
6245
+ }
6246
+ listed.add(included.relativePath);
6247
+ }
6248
+ includedByPart.set(part.filename, listed);
6249
+ if (typeof part.fileCount === "number" && part.fileCount !== listed.size) {
6250
+ drift.partIssues.push({
6251
+ part: maskDriftPath(part.filename),
6252
+ issue: `declares ${part.fileCount} file(s) but lists ${listed.size} in includedFiles`
6253
+ });
6254
+ }
5404
6255
  }
6256
+ const filePaths = /* @__PURE__ */ new Set();
5405
6257
  for (const file of manifest.files) {
5406
- if (file?.part && !partNames.has(file.part)) {
6258
+ if (filePaths.has(file.relativePath)) {
6259
+ drift.partIssues.push({
6260
+ part: "(files)",
6261
+ issue: `${maskDriftPath(file.relativePath)} appears more than once in files[]`
6262
+ });
6263
+ continue;
6264
+ }
6265
+ filePaths.add(file.relativePath);
6266
+ if (typeof file.part !== "string" || file.part.length === 0) {
6267
+ drift.partIssues.push({
6268
+ part: "(files)",
6269
+ issue: `${maskDriftPath(file.relativePath)} records no part`
6270
+ });
6271
+ continue;
6272
+ }
6273
+ if (!partNames.has(file.part)) {
6274
+ drift.partIssues.push({
6275
+ part: maskDriftPath(file.part),
6276
+ issue: `${maskDriftPath(file.relativePath)} points at a part that is not in the manifest`
6277
+ });
6278
+ continue;
6279
+ }
6280
+ if (!includedByPart.get(file.part)?.has(file.relativePath)) {
5407
6281
  drift.partIssues.push({
5408
- part: file.part,
5409
- issue: `${file.relativePath} points at a part that is not in the manifest`
6282
+ part: maskDriftPath(file.part),
6283
+ issue: `${maskDriftPath(file.relativePath)} is not listed in that part's includedFiles`
5410
6284
  });
5411
6285
  }
5412
6286
  }
6287
+ for (const [partName, listed] of includedByPart) {
6288
+ for (const relativePath of listed) {
6289
+ if (!filePaths.has(relativePath)) {
6290
+ drift.partIssues.push({
6291
+ part: maskDriftPath(partName),
6292
+ issue: `lists ${maskDriftPath(relativePath)}, which the manifest does not`
6293
+ });
6294
+ }
6295
+ }
6296
+ }
5413
6297
  const maskValue = (value) => findSecretInPath(value, config.secretRules)?.masked ?? value;
5414
6298
  const currentExcludes = config.excludePatterns.map(maskValue);
5415
6299
  const currentInclude = config.include.map(maskValue);
@@ -5565,6 +6449,13 @@ function validateSnapshot(configInput) {
5565
6449
  0
5566
6450
  );
5567
6451
  expectEqual("counts.totalFiles", counts.totalFiles, manifest.files.length);
6452
+ if (manifest.files.every((file) => typeof file?.lines === "number")) {
6453
+ expectEqual(
6454
+ "counts.totalLines",
6455
+ counts.totalLines,
6456
+ manifest.files.reduce((total, file) => total + file.lines, 0)
6457
+ );
6458
+ }
5568
6459
  expectEqual("counts.partsCount", counts.partsCount, manifest.parts.length);
5569
6460
  expectEqual("counts.skippedCount", counts.skippedCount, manifest.skipped.length);
5570
6461
  expectEqual("counts.totalSizeBytes", counts.totalSizeBytes, sumSourceBytes);
@@ -5588,6 +6479,37 @@ function validateSnapshot(configInput) {
5588
6479
  `totals.fullFiles + previewFiles (${totals.fullFiles} + ${totals.previewFiles}) != ${manifest.files.length} files`
5589
6480
  );
5590
6481
  }
6482
+ const recordedSettingsDigest = manifest.config && typeof manifest.config.digest === "string" ? manifest.config.digest : null;
6483
+ if (recordedSettingsDigest !== null && manifest.files.every((file) => typeof file?.hashSha256 === "string")) {
6484
+ const settingsLine = `settings:${recordedSettingsDigest}`;
6485
+ const currentDefinition = sha256Hex(
6486
+ Buffer.from(
6487
+ [
6488
+ ...manifest.files.map(
6489
+ (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}`
6490
+ ),
6491
+ settingsLine
6492
+ ].join("\n"),
6493
+ "utf8"
6494
+ )
6495
+ );
6496
+ const legacyDefinition = sha256Hex(
6497
+ Buffer.from(
6498
+ [
6499
+ ...manifest.files.map(
6500
+ (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
6501
+ ),
6502
+ settingsLine
6503
+ ].join("\n"),
6504
+ "utf8"
6505
+ )
6506
+ );
6507
+ if (manifest.fingerprint !== currentDefinition && manifest.fingerprint !== legacyDefinition) {
6508
+ totalsMismatches.push(
6509
+ "fingerprint: does not match the files and settings recorded in this manifest"
6510
+ );
6511
+ }
6512
+ }
5591
6513
  if (manifest.budgets && manifest.budgets.maxPartBytes !== config.maxPartBytes) {
5592
6514
  totalsMismatches.push(
5593
6515
  `budgets.maxPartBytes: manifest ${manifest.budgets.maxPartBytes} vs current ${config.maxPartBytes}`
@@ -5615,26 +6537,49 @@ function validateSnapshot(configInput) {
5615
6537
  drift.configMismatches.push(`manifest declared itself invalid: ${error}`);
5616
6538
  }
5617
6539
  }
5618
- for (const [key, artifact] of [
6540
+ const declaredArtifacts = [
6541
+ ["README.md", manifest.artifacts?.readme],
6542
+ ["reports/navigation.md", manifest.artifacts?.navigation],
6543
+ ["reports/project-tree.md", manifest.artifacts?.projectTree],
6544
+ ["reports/audit.md", manifest.artifacts?.audit],
5619
6545
  ["full-codebase.json", manifest.artifacts?.fullJson],
5620
6546
  ["full-codebase.md", manifest.artifacts?.fullMarkdown]
5621
- ]) {
6547
+ ];
6548
+ for (const [key, artifact] of declaredArtifacts) {
5622
6549
  if (!artifact) continue;
5623
- const artifactPath = path6.join(snapshotDir, key);
6550
+ const artifactPath = path6.join(snapshotDir, ...key.split("/"));
6551
+ let buffer;
5624
6552
  try {
5625
- const buffer = fs6.readFileSync(artifactPath);
5626
- if (sha256Hex(buffer) !== artifact.sha256 || buffer.length !== artifact.byteSize) {
5627
- drift.partIssues.push({ part: key, issue: "artifact does not match its recorded digest" });
5628
- }
6553
+ if (!fs7.statSync(artifactPath).isFile()) throw new Error("not a regular file");
6554
+ buffer = fs7.readFileSync(artifactPath);
5629
6555
  } catch {
5630
6556
  drift.partIssues.push({ part: key, issue: "declared artifact is missing" });
6557
+ continue;
6558
+ }
6559
+ if (sha256Hex(buffer) !== artifact.sha256 || buffer.length !== artifact.byteSize) {
6560
+ drift.partIssues.push({ part: key, issue: "artifact does not match its recorded digest" });
6561
+ continue;
6562
+ }
6563
+ if (key === "reports/navigation.md") {
6564
+ for (const match of buffer.toString("utf8").matchAll(/\]\(([^)\s]+)\)/g)) {
6565
+ const target = match[1].split("#")[0];
6566
+ if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
6567
+ const resolved = path6.resolve(snapshotDir, "reports", target);
6568
+ const relative14 = path6.relative(snapshotDir, resolved);
6569
+ if (relative14.startsWith("..") || path6.isAbsolute(relative14) || !fs7.existsSync(resolved)) {
6570
+ drift.partIssues.push({
6571
+ part: key,
6572
+ issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
6573
+ });
6574
+ }
6575
+ }
5631
6576
  }
5632
6577
  }
5633
6578
  const sarifArtifact = manifest.artifacts?.sarif;
5634
6579
  if (sarifArtifact) {
5635
6580
  const sarifKey = "reports/audit.sarif";
5636
6581
  try {
5637
- const buffer = fs6.readFileSync(path6.join(snapshotDir, "reports", "audit.sarif"));
6582
+ const buffer = fs7.readFileSync(path6.join(snapshotDir, "reports", "audit.sarif"));
5638
6583
  if (sha256Hex(buffer) !== sarifArtifact.sha256 || buffer.length !== sarifArtifact.byteSize) {
5639
6584
  drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
5640
6585
  }
@@ -5643,8 +6588,11 @@ function validateSnapshot(configInput) {
5643
6588
  }
5644
6589
  }
5645
6590
  if (manifest.git && manifest.git.branch && manifest.git.branch !== config.branch) {
6591
+ const maskBranch = (value) => findSecretInPath(value, config.secretRules)?.masked ?? value;
6592
+ const generatedOn = maskBranch(manifest.git.branch);
6593
+ const configuredAs = maskBranch(config.branch);
5646
6594
  warnings.push(
5647
- `Snapshot was generated on branch "${manifest.git.branch}" but the configured branch is "${config.branch}".`
6595
+ `Snapshot was generated on branch "${generatedOn}" but the configured branch is "${configuredAs}".`
5648
6596
  );
5649
6597
  }
5650
6598
  const errors = [];
@@ -5895,14 +6843,14 @@ function compareManifests(before, after) {
5895
6843
  function loadManifest(target) {
5896
6844
  let isDirectory;
5897
6845
  try {
5898
- isDirectory = fs7.statSync(target).isDirectory();
6846
+ isDirectory = fs8.statSync(target).isDirectory();
5899
6847
  } catch {
5900
6848
  throw new Error(`No snapshot found at ${target}: the path does not exist.`);
5901
6849
  }
5902
6850
  const manifestPath = isDirectory ? path7.join(target, "manifest.json") : target;
5903
6851
  let raw;
5904
6852
  try {
5905
- raw = fs7.readFileSync(manifestPath, "utf8");
6853
+ raw = fs8.readFileSync(manifestPath, "utf8");
5906
6854
  } catch {
5907
6855
  throw new Error(`Could not read a manifest at ${manifestPath}.`);
5908
6856
  }
@@ -5958,9 +6906,74 @@ function renderDiffText(diff) {
5958
6906
  }
5959
6907
 
5960
6908
  // src/explain.ts
5961
- import * as fs8 from "fs";
6909
+ import * as fs9 from "fs";
5962
6910
  import * as path9 from "path";
5963
6911
 
6912
+ // src/ast/skeleton.ts
6913
+ import ts3 from "typescript";
6914
+ function hasCollapsibleBody(node) {
6915
+ if (!("body" in node)) return false;
6916
+ const body = node.body;
6917
+ return body !== void 0 && ts3.isBlock(body);
6918
+ }
6919
+ function scriptKindFor(fileName) {
6920
+ const lower = fileName.toLowerCase();
6921
+ if (lower.endsWith(".tsx")) return ts3.ScriptKind.TSX;
6922
+ if (lower.endsWith(".jsx")) return ts3.ScriptKind.JSX;
6923
+ if (lower.endsWith(".js") || lower.endsWith(".mjs") || lower.endsWith(".cjs")) {
6924
+ return ts3.ScriptKind.JS;
6925
+ }
6926
+ return ts3.ScriptKind.TS;
6927
+ }
6928
+ function skeletonizeTypeScript(source, fileName = "file.ts") {
6929
+ const sourceFile = ts3.createSourceFile(
6930
+ fileName,
6931
+ source,
6932
+ ts3.ScriptTarget.Latest,
6933
+ // `setParentNodes: false`. Nothing here reads `.parent` — the one `getStart` call is given the
6934
+ // source file explicitly, which is the reason that argument exists. Asking for parent pointers
6935
+ // makes the parser run a second full pass over every node in the file to set them, on top of
6936
+ // the summary parse this same file already pays for.
6937
+ false,
6938
+ scriptKindFor(fileName)
6939
+ );
6940
+ const spans = [];
6941
+ const visit = (node) => {
6942
+ if ((ts3.isFunctionDeclaration(node) || ts3.isMethodDeclaration(node) || ts3.isConstructorDeclaration(node) || ts3.isGetAccessorDeclaration(node) || ts3.isSetAccessorDeclaration(node) || ts3.isFunctionExpression(node) || ts3.isArrowFunction(node)) && hasCollapsibleBody(node)) {
6943
+ const body = node.body;
6944
+ if (body.statements.length > 0) {
6945
+ const start = body.getStart(sourceFile);
6946
+ const end = body.getEnd();
6947
+ if (end > start) spans.push({ start, end });
6948
+ }
6949
+ }
6950
+ ts3.forEachChild(node, visit);
6951
+ };
6952
+ visit(sourceFile);
6953
+ if (spans.length === 0) return { text: source, collapsed: 0 };
6954
+ const outermost = [];
6955
+ for (const span of spans.sort((a, b) => a.start - b.start || b.end - a.end)) {
6956
+ const last = outermost[outermost.length - 1];
6957
+ if (last && span.start < last.end) continue;
6958
+ outermost.push(span);
6959
+ }
6960
+ const chunks = [];
6961
+ let cursor = 0;
6962
+ for (const span of outermost) {
6963
+ chunks.push(source.slice(cursor, span.start), "{ /* ... */ }");
6964
+ cursor = span.end;
6965
+ }
6966
+ chunks.push(source.slice(cursor));
6967
+ return { text: chunks.join(""), collapsed: outermost.length };
6968
+ }
6969
+ function isSkeletonizable(filePath) {
6970
+ const lower = filePath.toLowerCase();
6971
+ if (lower.endsWith(".d.ts") || lower.endsWith(".d.mts") || lower.endsWith(".d.cts")) {
6972
+ return false;
6973
+ }
6974
+ 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");
6975
+ }
6976
+
5964
6977
  // src/partitioner/preview.ts
5965
6978
  var LINE_ENDINGS = /\r\n|\r/g;
5966
6979
  var normaliseLineEndings = (content) => content.replace(LINE_ENDINGS, "\n");
@@ -5982,9 +6995,9 @@ function truncateToBytes(content, maxBytes) {
5982
6995
  if (maxBytes <= 0) return { content: "", isTruncated: content.length > 0 };
5983
6996
  const buffer = Buffer.from(content, "utf8");
5984
6997
  if (buffer.length <= maxBytes) return { content, isTruncated: false };
5985
- let slice = buffer.subarray(0, maxBytes).toString("utf8");
5986
- while (slice.endsWith("\uFFFD")) slice = slice.slice(0, -1);
5987
- return { content: slice, isTruncated: true };
6998
+ let end = maxBytes;
6999
+ while (end > 0 && (buffer[end] & 192) === 128) end -= 1;
7000
+ return { content: buffer.subarray(0, end).toString("utf8"), isTruncated: true };
5988
7001
  }
5989
7002
  function truncatePreview(content, headLines, tailLines) {
5990
7003
  const normalised = normaliseLineEndings(content);
@@ -6123,23 +7136,23 @@ function describeMatcher(matcher) {
6123
7136
  function normalizeTarget(cwd, target) {
6124
7137
  const resolvedCwd = path9.resolve(cwd);
6125
7138
  const absolute = path9.resolve(resolvedCwd, target);
6126
- const relative12 = path9.relative(resolvedCwd, absolute);
6127
- if (relative12 === "" || relative12 === ".." || relative12.startsWith(`..${path9.sep}`) || path9.isAbsolute(relative12)) {
7139
+ const relative14 = path9.relative(resolvedCwd, absolute);
7140
+ if (relative14 === "" || relative14 === ".." || relative14.startsWith(`..${path9.sep}`) || path9.isAbsolute(relative14)) {
6128
7141
  return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
6129
7142
  }
6130
- return { relative: relative12.split(path9.sep).join("/"), outsideRoot: false };
7143
+ return { relative: relative14.split(path9.sep).join("/"), outsideRoot: false };
6131
7144
  }
6132
7145
  function findRuleMatch(rules, relativePath) {
6133
7146
  return rules.find(
6134
7147
  (rule) => matchRule(relativePath, rule.match)
6135
7148
  );
6136
7149
  }
6137
- function findRecordedAncestor(skipped, relative12, maskedPath2) {
7150
+ function findRecordedAncestor(skipped, relative14, maskedPath2) {
6138
7151
  let nearest;
6139
7152
  for (const record of skipped) {
6140
7153
  const ancestorPath = record.path;
6141
7154
  if (ancestorPath.length === 0) continue;
6142
- const isAncestor = relative12.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
7155
+ const isAncestor = relative14.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
6143
7156
  if (!isAncestor) continue;
6144
7157
  if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
6145
7158
  }
@@ -6148,15 +7161,15 @@ function findRecordedAncestor(skipped, relative12, maskedPath2) {
6148
7161
  function readManifest2(config) {
6149
7162
  const manifestPath = path9.resolve(config.cwd, config.outDir, "manifest.json");
6150
7163
  try {
6151
- return JSON.parse(fs8.readFileSync(manifestPath, "utf8"));
7164
+ return JSON.parse(fs9.readFileSync(manifestPath, "utf8"));
6152
7165
  } catch {
6153
7166
  return null;
6154
7167
  }
6155
7168
  }
6156
7169
  function explainPath(config, target) {
6157
7170
  const normalized = normalizeTarget(config.cwd, target);
6158
- const relative12 = normalized.relative;
6159
- const maskedPath2 = findSecretInPath(relative12, config.secretRules)?.masked ?? relative12;
7171
+ const relative14 = normalized.relative;
7172
+ const maskedPath2 = findSecretInPath(relative14, config.secretRules)?.masked ?? relative14;
6160
7173
  if (normalized.outsideRoot) {
6161
7174
  return {
6162
7175
  path: maskedPath2,
@@ -6166,10 +7179,10 @@ function explainPath(config, target) {
6166
7179
  detail: "path resolves outside the configured repository root and was not inspected"
6167
7180
  };
6168
7181
  }
6169
- const absolute = path9.join(config.cwd, relative12);
7182
+ const absolute = path9.join(config.cwd, relative14);
6170
7183
  const result = {
6171
7184
  path: maskedPath2,
6172
- exists: fs8.existsSync(absolute),
7185
+ exists: fs9.existsSync(absolute),
6173
7186
  included: false
6174
7187
  };
6175
7188
  const collection = collectFiles(config.cwd, {
@@ -6184,11 +7197,11 @@ function explainPath(config, target) {
6184
7197
  // that is only missing because the walker dropped the tool's own output directory.
6185
7198
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
6186
7199
  (directory) => path9.relative(config.cwd, path9.resolve(config.cwd, directory)).replace(/\\/g, "/")
6187
- ).filter((relative13) => relative13.length > 0 && !relative13.startsWith(".."))
7200
+ ).filter((relative15) => relative15.length > 0 && !relative15.startsWith(".."))
6188
7201
  });
6189
- if (!collection.files.includes(relative12)) {
7202
+ if (!collection.files.includes(relative14)) {
6190
7203
  const record = collection.skipped.find(
6191
- (entry2) => entry2.path === relative12 || entry2.path === maskedPath2
7204
+ (entry2) => entry2.path === relative14 || entry2.path === maskedPath2
6192
7205
  );
6193
7206
  if (record) {
6194
7207
  result.reason = record.reason;
@@ -6197,7 +7210,7 @@ function explainPath(config, target) {
6197
7210
  result.reason = "missing";
6198
7211
  result.detail = "no such file or directory, relative to the configured cwd";
6199
7212
  } else {
6200
- const ancestor = findRecordedAncestor(collection.skipped, relative12, maskedPath2);
7213
+ const ancestor = findRecordedAncestor(collection.skipped, relative14, maskedPath2);
6201
7214
  if (ancestor) {
6202
7215
  result.reason = ancestor.reason;
6203
7216
  result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
@@ -6217,11 +7230,11 @@ function explainPath(config, target) {
6217
7230
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
6218
7231
  ...config.staged === true ? { staged: true } : {}
6219
7232
  });
6220
- inScope = scope.paths.has(relative12);
7233
+ inScope = scope.paths.has(relative14);
6221
7234
  if (!inScope && config.withDependents === true) {
6222
7235
  inScope = importsChangedFile(
6223
- relative12,
6224
- importsOfFile(relative12, absolute),
7236
+ relative14,
7237
+ importsOfFile(relative14, absolute),
6225
7238
  scope.paths,
6226
7239
  buildImportResolver(collection.files.map((file) => ({ relativePath: file })))
6227
7240
  );
@@ -6248,7 +7261,7 @@ function explainPath(config, target) {
6248
7261
  }
6249
7262
  let sizeOnDisk = null;
6250
7263
  try {
6251
- sizeOnDisk = fs8.statSync(absolute).size;
7264
+ sizeOnDisk = fs9.statSync(absolute).size;
6252
7265
  } catch {
6253
7266
  sizeOnDisk = null;
6254
7267
  }
@@ -6258,8 +7271,16 @@ function explainPath(config, target) {
6258
7271
  result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
6259
7272
  return result;
6260
7273
  }
6261
- if (fs8.existsSync(absolute) && fs8.statSync(absolute).isFile()) {
6262
- const buffer = fs8.readFileSync(absolute);
7274
+ if (fs9.existsSync(absolute) && fs9.statSync(absolute).isFile()) {
7275
+ let buffer;
7276
+ try {
7277
+ buffer = fs9.readFileSync(absolute);
7278
+ } catch (err) {
7279
+ result.included = false;
7280
+ result.reason = "read-error";
7281
+ result.detail = `${err.message} (explain could not read the file; generate records this as a skipped entry)`;
7282
+ return result;
7283
+ }
6263
7284
  const decoded = decodeText(buffer);
6264
7285
  if (decoded.binary) {
6265
7286
  result.included = false;
@@ -6271,21 +7292,30 @@ function explainPath(config, target) {
6271
7292
  result.bytes = buffer.length;
6272
7293
  result.lines = countLines(text2);
6273
7294
  if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
6274
- const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative12);
7295
+ const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative14);
6275
7296
  result.secretCount = findings.length;
6276
7297
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
7298
+ let inclusionMode = "full";
7299
+ if (config.skeleton === true && isSkeletonizable(relative14)) {
7300
+ const skeleton = skeletonizeTypeScript(text2, relative14);
7301
+ if (skeleton.collapsed > 0) inclusionMode = "signatures";
7302
+ }
7303
+ if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
7304
+ const preview = truncatePreview(text2, config.previewHeadLines, config.previewTailLines);
7305
+ inclusionMode = preview.isTruncated ? "preview" : "full";
7306
+ }
7307
+ result.inclusionMode = inclusionMode;
6277
7308
  }
6278
- result.layer = classifyLayer(relative12, config.layers);
6279
- result.kind = classifyKind(relative12, config.kinds);
6280
- result.language = detectLanguage(relative12);
6281
- const layerRule = findRuleMatch(config.layers, relative12);
7309
+ result.layer = classifyLayer(relative14, config.layers);
7310
+ result.kind = classifyKind(relative14, config.kinds);
7311
+ result.language = detectLanguage(relative14);
7312
+ const layerRule = findRuleMatch(config.layers, relative14);
6282
7313
  if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
6283
- const kindRule = findRuleMatch(config.kinds, relative12);
7314
+ const kindRule = findRuleMatch(config.kinds, relative14);
6284
7315
  if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
6285
7316
  const manifest = readManifest2(config);
6286
- const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative12) : void 0;
7317
+ const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative14) : void 0;
6287
7318
  result.part = entry?.part ?? null;
6288
- result.inclusionMode = entry?.inclusionMode;
6289
7319
  return result;
6290
7320
  }
6291
7321
  function renderExplainText(result) {
@@ -6324,7 +7354,7 @@ function renderExplainText(result) {
6324
7354
  }
6325
7355
 
6326
7356
  // src/wizard/init.ts
6327
- import * as fs10 from "fs";
7357
+ import * as fs11 from "fs";
6328
7358
  import * as path11 from "path";
6329
7359
 
6330
7360
  // src/ast/structured.ts
@@ -6500,20 +7530,72 @@ function summarizeMarkdown(content) {
6500
7530
  }
6501
7531
 
6502
7532
  // src/gitignore.ts
6503
- import * as fs9 from "fs";
7533
+ import * as fs10 from "fs";
6504
7534
  import * as path10 from "path";
7535
+ function decodeGitignore(buffer) {
7536
+ const startsWith = (...bytes) => buffer.length >= bytes.length && bytes.every((byte, index) => buffer[index] === byte);
7537
+ if (startsWith(239, 187, 191)) {
7538
+ const body = buffer.subarray(3);
7539
+ const text3 = body.toString("utf8");
7540
+ if (!Buffer.from(text3, "utf8").equals(body)) return null;
7541
+ return { text: text3, bom: buffer.subarray(0, 3), encoding: "utf8" };
7542
+ }
7543
+ if (startsWith(255, 254)) {
7544
+ const body = buffer.subarray(2);
7545
+ if (body.length % 2 !== 0) return null;
7546
+ const text3 = body.toString("utf16le");
7547
+ if (!Buffer.from(text3, "utf16le").equals(body)) return null;
7548
+ return { text: text3, bom: buffer.subarray(0, 2), encoding: "utf16le" };
7549
+ }
7550
+ if (startsWith(254, 255)) {
7551
+ const body = buffer.subarray(2);
7552
+ if (body.length % 2 !== 0) return null;
7553
+ const swapped = Buffer.from(body);
7554
+ swapped.swap16();
7555
+ const text3 = swapped.toString("utf16le");
7556
+ if (!Buffer.from(text3, "utf16le").equals(swapped)) return null;
7557
+ return { text: text3, bom: buffer.subarray(0, 2), encoding: "utf16be" };
7558
+ }
7559
+ const text2 = buffer.toString("utf8");
7560
+ if (!Buffer.from(text2, "utf8").equals(buffer)) return null;
7561
+ return { text: text2, bom: Buffer.alloc(0), encoding: "utf8" };
7562
+ }
7563
+ function encodeGitignore(decoded, text2) {
7564
+ if (decoded.encoding === "utf8") {
7565
+ return Buffer.concat([decoded.bom, Buffer.from(text2, "utf8")]);
7566
+ }
7567
+ const littleEndian = Buffer.from(text2, "utf16le");
7568
+ if (decoded.encoding === "utf16le") return Buffer.concat([decoded.bom, littleEndian]);
7569
+ const bigEndian = Buffer.from(littleEndian);
7570
+ bigEndian.swap16();
7571
+ return Buffer.concat([decoded.bom, bigEndian]);
7572
+ }
7573
+ function canonicalIgnorePattern(line) {
7574
+ const trimmed = line.trim();
7575
+ if (trimmed.length === 0 || trimmed.startsWith("#")) return trimmed;
7576
+ const negated = trimmed.startsWith("!");
7577
+ const body = (negated ? trimmed.slice(1) : trimmed).replace(/^\/+/, "").replace(/\/+$/, "");
7578
+ return `${negated ? "!" : ""}${body}`;
7579
+ }
6505
7580
  function appendGitignoreEntries(cwd, entries) {
6506
7581
  const wanted = [...new Set(entries)].filter((entry) => entry.trim().length > 0);
6507
7582
  if (wanted.length === 0) return { added: [], note: null };
6508
7583
  const ignorePath = path10.join(cwd, ".gitignore");
6509
7584
  const manual = `Add ${wanted.map((entry) => `"${entry}"`).join(" and ")} to your .gitignore yourself.`;
6510
- let existing = "";
7585
+ let decoded = { text: "", bom: Buffer.alloc(0), encoding: "utf8" };
6511
7586
  try {
6512
- if (fs9.existsSync(ignorePath)) {
6513
- if (fs9.statSync(ignorePath).isDirectory()) {
7587
+ if (fs10.existsSync(ignorePath)) {
7588
+ if (fs10.statSync(ignorePath).isDirectory()) {
6514
7589
  return { added: [], note: `${ignorePath} is a directory, so it was not updated. ${manual}` };
6515
7590
  }
6516
- existing = fs9.readFileSync(ignorePath, "utf8");
7591
+ const read = decodeGitignore(fs10.readFileSync(ignorePath));
7592
+ if (read === null) {
7593
+ return {
7594
+ added: [],
7595
+ note: `${ignorePath} is not valid UTF-8, UTF-16LE or UTF-16BE text, so it was not updated. ` + manual
7596
+ };
7597
+ }
7598
+ decoded = read;
6517
7599
  }
6518
7600
  } catch (err) {
6519
7601
  return {
@@ -6521,13 +7603,17 @@ function appendGitignoreEntries(cwd, entries) {
6521
7603
  note: `${ignorePath} could not be read (${err.message}). ${manual}`
6522
7604
  };
6523
7605
  }
6524
- const present = new Set(existing.split(/\r?\n/).map((line) => line.trim()));
6525
- const added = wanted.filter((entry) => !present.has(entry));
7606
+ const existing = decoded.text;
7607
+ const present = new Set(existing.split(/\r?\n/).map(canonicalIgnorePattern));
7608
+ const added = wanted.filter((entry) => !present.has(canonicalIgnorePattern(entry)));
6526
7609
  if (added.length === 0) return { added: [], note: null };
6527
- const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : "\n";
7610
+ const newline = existing.includes("\r\n") ? "\r\n" : "\n";
7611
+ const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : newline;
6528
7612
  try {
6529
- fs9.writeFileSync(ignorePath, `${existing}${prefix}${added.join("\n")}
6530
- `, "utf8");
7613
+ fs10.writeFileSync(
7614
+ ignorePath,
7615
+ encodeGitignore(decoded, `${existing}${prefix}${added.join(newline)}${newline}`)
7616
+ );
6531
7617
  } catch (err) {
6532
7618
  return { added: [], note: `${err.message}. ${manual}` };
6533
7619
  }
@@ -6537,15 +7623,6 @@ function gitignorePath(cwd, filePath) {
6537
7623
  return path10.relative(cwd, filePath).split(path10.sep).join("/");
6538
7624
  }
6539
7625
 
6540
- // src/version.ts
6541
- var GENERATOR_NAME = "codebase-snapshot";
6542
- var GENERATOR_VERSION = "0.9.15";
6543
- var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
6544
- function isOurGeneratorName(name) {
6545
- if (typeof name !== "string") return false;
6546
- return name === GENERATOR_NAME || LEGACY_GENERATOR_NAMES.includes(name);
6547
- }
6548
-
6549
7626
  // src/wizard/config-template.ts
6550
7627
  var DEFAULT_ANSWERS = {
6551
7628
  preset: "generic",
@@ -6857,7 +7934,7 @@ function keyReader(input) {
6857
7934
  next() {
6858
7935
  const queued = queue.shift();
6859
7936
  if (queued) return Promise.resolve(queued);
6860
- return new Promise((resolve10) => waiters.push(resolve10));
7937
+ return new Promise((resolve11) => waiters.push(resolve11));
6861
7938
  },
6862
7939
  close() {
6863
7940
  input.off("keypress", onKey);
@@ -7083,7 +8160,7 @@ function parsePackageJson(raw) {
7083
8160
  }
7084
8161
  function readPackageJson(cwd) {
7085
8162
  try {
7086
- return parsePackageJson(fs10.readFileSync(path11.join(cwd, "package.json"), "utf8"));
8163
+ return parsePackageJson(fs11.readFileSync(path11.join(cwd, "package.json"), "utf8"));
7087
8164
  } catch {
7088
8165
  return null;
7089
8166
  }
@@ -7120,7 +8197,7 @@ function artifactAnswers(options) {
7120
8197
  }
7121
8198
  function topLevelDirs(cwd) {
7122
8199
  try {
7123
- return fs10.readdirSync(cwd, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules").map((entry) => entry.name).sort();
8200
+ return fs11.readdirSync(cwd, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules").map((entry) => entry.name).sort();
7124
8201
  } catch {
7125
8202
  return [];
7126
8203
  }
@@ -7133,10 +8210,38 @@ function describeJsonValue(value) {
7133
8210
  }
7134
8211
  function writeFileOrExplain(target, content) {
7135
8212
  try {
7136
- fs10.writeFileSync(target, content, "utf8");
8213
+ let stats = null;
8214
+ try {
8215
+ stats = fs11.lstatSync(target);
8216
+ } catch {
8217
+ stats = null;
8218
+ }
8219
+ if (stats !== null && stats.isSymbolicLink()) {
8220
+ throw new Error(
8221
+ `Cannot write ${target}: it is a symbolic link, and writing through it would modify whatever it points at.`
8222
+ );
8223
+ }
8224
+ if (stats !== null && !stats.isFile()) {
8225
+ throw new Error(
8226
+ `Cannot write ${target}: ${stats.isDirectory() ? "it is a directory" : "it is not a regular file"}.`
8227
+ );
8228
+ }
8229
+ const temporary = `${target}.tmp-${process.pid}-${Date.now()}`;
8230
+ fs11.writeFileSync(temporary, content, { encoding: "utf8", flag: "wx" });
8231
+ try {
8232
+ fs11.renameSync(temporary, target);
8233
+ } catch (err) {
8234
+ try {
8235
+ fs11.unlinkSync(temporary);
8236
+ } catch {
8237
+ }
8238
+ throw err;
8239
+ }
7137
8240
  } catch (err) {
8241
+ const message = err.message;
8242
+ if (message.startsWith(`Cannot write ${target}:`)) throw err;
7138
8243
  const code = err.code;
7139
- const reason = code === "EACCES" || code === "EPERM" || code === "EROFS" ? `permission denied (${code})` : code === "EISDIR" ? "it is a directory" : `${err.message}`;
8244
+ const reason = code === "EACCES" || code === "EPERM" || code === "EROFS" ? `permission denied (${code})` : code === "EISDIR" ? "it is a directory" : message;
7140
8245
  throw new Error(`Cannot write ${target}: ${reason}`);
7141
8246
  }
7142
8247
  }
@@ -7180,14 +8285,14 @@ function updatePackageJson(cwd, notes) {
7180
8285
  scripts: [],
7181
8286
  dependency: { name: GENERATOR_NAME, range: null, added: false }
7182
8287
  };
7183
- if (!fs10.existsSync(packagePath)) {
8288
+ if (!fs11.existsSync(packagePath)) {
7184
8289
  notes.push("No package.json found, so npm scripts and the devDependency were not added.");
7185
8290
  return unchanged;
7186
8291
  }
7187
8292
  let raw;
7188
8293
  let parsed;
7189
8294
  try {
7190
- raw = fs10.readFileSync(packagePath, "utf8");
8295
+ raw = fs11.readFileSync(packagePath, "utf8");
7191
8296
  parsed = parsePackageJson(raw);
7192
8297
  } catch {
7193
8298
  notes.push("Could not parse package.json; npm scripts and the devDependency were not added.");
@@ -7258,7 +8363,7 @@ function updatePackageJson(cwd, notes) {
7258
8363
  writeFileOrExplain(packagePath, serializePackageJson(raw, parsed));
7259
8364
  return { scripts: added, dependency };
7260
8365
  }
7261
- var GITIGNORE_ENTRIES = ["snapshot/", "snapshot.tmp/"];
8366
+ var GITIGNORE_ENTRIES = ["/snapshot/", "/snapshot.tmp/"];
7262
8367
  function resolvePresetChoice(detectedName, presetName) {
7263
8368
  return {
7264
8369
  value: presetName,
@@ -7496,7 +8601,7 @@ async function runInit(options) {
7496
8601
  const configText = renderConfig(answers);
7497
8602
  const preferredName = chooseConfigFileName(options.cwd);
7498
8603
  const presentConfigs = CONFIG_CANDIDATES.filter(
7499
- (name) => fs10.existsSync(path11.join(options.cwd, name))
8604
+ (name) => fs11.existsSync(path11.join(options.cwd, name))
7500
8605
  );
7501
8606
  const present = presentConfigs[0] ?? null;
7502
8607
  if (presentConfigs.length > 1) {
@@ -7539,7 +8644,7 @@ async function runInit(options) {
7539
8644
  '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.'
7540
8645
  );
7541
8646
  }
7542
- if (fs10.existsSync(configPath) && !options.force && !reused) {
8647
+ if (fs11.existsSync(configPath) && !options.force && !reused) {
7543
8648
  throw new Error(`${configName} already exists. Re-run with --force to replace it.`);
7544
8649
  }
7545
8650
  if (!reused) writeFileOrExplain(configPath, configText);
@@ -7563,13 +8668,13 @@ async function runInit(options) {
7563
8668
  }
7564
8669
 
7565
8670
  // src/wizard/autopilot.ts
7566
- import * as fs11 from "fs";
8671
+ import * as fs12 from "fs";
7567
8672
  import * as path12 from "path";
7568
8673
  function describeTarget(cwd) {
7569
- const relative12 = path12.relative(process.cwd(), cwd);
7570
- if (relative12 === "") return "this directory";
7571
- if (relative12.startsWith("..") || path12.isAbsolute(relative12)) return cwd;
7572
- return relative12;
8674
+ const relative14 = path12.relative(process.cwd(), cwd);
8675
+ if (relative14 === "") return "this directory";
8676
+ if (relative14.startsWith("..") || path12.isAbsolute(relative14)) return cwd;
8677
+ return relative14;
7573
8678
  }
7574
8679
  function firstRunMessage(reason, cwd) {
7575
8680
  const where = describeTarget(cwd);
@@ -7592,7 +8697,7 @@ function planFirstRun(facts) {
7592
8697
  var NOT_CONTENT = /* @__PURE__ */ new Set([".git", ".hg", ".svn", ".bzr", ".DS_Store", "Thumbs.db"]);
7593
8698
  function isEffectivelyEmpty(cwd) {
7594
8699
  try {
7595
- return fs11.readdirSync(cwd).every((entry) => NOT_CONTENT.has(entry));
8700
+ return fs12.readdirSync(cwd).every((entry) => NOT_CONTENT.has(entry));
7596
8701
  } catch {
7597
8702
  return false;
7598
8703
  }
@@ -7600,7 +8705,7 @@ function isEffectivelyEmpty(cwd) {
7600
8705
  function hasPriorSnapshot(cwd, outDir) {
7601
8706
  let parsed;
7602
8707
  try {
7603
- parsed = JSON.parse(fs11.readFileSync(path12.join(cwd, outDir, ".codebase-snapshot"), "utf8"));
8708
+ parsed = JSON.parse(fs12.readFileSync(path12.join(cwd, outDir, ".codebase-snapshot"), "utf8"));
7604
8709
  } catch {
7605
8710
  return false;
7606
8711
  }
@@ -7610,6 +8715,7 @@ function hasPriorSnapshot(cwd, outDir) {
7610
8715
 
7611
8716
  // src/index.ts
7612
8717
  import * as crypto4 from "crypto";
8718
+ import { Worker as Worker2 } from "worker_threads";
7613
8719
 
7614
8720
  // src/stdout.ts
7615
8721
  import { AsyncLocalStorage } from "async_hooks";
@@ -7651,97 +8757,32 @@ function installStdoutRouter() {
7651
8757
  installs -= 1;
7652
8758
  if (installs === 0) {
7653
8759
  if (process.stdout.write === router && underlying !== null) {
7654
- process.stdout.write = underlying;
7655
- }
7656
- underlying = null;
7657
- router = null;
7658
- }
7659
- };
7660
- }
7661
- async function runWithStdoutCapture(fn) {
7662
- let text2 = "";
7663
- const release = installStdoutRouter();
7664
- try {
7665
- const value = await captureScope.run(
7666
- { write: (chunk) => void (text2 += chunk) },
7667
- fn
7668
- );
7669
- return { value, text: text2 };
7670
- } finally {
7671
- release();
7672
- }
7673
- }
7674
-
7675
- // src/index.ts
7676
- import * as fs14 from "fs";
7677
- import * as os2 from "os";
7678
- import * as path16 from "path";
7679
-
7680
- // src/ast/skeleton.ts
7681
- import ts2 from "typescript";
7682
- function hasCollapsibleBody(node) {
7683
- if (!("body" in node)) return false;
7684
- const body = node.body;
7685
- return body !== void 0 && ts2.isBlock(body);
7686
- }
7687
- function scriptKindFor(fileName) {
7688
- const lower = fileName.toLowerCase();
7689
- if (lower.endsWith(".tsx")) return ts2.ScriptKind.TSX;
7690
- if (lower.endsWith(".jsx")) return ts2.ScriptKind.JSX;
7691
- if (lower.endsWith(".js") || lower.endsWith(".mjs") || lower.endsWith(".cjs")) {
7692
- return ts2.ScriptKind.JS;
7693
- }
7694
- return ts2.ScriptKind.TS;
7695
- }
7696
- function skeletonizeTypeScript(source, fileName = "file.ts") {
7697
- const sourceFile = ts2.createSourceFile(
7698
- fileName,
7699
- source,
7700
- ts2.ScriptTarget.Latest,
7701
- // `setParentNodes: false`. Nothing here reads `.parent` — the one `getStart` call is given the
7702
- // source file explicitly, which is the reason that argument exists. Asking for parent pointers
7703
- // makes the parser run a second full pass over every node in the file to set them, on top of
7704
- // the summary parse this same file already pays for.
7705
- false,
7706
- scriptKindFor(fileName)
7707
- );
7708
- const spans = [];
7709
- const visit = (node) => {
7710
- if ((ts2.isFunctionDeclaration(node) || ts2.isMethodDeclaration(node) || ts2.isConstructorDeclaration(node) || ts2.isGetAccessorDeclaration(node) || ts2.isSetAccessorDeclaration(node) || ts2.isFunctionExpression(node) || ts2.isArrowFunction(node)) && hasCollapsibleBody(node)) {
7711
- const body = node.body;
7712
- if (body.statements.length > 0) {
7713
- const start = body.getStart(sourceFile);
7714
- const end = body.getEnd();
7715
- if (end > start) spans.push({ start, end });
8760
+ process.stdout.write = underlying;
7716
8761
  }
8762
+ underlying = null;
8763
+ router = null;
7717
8764
  }
7718
- ts2.forEachChild(node, visit);
7719
8765
  };
7720
- visit(sourceFile);
7721
- if (spans.length === 0) return { text: source, collapsed: 0 };
7722
- const outermost = [];
7723
- for (const span of spans.sort((a, b) => a.start - b.start || b.end - a.end)) {
7724
- const last = outermost[outermost.length - 1];
7725
- if (last && span.start < last.end) continue;
7726
- outermost.push(span);
7727
- }
7728
- const chunks = [];
7729
- let cursor = 0;
7730
- for (const span of outermost) {
7731
- chunks.push(source.slice(cursor, span.start), "{ /* ... */ }");
7732
- cursor = span.end;
7733
- }
7734
- chunks.push(source.slice(cursor));
7735
- return { text: chunks.join(""), collapsed: outermost.length };
7736
8766
  }
7737
- function isSkeletonizable(filePath) {
7738
- const lower = filePath.toLowerCase();
7739
- if (lower.endsWith(".d.ts") || lower.endsWith(".d.mts") || lower.endsWith(".d.cts")) {
7740
- return false;
8767
+ async function runWithStdoutCapture(fn) {
8768
+ let text2 = "";
8769
+ const release = installStdoutRouter();
8770
+ try {
8771
+ const value = await captureScope.run(
8772
+ { write: (chunk) => void (text2 += chunk) },
8773
+ fn
8774
+ );
8775
+ return { value, text: text2 };
8776
+ } finally {
8777
+ release();
7741
8778
  }
7742
- 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");
7743
8779
  }
7744
8780
 
8781
+ // src/index.ts
8782
+ import * as fs15 from "fs";
8783
+ import * as os2 from "os";
8784
+ import * as path16 from "path";
8785
+
7745
8786
  // src/generator/audit.ts
7746
8787
  function generateAuditReport(manifest, secretFindings, secretRules) {
7747
8788
  const mask = (value) => escapeControls(findSecretInPath(value, secretRules)?.masked ?? value);
@@ -7752,8 +8793,9 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
7752
8793
  `**Generated:** ${manifest.generatedAt} `,
7753
8794
  `**Git Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""}) `,
7754
8795
  `**Total Files:** ${formatNumber(manifest.counts.totalFiles)} `,
7755
- `**Total Lines:** ${formatNumber(manifest.counts.totalLines)} `,
7756
- `**Total Size:** ${(manifest.counts.totalSizeBytes / (1024 * 1024)).toFixed(2)} MB `,
8796
+ `**Source Lines:** ${formatNumber(manifest.counts.totalLines)} `,
8797
+ `**Emitted Lines:** ${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)} `,
8798
+ `**Total Size:** ${(manifest.counts.totalSizeBytes / (1024 * 1024)).toFixed(2)} MiB `,
7757
8799
  // This counts the bytes that were *emitted* after redaction, not the bytes
7758
8800
  // that were masked: calling it "redacted bytes" made a repository with zero
7759
8801
  // secrets report a non-zero redacted-byte figure directly above "no secrets
@@ -7793,9 +8835,19 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
7793
8835
  const parseIssues = manifest.files.filter(
7794
8836
  (file) => file.summary !== void 0 && typeof file.summary === "object" && "parseErrors" in file.summary && typeof file.summary.parseErrors === "number" && file.summary.parseErrors > 0
7795
8837
  );
8838
+ const unparsedPreviews = manifest.files.filter(
8839
+ (file) => file.summary === void 0 && (file.isPreviewTruncated === true || file.isLarge === true)
8840
+ ).length;
7796
8841
  lines.push("## 2. Parse & AST Diagnostics", "");
7797
8842
  if (parseIssues.length === 0) {
7798
- lines.push("\u2705 Every parsed file produced a complete structural summary.", "");
8843
+ if (unparsedPreviews > 0) {
8844
+ lines.push(
8845
+ `\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.`,
8846
+ ""
8847
+ );
8848
+ } else {
8849
+ lines.push("\u2705 Every parsed file produced a complete structural summary.", "");
8850
+ }
7799
8851
  } else {
7800
8852
  lines.push(
7801
8853
  `${parseIssues.length} file(s) produced an incomplete summary:`,
@@ -8028,19 +9080,19 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
8028
9080
  for (const sections of greedyGroups(prepared, budget)) groups.push({ sections, budget });
8029
9081
  }
8030
9082
  if (groups.length === 0) return [];
8031
- const measurements = /* @__PURE__ */ new Map();
9083
+ const assemblies = /* @__PURE__ */ new Map();
8032
9084
  const widthOf = (total) => Math.max(3, String(total).length);
8033
- const measure = (group, index, total) => {
8034
- const cached = measurements.get(group);
9085
+ const assemble = (group, index, total) => {
8035
9086
  const width = widthOf(total);
9087
+ const cached = assemblies.get(group);
8036
9088
  if (cached !== void 0 && cached.index === index && cached.width === width) {
8037
- return cached.size;
9089
+ return cached.value;
8038
9090
  }
8039
- const { content } = assembleGroup(group, index, total, contentFingerprint);
8040
- const size2 = Buffer.byteLength(content, "utf8");
8041
- measurements.set(group, { index, width, size: size2 });
8042
- return size2;
9091
+ const value = assembleGroup(group, index, total, contentFingerprint);
9092
+ assemblies.set(group, { index, width, value });
9093
+ return value;
8043
9094
  };
9095
+ const measure = (group, index, total) => Buffer.byteLength(assemble(group, index, total).content, "utf8");
8044
9096
  for (let pass = 0; pass < MAX_SPLIT_PASSES; pass++) {
8045
9097
  const total = groups.length;
8046
9098
  let oversized = -1;
@@ -8051,16 +9103,16 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
8051
9103
  break;
8052
9104
  }
8053
9105
  }
8054
- if (oversized === -1) return renderGroups(groups, contentFingerprint);
9106
+ if (oversized === -1) return renderGroups(groups, contentFingerprint, assemble);
8055
9107
  const group = groups[oversized];
8056
9108
  if (group.sections.length > 1) {
8057
9109
  const moved = group.sections.pop();
8058
9110
  groups.splice(oversized + 1, 0, { sections: [moved], budget: group.budget });
8059
- measurements.delete(group);
9111
+ assemblies.delete(group);
8060
9112
  continue;
8061
9113
  }
8062
9114
  const [section] = group.sections;
8063
- if (section === void 0) return renderGroups(groups, contentFingerprint);
9115
+ if (section === void 0) return renderGroups(groups, contentFingerprint, assemble);
8064
9116
  const overflow = measure(group, oversized, total) - group.budget;
8065
9117
  const currentContent = section.file.content ?? "";
8066
9118
  const shrinkTo = Math.max(
@@ -8077,10 +9129,10 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
8077
9129
  applyTruncatedContent(section.file, shrunk.content);
8078
9130
  section.text = renderFileSection(section.file);
8079
9131
  section.byteSize = Buffer.byteLength(section.text, "utf8");
8080
- measurements.delete(group);
9132
+ assemblies.delete(group);
8081
9133
  continue;
8082
9134
  }
8083
- const rendered = renderGroups(groups, contentFingerprint);
9135
+ const rendered = renderGroups(groups, contentFingerprint, assemble);
8084
9136
  const marker2 = TRUNCATION_MARKER;
8085
9137
  assertBudgetHoldsMarker(group.budget);
8086
9138
  const target = Math.max(
@@ -8094,7 +9146,7 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
8094
9146
  );
8095
9147
  return rendered;
8096
9148
  }
8097
- return renderGroups(groups, contentFingerprint).flatMap(
9149
+ return renderGroups(groups, contentFingerprint, assemble).flatMap(
8098
9150
  (part) => enforceBudget([part], part.metadata.budgetBytes)
8099
9151
  );
8100
9152
  }
@@ -8268,8 +9320,8 @@ function assembleGroup(group, index, total, contentFingerprint) {
8268
9320
  for (const section of group.sections) {
8269
9321
  section.file.part = filename;
8270
9322
  }
8271
- const layerCounts = {};
8272
- const kindCounts = {};
9323
+ const layerCounts = /* @__PURE__ */ Object.create(null);
9324
+ const kindCounts = /* @__PURE__ */ Object.create(null);
8273
9325
  for (const section of group.sections) {
8274
9326
  layerCounts[section.file.layer] = (layerCounts[section.file.layer] || 0) + 1;
8275
9327
  kindCounts[section.file.kind] = (kindCounts[section.file.kind] || 0) + 1;
@@ -8304,15 +9356,10 @@ function assembleGroup(group, index, total, contentFingerprint) {
8304
9356
  const estimatedTokens = estimateTokens(assembled);
8305
9357
  return { filename, content: insertTokenLine(assembled, estimatedTokens), estimatedTokens };
8306
9358
  }
8307
- function renderGroups(groups, contentFingerprint) {
9359
+ function renderGroups(groups, contentFingerprint, assemble = (group, index, total) => assembleGroup(group, index, total, contentFingerprint)) {
8308
9360
  const total = groups.length;
8309
9361
  return groups.map((group, index) => {
8310
- const { filename, content, estimatedTokens } = assembleGroup(
8311
- group,
8312
- index,
8313
- total,
8314
- contentFingerprint
8315
- );
9362
+ const { filename, content, estimatedTokens } = assemble(group, index, total);
8316
9363
  const byteSize = Buffer.byteLength(content, "utf8");
8317
9364
  const sha256 = crypto3.createHash("sha256").update(content).digest("hex");
8318
9365
  const layersCovered = Array.from(new Set(group.sections.map((s) => s.file.layer))).sort();
@@ -8529,9 +9576,10 @@ function generateReadme(manifest, artifacts) {
8529
9576
  `- **Schema Version:** \`${manifest.schemaVersion}\``,
8530
9577
  `- **Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""})`,
8531
9578
  `- **Total Tracked Files:** \`${manifest.counts.totalFiles}\``,
8532
- `- **Total Code Lines:** \`${formatNumber(manifest.counts.totalLines)}\``,
8533
- `- **Total Size:** \`${(manifest.counts.totalSizeBytes / (1024 * 1024)).toFixed(2)} MB\``,
8534
- `- **Emitted Content:** \`${(manifest.totals.totalContentBytes / (1024 * 1024)).toFixed(2)} MB\``,
9579
+ `- **Source Lines:** \`${formatNumber(manifest.counts.totalLines)}\``,
9580
+ `- **Emitted Lines:** \`${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)}\``,
9581
+ `- **Total Size:** \`${(manifest.counts.totalSizeBytes / (1024 * 1024)).toFixed(2)} MiB\``,
9582
+ `- **Emitted Content:** \`${(manifest.totals.totalContentBytes / (1024 * 1024)).toFixed(2)} MiB\``,
8535
9583
  `- **Part Count:** \`${manifest.counts.partsCount}\` (budget \`${(manifest.budgets.maxPartBytes / 1024).toFixed(0)} KB\` per part)`,
8536
9584
  `- **Generator:** \`${manifest.generator.name}@${manifest.generator.version}\``,
8537
9585
  "",
@@ -8649,7 +9697,7 @@ function generateProjectTree(filePaths) {
8649
9697
  }
8650
9698
 
8651
9699
  // src/update-check.ts
8652
- import * as fs12 from "fs";
9700
+ import * as fs13 from "fs";
8653
9701
  import * as http from "http";
8654
9702
  import * as https from "https";
8655
9703
  import * as os from "os";
@@ -8724,23 +9772,24 @@ function shouldCheck(argv, env) {
8724
9772
  for (const skip of ["mcp", "describe", "skill", "--version", "-v", "--help", "-h"]) {
8725
9773
  if (args.includes(skip)) return false;
8726
9774
  }
9775
+ let format = null;
8727
9776
  for (let index = 0; index < args.length; index += 1) {
8728
9777
  const argument = args[index];
9778
+ if (argument === "--") break;
8729
9779
  if (argument === "--format") {
8730
- if (args[index + 1] === "json") return false;
8731
- break;
8732
- }
8733
- if (argument.startsWith("--format=")) {
8734
- if (argument.slice("--format=".length) === "json") return false;
8735
- break;
9780
+ format = args[index + 1] ?? null;
9781
+ index += 1;
9782
+ continue;
8736
9783
  }
9784
+ if (argument.startsWith("--format=")) format = argument.slice("--format=".length);
8737
9785
  }
9786
+ if (format === "json") return false;
8738
9787
  return true;
8739
9788
  }
8740
9789
  function readCache(file) {
8741
9790
  let raw;
8742
9791
  try {
8743
- raw = fs12.readFileSync(file, "utf8");
9792
+ raw = fs13.readFileSync(file, "utf8");
8744
9793
  } catch {
8745
9794
  return null;
8746
9795
  }
@@ -8757,21 +9806,21 @@ function readCache(file) {
8757
9806
  }
8758
9807
  function writeCache(file, entry) {
8759
9808
  try {
8760
- fs12.mkdirSync(path13.dirname(file), { recursive: true });
8761
- fs12.writeFileSync(file, `${JSON.stringify(entry)}
9809
+ fs13.mkdirSync(path13.dirname(file), { recursive: true });
9810
+ fs13.writeFileSync(file, `${JSON.stringify(entry)}
8762
9811
  `, "utf8");
8763
9812
  } catch {
8764
9813
  }
8765
9814
  }
8766
9815
  function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOUT_MS) {
8767
- return new Promise((resolve10) => {
9816
+ return new Promise((resolve11) => {
8768
9817
  let settled = false;
8769
9818
  let request = null;
8770
9819
  const finish = (value) => {
8771
9820
  if (settled) return;
8772
9821
  settled = true;
8773
9822
  clearTimeout(deadline);
8774
- resolve10(value);
9823
+ resolve11(value);
8775
9824
  };
8776
9825
  const deadline = setTimeout(() => {
8777
9826
  request?.destroy();
@@ -8849,7 +9898,8 @@ function formatUpdateNotice(notice, kind) {
8849
9898
  }
8850
9899
 
8851
9900
  // src/agent/hook.ts
8852
- import * as fs13 from "fs";
9901
+ import * as childProcess2 from "child_process";
9902
+ import * as fs14 from "fs";
8853
9903
  import * as path14 from "path";
8854
9904
  var HOOK_MARKER = `# ${GENERATOR_NAME}: pre-commit snapshot check`;
8855
9905
  function shellQuote(value) {
@@ -8870,9 +9920,17 @@ set -e
8870
9920
  SNAPSHOT_DIR="${dir}"
8871
9921
 
8872
9922
  if [ ! -f "$SNAPSHOT_DIR/manifest.json" ]; then
8873
- echo "${GENERATOR_NAME}: no snapshot in $SNAPSHOT_DIR, skipping the staleness check." >&2
8874
- echo " Run \\"npx ${GENERATOR_NAME} generate\\" to create one." >&2
8875
- exit 0
9923
+ # Fail closed. A missing snapshot used to exit 0 with a reassuring message, so deleting or
9924
+ # renaming the output directory disabled the gate while every commit still succeeded \u2014 the one
9925
+ # failure mode a commit gate must not have. The opt-out is explicit and documented.
9926
+ if [ "\${CODEBASE_SNAPSHOT_ALLOW_MISSING:-}" = "1" ]; then
9927
+ echo "${GENERATOR_NAME}: no snapshot in $SNAPSHOT_DIR; skipping the check (CODEBASE_SNAPSHOT_ALLOW_MISSING=1)." >&2
9928
+ exit 0
9929
+ fi
9930
+ echo "${GENERATOR_NAME}: refusing the commit: no snapshot in $SNAPSHOT_DIR." >&2
9931
+ echo " Run \\"npx ${GENERATOR_NAME} generate\\", stage it, and commit again." >&2
9932
+ echo " To disable this gate, set CODEBASE_SNAPSHOT_ALLOW_MISSING=1." >&2
9933
+ exit 1
8876
9934
  fi
8877
9935
 
8878
9936
  if ! npx --no-install ${GENERATOR_NAME} validate >/dev/null 2>&1; then
@@ -8887,26 +9945,69 @@ function gitDirectory(cwd) {
8887
9945
  const dotGit = path14.join(cwd, ".git");
8888
9946
  let stats;
8889
9947
  try {
8890
- stats = fs13.statSync(dotGit);
9948
+ stats = fs14.statSync(dotGit);
8891
9949
  } catch {
8892
9950
  return null;
8893
9951
  }
8894
9952
  if (stats.isDirectory()) return dotGit;
8895
9953
  if (!stats.isFile()) return null;
8896
9954
  try {
8897
- const contents = fs13.readFileSync(dotGit, "utf8");
9955
+ const contents = fs14.readFileSync(dotGit, "utf8");
8898
9956
  const match = /^gitdir:\s*(.+)$/m.exec(contents);
8899
9957
  if (!match) return null;
8900
9958
  const target = match[1];
8901
9959
  const resolved = path14.isAbsolute(target.trim()) ? target.trim() : path14.join(cwd, target.trim());
8902
- return fs13.statSync(resolved).isDirectory() ? resolved : null;
9960
+ if (!fs14.statSync(resolved).isDirectory()) return null;
9961
+ if (isInside2(path14.resolve(cwd), path14.resolve(resolved))) return resolved;
9962
+ return isRegisteredWorktree(path14.resolve(resolved), cwd) ? resolved : null;
9963
+ } catch {
9964
+ return null;
9965
+ }
9966
+ }
9967
+ function isInside2(parent, child) {
9968
+ const relative14 = path14.relative(parent, child);
9969
+ return relative14 === "" || !relative14.startsWith("..") && !path14.isAbsolute(relative14);
9970
+ }
9971
+ function isRegisteredWorktree(gitDir, cwd) {
9972
+ try {
9973
+ const back = fs14.readFileSync(path14.join(gitDir, "gitdir"), "utf8").trim();
9974
+ return path14.resolve(gitDir, back) === path14.join(path14.resolve(cwd), ".git");
9975
+ } catch {
9976
+ return false;
9977
+ }
9978
+ }
9979
+ function gitOutput(cwd, args) {
9980
+ try {
9981
+ const output = childProcess2.execFileSync("git", args, {
9982
+ cwd,
9983
+ encoding: "utf8",
9984
+ stdio: ["ignore", "pipe", "ignore"]
9985
+ });
9986
+ const trimmed = output.trim();
9987
+ return trimmed.length > 0 ? trimmed : null;
8903
9988
  } catch {
8904
9989
  return null;
8905
9990
  }
8906
9991
  }
9992
+ function configuredHooksDirectory(cwd) {
9993
+ const hooks = gitOutput(cwd, ["rev-parse", "--git-path", "hooks"]);
9994
+ if (hooks === null) return null;
9995
+ const resolved = path14.resolve(cwd, hooks);
9996
+ const common = gitOutput(cwd, ["rev-parse", "--git-common-dir"]);
9997
+ const commonDir = common === null ? null : path14.resolve(cwd, common);
9998
+ if (isInside2(path14.resolve(cwd), resolved)) return { dir: resolved };
9999
+ if (commonDir !== null && isInside2(commonDir, resolved)) return { dir: resolved };
10000
+ return {
10001
+ 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.`
10002
+ };
10003
+ }
8907
10004
  function installPreCommitHook(cwd, outDir = "snapshot") {
8908
- const gitDir = gitDirectory(cwd);
8909
- if (gitDir === null) {
10005
+ const configured = configuredHooksDirectory(cwd);
10006
+ if (configured !== null && "refusal" in configured) {
10007
+ return { path: null, written: false, notes: [configured.refusal] };
10008
+ }
10009
+ const gitDir = configured === null ? gitDirectory(cwd) : null;
10010
+ if (configured === null && gitDir === null) {
8910
10011
  return {
8911
10012
  path: null,
8912
10013
  written: false,
@@ -8915,10 +10016,10 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
8915
10016
  ]
8916
10017
  };
8917
10018
  }
8918
- const hooksDir = path14.join(gitDir, "hooks");
10019
+ const hooksDir = configured === null ? path14.join(gitDir, "hooks") : configured.dir;
8919
10020
  const hookPath = path14.join(hooksDir, "pre-commit");
8920
10021
  try {
8921
- fs13.mkdirSync(hooksDir, { recursive: true });
10022
+ fs14.mkdirSync(hooksDir, { recursive: true });
8922
10023
  } catch (err) {
8923
10024
  return {
8924
10025
  path: hookPath,
@@ -8928,7 +10029,7 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
8928
10029
  }
8929
10030
  let existing = null;
8930
10031
  try {
8931
- existing = fs13.readFileSync(hookPath, "utf8");
10032
+ existing = fs14.readFileSync(hookPath, "utf8");
8932
10033
  } catch {
8933
10034
  existing = null;
8934
10035
  }
@@ -8943,8 +10044,8 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
8943
10044
  };
8944
10045
  }
8945
10046
  try {
8946
- fs13.writeFileSync(hookPath, hookScript(outDir), "utf8");
8947
- fs13.chmodSync(hookPath, 493);
10047
+ fs14.writeFileSync(hookPath, hookScript(outDir), "utf8");
10048
+ fs14.chmodSync(hookPath, 493);
8948
10049
  } catch (err) {
8949
10050
  return {
8950
10051
  path: hookPath,
@@ -9006,14 +10107,14 @@ const { parentPort, workerData } = require("node:worker_threads");
9006
10107
  })();
9007
10108
  `;
9008
10109
  function generateInWorker(cwd, cliOptions) {
9009
- return new Promise((resolve10) => {
10110
+ return new Promise((resolve11) => {
9010
10111
  let settled = false;
9011
10112
  let worker = null;
9012
10113
  const finish = (result) => {
9013
10114
  if (settled) return;
9014
10115
  settled = true;
9015
10116
  if (worker !== null) void worker.terminate();
9016
- resolve10(result);
10117
+ resolve11(result);
9017
10118
  };
9018
10119
  const isCjs = typeof __dirname !== "undefined";
9019
10120
  const directory = isCjs ? __dirname : path15.dirname(fileURLToPath(import.meta.url));
@@ -9046,7 +10147,6 @@ function generateInWorker(cwd, cliOptions) {
9046
10147
  }
9047
10148
 
9048
10149
  // src/index.ts
9049
- var SCHEMA_VERSION = "3.0.0";
9050
10150
  var SUMMARY_MAX_SOURCE_BYTES2 = SUMMARY_MAX_SOURCE_BYTES;
9051
10151
  var FILE_DERIVATIONS = /* @__PURE__ */ new Map();
9052
10152
  var FILE_DERIVATION_LIMIT_BYTES = 64 * 1024 * 1024;
@@ -9054,12 +10154,21 @@ var fileDerivationBytes = 0;
9054
10154
  function takeDerivation(path22, hash, settings) {
9055
10155
  const cached = FILE_DERIVATIONS.get(path22);
9056
10156
  if (cached === void 0 || cached.hash !== hash || cached.settings !== settings) return void 0;
10157
+ FILE_DERIVATIONS.delete(path22);
10158
+ FILE_DERIVATIONS.set(path22, cached);
9057
10159
  return cached;
9058
10160
  }
9059
10161
  function rememberDerivation(path22, hash, settings, derivation) {
9060
10162
  const bodyBytes = derivation.finalContent === derivation.redacted ? derivation.redacted.length : derivation.redacted.length + derivation.finalContent.length;
9061
10163
  const bytes = bodyBytes * 2 + 512;
9062
10164
  if (bytes > FILE_DERIVATION_LIMIT_BYTES / 4) return;
10165
+ const previous = FILE_DERIVATIONS.get(path22);
10166
+ if (previous !== void 0) {
10167
+ FILE_DERIVATIONS.delete(path22);
10168
+ fileDerivationBytes -= previous.bytes;
10169
+ } else {
10170
+ FILE_DERIVATIONS.delete(path22);
10171
+ }
9063
10172
  while (fileDerivationBytes + bytes > FILE_DERIVATION_LIMIT_BYTES) {
9064
10173
  const oldest = FILE_DERIVATIONS.keys().next();
9065
10174
  if (oldest.done === true) break;
@@ -9080,11 +10189,12 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
9080
10189
  const lineCount = countLines(rawContent);
9081
10190
  const { redacted, findings } = scanAndRedactSecrets(rawContent, config.secretRules, relativePath);
9082
10191
  const isLarge = sizeBytes > config.largeFileBytes;
10192
+ const oversizeForSummary = Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES2;
9083
10193
  let finalContent = redacted;
9084
10194
  let isPreviewTruncated = false;
9085
10195
  let includedLines = lineCount;
9086
10196
  let inclusionMode = "full";
9087
- if (config.skeleton === true && isSkeletonizable(relativePath)) {
10197
+ if (config.skeleton === true && isSkeletonizable(relativePath) && !oversizeForSummary) {
9088
10198
  const skeleton = skeletonizeTypeScript(redacted, relativePath);
9089
10199
  if (skeleton.collapsed > 0) {
9090
10200
  finalContent = skeleton.text;
@@ -9104,7 +10214,7 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
9104
10214
  let summarySkip = null;
9105
10215
  let summaryWarning = null;
9106
10216
  let dependentImports = null;
9107
- if (Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES2) {
10217
+ if (oversizeForSummary) {
9108
10218
  summarySkip = "oversize";
9109
10219
  dependentImports = [];
9110
10220
  } else if (SKIP_PREVIEW_SUMMARIES && isPreviewTruncated && hasStructuralSummary(relativePath)) {
@@ -9192,8 +10302,8 @@ function retain(items, keep) {
9192
10302
  items.length = write;
9193
10303
  }
9194
10304
  var SKIP_PREVIEW_SUMMARIES = true;
9195
- function buildIndexes(files) {
9196
- const resolver = buildImportResolver(files);
10305
+ function buildIndexes(files, tsconfigPaths) {
10306
+ const resolver = buildImportResolver(files, { tsconfig: tsconfigPaths });
9197
10307
  const importerCounts = /* @__PURE__ */ new Map();
9198
10308
  const byFile = files.filter((file) => isSourceSummary(file.summary)).map((file) => {
9199
10309
  const summary = file.summary;
@@ -9336,20 +10446,20 @@ function listEntries(dir) {
9336
10446
  const walk = (absolute, prefix) => {
9337
10447
  let children;
9338
10448
  try {
9339
- children = fs14.readdirSync(absolute, { withFileTypes: true });
10449
+ children = fs15.readdirSync(absolute, { withFileTypes: true });
9340
10450
  } catch {
9341
10451
  return;
9342
10452
  }
9343
10453
  for (const child of children) {
9344
- const relative12 = prefix === "" ? child.name : `${prefix}/${child.name}`;
9345
- entries.push(relative12);
9346
- if (child.isDirectory()) walk(path16.join(absolute, child.name), relative12);
10454
+ const relative14 = prefix === "" ? child.name : `${prefix}/${child.name}`;
10455
+ entries.push(relative14);
10456
+ if (child.isDirectory()) walk(path16.join(absolute, child.name), relative14);
9347
10457
  }
9348
10458
  };
9349
10459
  walk(dir, "");
9350
10460
  return entries.sort();
9351
10461
  }
9352
- function markerInventory(dir) {
10462
+ function markerInventory(dir, written) {
9353
10463
  const entries = listEntries(dir);
9354
10464
  const files = [];
9355
10465
  for (const entry of entries) {
@@ -9358,14 +10468,19 @@ function markerInventory(dir) {
9358
10468
  const full = path16.join(dir, ...entry.split("/"));
9359
10469
  let stats;
9360
10470
  try {
9361
- stats = fs14.lstatSync(full);
10471
+ stats = fs15.lstatSync(full);
9362
10472
  } catch {
9363
10473
  continue;
9364
10474
  }
9365
10475
  if (!stats.isFile()) continue;
10476
+ const recorded = written?.get(entry);
10477
+ if (recorded !== void 0 && recorded.digest.bytes === stats.size && recorded.mtimeMs === stats.mtimeMs) {
10478
+ files.push(recorded.digest);
10479
+ continue;
10480
+ }
9366
10481
  let digest;
9367
10482
  try {
9368
- digest = sha256Hex2(fs14.readFileSync(full));
10483
+ digest = sha256Hex2(fs15.readFileSync(full));
9369
10484
  } catch {
9370
10485
  continue;
9371
10486
  }
@@ -9373,8 +10488,8 @@ function markerInventory(dir) {
9373
10488
  }
9374
10489
  return { entries, files };
9375
10490
  }
9376
- function markerPayload(dir, state, id, createdAt) {
9377
- const { entries, files } = markerInventory(dir);
10491
+ function markerPayload(dir, state, id, createdAt, written) {
10492
+ const { entries, files } = markerInventory(dir, written);
9378
10493
  const marker2 = {
9379
10494
  generator: GENERATOR_NAME,
9380
10495
  version: GENERATOR_VERSION,
@@ -9387,13 +10502,13 @@ function markerPayload(dir, state, id, createdAt) {
9387
10502
  files
9388
10503
  };
9389
10504
  const manifestPath = path16.join(dir, "manifest.json");
9390
- if (fs14.existsSync(manifestPath)) {
9391
- marker2.manifestSha256 = sha256Hex2(fs14.readFileSync(manifestPath));
10505
+ if (fs15.existsSync(manifestPath)) {
10506
+ marker2.manifestSha256 = sha256Hex2(fs15.readFileSync(manifestPath));
9392
10507
  }
9393
10508
  return marker2;
9394
10509
  }
9395
10510
  function writeOwnershipMarker(dir, marker2) {
9396
- fs14.writeFileSync(
10511
+ fs15.writeFileSync(
9397
10512
  path16.join(dir, OWNERSHIP_MARKER),
9398
10513
  `${JSON.stringify(marker2, null, 2)}
9399
10514
  `,
@@ -9407,12 +10522,12 @@ function markerBelongsTo(dir, id) {
9407
10522
  }
9408
10523
  function readOwnershipMarker(dir) {
9409
10524
  const markerPath = path16.join(dir, OWNERSHIP_MARKER);
9410
- if (!fs14.existsSync(markerPath)) {
10525
+ if (!fs15.existsSync(markerPath)) {
9411
10526
  return { marker: null, problem: "it holds no .codebase-snapshot marker" };
9412
10527
  }
9413
10528
  let raw;
9414
10529
  try {
9415
- raw = fs14.readFileSync(markerPath, "utf8");
10530
+ raw = fs15.readFileSync(markerPath, "utf8");
9416
10531
  } catch {
9417
10532
  return { marker: null, problem: "its .codebase-snapshot marker could not be read" };
9418
10533
  }
@@ -9515,7 +10630,7 @@ function verifyMarkerInventory(dir, entries, files) {
9515
10630
  const full = path16.join(dir, ...entry.split("/"));
9516
10631
  let stats;
9517
10632
  try {
9518
- stats = fs14.lstatSync(full);
10633
+ stats = fs15.lstatSync(full);
9519
10634
  } catch {
9520
10635
  return `its .codebase-snapshot inventory lists ${entry}, which cannot be read`;
9521
10636
  }
@@ -9540,7 +10655,7 @@ function verifyMarkerInventory(dir, entries, files) {
9540
10655
  }
9541
10656
  let digest;
9542
10657
  try {
9543
- digest = sha256Hex2(fs14.readFileSync(full));
10658
+ digest = sha256Hex2(fs15.readFileSync(full));
9544
10659
  } catch {
9545
10660
  return `its .codebase-snapshot inventory cannot verify ${entry}: the file could not be read`;
9546
10661
  }
@@ -9562,11 +10677,11 @@ function assessSnapshotDirectory(dir) {
9562
10677
  };
9563
10678
  }
9564
10679
  const manifestPath = path16.join(dir, "manifest.json");
9565
- const hasManifest = fs14.existsSync(manifestPath);
10680
+ const hasManifest = fs15.existsSync(manifestPath);
9566
10681
  if (hasManifest) {
9567
10682
  let raw;
9568
10683
  try {
9569
- raw = fs14.readFileSync(manifestPath, "utf8");
10684
+ raw = fs15.readFileSync(manifestPath, "utf8");
9570
10685
  } catch {
9571
10686
  return {
9572
10687
  owned: false,
@@ -9661,7 +10776,7 @@ function containsNoFiles(dir) {
9661
10776
  const current = pending.pop();
9662
10777
  let entries;
9663
10778
  try {
9664
- entries = fs14.readdirSync(current, { withFileTypes: true });
10779
+ entries = fs15.readdirSync(current, { withFileTypes: true });
9665
10780
  } catch {
9666
10781
  return false;
9667
10782
  }
@@ -9676,13 +10791,13 @@ function containsNoFiles(dir) {
9676
10791
  return true;
9677
10792
  }
9678
10793
  function assertReplaceable(target, label, secretRules) {
9679
- if (!fs14.existsSync(target)) return;
9680
- if (!fs14.statSync(target).isDirectory()) {
10794
+ if (!fs15.existsSync(target)) return;
10795
+ if (!fs15.statSync(target).isDirectory()) {
9681
10796
  throw new Error(
9682
10797
  `Refusing to write into ${label} ${target}: it exists but is not a directory.`
9683
10798
  );
9684
10799
  }
9685
- const entries = fs14.readdirSync(target);
10800
+ const entries = fs15.readdirSync(target);
9686
10801
  if (entries.length === 0) return;
9687
10802
  if (entries.every((name) => IGNORABLE_ENTRIES.has(name))) return;
9688
10803
  if (containsNoFiles(target)) return;
@@ -9702,18 +10817,18 @@ function assertReplaceable(target, label, secretRules) {
9702
10817
  );
9703
10818
  }
9704
10819
  function assertStagingRootUsable(tmpDir, secretRules) {
9705
- if (!fs14.existsSync(tmpDir)) return;
9706
- if (!fs14.statSync(tmpDir).isDirectory()) {
10820
+ if (!fs15.existsSync(tmpDir)) return;
10821
+ if (!fs15.statSync(tmpDir).isDirectory()) {
9707
10822
  throw new Error(`Refusing to write into tmpDir ${tmpDir}: it exists but is not a directory.`);
9708
10823
  }
9709
- const entries = fs14.readdirSync(tmpDir);
10824
+ const entries = fs15.readdirSync(tmpDir);
9710
10825
  if (entries.length === 0) return;
9711
10826
  const foreign = entries.filter((name) => {
9712
10827
  const full = path16.join(tmpDir, name);
9713
10828
  if (!name.startsWith(RUN_DIR_PREFIX)) return true;
9714
10829
  let stats;
9715
10830
  try {
9716
- stats = fs14.statSync(full);
10831
+ stats = fs15.statSync(full);
9717
10832
  } catch {
9718
10833
  return true;
9719
10834
  }
@@ -9721,7 +10836,7 @@ function assertStagingRootUsable(tmpDir, secretRules) {
9721
10836
  const { marker: marker2 } = readOwnershipMarker(full);
9722
10837
  if (marker2) return false;
9723
10838
  try {
9724
- return fs14.readdirSync(full).length > 0;
10839
+ return fs15.readdirSync(full).length > 0;
9725
10840
  } catch {
9726
10841
  return true;
9727
10842
  }
@@ -9736,7 +10851,7 @@ function assertStagingRootUsable(tmpDir, secretRules) {
9736
10851
  function cleanStaleRunDirs(tmpDir) {
9737
10852
  let entries;
9738
10853
  try {
9739
- entries = fs14.readdirSync(tmpDir);
10854
+ entries = fs15.readdirSync(tmpDir);
9740
10855
  } catch {
9741
10856
  return;
9742
10857
  }
@@ -9750,58 +10865,101 @@ function cleanStaleRunDirs(tmpDir) {
9750
10865
  const abandoned = typeof marker2.pid === "number" && !isProcessAlive(marker2.pid);
9751
10866
  if (aged || abandoned) {
9752
10867
  try {
9753
- fs14.rmSync(full, { recursive: true, force: true });
10868
+ fs15.rmSync(full, { recursive: true, force: true });
9754
10869
  } catch {
9755
10870
  }
9756
10871
  }
9757
10872
  continue;
9758
10873
  }
9759
10874
  try {
9760
- if (fs14.readdirSync(full).length === 0) fs14.rmSync(full, { recursive: true, force: true });
10875
+ if (fs15.readdirSync(full).length === 0) fs15.rmSync(full, { recursive: true, force: true });
9761
10876
  } catch {
9762
10877
  }
9763
10878
  }
9764
10879
  }
9765
10880
  function removeIfEmpty(dir) {
9766
10881
  try {
9767
- if (fs14.readdirSync(dir).length === 0) fs14.rmSync(dir, { recursive: true, force: true });
10882
+ if (fs15.readdirSync(dir).length === 0) fs15.rmSync(dir, { recursive: true, force: true });
9768
10883
  } catch {
9769
10884
  }
9770
10885
  }
9771
10886
  function ensureParentDirectory(target, label) {
9772
10887
  const parent = path16.dirname(target);
9773
- if (fs14.existsSync(parent) && !fs14.statSync(parent).isDirectory()) {
10888
+ if (fs15.existsSync(parent) && !fs15.statSync(parent).isDirectory()) {
9774
10889
  throw new Error(
9775
10890
  `Refusing to create ${label} ${target}: ${parent} exists but is not a directory.`
9776
10891
  );
9777
10892
  }
9778
10893
  try {
9779
- fs14.mkdirSync(parent, { recursive: true });
10894
+ fs15.mkdirSync(parent, { recursive: true });
9780
10895
  } catch (err) {
9781
10896
  throw new Error(
9782
10897
  `Refusing to create ${label} ${target}: its parent ${parent} could not be created (${err.message}).`
9783
10898
  );
9784
10899
  }
9785
10900
  }
10901
+ var LOCK_HEARTBEAT_MS = 5e3;
10902
+ var LOCK_STALE_HEARTBEAT_MS = 12e4;
10903
+ var LOCK_HEARTBEAT_SOURCE = `
10904
+ const { parentPort, workerData } = require("node:worker_threads");
10905
+ const fs = require("node:fs");
10906
+ const { lockPath, intervalMs } = workerData;
10907
+ const timer = setInterval(() => {
10908
+ try {
10909
+ const now = new Date();
10910
+ fs.utimesSync(lockPath, now, now);
10911
+ } catch (err) {
10912
+ // The lock was reclaimed or removed; nothing left to keep alive.
10913
+ }
10914
+ }, intervalMs);
10915
+ timer.unref();
10916
+ if (parentPort) {
10917
+ parentPort.on("message", (message) => {
10918
+ if (message === "stop") {
10919
+ clearInterval(timer);
10920
+ process.exit(0);
10921
+ }
10922
+ });
10923
+ }
10924
+ `;
10925
+ function startLockHeartbeat(lockPath) {
10926
+ try {
10927
+ const worker = new Worker2(LOCK_HEARTBEAT_SOURCE, {
10928
+ eval: true,
10929
+ workerData: { lockPath, intervalMs: LOCK_HEARTBEAT_MS }
10930
+ });
10931
+ worker.unref();
10932
+ return () => {
10933
+ void worker.terminate().catch(() => void 0);
10934
+ };
10935
+ } catch {
10936
+ return () => void 0;
10937
+ }
10938
+ }
9786
10939
  function acquireRunLock(stagingRoot) {
9787
10940
  const lockPath = lockPathFor(stagingRoot);
9788
10941
  const payload = `${JSON.stringify({
9789
10942
  pid: process.pid,
9790
10943
  stagingRoot,
10944
+ host: os2.hostname(),
10945
+ runId: crypto4.randomUUID(),
10946
+ heartbeatMs: LOCK_HEARTBEAT_MS,
9791
10947
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
9792
10948
  })}
9793
10949
  `;
9794
10950
  for (let attempt = 0; attempt < 2; attempt += 1) {
9795
10951
  try {
9796
- const handle = fs14.openSync(lockPath, "wx");
10952
+ const handle = fs15.openSync(lockPath, "wx");
9797
10953
  try {
9798
- fs14.writeSync(handle, payload);
10954
+ fs15.writeSync(handle, payload);
9799
10955
  } finally {
9800
- fs14.closeSync(handle);
10956
+ fs15.closeSync(handle);
9801
10957
  }
10958
+ const stopHeartbeat = startLockHeartbeat(lockPath);
9802
10959
  return () => {
10960
+ stopHeartbeat();
9803
10961
  try {
9804
- fs14.rmSync(lockPath, { force: true });
10962
+ fs15.rmSync(lockPath, { force: true });
9805
10963
  } catch {
9806
10964
  }
9807
10965
  };
@@ -9809,7 +10967,7 @@ function acquireRunLock(stagingRoot) {
9809
10967
  if (err.code !== "EEXIST") throw err;
9810
10968
  if (attempt === 0 && reclaimStaleLock(lockPath)) continue;
9811
10969
  throw new Error(
9812
- `Another generate run is already using the staging directory ${stagingRoot}. Wait for it to finish, or delete ${lockPath} if no other run is active.`
10970
+ `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.`
9813
10971
  );
9814
10972
  }
9815
10973
  }
@@ -9826,7 +10984,7 @@ function canonicalLockTarget(targetPath2) {
9826
10984
  const tail = [];
9827
10985
  for (; ; ) {
9828
10986
  try {
9829
- return path16.join(fs14.realpathSync(existing), ...tail);
10987
+ return path16.join(fs15.realpathSync(existing), ...tail);
9830
10988
  } catch {
9831
10989
  const parent = path16.dirname(existing);
9832
10990
  if (parent === existing) return resolved;
@@ -9838,10 +10996,17 @@ function canonicalLockTarget(targetPath2) {
9838
10996
  function lockPathFor(stagingRoot) {
9839
10997
  return path16.join(os2.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
9840
10998
  }
10999
+ function lockHeartbeatAgeMs(lockPath) {
11000
+ try {
11001
+ return Date.now() - fs15.statSync(lockPath).mtimeMs;
11002
+ } catch {
11003
+ return Number.POSITIVE_INFINITY;
11004
+ }
11005
+ }
9841
11006
  function lockOwnerIsGone(lockPath) {
9842
11007
  let raw;
9843
11008
  try {
9844
- raw = fs14.readFileSync(lockPath, "utf8");
11009
+ raw = fs15.readFileSync(lockPath, "utf8");
9845
11010
  } catch {
9846
11011
  return false;
9847
11012
  }
@@ -9854,96 +11019,120 @@ function lockOwnerIsGone(lockPath) {
9854
11019
  if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return lockFileIsAncient(lockPath);
9855
11020
  try {
9856
11021
  process.kill(pid, 0);
9857
- return false;
11022
+ return lockFileIsAncient(lockPath);
9858
11023
  } catch (err) {
9859
- return err.code === "ESRCH";
11024
+ if (err.code !== "ESRCH") return lockFileIsAncient(lockPath);
11025
+ return true;
9860
11026
  }
9861
11027
  }
9862
11028
  function reclaimStaleLock(lockPath) {
9863
11029
  let before;
9864
11030
  try {
9865
- before = fs14.statSync(lockPath);
11031
+ before = fs15.statSync(lockPath);
9866
11032
  } catch {
9867
11033
  return true;
9868
11034
  }
9869
11035
  if (!lockOwnerIsGone(lockPath)) return false;
9870
11036
  try {
9871
- const current = fs14.statSync(lockPath);
11037
+ const current = fs15.statSync(lockPath);
9872
11038
  const sameFile = current.ino === before.ino && current.birthtimeMs === before.birthtimeMs && current.mtimeMs === before.mtimeMs;
9873
11039
  if (!sameFile) return false;
9874
- fs14.rmSync(lockPath, { force: true });
11040
+ fs15.rmSync(lockPath, { force: true });
9875
11041
  return true;
9876
11042
  } catch {
9877
11043
  return false;
9878
11044
  }
9879
11045
  }
9880
11046
  function lockFileIsAncient(lockPath) {
9881
- try {
9882
- return Date.now() - fs14.statSync(lockPath).mtimeMs > STALE_RUN_MS;
9883
- } catch {
9884
- return false;
9885
- }
11047
+ return lockHeartbeatAgeMs(lockPath) > LOCK_STALE_HEARTBEAT_MS;
9886
11048
  }
9887
11049
  function writeManifestAtomically(manifestPath, manifest) {
9888
11050
  const tempPath = `${manifestPath}.${process.pid}.tmp`;
9889
- fs14.writeFileSync(tempPath, JSON.stringify(manifest, null, 2), "utf8");
11051
+ fs15.writeFileSync(tempPath, JSON.stringify(manifest, null, 2), "utf8");
9890
11052
  try {
9891
- fs14.renameSync(tempPath, manifestPath);
11053
+ fs15.renameSync(tempPath, manifestPath);
9892
11054
  } catch (err) {
9893
11055
  try {
9894
- fs14.rmSync(tempPath, { force: true });
11056
+ fs15.rmSync(tempPath, { force: true });
9895
11057
  } catch {
9896
11058
  }
9897
11059
  throw err;
9898
11060
  }
9899
11061
  }
9900
- function swapIntoPlace(stagingDir, outDir) {
11062
+ function swapIntoPlace(stagingDir, outDir, beforeSwap) {
9901
11063
  ensureParentDirectory(outDir, "outDir");
9902
11064
  const deadline = Date.now() + 3e3;
9903
- for (let attempt = 0; ; attempt += 1) {
11065
+ let delay = 25;
11066
+ for (; ; ) {
9904
11067
  try {
9905
- swapOnce(stagingDir, outDir);
11068
+ swapOnce(stagingDir, outDir, beforeSwap);
9906
11069
  return;
9907
11070
  } catch (err) {
9908
11071
  const code = err.code;
9909
- const racy = code === "ENOENT" || code === "ENOTEMPTY" || code === "EEXIST" || code === "EPERM";
9910
- if (!racy || attempt >= 10 || Date.now() > deadline) throw err;
9911
- sleepSync(50);
11072
+ const retryable = code === "ENOENT" || code === "ENOTEMPTY" || code === "EEXIST" || code === "EPERM";
11073
+ const remaining = deadline - Date.now();
11074
+ if (!retryable || remaining <= 0) throw err;
11075
+ sleepSync(Math.min(delay, remaining));
11076
+ delay = Math.min(delay * 2, 400);
9912
11077
  }
9913
11078
  }
9914
11079
  }
9915
- function swapOnce(stagingDir, outDir) {
11080
+ function recoverInterruptedPublish(outDir) {
11081
+ if (fs15.existsSync(outDir)) return;
11082
+ const parent = path16.dirname(outDir);
11083
+ const base = path16.basename(outDir);
11084
+ let backups;
11085
+ try {
11086
+ backups = fs15.readdirSync(parent).filter((name) => name.startsWith(`${base}.backup-`));
11087
+ } catch {
11088
+ return;
11089
+ }
11090
+ if (backups.length !== 1) return;
11091
+ const backupDir = path16.join(parent, backups[0]);
11092
+ const { marker: marker2, problem } = readOwnershipMarker(backupDir);
11093
+ if (problem !== null || marker2 === null || marker2.state !== "complete") return;
11094
+ try {
11095
+ fs15.renameSync(backupDir, outDir);
11096
+ process.stderr.write(
11097
+ `\u26A0 Recovered ${outDir} from ${backupDir}, left by an interrupted run. That snapshot is the one from before the interrupted run.
11098
+ `
11099
+ );
11100
+ } catch {
11101
+ }
11102
+ }
11103
+ function swapOnce(stagingDir, outDir, beforeSwap) {
9916
11104
  const backupDir = `${outDir}.backup-${process.pid}-${Date.now()}`;
9917
- const hadPrevious = fs14.existsSync(outDir);
9918
- if (hadPrevious) fs14.renameSync(outDir, backupDir);
11105
+ const hadPrevious = fs15.existsSync(outDir);
11106
+ if (hadPrevious) beforeSwap?.();
11107
+ if (hadPrevious) fs15.renameSync(outDir, backupDir);
9919
11108
  try {
9920
11109
  try {
9921
- fs14.renameSync(stagingDir, outDir);
11110
+ fs15.renameSync(stagingDir, outDir);
9922
11111
  } catch (err) {
9923
11112
  if (err.code !== "EXDEV") throw err;
9924
11113
  const partialDir = `${outDir}.partial-${process.pid}-${Date.now()}`;
9925
11114
  try {
9926
- fs14.cpSync(stagingDir, partialDir, { recursive: true });
9927
- fs14.renameSync(partialDir, outDir);
9928
- fs14.rmSync(stagingDir, { recursive: true, force: true });
11115
+ fs15.cpSync(stagingDir, partialDir, { recursive: true });
11116
+ fs15.renameSync(partialDir, outDir);
11117
+ fs15.rmSync(stagingDir, { recursive: true, force: true });
9929
11118
  } catch (copyErr) {
9930
11119
  try {
9931
- fs14.rmSync(partialDir, { recursive: true, force: true });
11120
+ fs15.rmSync(partialDir, { recursive: true, force: true });
9932
11121
  } catch {
9933
11122
  }
9934
11123
  throw copyErr;
9935
11124
  }
9936
11125
  }
9937
11126
  } catch (err) {
9938
- if (hadPrevious && fs14.existsSync(backupDir)) {
9939
- if (fs14.existsSync(outDir)) fs14.rmSync(outDir, { recursive: true, force: true });
9940
- fs14.renameSync(backupDir, outDir);
11127
+ if (hadPrevious && fs15.existsSync(backupDir)) {
11128
+ if (fs15.existsSync(outDir)) fs15.rmSync(outDir, { recursive: true, force: true });
11129
+ fs15.renameSync(backupDir, outDir);
9941
11130
  }
9942
11131
  throw err;
9943
11132
  }
9944
11133
  if (hadPrevious) {
9945
11134
  try {
9946
- fs14.rmSync(backupDir, { recursive: true, force: true });
11135
+ fs15.rmSync(backupDir, { recursive: true, force: true });
9947
11136
  } catch (err) {
9948
11137
  process.stderr.write(
9949
11138
  `\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.
@@ -10020,6 +11209,13 @@ function generateSnapshot(configInput, options) {
10020
11209
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput ?? null);
10021
11210
  const dryRun = options?.dryRun ?? false;
10022
11211
  const gitInfo = getGitInfo(config.cwd, config.branch);
11212
+ const changedScope = config.changedSince !== void 0 || config.staged === true ? resolveChangedScope(config.cwd, {
11213
+ ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
11214
+ ...config.staged === true ? { staged: true } : {}
11215
+ }) : null;
11216
+ const changedPaths = changedScope === null ? null : new Set(changedScope.paths);
11217
+ const stagedPaths = changedScope?.stagedPaths ?? /* @__PURE__ */ new Set();
11218
+ const stagedDeletedPaths = changedScope?.deletedPaths ?? /* @__PURE__ */ new Set();
10023
11219
  const collection = collectFiles(config.cwd, {
10024
11220
  includePatterns: config.include,
10025
11221
  excludePatterns: [...config.excludePatterns, ...config.presetExclude],
@@ -10031,13 +11227,11 @@ function generateSnapshot(configInput, options) {
10031
11227
  // output — but only at these exact paths, not at every directory that shares the name.
10032
11228
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
10033
11229
  (directory) => path16.relative(config.cwd, path16.resolve(config.cwd, directory)).replace(/\\/g, "/")
10034
- ).filter((relative12) => relative12.length > 0 && !relative12.startsWith(".."))
11230
+ ).filter((relative14) => relative14.length > 0 && !relative14.startsWith("..")),
11231
+ // A staged path can be absent from the working tree while its index blob exists. Discovery
11232
+ // lists the working tree, so those paths would never reach the scan at all.
11233
+ ...stagedPaths.size > 0 ? { extraPaths: [...stagedPaths] } : {}
10035
11234
  });
10036
- const changedScope = config.changedSince !== void 0 || config.staged === true ? resolveChangedScope(config.cwd, {
10037
- ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
10038
- ...config.staged === true ? { staged: true } : {}
10039
- }) : null;
10040
- const changedPaths = changedScope === null ? null : new Set(changedScope.paths);
10041
11235
  const unchangedPaths = [];
10042
11236
  const candidateFiles = changedPaths !== null && config.withDependents !== true ? collection.files.filter((relativePath) => {
10043
11237
  if (changedPaths.has(relativePath)) return true;
@@ -10059,45 +11253,92 @@ function generateSnapshot(configInput, options) {
10059
11253
  const oversizeSummaryPaths = [];
10060
11254
  const previewSummaryPaths = [];
10061
11255
  const skippedSummaryImports = /* @__PURE__ */ new Map();
10062
- const layerCounts = {};
10063
- const kindCounts = {};
11256
+ const layerCounts = /* @__PURE__ */ Object.create(null);
11257
+ const kindCounts = /* @__PURE__ */ Object.create(null);
10064
11258
  let totalLines = 0;
10065
11259
  let totalSizeBytes = 0;
10066
11260
  let largeFileCount = 0;
10067
11261
  for (const relativePath of candidateFiles) {
10068
11262
  const absolutePath = path16.join(config.cwd, relativePath);
10069
- let stats;
10070
- try {
10071
- stats = fs14.statSync(absolutePath);
10072
- if (!stats.isFile()) {
10073
- const nestedRepository = stats.isDirectory() && fs14.existsSync(path16.join(absolutePath, ".git"));
10074
- skipped.push(
10075
- nestedRepository ? {
11263
+ const fromIndex = stagedPaths.has(relativePath);
11264
+ let buffer;
11265
+ let sizeBytes;
11266
+ if (fromIndex && stagedDeletedPaths.has(relativePath)) {
11267
+ skipped.push({
11268
+ path: relativePath,
11269
+ reason: "deleted",
11270
+ detail: "staged for deletion; it is not part of the next commit"
11271
+ });
11272
+ continue;
11273
+ }
11274
+ if (fromIndex) {
11275
+ const staged = readStagedBlob(config.cwd, relativePath);
11276
+ if (staged === null) {
11277
+ skipped.push({
11278
+ path: relativePath,
11279
+ reason: "deleted",
11280
+ detail: "staged path has no blob in the index; it is not part of the next commit"
11281
+ });
11282
+ continue;
11283
+ }
11284
+ if (isBinaryExtension(absolutePath)) {
11285
+ skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${staged.length} B` });
11286
+ continue;
11287
+ }
11288
+ buffer = staged;
11289
+ sizeBytes = staged.length;
11290
+ } else {
11291
+ let stats;
11292
+ try {
11293
+ stats = fs15.statSync(absolutePath);
11294
+ if (!stats.isFile()) {
11295
+ const nestedRepository = stats.isDirectory() && fs15.existsSync(path16.join(absolutePath, ".git"));
11296
+ skipped.push(
11297
+ nestedRepository ? {
11298
+ path: relativePath,
11299
+ reason: "nested-repository",
11300
+ detail: "a directory belonging to another repository (nested checkout or submodule); its contents are not scanned"
11301
+ } : { path: relativePath, reason: "not-file" }
11302
+ );
11303
+ continue;
11304
+ }
11305
+ } catch (err) {
11306
+ const code = err.code;
11307
+ if (code === "ENOENT" || code === "ENOTDIR") {
11308
+ skipped.push({
10076
11309
  path: relativePath,
10077
- reason: "nested-repository",
10078
- detail: "a directory belonging to another repository (nested checkout or submodule); its contents are not scanned"
10079
- } : { path: relativePath, reason: "not-file" }
10080
- );
11310
+ reason: "missing",
11311
+ detail: "tracked but absent from disk (deleted without staging)"
11312
+ });
11313
+ } else {
11314
+ skipped.push({
11315
+ path: relativePath,
11316
+ reason: "read-error",
11317
+ detail: String(err.message).replace(/\s+/g, " ")
11318
+ });
11319
+ }
10081
11320
  continue;
10082
11321
  }
10083
- } catch {
10084
- skipped.push({ path: relativePath, reason: "read-error" });
10085
- continue;
10086
- }
10087
- if (isBinaryExtension(absolutePath)) {
10088
- skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${stats.size} B` });
10089
- continue;
10090
- }
10091
- if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) {
10092
- skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${stats.size} B` });
10093
- continue;
10094
- }
10095
- let buffer;
10096
- try {
10097
- buffer = fs14.readFileSync(absolutePath);
10098
- } catch {
10099
- skipped.push({ path: relativePath, reason: "read-error" });
10100
- continue;
11322
+ if (isBinaryExtension(absolutePath)) {
11323
+ skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${stats.size} B` });
11324
+ continue;
11325
+ }
11326
+ if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) {
11327
+ skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${stats.size} B` });
11328
+ continue;
11329
+ }
11330
+ try {
11331
+ buffer = fs15.readFileSync(absolutePath);
11332
+ } catch (err) {
11333
+ const code = err.code;
11334
+ skipped.push({
11335
+ path: relativePath,
11336
+ reason: code === "ENOENT" || code === "ENOTDIR" ? "missing" : "read-error",
11337
+ detail: String(err.message).replace(/\s+/g, " ")
11338
+ });
11339
+ continue;
11340
+ }
11341
+ sizeBytes = stats.size;
10101
11342
  }
10102
11343
  let decoded;
10103
11344
  try {
@@ -10106,7 +11347,7 @@ function generateSnapshot(configInput, options) {
10106
11347
  skipped.push({
10107
11348
  path: relativePath,
10108
11349
  reason: "read-error",
10109
- detail: `Size: ${stats.size} B; could not be decoded: ${err.message}`.replace(
11350
+ detail: `Size: ${sizeBytes} B; could not be decoded: ${err.message}`.replace(
10110
11351
  /\s+/g,
10111
11352
  " "
10112
11353
  )
@@ -10117,13 +11358,13 @@ function generateSnapshot(configInput, options) {
10117
11358
  skipped.push({
10118
11359
  path: relativePath,
10119
11360
  reason: "binary",
10120
- detail: `Size: ${stats.size} B; ${decoded.binaryReason ?? "binary content"}`
11361
+ detail: `Size: ${sizeBytes} B; ${decoded.binaryReason ?? "binary content"}`
10121
11362
  });
10122
11363
  continue;
10123
11364
  }
10124
11365
  const hashSha256 = sha256Hex2(buffer);
10125
11366
  const rawContent = decoded.text;
10126
- totalSizeBytes += stats.size;
11367
+ totalSizeBytes += sizeBytes;
10127
11368
  if (decoded.encoding !== "utf-8") {
10128
11369
  encodingNotes.push({
10129
11370
  path: relativePath,
@@ -10137,7 +11378,7 @@ function generateSnapshot(configInput, options) {
10137
11378
  bump(layerCounts, layer2);
10138
11379
  bump(kindCounts, kind);
10139
11380
  const derivation = takeDerivation(absolutePath, hashSha256, derivationKey) ?? (() => {
10140
- const fresh = deriveFile(relativePath, rawContent, stats.size, config);
11381
+ const fresh = deriveFile(relativePath, rawContent, sizeBytes, config);
10141
11382
  rememberDerivation(absolutePath, hashSha256, derivationKey, fresh);
10142
11383
  return fresh;
10143
11384
  })();
@@ -10158,7 +11399,7 @@ function generateSnapshot(configInput, options) {
10158
11399
  }
10159
11400
  files.push({
10160
11401
  relativePath,
10161
- sizeBytes: stats.size,
11402
+ sizeBytes,
10162
11403
  lines: lineCount,
10163
11404
  hashSha256,
10164
11405
  part: "",
@@ -10179,7 +11420,10 @@ function generateSnapshot(configInput, options) {
10179
11420
  }
10180
11421
  if (changedScope !== null && changedPaths !== null && config.withDependents === true) {
10181
11422
  const keep = new Set(changedPaths);
10182
- const resolver = buildImportResolver(files);
11423
+ const resolver = buildImportResolver(files, {
11424
+ extraPaths: changedPaths,
11425
+ tsconfig: tsconfigPathsFor(config.cwd)
11426
+ });
10183
11427
  for (const file of files) {
10184
11428
  const fileImports = isSourceSummary(file.summary) ? file.summary.imports : skippedSummaryImports.get(file.relativePath) ?? [];
10185
11429
  if (fileImports.length === 0) continue;
@@ -10273,7 +11517,7 @@ function generateSnapshot(configInput, options) {
10273
11517
  const fingerprint = sha256Hex2(
10274
11518
  [
10275
11519
  ...files.map(
10276
- (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
11520
+ (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}`
10277
11521
  ),
10278
11522
  `settings:${configDigest(config)}`
10279
11523
  ].join("\n")
@@ -10360,6 +11604,8 @@ function generateSnapshot(configInput, options) {
10360
11604
  skippedFiles: skipped.length,
10361
11605
  totalSourceBytes: totalSizeBytes,
10362
11606
  totalContentBytes,
11607
+ sourceLines: totalLines,
11608
+ emittedLines: files.reduce((total, file) => total + file.includedLines, 0),
10363
11609
  // The parts are what a model is handed, so the estimate is over the parts rather than
10364
11610
  // over the sources: previews and the byte budget both shrink the number.
10365
11611
  estimatedTokens: parts.reduce((total, part) => total + part.metadata.estimatedTokens, 0),
@@ -10378,7 +11624,7 @@ function generateSnapshot(configInput, options) {
10378
11624
  },
10379
11625
  layers: layerCounts,
10380
11626
  kinds: kindCounts,
10381
- indexes: buildIndexes(files),
11627
+ indexes: buildIndexes(files, tsconfigPathsFor(config.cwd)),
10382
11628
  parts: parts.map((part) => part.metadata),
10383
11629
  files: files.map((file) => {
10384
11630
  const { content: _content, ...rest } = file;
@@ -10395,6 +11641,23 @@ function generateSnapshot(configInput, options) {
10395
11641
  );
10396
11642
  manifest.totals.warningCount = manifest.warnings.length;
10397
11643
  }
11644
+ if (files.some((file) => file.isPreviewTruncated) && config.largeFileBytes <= config.maxPartBytes) {
11645
+ manifest.warnings.push(
11646
+ `${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.`
11647
+ );
11648
+ manifest.totals.warningCount = manifest.warnings.length;
11649
+ }
11650
+ if (config.maxPartTokens !== void 0) {
11651
+ const overTokenBudget = parts.filter(
11652
+ (part) => part.metadata.estimatedTokens > (config.maxPartTokens ?? 0)
11653
+ );
11654
+ if (overTokenBudget.length > 0) {
11655
+ manifest.warnings.push(
11656
+ `${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.`
11657
+ );
11658
+ manifest.totals.warningCount = manifest.warnings.length;
11659
+ }
11660
+ }
10398
11661
  if (secretFindings.length > 0 && !config.artifacts.audit) {
10399
11662
  manifest.warnings.push(
10400
11663
  `${secretFindings.length} line(s) contain redacted values; reports/audit.md is disabled, so the per-line detail was not written.`
@@ -10423,6 +11686,18 @@ function generateSnapshot(configInput, options) {
10423
11686
  sha256: sha256Hex2(sarifText)
10424
11687
  };
10425
11688
  }
11689
+ const artifacts = config.artifacts;
11690
+ const artifactRecord = (text2) => ({
11691
+ byteSize: Buffer.byteLength(text2, "utf8"),
11692
+ sha256: sha256Hex2(text2)
11693
+ });
11694
+ const navigationText = artifacts.navigation ? generateNavigation(manifest) : null;
11695
+ if (navigationText !== null) manifest.artifacts.navigation = artifactRecord(navigationText);
11696
+ const auditText = artifacts.audit ? generateAuditReport(manifest, secretFindings, config.secretRules) : null;
11697
+ if (auditText !== null) manifest.artifacts.audit = artifactRecord(auditText);
11698
+ const readmeText = artifacts.readme ? generateReadme(manifest, artifacts) : null;
11699
+ if (readmeText !== null) manifest.artifacts.readme = artifactRecord(readmeText);
11700
+ if (projectTree !== null) manifest.artifacts.projectTree = artifactRecord(projectTree);
10426
11701
  let monolithJson = null;
10427
11702
  let monolithMarkdown = null;
10428
11703
  if (config.includeMonolith) {
@@ -10437,26 +11712,33 @@ function generateSnapshot(configInput, options) {
10437
11712
  includedLines: countLines(content)
10438
11713
  };
10439
11714
  });
10440
- const markdown = generateMonolithMarkdown(manifest, fullFiles);
10441
- const markdownBytes = Buffer.byteLength(markdown, "utf8");
10442
- if (!config.maxMonolithBytes || markdownBytes <= config.maxMonolithBytes) {
11715
+ const bodyBytes = fullFiles.reduce((total, file) => total + file.includedBytes, 0);
11716
+ const definitelyTooLarge = config.maxMonolithBytes !== null && bodyBytes > config.maxMonolithBytes;
11717
+ if (definitelyTooLarge) {
11718
+ const reason = `their bodies total ${bodyBytes} B, which already exceeds maxMonolithBytes ${config.maxMonolithBytes ?? 0} B`;
11719
+ manifest.warnings.push(`full-codebase.md skipped: ${reason}`);
11720
+ manifest.warnings.push(`full-codebase.json skipped: ${reason}`);
11721
+ }
11722
+ const markdown = definitelyTooLarge ? null : generateMonolithMarkdown(manifest, fullFiles);
11723
+ const markdownBytes = markdown === null ? 0 : Buffer.byteLength(markdown, "utf8");
11724
+ if (markdown !== null && (!config.maxMonolithBytes || markdownBytes <= config.maxMonolithBytes)) {
10443
11725
  monolithMarkdown = markdown;
10444
11726
  manifest.artifacts.fullMarkdown = {
10445
11727
  byteSize: markdownBytes,
10446
11728
  sha256: sha256Hex2(markdown)
10447
11729
  };
10448
- } else {
11730
+ } else if (!definitelyTooLarge) {
10449
11731
  manifest.warnings.push(
10450
11732
  `full-codebase.md skipped: ${markdownBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
10451
11733
  );
10452
11734
  }
10453
11735
  manifest.totals.warningCount = manifest.warnings.length;
10454
- const json = generateMonolithJson(manifest, fullFiles);
10455
- const jsonBytes = Buffer.byteLength(json, "utf8");
10456
- if (!config.maxMonolithBytes || jsonBytes <= config.maxMonolithBytes) {
11736
+ const json = definitelyTooLarge ? null : generateMonolithJson(manifest, fullFiles);
11737
+ const jsonBytes = json === null ? 0 : Buffer.byteLength(json, "utf8");
11738
+ if (json !== null && (!config.maxMonolithBytes || jsonBytes <= config.maxMonolithBytes)) {
10457
11739
  monolithJson = json;
10458
11740
  manifest.artifacts.fullJson = { byteSize: jsonBytes, sha256: sha256Hex2(json) };
10459
- } else {
11741
+ } else if (!definitelyTooLarge) {
10460
11742
  manifest.warnings.push(
10461
11743
  `full-codebase.json skipped: ${jsonBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
10462
11744
  );
@@ -10464,26 +11746,34 @@ function generateSnapshot(configInput, options) {
10464
11746
  manifest.totals.warningCount = manifest.warnings.length;
10465
11747
  }
10466
11748
  const { outDir, tmpDir } = resolveSafeOutputDirs(config);
10467
- const { artifacts } = config;
10468
11749
  assertReplaceable(outDir, "outDir", config.secretRules);
10469
11750
  assertStagingRootUsable(tmpDir, config.secretRules);
10470
11751
  if (dryRun) {
10471
11752
  return manifest;
10472
11753
  }
10473
11754
  const lockKeys = Array.from(/* @__PURE__ */ new Set([tmpDir, outDir])).sort();
10474
- const releases = lockKeys.map((key) => acquireRunLock(key));
11755
+ const releases = [];
11756
+ try {
11757
+ for (const key of lockKeys) releases.push(acquireRunLock(key));
11758
+ } catch (error) {
11759
+ for (const release of [...releases].reverse()) release();
11760
+ throw error;
11761
+ }
10475
11762
  const releaseLock = () => {
10476
11763
  for (const release of [...releases].reverse()) release();
10477
11764
  };
11765
+ recoverInterruptedPublish(outDir);
11766
+ assertReplaceable(outDir, "outDir", config.secretRules);
10478
11767
  let stagingDir = null;
11768
+ let releaseDeferred = false;
10479
11769
  try {
10480
11770
  ensureParentDirectory(outDir, "outDir");
10481
- fs14.mkdirSync(tmpDir, { recursive: true });
11771
+ fs15.mkdirSync(tmpDir, { recursive: true });
10482
11772
  cleanStaleRunDirs(tmpDir);
10483
11773
  const snapshotId = crypto4.randomUUID();
10484
11774
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
10485
11775
  stagingDir = path16.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
10486
- fs14.mkdirSync(stagingDir);
11776
+ fs15.mkdirSync(stagingDir);
10487
11777
  writeOwnershipMarker(stagingDir, {
10488
11778
  generator: GENERATOR_NAME,
10489
11779
  version: GENERATOR_VERSION,
@@ -10495,45 +11785,66 @@ function generateSnapshot(configInput, options) {
10495
11785
  });
10496
11786
  const partsDir = path16.join(stagingDir, "parts");
10497
11787
  const reportsDir = path16.join(stagingDir, "reports");
10498
- if (artifacts.parts) fs14.mkdirSync(partsDir, { recursive: true });
11788
+ if (artifacts.parts) fs15.mkdirSync(partsDir, { recursive: true });
10499
11789
  if (artifacts.navigation || artifacts.projectTree || artifacts.audit || config.sarif === true) {
10500
- fs14.mkdirSync(reportsDir, { recursive: true });
10501
- }
11790
+ fs15.mkdirSync(reportsDir, { recursive: true });
11791
+ }
11792
+ const writtenArtifacts = /* @__PURE__ */ new Map();
11793
+ const writeArtifact = (targetDir, relativeEntry, data) => {
11794
+ const full = path16.join(targetDir, ...relativeEntry.split("/"));
11795
+ fs15.writeFileSync(full, data, "utf8");
11796
+ const stats = fs15.statSync(full);
11797
+ writtenArtifacts.set(relativeEntry, {
11798
+ digest: { path: relativeEntry, bytes: stats.size, sha256: sha256Hex2(data) },
11799
+ mtimeMs: stats.mtimeMs
11800
+ });
11801
+ };
11802
+ const recordArtifact = (targetDir, relativeEntry) => {
11803
+ const full = path16.join(targetDir, ...relativeEntry.split("/"));
11804
+ const stats = fs15.statSync(full);
11805
+ writtenArtifacts.set(relativeEntry, {
11806
+ digest: {
11807
+ path: relativeEntry,
11808
+ bytes: stats.size,
11809
+ sha256: sha256Hex2(fs15.readFileSync(full))
11810
+ },
11811
+ mtimeMs: stats.mtimeMs
11812
+ });
11813
+ };
10502
11814
  if (artifacts.parts) {
10503
11815
  for (const part of parts) {
10504
- fs14.writeFileSync(path16.join(partsDir, part.filename), part.markdown, "utf8");
11816
+ writeArtifact(partsDir, part.filename, part.markdown);
10505
11817
  }
10506
11818
  }
10507
11819
  if (projectTree !== null) {
10508
- fs14.writeFileSync(path16.join(reportsDir, "project-tree.md"), projectTree, "utf8");
11820
+ writeArtifact(reportsDir, "project-tree.md", projectTree);
10509
11821
  }
10510
- if (artifacts.navigation) {
10511
- fs14.writeFileSync(path16.join(reportsDir, "navigation.md"), generateNavigation(manifest), "utf8");
11822
+ if (navigationText !== null) {
11823
+ writeArtifact(reportsDir, "navigation.md", navigationText);
10512
11824
  }
10513
- if (artifacts.audit) {
10514
- fs14.writeFileSync(
10515
- path16.join(reportsDir, "audit.md"),
10516
- generateAuditReport(manifest, secretFindings, config.secretRules),
10517
- "utf8"
10518
- );
11825
+ if (auditText !== null) {
11826
+ writeArtifact(reportsDir, "audit.md", auditText);
10519
11827
  }
10520
11828
  if (sarifText !== null) {
10521
- fs14.writeFileSync(path16.join(reportsDir, "audit.sarif"), sarifText, "utf8");
11829
+ writeArtifact(reportsDir, "audit.sarif", sarifText);
10522
11830
  }
10523
- if (artifacts.readme) {
10524
- fs14.writeFileSync(path16.join(stagingDir, "README.md"), generateReadme(manifest, artifacts), "utf8");
11831
+ if (readmeText !== null) {
11832
+ writeArtifact(stagingDir, "README.md", readmeText);
10525
11833
  }
10526
11834
  if (artifacts.manifest) {
10527
- fs14.writeFileSync(path16.join(stagingDir, "manifest.json"), JSON.stringify(manifest, null, 2), "utf8");
11835
+ writeArtifact(stagingDir, "manifest.json", JSON.stringify(manifest, null, 2));
10528
11836
  }
10529
11837
  if (monolithJson !== null) {
10530
- fs14.writeFileSync(path16.join(stagingDir, "full-codebase.json"), monolithJson, "utf8");
11838
+ writeArtifact(stagingDir, "full-codebase.json", monolithJson);
10531
11839
  }
10532
11840
  if (monolithMarkdown !== null) {
10533
- fs14.writeFileSync(path16.join(stagingDir, "full-codebase.md"), monolithMarkdown, "utf8");
11841
+ writeArtifact(stagingDir, "full-codebase.md", monolithMarkdown);
10534
11842
  }
10535
- writeOwnershipMarker(stagingDir, markerPayload(stagingDir, "complete", snapshotId, createdAt));
10536
- swapIntoPlace(stagingDir, outDir);
11843
+ writeOwnershipMarker(
11844
+ stagingDir,
11845
+ markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts)
11846
+ );
11847
+ swapIntoPlace(stagingDir, outDir, () => assertReplaceable(outDir, "outDir", config.secretRules));
10537
11848
  stagingDir = null;
10538
11849
  const warningsBeforeHook = manifest.warnings.length;
10539
11850
  const pendingHook = runAfterGenerate(config, manifest);
@@ -10541,8 +11852,12 @@ function generateSnapshot(configInput, options) {
10541
11852
  if (!markerBelongsTo(outDir, snapshotId)) return;
10542
11853
  if (artifacts.manifest && manifest.warnings.length !== warningsBeforeHook) {
10543
11854
  writeManifestAtomically(path16.join(outDir, "manifest.json"), manifest);
11855
+ recordArtifact(outDir, "manifest.json");
10544
11856
  }
10545
- writeOwnershipMarker(outDir, markerPayload(outDir, "complete", snapshotId, createdAt));
11857
+ writeOwnershipMarker(
11858
+ outDir,
11859
+ markerPayload(outDir, "complete", snapshotId, createdAt, writtenArtifacts)
11860
+ );
10546
11861
  };
10547
11862
  if (config.hooks.afterGenerate) shipHookState();
10548
11863
  if (pendingHook) {
@@ -10569,25 +11884,32 @@ function generateSnapshot(configInput, options) {
10569
11884
  if (pendingHooks.get(outDir) === tracked) pendingHooks.delete(outDir);
10570
11885
  });
10571
11886
  pendingHooks.set(outDir, tracked);
11887
+ releaseDeferred = true;
11888
+ void tracked.finally(() => {
11889
+ removeIfEmpty(tmpDir);
11890
+ releaseLock();
11891
+ });
10572
11892
  }
10573
11893
  return manifest;
10574
11894
  } catch (err) {
10575
11895
  if (stagingDir !== null) {
10576
11896
  try {
10577
- fs14.rmSync(stagingDir, { recursive: true, force: true });
11897
+ fs15.rmSync(stagingDir, { recursive: true, force: true });
10578
11898
  } catch {
10579
11899
  }
10580
11900
  }
10581
11901
  throw err;
10582
11902
  } finally {
10583
- removeIfEmpty(tmpDir);
10584
- releaseLock();
11903
+ if (!releaseDeferred) {
11904
+ removeIfEmpty(tmpDir);
11905
+ releaseLock();
11906
+ }
10585
11907
  }
10586
11908
  }
10587
11909
  var pendingHooks = /* @__PURE__ */ new Map();
10588
11910
 
10589
11911
  // src/mcp/tools.ts
10590
- import * as fs16 from "fs";
11912
+ import * as fs17 from "fs";
10591
11913
  import * as path18 from "path";
10592
11914
 
10593
11915
  // src/mcp/part.ts
@@ -10695,7 +12017,7 @@ function windowText(body, fromLine, lineCount) {
10695
12017
  }
10696
12018
 
10697
12019
  // src/mcp/workspace.ts
10698
- import * as fs15 from "fs";
12020
+ import * as fs16 from "fs";
10699
12021
  import * as path17 from "path";
10700
12022
  function foldForComparison(value) {
10701
12023
  return process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
@@ -10703,12 +12025,12 @@ function foldForComparison(value) {
10703
12025
  function canonicalPath(value) {
10704
12026
  const absolute = path17.resolve(value);
10705
12027
  try {
10706
- return fs15.realpathSync(absolute);
12028
+ return fs16.realpathSync(absolute);
10707
12029
  } catch {
10708
12030
  return absolute;
10709
12031
  }
10710
12032
  }
10711
- function isInside2(parent, child) {
12033
+ function isInside3(parent, child) {
10712
12034
  const foldedParent = foldForComparison(parent);
10713
12035
  const foldedChild = foldForComparison(child);
10714
12036
  return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path17.sep}`);
@@ -10716,7 +12038,7 @@ function isInside2(parent, child) {
10716
12038
  function resolveThroughExistingAncestor(target) {
10717
12039
  let existing = target;
10718
12040
  const missing = [];
10719
- while (!fs15.existsSync(existing)) {
12041
+ while (!fs16.existsSync(existing)) {
10720
12042
  missing.unshift(path17.basename(existing));
10721
12043
  const parent = path17.dirname(existing);
10722
12044
  if (parent === existing) break;
@@ -10733,7 +12055,7 @@ function resolveRoot(requested, context) {
10733
12055
  const absolute = path17.resolve(context.cwd, wanted);
10734
12056
  let stats;
10735
12057
  try {
10736
- stats = fs15.statSync(absolute);
12058
+ stats = fs16.statSync(absolute);
10737
12059
  } catch {
10738
12060
  return { ok: false, message: `"${wanted}" does not exist, so it cannot be a repository root.` };
10739
12061
  }
@@ -10742,7 +12064,7 @@ function resolveRoot(requested, context) {
10742
12064
  }
10743
12065
  const resolved = canonicalPath(absolute);
10744
12066
  for (const allowed of context.roots) {
10745
- if (isInside2(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
12067
+ if (isInside3(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
10746
12068
  }
10747
12069
  const shown = context.roots.join(", ");
10748
12070
  return {
@@ -10750,8 +12072,8 @@ function resolveRoot(requested, context) {
10750
12072
  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.`
10751
12073
  };
10752
12074
  }
10753
- async function openWorkspace(root, overrides = {}, allowedRoots) {
10754
- const loaded = await loadConfigFileDetailed(root);
12075
+ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
12076
+ const loaded = await loadConfigFileDetailed(root, options);
10755
12077
  if (loaded.errors.length > 0) {
10756
12078
  return {
10757
12079
  ok: false,
@@ -10786,7 +12108,7 @@ async function openWorkspace(root, overrides = {}, allowedRoots) {
10786
12108
  const requested = overrides.outDir.trim();
10787
12109
  const permitted = allowedRoots !== void 0 && allowedRoots.length > 0 ? allowedRoots : [root];
10788
12110
  const resolved = resolveThroughExistingAncestor(path17.resolve(root, requested));
10789
- if (!permitted.some((allowed) => isInside2(canonicalPath(allowed), resolved))) {
12111
+ if (!permitted.some((allowed) => isInside3(canonicalPath(allowed), resolved))) {
10790
12112
  const shown = permitted.map((allowed) => canonicalPath(allowed)).join(", ");
10791
12113
  return {
10792
12114
  ok: false,
@@ -10815,6 +12137,7 @@ async function openWorkspace(root, overrides = {}, allowedRoots) {
10815
12137
  return { ok: false, message: error instanceof Error ? error.message : String(error) };
10816
12138
  }
10817
12139
  }
12140
+ var MANIFEST_CACHE_LIMIT = 8;
10818
12141
  var manifestCache = /* @__PURE__ */ new Map();
10819
12142
  function manifestPathFor(workspace) {
10820
12143
  return path17.resolve(workspace.root, workspace.config.outDir, "manifest.json");
@@ -10823,8 +12146,20 @@ function partPathFor(workspace, filename) {
10823
12146
  if (filename.length === 0 || filename.includes("\0")) return null;
10824
12147
  const partsDir = path17.resolve(workspace.root, workspace.config.outDir, "parts");
10825
12148
  const resolved = path17.resolve(partsDir, filename);
10826
- const relative12 = path17.relative(partsDir, resolved);
10827
- if (relative12.length === 0 || relative12.includes(path17.sep) || relative12.includes("/") || relative12.includes("\\") || path17.isAbsolute(relative12)) {
12149
+ const relative14 = path17.relative(partsDir, resolved);
12150
+ if (relative14.length === 0 || relative14.includes(path17.sep) || relative14.includes("/") || relative14.includes("\\") || path17.isAbsolute(relative14)) {
12151
+ return null;
12152
+ }
12153
+ let stats;
12154
+ try {
12155
+ stats = fs16.lstatSync(resolved);
12156
+ } catch {
12157
+ return null;
12158
+ }
12159
+ if (!stats.isFile()) return null;
12160
+ try {
12161
+ if (path17.dirname(fs16.realpathSync(resolved)) !== fs16.realpathSync(partsDir)) return null;
12162
+ } catch {
10828
12163
  return null;
10829
12164
  }
10830
12165
  return resolved;
@@ -10834,7 +12169,7 @@ function readManifest3(workspace) {
10834
12169
  const shown = path17.relative(workspace.root, file).split(path17.sep).join("/") || file;
10835
12170
  let stats;
10836
12171
  try {
10837
- stats = fs15.statSync(file);
12172
+ stats = fs16.statSync(file);
10838
12173
  } catch {
10839
12174
  return {
10840
12175
  ok: false,
@@ -10843,12 +12178,12 @@ function readManifest3(workspace) {
10843
12178
  };
10844
12179
  }
10845
12180
  const cached = manifestCache.get(file);
10846
- if (cached && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size) {
12181
+ if (cached && cached.mtimeMs === stats.mtimeMs && cached.ctimeMs === stats.ctimeMs && cached.size === stats.size) {
10847
12182
  return { ok: true, manifest: cached.manifest, file };
10848
12183
  }
10849
12184
  let raw;
10850
12185
  try {
10851
- raw = fs15.readFileSync(file, "utf8");
12186
+ raw = fs16.readFileSync(file, "utf8");
10852
12187
  } catch (error) {
10853
12188
  return {
10854
12189
  ok: false,
@@ -10867,7 +12202,18 @@ function readManifest3(workspace) {
10867
12202
  return { ok: false, missing: false, message: `${shown} is not a snapshot manifest: ${problem}` };
10868
12203
  }
10869
12204
  const manifest = parsed;
10870
- manifestCache.set(file, { mtimeMs: stats.mtimeMs, size: stats.size, manifest });
12205
+ manifestCache.delete(file);
12206
+ manifestCache.set(file, {
12207
+ mtimeMs: stats.mtimeMs,
12208
+ ctimeMs: stats.ctimeMs,
12209
+ size: stats.size,
12210
+ manifest
12211
+ });
12212
+ while (manifestCache.size > MANIFEST_CACHE_LIMIT) {
12213
+ const oldest = manifestCache.keys().next().value;
12214
+ if (oldest === void 0) break;
12215
+ manifestCache.delete(oldest);
12216
+ }
10871
12217
  return { ok: true, manifest, file };
10872
12218
  }
10873
12219
  function forgetManifest(file) {
@@ -10970,11 +12316,11 @@ function toRelativePath(root, value) {
10970
12316
  if (cleaned.length === 0 || cleaned.includes("\0")) return null;
10971
12317
  const resolvedRoot = path18.resolve(root);
10972
12318
  const absolute = path18.resolve(resolvedRoot, cleaned);
10973
- const relative12 = path18.relative(resolvedRoot, absolute);
10974
- if (relative12 === "" || relative12 === ".." || relative12.startsWith(`..${path18.sep}`) || path18.isAbsolute(relative12)) {
12319
+ const relative14 = path18.relative(resolvedRoot, absolute);
12320
+ if (relative14 === "" || relative14 === ".." || relative14.startsWith(`..${path18.sep}`) || path18.isAbsolute(relative14)) {
10975
12321
  return null;
10976
12322
  }
10977
- return relative12.split(path18.sep).join("/");
12323
+ return relative14.split(path18.sep).join("/");
10978
12324
  }
10979
12325
  function symbolsOf(entry) {
10980
12326
  const summary = entry.summary;
@@ -11015,7 +12361,9 @@ function symbolsOf(entry) {
11015
12361
  async function prepare(args, context, overrides = {}) {
11016
12362
  const rootOutcome = resolveRoot(args.root, context);
11017
12363
  if (!rootOutcome.ok) return { ok: false, outcome: failure(rootOutcome.message) };
11018
- const opened = await openWorkspace(rootOutcome.root, overrides, context.roots);
12364
+ const opened = await openWorkspace(rootOutcome.root, overrides, context.roots, {
12365
+ allowExecutableConfig: false
12366
+ });
11019
12367
  if (!opened.ok) return { ok: false, outcome: failure(opened.message) };
11020
12368
  return { ok: true, workspace: opened.workspace };
11021
12369
  }
@@ -11371,10 +12719,12 @@ var locateTool = {
11371
12719
  else if (wants("kind") && entry.kind.toLowerCase().includes(needle)) add(entry, "kind");
11372
12720
  }
11373
12721
  if (wants("route")) {
12722
+ const matchedPaths = new Set(matches.map((match) => match.path));
11374
12723
  for (const route of manifest.indexes.routes) {
11375
12724
  const method = route.methods.find((name) => name.toLowerCase().includes(needle));
11376
12725
  if (!route.path.toLowerCase().includes(needle) && method === void 0) continue;
11377
- if (matches.some((match) => match.path === route.path)) continue;
12726
+ if (matchedPaths.has(route.path)) continue;
12727
+ matchedPaths.add(route.path);
11378
12728
  matches.push({
11379
12729
  path: route.path,
11380
12730
  part: route.part,
@@ -11567,7 +12917,9 @@ var readTool = {
11567
12917
  fromLine: { type: "integer" },
11568
12918
  returnedLines: { type: "integer" },
11569
12919
  totalLines: { type: "integer" },
11570
- nextFromLine: { type: "integer" }
12920
+ nextFromLine: { type: "integer" },
12921
+ pageable: { type: "boolean" },
12922
+ reason: { type: "string" }
11571
12923
  }
11572
12924
  },
11573
12925
  annotations: READ_ONLY,
@@ -11606,7 +12958,7 @@ var readTool = {
11606
12958
  }
11607
12959
  let partText;
11608
12960
  try {
11609
- partText = fs16.readFileSync(partPath, "utf8");
12961
+ partText = fs17.readFileSync(partPath, "utf8");
11610
12962
  } catch {
11611
12963
  return failure(
11612
12964
  `${entry.part} could not be read, so the snapshot is damaged. Run snapshot_generate to rebuild it.`
@@ -11623,15 +12975,20 @@ var readTool = {
11623
12975
  const window = windowText(section.body, fromLine, lineCount);
11624
12976
  let body = window.text;
11625
12977
  let truncatedByBytes = false;
12978
+ let clippedInsideLine = false;
11626
12979
  if (Buffer.byteLength(body, "utf8") > MAX_RESULT_BYTES) {
11627
12980
  const clipped = truncateToBytes(body, MAX_RESULT_BYTES);
11628
- body = clipped.content;
11629
- const lastBreak = body.lastIndexOf("\n");
11630
- body = lastBreak > 0 ? body.slice(0, lastBreak) : body;
12981
+ const lastBreak = clipped.content.lastIndexOf("\n");
12982
+ if (lastBreak > 0) {
12983
+ body = clipped.content.slice(0, lastBreak);
12984
+ } else {
12985
+ body = clipped.content;
12986
+ clippedInsideLine = true;
12987
+ }
11631
12988
  truncatedByBytes = true;
11632
12989
  }
11633
12990
  const returnedLines = body.length === 0 ? 0 : body.split("\n").length;
11634
- const moreRemain = !window.pastEnd && (window.truncated || truncatedByBytes);
12991
+ const moreRemain = !clippedInsideLine && !window.pastEnd && (window.truncated || truncatedByBytes);
11635
12992
  const header = [
11636
12993
  `${entry.relativePath} \u2014 ${entry.part}, ${entry.layer}/${entry.kind}, ${entry.language}`,
11637
12994
  // The line range is the answer to "where am I in this file", and it is computed from the
@@ -11645,12 +13002,17 @@ var readTool = {
11645
13002
  ] : section.inclusion === "signatures" ? [
11646
13003
  "Signatures: function and method bodies were replaced with `{ /* ... */ }` when the snapshot was generated."
11647
13004
  ] : [],
11648
- 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}.`
13005
+ 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}.`
11649
13006
  ];
11650
13007
  const lines = [...header, "", body];
11651
13008
  if (moreRemain) {
11652
13009
  const next = window.fromLine + returnedLines;
11653
13010
  lines.push("", `Truncated. Call snapshot_read with fromLine=${next} for the rest.`);
13011
+ } else if (clippedInsideLine) {
13012
+ lines.push(
13013
+ "",
13014
+ "Truncated. The remainder of this line is not reachable through snapshot_read; read the file from disk to see it."
13015
+ );
11654
13016
  }
11655
13017
  return {
11656
13018
  text: lines.join("\n"),
@@ -11664,7 +13026,9 @@ var readTool = {
11664
13026
  fromLine: window.fromLine,
11665
13027
  returnedLines,
11666
13028
  totalLines: window.totalLines,
11667
- truncated: moreRemain,
13029
+ truncated: moreRemain || clippedInsideLine,
13030
+ pageable: !clippedInsideLine,
13031
+ ...clippedInsideLine ? { reason: "line exceeds the result limit; its remainder is not reachable by fromLine" } : {},
11668
13032
  nextFromLine: moreRemain ? window.fromLine + returnedLines : null,
11669
13033
  sha256: entry.hashSha256
11670
13034
  }
@@ -11822,6 +13186,13 @@ var ERROR_CODES = {
11822
13186
  * invent a partial one.
11823
13187
  */
11824
13188
  resourceTooLarge: -32e3,
13189
+ /**
13190
+ * The server is at its concurrency limit.
13191
+ *
13192
+ * Implementation-defined range, like `resourceTooLarge`. A typed error rather than silent
13193
+ * queueing or a dropped request: the caller can retry, and knows why.
13194
+ */
13195
+ overloaded: -32001,
11825
13196
  unsupportedProtocolVersion: -32022
11826
13197
  };
11827
13198
  var METHOD3 = {
@@ -11958,13 +13329,14 @@ var COMMAND_OPTION_SCOPE = {
11958
13329
  "with-dependents",
11959
13330
  "cwd",
11960
13331
  "out-dir",
11961
- "max-part-bytes",
13332
+ // `--large-file-bytes` changes the inclusion mode `explain` reports, so it belongs here.
13333
+ // `--max-part-bytes`, `--max-monolith-bytes`, `--include-monolith`, `--skip-artifacts` and
13334
+ // `--only-artifacts` were accepted and never read: a per-file answer cannot depend on how the
13335
+ // whole snapshot is partitioned, and none of them changes whether this file is included.
13336
+ // Removed rather than implemented, because a flag that parses and does nothing is the defect
13337
+ // this table exists to prevent.
11962
13338
  "large-file-bytes",
11963
- "max-monolith-bytes",
11964
- "include-monolith",
11965
13339
  "include-sensitive-files",
11966
- "skip-artifacts",
11967
- "only-artifacts",
11968
13340
  "no-config",
11969
13341
  "discovery",
11970
13342
  "no-update-check",
@@ -12312,7 +13684,7 @@ function buildAgentContract() {
12312
13684
  type: "string",
12313
13685
  default: "unset",
12314
13686
  appliesTo: optionAppliesTo("max-part-tokens"),
12315
- summary: "Ceiling on a part expressed in tokens. Narrows --max-part-bytes instead of replacing it; the manifest records both units. Minimum 1024."
13687
+ 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."
12316
13688
  },
12317
13689
  {
12318
13690
  flag: "--large-file-bytes",
@@ -12347,7 +13719,7 @@ function buildAgentContract() {
12347
13719
  type: "string",
12348
13720
  default: "auto",
12349
13721
  appliesTo: optionAppliesTo("discovery"),
12350
- 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)."
13722
+ 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)."
12351
13723
  },
12352
13724
  {
12353
13725
  flag: "--skip-artifacts",
@@ -12368,7 +13740,7 @@ function buildAgentContract() {
12368
13740
  type: "boolean",
12369
13741
  default: false,
12370
13742
  appliesTo: optionAppliesTo("skeleton"),
12371
- 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.'
13743
+ 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.'
12372
13744
  },
12373
13745
  {
12374
13746
  flag: "--sarif",
@@ -12482,7 +13854,7 @@ function buildAgentContract() {
12482
13854
  type: "boolean",
12483
13855
  default: false,
12484
13856
  appliesTo: optionAppliesTo("autopilot"),
12485
- 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)."
13857
+ 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)."
12486
13858
  },
12487
13859
  {
12488
13860
  flag: "--install",
@@ -12656,7 +14028,7 @@ function buildAgentContract() {
12656
14028
  }
12657
14029
 
12658
14030
  // src/agent/install-skill.ts
12659
- import * as fs17 from "fs";
14031
+ import * as fs18 from "fs";
12660
14032
  import * as path19 from "path";
12661
14033
 
12662
14034
  // src/agent/skill.ts
@@ -12826,11 +14198,11 @@ function targetPath(cwd, target) {
12826
14198
  }
12827
14199
  }
12828
14200
  function assertWritableInsideRepository(cwd, filePath) {
12829
- const root = fs17.realpathSync(cwd);
14201
+ const root = fs18.realpathSync(cwd);
12830
14202
  const shown = path19.relative(root, filePath) || filePath;
12831
14203
  let stat = null;
12832
14204
  try {
12833
- stat = fs17.lstatSync(filePath);
14205
+ stat = fs18.lstatSync(filePath);
12834
14206
  } catch {
12835
14207
  stat = null;
12836
14208
  }
@@ -12846,13 +14218,13 @@ function assertWritableInsideRepository(cwd, filePath) {
12846
14218
  }
12847
14219
  let existing = filePath;
12848
14220
  const missing = [];
12849
- while (!fs17.existsSync(existing)) {
14221
+ while (!fs18.existsSync(existing)) {
12850
14222
  missing.unshift(path19.basename(existing));
12851
14223
  const parent = path19.dirname(existing);
12852
14224
  if (parent === existing) break;
12853
14225
  existing = parent;
12854
14226
  }
12855
- const realAncestor = fs17.realpathSync(existing);
14227
+ const realAncestor = fs18.realpathSync(existing);
12856
14228
  const resolved = missing.length === 0 ? realAncestor : path19.join(realAncestor, ...missing);
12857
14229
  if (resolved !== root && !resolved.startsWith(`${root}${path19.sep}`)) {
12858
14230
  throw new Error(
@@ -12861,17 +14233,17 @@ function assertWritableInsideRepository(cwd, filePath) {
12861
14233
  }
12862
14234
  }
12863
14235
  function writeIfChanged(target, filePath, content) {
12864
- const existing = fs17.existsSync(filePath) ? fs17.readFileSync(filePath, "utf8") : null;
14236
+ const existing = fs18.existsSync(filePath) ? fs18.readFileSync(filePath, "utf8") : null;
12865
14237
  if (existing === content) return { target, path: filePath, action: "unchanged" };
12866
- fs17.mkdirSync(path19.dirname(filePath), { recursive: true });
12867
- fs17.writeFileSync(filePath, content, "utf8");
14238
+ fs18.mkdirSync(path19.dirname(filePath), { recursive: true });
14239
+ fs18.writeFileSync(filePath, content, "utf8");
12868
14240
  return { target, path: filePath, action: existing === null ? "created" : "updated" };
12869
14241
  }
12870
14242
  function legacyAgentsNote(cwd) {
12871
14243
  const filePath = path19.join(cwd, "AGENTS.md");
12872
14244
  try {
12873
- if (!fs17.existsSync(filePath)) return null;
12874
- if (!fs17.readFileSync(filePath, "utf8").includes(LEGACY_AGENTS_MARKER)) return null;
14245
+ if (!fs18.existsSync(filePath)) return null;
14246
+ if (!fs18.readFileSync(filePath, "utf8").includes(LEGACY_AGENTS_MARKER)) return null;
12875
14247
  } catch {
12876
14248
  return null;
12877
14249
  }
@@ -12883,7 +14255,7 @@ function installSkill(cwd, target = "all") {
12883
14255
  const notes = [];
12884
14256
  const wanted = target === "all" ? ["claude", "cursor"] : [target];
12885
14257
  for (const item of wanted) assertWritableInsideRepository(cwd, targetPath(cwd, item));
12886
- const createsSomething = wanted.some((item) => !fs17.existsSync(targetPath(cwd, item)));
14258
+ const createsSomething = wanted.some((item) => !fs18.existsSync(targetPath(cwd, item)));
12887
14259
  if (createsSomething) {
12888
14260
  assertWritableInsideRepository(cwd, path19.join(cwd, ".gitignore"));
12889
14261
  }
@@ -12999,7 +14371,7 @@ function negotiateLegacyVersion(requested) {
12999
14371
  }
13000
14372
 
13001
14373
  // src/mcp/resources.ts
13002
- import * as fs18 from "fs";
14374
+ import * as fs19 from "fs";
13003
14375
  import * as path20 from "path";
13004
14376
  var MAX_RESOURCE_BYTES = 512 * 1024;
13005
14377
  var ResourceTooLargeError = class extends Error {
@@ -13044,13 +14416,13 @@ function formatBytes2(bytes) {
13044
14416
  async function workspaceFor(context) {
13045
14417
  const root = resolveRoot(void 0, context);
13046
14418
  if (!root.ok) return { error: root.message };
13047
- const opened = await openWorkspace(root.root);
14419
+ const opened = await openWorkspace(root.root, {}, void 0, { allowExecutableConfig: false });
13048
14420
  if (!opened.ok) return { error: opened.message };
13049
14421
  return opened.workspace;
13050
14422
  }
13051
14423
  function readFileIfPresent(file) {
13052
14424
  try {
13053
- return fs18.readFileSync(file, "utf8");
14425
+ return fs19.readFileSync(file, "utf8");
13054
14426
  } catch {
13055
14427
  return null;
13056
14428
  }
@@ -13168,7 +14540,7 @@ function buildResourceProvider() {
13168
14540
  if (partPath === null) return null;
13169
14541
  let partBytes;
13170
14542
  try {
13171
- partBytes = fs18.statSync(partPath).size;
14543
+ partBytes = fs19.statSync(partPath).size;
13172
14544
  } catch {
13173
14545
  return null;
13174
14546
  }
@@ -13586,11 +14958,11 @@ var MAX_LINE_BYTES = 32 * 1024 * 1024;
13586
14958
  function createWriter(output) {
13587
14959
  return {
13588
14960
  write(value) {
13589
- return new Promise((resolve10, reject) => {
14961
+ return new Promise((resolve11, reject) => {
13590
14962
  output.write(`${JSON.stringify(value)}
13591
14963
  `, (error) => {
13592
14964
  if (error) reject(error);
13593
- else resolve10();
14965
+ else resolve11();
13594
14966
  });
13595
14967
  });
13596
14968
  }
@@ -13723,11 +15095,12 @@ async function runStdioServer(options) {
13723
15095
  });
13724
15096
  return writeChain;
13725
15097
  };
15098
+ const MAX_IN_FLIGHT = 4;
13726
15099
  let inFlight = 0;
13727
15100
  let inputEnded = false;
13728
15101
  let resolveDone = () => void 0;
13729
- const finished = new Promise((resolve10) => {
13730
- resolveDone = resolve10;
15102
+ const finished = new Promise((resolve11) => {
15103
+ resolveDone = resolve11;
13731
15104
  });
13732
15105
  const finishIfIdle = () => {
13733
15106
  if (inputEnded && inFlight === 0) resolveDone(0);
@@ -13743,9 +15116,31 @@ async function runStdioServer(options) {
13743
15116
  const response = await server.handle(message);
13744
15117
  if (response) await send(response);
13745
15118
  };
15119
+ const rejectOverloaded = (line) => {
15120
+ let id = null;
15121
+ try {
15122
+ const parsed = JSON.parse(line);
15123
+ if (!isJsonObject(parsed)) return;
15124
+ if (typeof parsed.id === "string" || typeof parsed.id === "number") id = parsed.id;
15125
+ else return;
15126
+ } catch {
15127
+ return;
15128
+ }
15129
+ void send(
15130
+ errorResponse(
15131
+ id,
15132
+ ERROR_CODES.overloaded,
15133
+ `The server is already handling ${MAX_IN_FLIGHT} requests; retry this one when it is free.`
15134
+ )
15135
+ );
15136
+ };
13746
15137
  const stopReading = createLineReader(process.stdin, {
13747
15138
  onOverflow: (bytes) => log(`mcp: discarded an oversized message (${bytes} bytes)`),
13748
15139
  onLine: (line) => {
15140
+ if (inFlight >= MAX_IN_FLIGHT) {
15141
+ rejectOverloaded(line);
15142
+ return;
15143
+ }
13749
15144
  inFlight += 1;
13750
15145
  void handleLine(line).finally(() => {
13751
15146
  inFlight -= 1;
@@ -13998,10 +15393,10 @@ function parseCliArgs(argv) {
13998
15393
  }
13999
15394
  if (values.cwd !== void 0) {
14000
15395
  const target = String(values.cwd);
14001
- if (!fs19.existsSync(target)) {
15396
+ if (!fs20.existsSync(target)) {
14002
15397
  throw new UsageError(`--cwd directory does not exist: ${target}`);
14003
15398
  }
14004
- if (!fs19.statSync(target).isDirectory()) {
15399
+ if (!fs20.statSync(target).isDirectory()) {
14005
15400
  throw new UsageError(`--cwd is not a directory: ${target}`);
14006
15401
  }
14007
15402
  }
@@ -14105,7 +15500,9 @@ function parseCliArgs(argv) {
14105
15500
  )
14106
15501
  )
14107
15502
  );
14108
- 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)." : "";
15503
+ const setupOnly = ["--preset", "--include", "--exclude", "--install-hook"];
15504
+ const autopilotChose = values.autopilot === true && ignored.some((flag) => setupOnly.includes(flag));
15505
+ 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)." : "";
14109
15506
  throw new UsageError(
14110
15507
  `${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}`
14111
15508
  );
@@ -14227,8 +15624,8 @@ function splitList(value) {
14227
15624
  }
14228
15625
  function displayOutPath(cwd, outDir, ...segments) {
14229
15626
  const absolute = path21.resolve(cwd, outDir, ...segments);
14230
- const relative12 = path21.relative(cwd, absolute);
14231
- if (relative12 && !relative12.startsWith("..") && !path21.isAbsolute(relative12)) return relative12;
15627
+ const relative14 = path21.relative(cwd, absolute);
15628
+ if (relative14 && !relative14.startsWith("..") && !path21.isAbsolute(relative14)) return relative14;
14232
15629
  return absolute;
14233
15630
  }
14234
15631
  function nextStepHint(cwd, scriptsAddedNow) {
@@ -14236,7 +15633,7 @@ function nextStepHint(cwd, scriptsAddedNow) {
14236
15633
  if (!hasScript) {
14237
15634
  try {
14238
15635
  const parsed = JSON.parse(
14239
- stripJsonComments2(fs19.readFileSync(path21.join(cwd, "package.json"), "utf8"))
15636
+ stripJsonComments2(fs20.readFileSync(path21.join(cwd, "package.json"), "utf8"))
14240
15637
  );
14241
15638
  hasScript = typeof parsed.scripts?.snapshot === "string";
14242
15639
  } catch {
@@ -14245,7 +15642,7 @@ function nextStepHint(cwd, scriptsAddedNow) {
14245
15642
  }
14246
15643
  if (!hasScript) return `npx ${GENERATOR_NAME} generate`;
14247
15644
  const bin = path21.join(cwd, "node_modules", ".bin", "codebase-snapshot");
14248
- const installed = fs19.existsSync(bin) || fs19.existsSync(`${bin}.cmd`);
15645
+ const installed = fs20.existsSync(bin) || fs20.existsSync(`${bin}.cmd`);
14249
15646
  return installed ? "npm run snapshot" : "npm install && npm run snapshot";
14250
15647
  }
14251
15648
  function presetSummary(init) {
@@ -14302,16 +15699,25 @@ async function runInitCommand(invocation) {
14302
15699
  }
14303
15700
  }
14304
15701
  function detectPackageManager(cwd) {
14305
- const has = (name) => fs19.existsSync(path21.join(cwd, name));
15702
+ const has = (name) => fs20.existsSync(path21.join(cwd, name));
14306
15703
  if (has("bun.lockb") || has("bun.lock")) return { name: "bun", command: "bun", args: ["install"] };
14307
15704
  if (has("pnpm-lock.yaml")) return { name: "pnpm", command: "pnpm", args: ["install"] };
14308
15705
  if (has("yarn.lock")) return { name: "yarn", command: "yarn", args: ["install"] };
14309
15706
  return { name: "npm", command: "npm", args: ["install"] };
14310
15707
  }
15708
+ var INHERITED_NPM_SETTINGS = /* @__PURE__ */ new Set([
15709
+ "npm_config_registry",
15710
+ "npm_config_proxy",
15711
+ "npm_config_https_proxy",
15712
+ "npm_config_noproxy",
15713
+ "npm_config_cafile",
15714
+ "npm_config_ca",
15715
+ "npm_config_strict_ssl"
15716
+ ]);
14311
15717
  function cleanInstallEnv(env = process.env) {
14312
15718
  const cleaned = {};
14313
15719
  for (const [key, value] of Object.entries(env)) {
14314
- if (/^npm_config_/i.test(key)) continue;
15720
+ if (/^npm_config_/i.test(key) && !INHERITED_NPM_SETTINGS.has(key.toLowerCase())) continue;
14315
15721
  if (key === "npm_lifecycle_event" || key === "npm_lifecycle_script") continue;
14316
15722
  cleaned[key] = value;
14317
15723
  }
@@ -14735,12 +16141,12 @@ ${USAGE}
14735
16141
  }
14736
16142
  if (invocation.command === "report") {
14737
16143
  const manifestPath = path21.resolve(resolved.cwd, resolved.outDir, "manifest.json");
14738
- if (!fs19.existsSync(manifestPath)) {
16144
+ if (!fs20.existsSync(manifestPath)) {
14739
16145
  return fail(invocation.format, `Manifest not found at ${manifestPath}. Run generate first.`);
14740
16146
  }
14741
16147
  let manifest;
14742
16148
  try {
14743
- manifest = JSON.parse(fs19.readFileSync(manifestPath, "utf8"));
16149
+ manifest = JSON.parse(fs20.readFileSync(manifestPath, "utf8"));
14744
16150
  } catch (err) {
14745
16151
  return fail(invocation.format, `Could not read ${manifestPath}: ${err.message}`);
14746
16152
  }
@@ -14916,8 +16322,8 @@ function comparablePath(value) {
14916
16322
  return process.platform === "win32" ? absolute.toLowerCase() : absolute;
14917
16323
  }
14918
16324
  function isSameOrInside(parent, candidate) {
14919
- const relative12 = path21.relative(parent, candidate);
14920
- return relative12 === "" || relative12 !== ".." && !relative12.startsWith(`..${path21.sep}`) && !path21.isAbsolute(relative12);
16325
+ const relative14 = path21.relative(parent, candidate);
16326
+ return relative14 === "" || relative14 !== ".." && !relative14.startsWith(`..${path21.sep}`) && !path21.isAbsolute(relative14);
14921
16327
  }
14922
16328
  function isGeneratedWatchPath(candidate, paths) {
14923
16329
  const absolute = comparablePath(path21.resolve(paths.cwd, candidate));
@@ -15033,7 +16439,7 @@ async function runWatchLoop(invocation, resolved, options) {
15033
16439
  if (!options.generatedAlready) void regenerate();
15034
16440
  let watcher;
15035
16441
  try {
15036
- watcher = fs19.watch(resolved.cwd, { recursive: true }, (_event, filename) => {
16442
+ watcher = fs20.watch(resolved.cwd, { recursive: true }, (_event, filename) => {
15037
16443
  const decision = decideWatchEvent(
15038
16444
  state,
15039
16445
  {
@@ -15063,12 +16469,12 @@ async function runWatchLoop(invocation, resolved, options) {
15063
16469
  info(`\u26A0 Watch error: ${err.message}`);
15064
16470
  info(" The watcher may have missed changes. Restart with Ctrl+C if they stop arriving.");
15065
16471
  });
15066
- await new Promise((resolve10) => {
16472
+ await new Promise((resolve11) => {
15067
16473
  const stop = () => {
15068
16474
  stopped = true;
15069
16475
  if (timer) clearTimeout(timer);
15070
16476
  watcher.close();
15071
- resolve10();
16477
+ resolve11();
15072
16478
  };
15073
16479
  process.once("SIGINT", stop);
15074
16480
  process.once("SIGTERM", stop);