codebase-snapshot 0.9.16 → 0.9.18

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.18";
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
+ }
4354
+ }
4355
+ if (config.baseUrl !== null) {
4356
+ return lookupPath(path4.posix.normalize(path4.posix.join(config.baseUrl, specifier)));
3688
4357
  }
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);
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];
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];
3723
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.16";
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";
@@ -7646,102 +8752,37 @@ function installStdoutRouter() {
7646
8752
  installs += 1;
7647
8753
  let released = false;
7648
8754
  return () => {
7649
- if (released) return;
7650
- released = true;
7651
- installs -= 1;
7652
- if (installs === 0) {
7653
- 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 });
8755
+ if (released) return;
8756
+ released = true;
8757
+ installs -= 1;
8758
+ if (installs === 0) {
8759
+ if (process.stdout.write === router && underlying !== null) {
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,13 +9697,14 @@ 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";
8656
9704
  import * as path13 from "path";
8657
9705
  var PACKAGE_LATEST_URL = "https://registry.npmjs.org/codebase-snapshot/latest";
8658
9706
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
9707
+ var UP_TO_DATE_INTERVAL_MS = 60 * 60 * 1e3;
8659
9708
  var FAILURE_INTERVAL_MS = 60 * 60 * 1e3;
8660
9709
  var REQUEST_TIMEOUT_MS = 1200;
8661
9710
  function installKind(scriptPath = process.argv[1] ?? "", cwd = process.cwd()) {
@@ -8724,23 +9773,24 @@ function shouldCheck(argv, env) {
8724
9773
  for (const skip of ["mcp", "describe", "skill", "--version", "-v", "--help", "-h"]) {
8725
9774
  if (args.includes(skip)) return false;
8726
9775
  }
9776
+ let format = null;
8727
9777
  for (let index = 0; index < args.length; index += 1) {
8728
9778
  const argument = args[index];
9779
+ if (argument === "--") break;
8729
9780
  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;
9781
+ format = args[index + 1] ?? null;
9782
+ index += 1;
9783
+ continue;
8736
9784
  }
9785
+ if (argument.startsWith("--format=")) format = argument.slice("--format=".length);
8737
9786
  }
9787
+ if (format === "json") return false;
8738
9788
  return true;
8739
9789
  }
8740
9790
  function readCache(file) {
8741
9791
  let raw;
8742
9792
  try {
8743
- raw = fs12.readFileSync(file, "utf8");
9793
+ raw = fs13.readFileSync(file, "utf8");
8744
9794
  } catch {
8745
9795
  return null;
8746
9796
  }
@@ -8757,21 +9807,21 @@ function readCache(file) {
8757
9807
  }
8758
9808
  function writeCache(file, entry) {
8759
9809
  try {
8760
- fs12.mkdirSync(path13.dirname(file), { recursive: true });
8761
- fs12.writeFileSync(file, `${JSON.stringify(entry)}
9810
+ fs13.mkdirSync(path13.dirname(file), { recursive: true });
9811
+ fs13.writeFileSync(file, `${JSON.stringify(entry)}
8762
9812
  `, "utf8");
8763
9813
  } catch {
8764
9814
  }
8765
9815
  }
8766
9816
  function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOUT_MS) {
8767
- return new Promise((resolve10) => {
9817
+ return new Promise((resolve11) => {
8768
9818
  let settled = false;
8769
9819
  let request = null;
8770
9820
  const finish = (value) => {
8771
9821
  if (settled) return;
8772
9822
  settled = true;
8773
9823
  clearTimeout(deadline);
8774
- resolve10(value);
9824
+ resolve11(value);
8775
9825
  };
8776
9826
  const deadline = setTimeout(() => {
8777
9827
  request?.destroy();
@@ -8829,7 +9879,8 @@ async function checkForUpdate(options) {
8829
9879
  needsFetch = age >= FAILURE_INTERVAL_MS;
8830
9880
  } else {
8831
9881
  latest = cached.latest;
8832
- needsFetch = age >= CHECK_INTERVAL_MS;
9882
+ const interval = isNewer(cached.latest, options.current) ? CHECK_INTERVAL_MS : UP_TO_DATE_INTERVAL_MS;
9883
+ needsFetch = age >= interval;
8833
9884
  }
8834
9885
  }
8835
9886
  if (needsFetch) {
@@ -8849,7 +9900,8 @@ function formatUpdateNotice(notice, kind) {
8849
9900
  }
8850
9901
 
8851
9902
  // src/agent/hook.ts
8852
- import * as fs13 from "fs";
9903
+ import * as childProcess2 from "child_process";
9904
+ import * as fs14 from "fs";
8853
9905
  import * as path14 from "path";
8854
9906
  var HOOK_MARKER = `# ${GENERATOR_NAME}: pre-commit snapshot check`;
8855
9907
  function shellQuote(value) {
@@ -8870,9 +9922,17 @@ set -e
8870
9922
  SNAPSHOT_DIR="${dir}"
8871
9923
 
8872
9924
  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
9925
+ # Fail closed. A missing snapshot used to exit 0 with a reassuring message, so deleting or
9926
+ # renaming the output directory disabled the gate while every commit still succeeded \u2014 the one
9927
+ # failure mode a commit gate must not have. The opt-out is explicit and documented.
9928
+ if [ "\${CODEBASE_SNAPSHOT_ALLOW_MISSING:-}" = "1" ]; then
9929
+ echo "${GENERATOR_NAME}: no snapshot in $SNAPSHOT_DIR; skipping the check (CODEBASE_SNAPSHOT_ALLOW_MISSING=1)." >&2
9930
+ exit 0
9931
+ fi
9932
+ echo "${GENERATOR_NAME}: refusing the commit: no snapshot in $SNAPSHOT_DIR." >&2
9933
+ echo " Run \\"npx ${GENERATOR_NAME} generate\\", stage it, and commit again." >&2
9934
+ echo " To disable this gate, set CODEBASE_SNAPSHOT_ALLOW_MISSING=1." >&2
9935
+ exit 1
8876
9936
  fi
8877
9937
 
8878
9938
  if ! npx --no-install ${GENERATOR_NAME} validate >/dev/null 2>&1; then
@@ -8887,26 +9947,69 @@ function gitDirectory(cwd) {
8887
9947
  const dotGit = path14.join(cwd, ".git");
8888
9948
  let stats;
8889
9949
  try {
8890
- stats = fs13.statSync(dotGit);
9950
+ stats = fs14.statSync(dotGit);
8891
9951
  } catch {
8892
9952
  return null;
8893
9953
  }
8894
9954
  if (stats.isDirectory()) return dotGit;
8895
9955
  if (!stats.isFile()) return null;
8896
9956
  try {
8897
- const contents = fs13.readFileSync(dotGit, "utf8");
9957
+ const contents = fs14.readFileSync(dotGit, "utf8");
8898
9958
  const match = /^gitdir:\s*(.+)$/m.exec(contents);
8899
9959
  if (!match) return null;
8900
9960
  const target = match[1];
8901
9961
  const resolved = path14.isAbsolute(target.trim()) ? target.trim() : path14.join(cwd, target.trim());
8902
- return fs13.statSync(resolved).isDirectory() ? resolved : null;
9962
+ if (!fs14.statSync(resolved).isDirectory()) return null;
9963
+ if (isInside2(path14.resolve(cwd), path14.resolve(resolved))) return resolved;
9964
+ return isRegisteredWorktree(path14.resolve(resolved), cwd) ? resolved : null;
9965
+ } catch {
9966
+ return null;
9967
+ }
9968
+ }
9969
+ function isInside2(parent, child) {
9970
+ const relative14 = path14.relative(parent, child);
9971
+ return relative14 === "" || !relative14.startsWith("..") && !path14.isAbsolute(relative14);
9972
+ }
9973
+ function isRegisteredWorktree(gitDir, cwd) {
9974
+ try {
9975
+ const back = fs14.readFileSync(path14.join(gitDir, "gitdir"), "utf8").trim();
9976
+ return path14.resolve(gitDir, back) === path14.join(path14.resolve(cwd), ".git");
9977
+ } catch {
9978
+ return false;
9979
+ }
9980
+ }
9981
+ function gitOutput(cwd, args) {
9982
+ try {
9983
+ const output = childProcess2.execFileSync("git", args, {
9984
+ cwd,
9985
+ encoding: "utf8",
9986
+ stdio: ["ignore", "pipe", "ignore"]
9987
+ });
9988
+ const trimmed = output.trim();
9989
+ return trimmed.length > 0 ? trimmed : null;
8903
9990
  } catch {
8904
9991
  return null;
8905
9992
  }
8906
9993
  }
9994
+ function configuredHooksDirectory(cwd) {
9995
+ const hooks = gitOutput(cwd, ["rev-parse", "--git-path", "hooks"]);
9996
+ if (hooks === null) return null;
9997
+ const resolved = path14.resolve(cwd, hooks);
9998
+ const common = gitOutput(cwd, ["rev-parse", "--git-common-dir"]);
9999
+ const commonDir = common === null ? null : path14.resolve(cwd, common);
10000
+ if (isInside2(path14.resolve(cwd), resolved)) return { dir: resolved };
10001
+ if (commonDir !== null && isInside2(commonDir, resolved)) return { dir: resolved };
10002
+ return {
10003
+ 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.`
10004
+ };
10005
+ }
8907
10006
  function installPreCommitHook(cwd, outDir = "snapshot") {
8908
- const gitDir = gitDirectory(cwd);
8909
- if (gitDir === null) {
10007
+ const configured = configuredHooksDirectory(cwd);
10008
+ if (configured !== null && "refusal" in configured) {
10009
+ return { path: null, written: false, notes: [configured.refusal] };
10010
+ }
10011
+ const gitDir = configured === null ? gitDirectory(cwd) : null;
10012
+ if (configured === null && gitDir === null) {
8910
10013
  return {
8911
10014
  path: null,
8912
10015
  written: false,
@@ -8915,10 +10018,10 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
8915
10018
  ]
8916
10019
  };
8917
10020
  }
8918
- const hooksDir = path14.join(gitDir, "hooks");
10021
+ const hooksDir = configured === null ? path14.join(gitDir, "hooks") : configured.dir;
8919
10022
  const hookPath = path14.join(hooksDir, "pre-commit");
8920
10023
  try {
8921
- fs13.mkdirSync(hooksDir, { recursive: true });
10024
+ fs14.mkdirSync(hooksDir, { recursive: true });
8922
10025
  } catch (err) {
8923
10026
  return {
8924
10027
  path: hookPath,
@@ -8928,7 +10031,7 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
8928
10031
  }
8929
10032
  let existing = null;
8930
10033
  try {
8931
- existing = fs13.readFileSync(hookPath, "utf8");
10034
+ existing = fs14.readFileSync(hookPath, "utf8");
8932
10035
  } catch {
8933
10036
  existing = null;
8934
10037
  }
@@ -8943,8 +10046,8 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
8943
10046
  };
8944
10047
  }
8945
10048
  try {
8946
- fs13.writeFileSync(hookPath, hookScript(outDir), "utf8");
8947
- fs13.chmodSync(hookPath, 493);
10049
+ fs14.writeFileSync(hookPath, hookScript(outDir), "utf8");
10050
+ fs14.chmodSync(hookPath, 493);
8948
10051
  } catch (err) {
8949
10052
  return {
8950
10053
  path: hookPath,
@@ -9006,14 +10109,14 @@ const { parentPort, workerData } = require("node:worker_threads");
9006
10109
  })();
9007
10110
  `;
9008
10111
  function generateInWorker(cwd, cliOptions) {
9009
- return new Promise((resolve10) => {
10112
+ return new Promise((resolve11) => {
9010
10113
  let settled = false;
9011
10114
  let worker = null;
9012
10115
  const finish = (result) => {
9013
10116
  if (settled) return;
9014
10117
  settled = true;
9015
10118
  if (worker !== null) void worker.terminate();
9016
- resolve10(result);
10119
+ resolve11(result);
9017
10120
  };
9018
10121
  const isCjs = typeof __dirname !== "undefined";
9019
10122
  const directory = isCjs ? __dirname : path15.dirname(fileURLToPath(import.meta.url));
@@ -9046,7 +10149,6 @@ function generateInWorker(cwd, cliOptions) {
9046
10149
  }
9047
10150
 
9048
10151
  // src/index.ts
9049
- var SCHEMA_VERSION = "3.0.0";
9050
10152
  var SUMMARY_MAX_SOURCE_BYTES2 = SUMMARY_MAX_SOURCE_BYTES;
9051
10153
  var FILE_DERIVATIONS = /* @__PURE__ */ new Map();
9052
10154
  var FILE_DERIVATION_LIMIT_BYTES = 64 * 1024 * 1024;
@@ -9054,12 +10156,21 @@ var fileDerivationBytes = 0;
9054
10156
  function takeDerivation(path22, hash, settings) {
9055
10157
  const cached = FILE_DERIVATIONS.get(path22);
9056
10158
  if (cached === void 0 || cached.hash !== hash || cached.settings !== settings) return void 0;
10159
+ FILE_DERIVATIONS.delete(path22);
10160
+ FILE_DERIVATIONS.set(path22, cached);
9057
10161
  return cached;
9058
10162
  }
9059
10163
  function rememberDerivation(path22, hash, settings, derivation) {
9060
10164
  const bodyBytes = derivation.finalContent === derivation.redacted ? derivation.redacted.length : derivation.redacted.length + derivation.finalContent.length;
9061
10165
  const bytes = bodyBytes * 2 + 512;
9062
10166
  if (bytes > FILE_DERIVATION_LIMIT_BYTES / 4) return;
10167
+ const previous = FILE_DERIVATIONS.get(path22);
10168
+ if (previous !== void 0) {
10169
+ FILE_DERIVATIONS.delete(path22);
10170
+ fileDerivationBytes -= previous.bytes;
10171
+ } else {
10172
+ FILE_DERIVATIONS.delete(path22);
10173
+ }
9063
10174
  while (fileDerivationBytes + bytes > FILE_DERIVATION_LIMIT_BYTES) {
9064
10175
  const oldest = FILE_DERIVATIONS.keys().next();
9065
10176
  if (oldest.done === true) break;
@@ -9080,11 +10191,12 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
9080
10191
  const lineCount = countLines(rawContent);
9081
10192
  const { redacted, findings } = scanAndRedactSecrets(rawContent, config.secretRules, relativePath);
9082
10193
  const isLarge = sizeBytes > config.largeFileBytes;
10194
+ const oversizeForSummary = Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES2;
9083
10195
  let finalContent = redacted;
9084
10196
  let isPreviewTruncated = false;
9085
10197
  let includedLines = lineCount;
9086
10198
  let inclusionMode = "full";
9087
- if (config.skeleton === true && isSkeletonizable(relativePath)) {
10199
+ if (config.skeleton === true && isSkeletonizable(relativePath) && !oversizeForSummary) {
9088
10200
  const skeleton = skeletonizeTypeScript(redacted, relativePath);
9089
10201
  if (skeleton.collapsed > 0) {
9090
10202
  finalContent = skeleton.text;
@@ -9104,7 +10216,7 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
9104
10216
  let summarySkip = null;
9105
10217
  let summaryWarning = null;
9106
10218
  let dependentImports = null;
9107
- if (Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES2) {
10219
+ if (oversizeForSummary) {
9108
10220
  summarySkip = "oversize";
9109
10221
  dependentImports = [];
9110
10222
  } else if (SKIP_PREVIEW_SUMMARIES && isPreviewTruncated && hasStructuralSummary(relativePath)) {
@@ -9192,8 +10304,8 @@ function retain(items, keep) {
9192
10304
  items.length = write;
9193
10305
  }
9194
10306
  var SKIP_PREVIEW_SUMMARIES = true;
9195
- function buildIndexes(files) {
9196
- const resolver = buildImportResolver(files);
10307
+ function buildIndexes(files, tsconfigPaths) {
10308
+ const resolver = buildImportResolver(files, { tsconfig: tsconfigPaths });
9197
10309
  const importerCounts = /* @__PURE__ */ new Map();
9198
10310
  const byFile = files.filter((file) => isSourceSummary(file.summary)).map((file) => {
9199
10311
  const summary = file.summary;
@@ -9336,20 +10448,20 @@ function listEntries(dir) {
9336
10448
  const walk = (absolute, prefix) => {
9337
10449
  let children;
9338
10450
  try {
9339
- children = fs14.readdirSync(absolute, { withFileTypes: true });
10451
+ children = fs15.readdirSync(absolute, { withFileTypes: true });
9340
10452
  } catch {
9341
10453
  return;
9342
10454
  }
9343
10455
  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);
10456
+ const relative14 = prefix === "" ? child.name : `${prefix}/${child.name}`;
10457
+ entries.push(relative14);
10458
+ if (child.isDirectory()) walk(path16.join(absolute, child.name), relative14);
9347
10459
  }
9348
10460
  };
9349
10461
  walk(dir, "");
9350
10462
  return entries.sort();
9351
10463
  }
9352
- function markerInventory(dir) {
10464
+ function markerInventory(dir, written) {
9353
10465
  const entries = listEntries(dir);
9354
10466
  const files = [];
9355
10467
  for (const entry of entries) {
@@ -9358,14 +10470,19 @@ function markerInventory(dir) {
9358
10470
  const full = path16.join(dir, ...entry.split("/"));
9359
10471
  let stats;
9360
10472
  try {
9361
- stats = fs14.lstatSync(full);
10473
+ stats = fs15.lstatSync(full);
9362
10474
  } catch {
9363
10475
  continue;
9364
10476
  }
9365
10477
  if (!stats.isFile()) continue;
10478
+ const recorded = written?.get(entry);
10479
+ if (recorded !== void 0 && recorded.digest.bytes === stats.size && recorded.mtimeMs === stats.mtimeMs) {
10480
+ files.push(recorded.digest);
10481
+ continue;
10482
+ }
9366
10483
  let digest;
9367
10484
  try {
9368
- digest = sha256Hex2(fs14.readFileSync(full));
10485
+ digest = sha256Hex2(fs15.readFileSync(full));
9369
10486
  } catch {
9370
10487
  continue;
9371
10488
  }
@@ -9373,8 +10490,8 @@ function markerInventory(dir) {
9373
10490
  }
9374
10491
  return { entries, files };
9375
10492
  }
9376
- function markerPayload(dir, state, id, createdAt) {
9377
- const { entries, files } = markerInventory(dir);
10493
+ function markerPayload(dir, state, id, createdAt, written) {
10494
+ const { entries, files } = markerInventory(dir, written);
9378
10495
  const marker2 = {
9379
10496
  generator: GENERATOR_NAME,
9380
10497
  version: GENERATOR_VERSION,
@@ -9387,13 +10504,13 @@ function markerPayload(dir, state, id, createdAt) {
9387
10504
  files
9388
10505
  };
9389
10506
  const manifestPath = path16.join(dir, "manifest.json");
9390
- if (fs14.existsSync(manifestPath)) {
9391
- marker2.manifestSha256 = sha256Hex2(fs14.readFileSync(manifestPath));
10507
+ if (fs15.existsSync(manifestPath)) {
10508
+ marker2.manifestSha256 = sha256Hex2(fs15.readFileSync(manifestPath));
9392
10509
  }
9393
10510
  return marker2;
9394
10511
  }
9395
10512
  function writeOwnershipMarker(dir, marker2) {
9396
- fs14.writeFileSync(
10513
+ fs15.writeFileSync(
9397
10514
  path16.join(dir, OWNERSHIP_MARKER),
9398
10515
  `${JSON.stringify(marker2, null, 2)}
9399
10516
  `,
@@ -9407,12 +10524,12 @@ function markerBelongsTo(dir, id) {
9407
10524
  }
9408
10525
  function readOwnershipMarker(dir) {
9409
10526
  const markerPath = path16.join(dir, OWNERSHIP_MARKER);
9410
- if (!fs14.existsSync(markerPath)) {
10527
+ if (!fs15.existsSync(markerPath)) {
9411
10528
  return { marker: null, problem: "it holds no .codebase-snapshot marker" };
9412
10529
  }
9413
10530
  let raw;
9414
10531
  try {
9415
- raw = fs14.readFileSync(markerPath, "utf8");
10532
+ raw = fs15.readFileSync(markerPath, "utf8");
9416
10533
  } catch {
9417
10534
  return { marker: null, problem: "its .codebase-snapshot marker could not be read" };
9418
10535
  }
@@ -9515,7 +10632,7 @@ function verifyMarkerInventory(dir, entries, files) {
9515
10632
  const full = path16.join(dir, ...entry.split("/"));
9516
10633
  let stats;
9517
10634
  try {
9518
- stats = fs14.lstatSync(full);
10635
+ stats = fs15.lstatSync(full);
9519
10636
  } catch {
9520
10637
  return `its .codebase-snapshot inventory lists ${entry}, which cannot be read`;
9521
10638
  }
@@ -9540,7 +10657,7 @@ function verifyMarkerInventory(dir, entries, files) {
9540
10657
  }
9541
10658
  let digest;
9542
10659
  try {
9543
- digest = sha256Hex2(fs14.readFileSync(full));
10660
+ digest = sha256Hex2(fs15.readFileSync(full));
9544
10661
  } catch {
9545
10662
  return `its .codebase-snapshot inventory cannot verify ${entry}: the file could not be read`;
9546
10663
  }
@@ -9562,11 +10679,11 @@ function assessSnapshotDirectory(dir) {
9562
10679
  };
9563
10680
  }
9564
10681
  const manifestPath = path16.join(dir, "manifest.json");
9565
- const hasManifest = fs14.existsSync(manifestPath);
10682
+ const hasManifest = fs15.existsSync(manifestPath);
9566
10683
  if (hasManifest) {
9567
10684
  let raw;
9568
10685
  try {
9569
- raw = fs14.readFileSync(manifestPath, "utf8");
10686
+ raw = fs15.readFileSync(manifestPath, "utf8");
9570
10687
  } catch {
9571
10688
  return {
9572
10689
  owned: false,
@@ -9661,7 +10778,7 @@ function containsNoFiles(dir) {
9661
10778
  const current = pending.pop();
9662
10779
  let entries;
9663
10780
  try {
9664
- entries = fs14.readdirSync(current, { withFileTypes: true });
10781
+ entries = fs15.readdirSync(current, { withFileTypes: true });
9665
10782
  } catch {
9666
10783
  return false;
9667
10784
  }
@@ -9676,13 +10793,13 @@ function containsNoFiles(dir) {
9676
10793
  return true;
9677
10794
  }
9678
10795
  function assertReplaceable(target, label, secretRules) {
9679
- if (!fs14.existsSync(target)) return;
9680
- if (!fs14.statSync(target).isDirectory()) {
10796
+ if (!fs15.existsSync(target)) return;
10797
+ if (!fs15.statSync(target).isDirectory()) {
9681
10798
  throw new Error(
9682
10799
  `Refusing to write into ${label} ${target}: it exists but is not a directory.`
9683
10800
  );
9684
10801
  }
9685
- const entries = fs14.readdirSync(target);
10802
+ const entries = fs15.readdirSync(target);
9686
10803
  if (entries.length === 0) return;
9687
10804
  if (entries.every((name) => IGNORABLE_ENTRIES.has(name))) return;
9688
10805
  if (containsNoFiles(target)) return;
@@ -9702,18 +10819,18 @@ function assertReplaceable(target, label, secretRules) {
9702
10819
  );
9703
10820
  }
9704
10821
  function assertStagingRootUsable(tmpDir, secretRules) {
9705
- if (!fs14.existsSync(tmpDir)) return;
9706
- if (!fs14.statSync(tmpDir).isDirectory()) {
10822
+ if (!fs15.existsSync(tmpDir)) return;
10823
+ if (!fs15.statSync(tmpDir).isDirectory()) {
9707
10824
  throw new Error(`Refusing to write into tmpDir ${tmpDir}: it exists but is not a directory.`);
9708
10825
  }
9709
- const entries = fs14.readdirSync(tmpDir);
10826
+ const entries = fs15.readdirSync(tmpDir);
9710
10827
  if (entries.length === 0) return;
9711
10828
  const foreign = entries.filter((name) => {
9712
10829
  const full = path16.join(tmpDir, name);
9713
10830
  if (!name.startsWith(RUN_DIR_PREFIX)) return true;
9714
10831
  let stats;
9715
10832
  try {
9716
- stats = fs14.statSync(full);
10833
+ stats = fs15.statSync(full);
9717
10834
  } catch {
9718
10835
  return true;
9719
10836
  }
@@ -9721,7 +10838,7 @@ function assertStagingRootUsable(tmpDir, secretRules) {
9721
10838
  const { marker: marker2 } = readOwnershipMarker(full);
9722
10839
  if (marker2) return false;
9723
10840
  try {
9724
- return fs14.readdirSync(full).length > 0;
10841
+ return fs15.readdirSync(full).length > 0;
9725
10842
  } catch {
9726
10843
  return true;
9727
10844
  }
@@ -9736,7 +10853,7 @@ function assertStagingRootUsable(tmpDir, secretRules) {
9736
10853
  function cleanStaleRunDirs(tmpDir) {
9737
10854
  let entries;
9738
10855
  try {
9739
- entries = fs14.readdirSync(tmpDir);
10856
+ entries = fs15.readdirSync(tmpDir);
9740
10857
  } catch {
9741
10858
  return;
9742
10859
  }
@@ -9750,58 +10867,101 @@ function cleanStaleRunDirs(tmpDir) {
9750
10867
  const abandoned = typeof marker2.pid === "number" && !isProcessAlive(marker2.pid);
9751
10868
  if (aged || abandoned) {
9752
10869
  try {
9753
- fs14.rmSync(full, { recursive: true, force: true });
10870
+ fs15.rmSync(full, { recursive: true, force: true });
9754
10871
  } catch {
9755
10872
  }
9756
10873
  }
9757
10874
  continue;
9758
10875
  }
9759
10876
  try {
9760
- if (fs14.readdirSync(full).length === 0) fs14.rmSync(full, { recursive: true, force: true });
10877
+ if (fs15.readdirSync(full).length === 0) fs15.rmSync(full, { recursive: true, force: true });
9761
10878
  } catch {
9762
10879
  }
9763
10880
  }
9764
10881
  }
9765
10882
  function removeIfEmpty(dir) {
9766
10883
  try {
9767
- if (fs14.readdirSync(dir).length === 0) fs14.rmSync(dir, { recursive: true, force: true });
10884
+ if (fs15.readdirSync(dir).length === 0) fs15.rmSync(dir, { recursive: true, force: true });
9768
10885
  } catch {
9769
10886
  }
9770
10887
  }
9771
10888
  function ensureParentDirectory(target, label) {
9772
10889
  const parent = path16.dirname(target);
9773
- if (fs14.existsSync(parent) && !fs14.statSync(parent).isDirectory()) {
10890
+ if (fs15.existsSync(parent) && !fs15.statSync(parent).isDirectory()) {
9774
10891
  throw new Error(
9775
10892
  `Refusing to create ${label} ${target}: ${parent} exists but is not a directory.`
9776
10893
  );
9777
10894
  }
9778
10895
  try {
9779
- fs14.mkdirSync(parent, { recursive: true });
10896
+ fs15.mkdirSync(parent, { recursive: true });
9780
10897
  } catch (err) {
9781
10898
  throw new Error(
9782
10899
  `Refusing to create ${label} ${target}: its parent ${parent} could not be created (${err.message}).`
9783
10900
  );
9784
10901
  }
9785
10902
  }
10903
+ var LOCK_HEARTBEAT_MS = 5e3;
10904
+ var LOCK_STALE_HEARTBEAT_MS = 12e4;
10905
+ var LOCK_HEARTBEAT_SOURCE = `
10906
+ const { parentPort, workerData } = require("node:worker_threads");
10907
+ const fs = require("node:fs");
10908
+ const { lockPath, intervalMs } = workerData;
10909
+ const timer = setInterval(() => {
10910
+ try {
10911
+ const now = new Date();
10912
+ fs.utimesSync(lockPath, now, now);
10913
+ } catch (err) {
10914
+ // The lock was reclaimed or removed; nothing left to keep alive.
10915
+ }
10916
+ }, intervalMs);
10917
+ timer.unref();
10918
+ if (parentPort) {
10919
+ parentPort.on("message", (message) => {
10920
+ if (message === "stop") {
10921
+ clearInterval(timer);
10922
+ process.exit(0);
10923
+ }
10924
+ });
10925
+ }
10926
+ `;
10927
+ function startLockHeartbeat(lockPath) {
10928
+ try {
10929
+ const worker = new Worker2(LOCK_HEARTBEAT_SOURCE, {
10930
+ eval: true,
10931
+ workerData: { lockPath, intervalMs: LOCK_HEARTBEAT_MS }
10932
+ });
10933
+ worker.unref();
10934
+ return () => {
10935
+ void worker.terminate().catch(() => void 0);
10936
+ };
10937
+ } catch {
10938
+ return () => void 0;
10939
+ }
10940
+ }
9786
10941
  function acquireRunLock(stagingRoot) {
9787
10942
  const lockPath = lockPathFor(stagingRoot);
9788
10943
  const payload = `${JSON.stringify({
9789
10944
  pid: process.pid,
9790
10945
  stagingRoot,
10946
+ host: os2.hostname(),
10947
+ runId: crypto4.randomUUID(),
10948
+ heartbeatMs: LOCK_HEARTBEAT_MS,
9791
10949
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
9792
10950
  })}
9793
10951
  `;
9794
10952
  for (let attempt = 0; attempt < 2; attempt += 1) {
9795
10953
  try {
9796
- const handle = fs14.openSync(lockPath, "wx");
10954
+ const handle = fs15.openSync(lockPath, "wx");
9797
10955
  try {
9798
- fs14.writeSync(handle, payload);
10956
+ fs15.writeSync(handle, payload);
9799
10957
  } finally {
9800
- fs14.closeSync(handle);
10958
+ fs15.closeSync(handle);
9801
10959
  }
10960
+ const stopHeartbeat = startLockHeartbeat(lockPath);
9802
10961
  return () => {
10962
+ stopHeartbeat();
9803
10963
  try {
9804
- fs14.rmSync(lockPath, { force: true });
10964
+ fs15.rmSync(lockPath, { force: true });
9805
10965
  } catch {
9806
10966
  }
9807
10967
  };
@@ -9809,7 +10969,7 @@ function acquireRunLock(stagingRoot) {
9809
10969
  if (err.code !== "EEXIST") throw err;
9810
10970
  if (attempt === 0 && reclaimStaleLock(lockPath)) continue;
9811
10971
  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.`
10972
+ `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
10973
  );
9814
10974
  }
9815
10975
  }
@@ -9826,7 +10986,7 @@ function canonicalLockTarget(targetPath2) {
9826
10986
  const tail = [];
9827
10987
  for (; ; ) {
9828
10988
  try {
9829
- return path16.join(fs14.realpathSync(existing), ...tail);
10989
+ return path16.join(fs15.realpathSync(existing), ...tail);
9830
10990
  } catch {
9831
10991
  const parent = path16.dirname(existing);
9832
10992
  if (parent === existing) return resolved;
@@ -9838,10 +10998,17 @@ function canonicalLockTarget(targetPath2) {
9838
10998
  function lockPathFor(stagingRoot) {
9839
10999
  return path16.join(os2.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
9840
11000
  }
11001
+ function lockHeartbeatAgeMs(lockPath) {
11002
+ try {
11003
+ return Date.now() - fs15.statSync(lockPath).mtimeMs;
11004
+ } catch {
11005
+ return Number.POSITIVE_INFINITY;
11006
+ }
11007
+ }
9841
11008
  function lockOwnerIsGone(lockPath) {
9842
11009
  let raw;
9843
11010
  try {
9844
- raw = fs14.readFileSync(lockPath, "utf8");
11011
+ raw = fs15.readFileSync(lockPath, "utf8");
9845
11012
  } catch {
9846
11013
  return false;
9847
11014
  }
@@ -9854,96 +11021,120 @@ function lockOwnerIsGone(lockPath) {
9854
11021
  if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return lockFileIsAncient(lockPath);
9855
11022
  try {
9856
11023
  process.kill(pid, 0);
9857
- return false;
11024
+ return lockFileIsAncient(lockPath);
9858
11025
  } catch (err) {
9859
- return err.code === "ESRCH";
11026
+ if (err.code !== "ESRCH") return lockFileIsAncient(lockPath);
11027
+ return true;
9860
11028
  }
9861
11029
  }
9862
11030
  function reclaimStaleLock(lockPath) {
9863
11031
  let before;
9864
11032
  try {
9865
- before = fs14.statSync(lockPath);
11033
+ before = fs15.statSync(lockPath);
9866
11034
  } catch {
9867
11035
  return true;
9868
11036
  }
9869
11037
  if (!lockOwnerIsGone(lockPath)) return false;
9870
11038
  try {
9871
- const current = fs14.statSync(lockPath);
11039
+ const current = fs15.statSync(lockPath);
9872
11040
  const sameFile = current.ino === before.ino && current.birthtimeMs === before.birthtimeMs && current.mtimeMs === before.mtimeMs;
9873
11041
  if (!sameFile) return false;
9874
- fs14.rmSync(lockPath, { force: true });
11042
+ fs15.rmSync(lockPath, { force: true });
9875
11043
  return true;
9876
11044
  } catch {
9877
11045
  return false;
9878
11046
  }
9879
11047
  }
9880
11048
  function lockFileIsAncient(lockPath) {
9881
- try {
9882
- return Date.now() - fs14.statSync(lockPath).mtimeMs > STALE_RUN_MS;
9883
- } catch {
9884
- return false;
9885
- }
11049
+ return lockHeartbeatAgeMs(lockPath) > LOCK_STALE_HEARTBEAT_MS;
9886
11050
  }
9887
11051
  function writeManifestAtomically(manifestPath, manifest) {
9888
11052
  const tempPath = `${manifestPath}.${process.pid}.tmp`;
9889
- fs14.writeFileSync(tempPath, JSON.stringify(manifest, null, 2), "utf8");
11053
+ fs15.writeFileSync(tempPath, JSON.stringify(manifest, null, 2), "utf8");
9890
11054
  try {
9891
- fs14.renameSync(tempPath, manifestPath);
11055
+ fs15.renameSync(tempPath, manifestPath);
9892
11056
  } catch (err) {
9893
11057
  try {
9894
- fs14.rmSync(tempPath, { force: true });
11058
+ fs15.rmSync(tempPath, { force: true });
9895
11059
  } catch {
9896
11060
  }
9897
11061
  throw err;
9898
11062
  }
9899
11063
  }
9900
- function swapIntoPlace(stagingDir, outDir) {
11064
+ function swapIntoPlace(stagingDir, outDir, beforeSwap) {
9901
11065
  ensureParentDirectory(outDir, "outDir");
9902
11066
  const deadline = Date.now() + 3e3;
9903
- for (let attempt = 0; ; attempt += 1) {
11067
+ let delay = 25;
11068
+ for (; ; ) {
9904
11069
  try {
9905
- swapOnce(stagingDir, outDir);
11070
+ swapOnce(stagingDir, outDir, beforeSwap);
9906
11071
  return;
9907
11072
  } catch (err) {
9908
11073
  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);
11074
+ const retryable = code === "ENOENT" || code === "ENOTEMPTY" || code === "EEXIST" || code === "EPERM";
11075
+ const remaining = deadline - Date.now();
11076
+ if (!retryable || remaining <= 0) throw err;
11077
+ sleepSync(Math.min(delay, remaining));
11078
+ delay = Math.min(delay * 2, 400);
9912
11079
  }
9913
11080
  }
9914
11081
  }
9915
- function swapOnce(stagingDir, outDir) {
11082
+ function recoverInterruptedPublish(outDir) {
11083
+ if (fs15.existsSync(outDir)) return;
11084
+ const parent = path16.dirname(outDir);
11085
+ const base = path16.basename(outDir);
11086
+ let backups;
11087
+ try {
11088
+ backups = fs15.readdirSync(parent).filter((name) => name.startsWith(`${base}.backup-`));
11089
+ } catch {
11090
+ return;
11091
+ }
11092
+ if (backups.length !== 1) return;
11093
+ const backupDir = path16.join(parent, backups[0]);
11094
+ const { marker: marker2, problem } = readOwnershipMarker(backupDir);
11095
+ if (problem !== null || marker2 === null || marker2.state !== "complete") return;
11096
+ try {
11097
+ fs15.renameSync(backupDir, outDir);
11098
+ process.stderr.write(
11099
+ `\u26A0 Recovered ${outDir} from ${backupDir}, left by an interrupted run. That snapshot is the one from before the interrupted run.
11100
+ `
11101
+ );
11102
+ } catch {
11103
+ }
11104
+ }
11105
+ function swapOnce(stagingDir, outDir, beforeSwap) {
9916
11106
  const backupDir = `${outDir}.backup-${process.pid}-${Date.now()}`;
9917
- const hadPrevious = fs14.existsSync(outDir);
9918
- if (hadPrevious) fs14.renameSync(outDir, backupDir);
11107
+ const hadPrevious = fs15.existsSync(outDir);
11108
+ if (hadPrevious) beforeSwap?.();
11109
+ if (hadPrevious) fs15.renameSync(outDir, backupDir);
9919
11110
  try {
9920
11111
  try {
9921
- fs14.renameSync(stagingDir, outDir);
11112
+ fs15.renameSync(stagingDir, outDir);
9922
11113
  } catch (err) {
9923
11114
  if (err.code !== "EXDEV") throw err;
9924
11115
  const partialDir = `${outDir}.partial-${process.pid}-${Date.now()}`;
9925
11116
  try {
9926
- fs14.cpSync(stagingDir, partialDir, { recursive: true });
9927
- fs14.renameSync(partialDir, outDir);
9928
- fs14.rmSync(stagingDir, { recursive: true, force: true });
11117
+ fs15.cpSync(stagingDir, partialDir, { recursive: true });
11118
+ fs15.renameSync(partialDir, outDir);
11119
+ fs15.rmSync(stagingDir, { recursive: true, force: true });
9929
11120
  } catch (copyErr) {
9930
11121
  try {
9931
- fs14.rmSync(partialDir, { recursive: true, force: true });
11122
+ fs15.rmSync(partialDir, { recursive: true, force: true });
9932
11123
  } catch {
9933
11124
  }
9934
11125
  throw copyErr;
9935
11126
  }
9936
11127
  }
9937
11128
  } 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);
11129
+ if (hadPrevious && fs15.existsSync(backupDir)) {
11130
+ if (fs15.existsSync(outDir)) fs15.rmSync(outDir, { recursive: true, force: true });
11131
+ fs15.renameSync(backupDir, outDir);
9941
11132
  }
9942
11133
  throw err;
9943
11134
  }
9944
11135
  if (hadPrevious) {
9945
11136
  try {
9946
- fs14.rmSync(backupDir, { recursive: true, force: true });
11137
+ fs15.rmSync(backupDir, { recursive: true, force: true });
9947
11138
  } catch (err) {
9948
11139
  process.stderr.write(
9949
11140
  `\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 +11211,13 @@ function generateSnapshot(configInput, options) {
10020
11211
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput ?? null);
10021
11212
  const dryRun = options?.dryRun ?? false;
10022
11213
  const gitInfo = getGitInfo(config.cwd, config.branch);
11214
+ const changedScope = config.changedSince !== void 0 || config.staged === true ? resolveChangedScope(config.cwd, {
11215
+ ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
11216
+ ...config.staged === true ? { staged: true } : {}
11217
+ }) : null;
11218
+ const changedPaths = changedScope === null ? null : new Set(changedScope.paths);
11219
+ const stagedPaths = changedScope?.stagedPaths ?? /* @__PURE__ */ new Set();
11220
+ const stagedDeletedPaths = changedScope?.deletedPaths ?? /* @__PURE__ */ new Set();
10023
11221
  const collection = collectFiles(config.cwd, {
10024
11222
  includePatterns: config.include,
10025
11223
  excludePatterns: [...config.excludePatterns, ...config.presetExclude],
@@ -10031,13 +11229,11 @@ function generateSnapshot(configInput, options) {
10031
11229
  // output — but only at these exact paths, not at every directory that shares the name.
10032
11230
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
10033
11231
  (directory) => path16.relative(config.cwd, path16.resolve(config.cwd, directory)).replace(/\\/g, "/")
10034
- ).filter((relative12) => relative12.length > 0 && !relative12.startsWith(".."))
11232
+ ).filter((relative14) => relative14.length > 0 && !relative14.startsWith("..")),
11233
+ // A staged path can be absent from the working tree while its index blob exists. Discovery
11234
+ // lists the working tree, so those paths would never reach the scan at all.
11235
+ ...stagedPaths.size > 0 ? { extraPaths: [...stagedPaths] } : {}
10035
11236
  });
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
11237
  const unchangedPaths = [];
10042
11238
  const candidateFiles = changedPaths !== null && config.withDependents !== true ? collection.files.filter((relativePath) => {
10043
11239
  if (changedPaths.has(relativePath)) return true;
@@ -10059,45 +11255,92 @@ function generateSnapshot(configInput, options) {
10059
11255
  const oversizeSummaryPaths = [];
10060
11256
  const previewSummaryPaths = [];
10061
11257
  const skippedSummaryImports = /* @__PURE__ */ new Map();
10062
- const layerCounts = {};
10063
- const kindCounts = {};
11258
+ const layerCounts = /* @__PURE__ */ Object.create(null);
11259
+ const kindCounts = /* @__PURE__ */ Object.create(null);
10064
11260
  let totalLines = 0;
10065
11261
  let totalSizeBytes = 0;
10066
11262
  let largeFileCount = 0;
10067
11263
  for (const relativePath of candidateFiles) {
10068
11264
  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 ? {
11265
+ const fromIndex = stagedPaths.has(relativePath);
11266
+ let buffer;
11267
+ let sizeBytes;
11268
+ if (fromIndex && stagedDeletedPaths.has(relativePath)) {
11269
+ skipped.push({
11270
+ path: relativePath,
11271
+ reason: "deleted",
11272
+ detail: "staged for deletion; it is not part of the next commit"
11273
+ });
11274
+ continue;
11275
+ }
11276
+ if (fromIndex) {
11277
+ const staged = readStagedBlob(config.cwd, relativePath);
11278
+ if (staged === null) {
11279
+ skipped.push({
11280
+ path: relativePath,
11281
+ reason: "deleted",
11282
+ detail: "staged path has no blob in the index; it is not part of the next commit"
11283
+ });
11284
+ continue;
11285
+ }
11286
+ if (isBinaryExtension(absolutePath)) {
11287
+ skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${staged.length} B` });
11288
+ continue;
11289
+ }
11290
+ buffer = staged;
11291
+ sizeBytes = staged.length;
11292
+ } else {
11293
+ let stats;
11294
+ try {
11295
+ stats = fs15.statSync(absolutePath);
11296
+ if (!stats.isFile()) {
11297
+ const nestedRepository = stats.isDirectory() && fs15.existsSync(path16.join(absolutePath, ".git"));
11298
+ skipped.push(
11299
+ nestedRepository ? {
11300
+ path: relativePath,
11301
+ reason: "nested-repository",
11302
+ detail: "a directory belonging to another repository (nested checkout or submodule); its contents are not scanned"
11303
+ } : { path: relativePath, reason: "not-file" }
11304
+ );
11305
+ continue;
11306
+ }
11307
+ } catch (err) {
11308
+ const code = err.code;
11309
+ if (code === "ENOENT" || code === "ENOTDIR") {
11310
+ skipped.push({
10076
11311
  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
- );
11312
+ reason: "missing",
11313
+ detail: "tracked but absent from disk (deleted without staging)"
11314
+ });
11315
+ } else {
11316
+ skipped.push({
11317
+ path: relativePath,
11318
+ reason: "read-error",
11319
+ detail: String(err.message).replace(/\s+/g, " ")
11320
+ });
11321
+ }
10081
11322
  continue;
10082
11323
  }
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;
11324
+ if (isBinaryExtension(absolutePath)) {
11325
+ skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${stats.size} B` });
11326
+ continue;
11327
+ }
11328
+ if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) {
11329
+ skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${stats.size} B` });
11330
+ continue;
11331
+ }
11332
+ try {
11333
+ buffer = fs15.readFileSync(absolutePath);
11334
+ } catch (err) {
11335
+ const code = err.code;
11336
+ skipped.push({
11337
+ path: relativePath,
11338
+ reason: code === "ENOENT" || code === "ENOTDIR" ? "missing" : "read-error",
11339
+ detail: String(err.message).replace(/\s+/g, " ")
11340
+ });
11341
+ continue;
11342
+ }
11343
+ sizeBytes = stats.size;
10101
11344
  }
10102
11345
  let decoded;
10103
11346
  try {
@@ -10106,7 +11349,7 @@ function generateSnapshot(configInput, options) {
10106
11349
  skipped.push({
10107
11350
  path: relativePath,
10108
11351
  reason: "read-error",
10109
- detail: `Size: ${stats.size} B; could not be decoded: ${err.message}`.replace(
11352
+ detail: `Size: ${sizeBytes} B; could not be decoded: ${err.message}`.replace(
10110
11353
  /\s+/g,
10111
11354
  " "
10112
11355
  )
@@ -10117,13 +11360,13 @@ function generateSnapshot(configInput, options) {
10117
11360
  skipped.push({
10118
11361
  path: relativePath,
10119
11362
  reason: "binary",
10120
- detail: `Size: ${stats.size} B; ${decoded.binaryReason ?? "binary content"}`
11363
+ detail: `Size: ${sizeBytes} B; ${decoded.binaryReason ?? "binary content"}`
10121
11364
  });
10122
11365
  continue;
10123
11366
  }
10124
11367
  const hashSha256 = sha256Hex2(buffer);
10125
11368
  const rawContent = decoded.text;
10126
- totalSizeBytes += stats.size;
11369
+ totalSizeBytes += sizeBytes;
10127
11370
  if (decoded.encoding !== "utf-8") {
10128
11371
  encodingNotes.push({
10129
11372
  path: relativePath,
@@ -10137,7 +11380,7 @@ function generateSnapshot(configInput, options) {
10137
11380
  bump(layerCounts, layer2);
10138
11381
  bump(kindCounts, kind);
10139
11382
  const derivation = takeDerivation(absolutePath, hashSha256, derivationKey) ?? (() => {
10140
- const fresh = deriveFile(relativePath, rawContent, stats.size, config);
11383
+ const fresh = deriveFile(relativePath, rawContent, sizeBytes, config);
10141
11384
  rememberDerivation(absolutePath, hashSha256, derivationKey, fresh);
10142
11385
  return fresh;
10143
11386
  })();
@@ -10158,7 +11401,7 @@ function generateSnapshot(configInput, options) {
10158
11401
  }
10159
11402
  files.push({
10160
11403
  relativePath,
10161
- sizeBytes: stats.size,
11404
+ sizeBytes,
10162
11405
  lines: lineCount,
10163
11406
  hashSha256,
10164
11407
  part: "",
@@ -10179,7 +11422,10 @@ function generateSnapshot(configInput, options) {
10179
11422
  }
10180
11423
  if (changedScope !== null && changedPaths !== null && config.withDependents === true) {
10181
11424
  const keep = new Set(changedPaths);
10182
- const resolver = buildImportResolver(files);
11425
+ const resolver = buildImportResolver(files, {
11426
+ extraPaths: changedPaths,
11427
+ tsconfig: tsconfigPathsFor(config.cwd)
11428
+ });
10183
11429
  for (const file of files) {
10184
11430
  const fileImports = isSourceSummary(file.summary) ? file.summary.imports : skippedSummaryImports.get(file.relativePath) ?? [];
10185
11431
  if (fileImports.length === 0) continue;
@@ -10273,7 +11519,7 @@ function generateSnapshot(configInput, options) {
10273
11519
  const fingerprint = sha256Hex2(
10274
11520
  [
10275
11521
  ...files.map(
10276
- (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
11522
+ (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}`
10277
11523
  ),
10278
11524
  `settings:${configDigest(config)}`
10279
11525
  ].join("\n")
@@ -10360,6 +11606,8 @@ function generateSnapshot(configInput, options) {
10360
11606
  skippedFiles: skipped.length,
10361
11607
  totalSourceBytes: totalSizeBytes,
10362
11608
  totalContentBytes,
11609
+ sourceLines: totalLines,
11610
+ emittedLines: files.reduce((total, file) => total + file.includedLines, 0),
10363
11611
  // The parts are what a model is handed, so the estimate is over the parts rather than
10364
11612
  // over the sources: previews and the byte budget both shrink the number.
10365
11613
  estimatedTokens: parts.reduce((total, part) => total + part.metadata.estimatedTokens, 0),
@@ -10378,7 +11626,7 @@ function generateSnapshot(configInput, options) {
10378
11626
  },
10379
11627
  layers: layerCounts,
10380
11628
  kinds: kindCounts,
10381
- indexes: buildIndexes(files),
11629
+ indexes: buildIndexes(files, tsconfigPathsFor(config.cwd)),
10382
11630
  parts: parts.map((part) => part.metadata),
10383
11631
  files: files.map((file) => {
10384
11632
  const { content: _content, ...rest } = file;
@@ -10395,6 +11643,23 @@ function generateSnapshot(configInput, options) {
10395
11643
  );
10396
11644
  manifest.totals.warningCount = manifest.warnings.length;
10397
11645
  }
11646
+ if (files.some((file) => file.isPreviewTruncated) && config.largeFileBytes <= config.maxPartBytes) {
11647
+ manifest.warnings.push(
11648
+ `${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.`
11649
+ );
11650
+ manifest.totals.warningCount = manifest.warnings.length;
11651
+ }
11652
+ if (config.maxPartTokens !== void 0) {
11653
+ const overTokenBudget = parts.filter(
11654
+ (part) => part.metadata.estimatedTokens > (config.maxPartTokens ?? 0)
11655
+ );
11656
+ if (overTokenBudget.length > 0) {
11657
+ manifest.warnings.push(
11658
+ `${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.`
11659
+ );
11660
+ manifest.totals.warningCount = manifest.warnings.length;
11661
+ }
11662
+ }
10398
11663
  if (secretFindings.length > 0 && !config.artifacts.audit) {
10399
11664
  manifest.warnings.push(
10400
11665
  `${secretFindings.length} line(s) contain redacted values; reports/audit.md is disabled, so the per-line detail was not written.`
@@ -10423,6 +11688,18 @@ function generateSnapshot(configInput, options) {
10423
11688
  sha256: sha256Hex2(sarifText)
10424
11689
  };
10425
11690
  }
11691
+ const artifacts = config.artifacts;
11692
+ const artifactRecord = (text2) => ({
11693
+ byteSize: Buffer.byteLength(text2, "utf8"),
11694
+ sha256: sha256Hex2(text2)
11695
+ });
11696
+ const navigationText = artifacts.navigation ? generateNavigation(manifest) : null;
11697
+ if (navigationText !== null) manifest.artifacts.navigation = artifactRecord(navigationText);
11698
+ const auditText = artifacts.audit ? generateAuditReport(manifest, secretFindings, config.secretRules) : null;
11699
+ if (auditText !== null) manifest.artifacts.audit = artifactRecord(auditText);
11700
+ const readmeText = artifacts.readme ? generateReadme(manifest, artifacts) : null;
11701
+ if (readmeText !== null) manifest.artifacts.readme = artifactRecord(readmeText);
11702
+ if (projectTree !== null) manifest.artifacts.projectTree = artifactRecord(projectTree);
10426
11703
  let monolithJson = null;
10427
11704
  let monolithMarkdown = null;
10428
11705
  if (config.includeMonolith) {
@@ -10437,26 +11714,33 @@ function generateSnapshot(configInput, options) {
10437
11714
  includedLines: countLines(content)
10438
11715
  };
10439
11716
  });
10440
- const markdown = generateMonolithMarkdown(manifest, fullFiles);
10441
- const markdownBytes = Buffer.byteLength(markdown, "utf8");
10442
- if (!config.maxMonolithBytes || markdownBytes <= config.maxMonolithBytes) {
11717
+ const bodyBytes = fullFiles.reduce((total, file) => total + file.includedBytes, 0);
11718
+ const definitelyTooLarge = config.maxMonolithBytes !== null && bodyBytes > config.maxMonolithBytes;
11719
+ if (definitelyTooLarge) {
11720
+ const reason = `their bodies total ${bodyBytes} B, which already exceeds maxMonolithBytes ${config.maxMonolithBytes ?? 0} B`;
11721
+ manifest.warnings.push(`full-codebase.md skipped: ${reason}`);
11722
+ manifest.warnings.push(`full-codebase.json skipped: ${reason}`);
11723
+ }
11724
+ const markdown = definitelyTooLarge ? null : generateMonolithMarkdown(manifest, fullFiles);
11725
+ const markdownBytes = markdown === null ? 0 : Buffer.byteLength(markdown, "utf8");
11726
+ if (markdown !== null && (!config.maxMonolithBytes || markdownBytes <= config.maxMonolithBytes)) {
10443
11727
  monolithMarkdown = markdown;
10444
11728
  manifest.artifacts.fullMarkdown = {
10445
11729
  byteSize: markdownBytes,
10446
11730
  sha256: sha256Hex2(markdown)
10447
11731
  };
10448
- } else {
11732
+ } else if (!definitelyTooLarge) {
10449
11733
  manifest.warnings.push(
10450
11734
  `full-codebase.md skipped: ${markdownBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
10451
11735
  );
10452
11736
  }
10453
11737
  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) {
11738
+ const json = definitelyTooLarge ? null : generateMonolithJson(manifest, fullFiles);
11739
+ const jsonBytes = json === null ? 0 : Buffer.byteLength(json, "utf8");
11740
+ if (json !== null && (!config.maxMonolithBytes || jsonBytes <= config.maxMonolithBytes)) {
10457
11741
  monolithJson = json;
10458
11742
  manifest.artifacts.fullJson = { byteSize: jsonBytes, sha256: sha256Hex2(json) };
10459
- } else {
11743
+ } else if (!definitelyTooLarge) {
10460
11744
  manifest.warnings.push(
10461
11745
  `full-codebase.json skipped: ${jsonBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
10462
11746
  );
@@ -10464,7 +11748,6 @@ function generateSnapshot(configInput, options) {
10464
11748
  manifest.totals.warningCount = manifest.warnings.length;
10465
11749
  }
10466
11750
  const { outDir, tmpDir } = resolveSafeOutputDirs(config);
10467
- const { artifacts } = config;
10468
11751
  assertReplaceable(outDir, "outDir", config.secretRules);
10469
11752
  assertStagingRootUsable(tmpDir, config.secretRules);
10470
11753
  if (dryRun) {
@@ -10481,15 +11764,18 @@ function generateSnapshot(configInput, options) {
10481
11764
  const releaseLock = () => {
10482
11765
  for (const release of [...releases].reverse()) release();
10483
11766
  };
11767
+ recoverInterruptedPublish(outDir);
11768
+ assertReplaceable(outDir, "outDir", config.secretRules);
10484
11769
  let stagingDir = null;
11770
+ let releaseDeferred = false;
10485
11771
  try {
10486
11772
  ensureParentDirectory(outDir, "outDir");
10487
- fs14.mkdirSync(tmpDir, { recursive: true });
11773
+ fs15.mkdirSync(tmpDir, { recursive: true });
10488
11774
  cleanStaleRunDirs(tmpDir);
10489
11775
  const snapshotId = crypto4.randomUUID();
10490
11776
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
10491
11777
  stagingDir = path16.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
10492
- fs14.mkdirSync(stagingDir);
11778
+ fs15.mkdirSync(stagingDir);
10493
11779
  writeOwnershipMarker(stagingDir, {
10494
11780
  generator: GENERATOR_NAME,
10495
11781
  version: GENERATOR_VERSION,
@@ -10501,45 +11787,66 @@ function generateSnapshot(configInput, options) {
10501
11787
  });
10502
11788
  const partsDir = path16.join(stagingDir, "parts");
10503
11789
  const reportsDir = path16.join(stagingDir, "reports");
10504
- if (artifacts.parts) fs14.mkdirSync(partsDir, { recursive: true });
11790
+ if (artifacts.parts) fs15.mkdirSync(partsDir, { recursive: true });
10505
11791
  if (artifacts.navigation || artifacts.projectTree || artifacts.audit || config.sarif === true) {
10506
- fs14.mkdirSync(reportsDir, { recursive: true });
10507
- }
11792
+ fs15.mkdirSync(reportsDir, { recursive: true });
11793
+ }
11794
+ const writtenArtifacts = /* @__PURE__ */ new Map();
11795
+ const writeArtifact = (targetDir, relativeEntry, data) => {
11796
+ const full = path16.join(targetDir, ...relativeEntry.split("/"));
11797
+ fs15.writeFileSync(full, data, "utf8");
11798
+ const stats = fs15.statSync(full);
11799
+ writtenArtifacts.set(relativeEntry, {
11800
+ digest: { path: relativeEntry, bytes: stats.size, sha256: sha256Hex2(data) },
11801
+ mtimeMs: stats.mtimeMs
11802
+ });
11803
+ };
11804
+ const recordArtifact = (targetDir, relativeEntry) => {
11805
+ const full = path16.join(targetDir, ...relativeEntry.split("/"));
11806
+ const stats = fs15.statSync(full);
11807
+ writtenArtifacts.set(relativeEntry, {
11808
+ digest: {
11809
+ path: relativeEntry,
11810
+ bytes: stats.size,
11811
+ sha256: sha256Hex2(fs15.readFileSync(full))
11812
+ },
11813
+ mtimeMs: stats.mtimeMs
11814
+ });
11815
+ };
10508
11816
  if (artifacts.parts) {
10509
11817
  for (const part of parts) {
10510
- fs14.writeFileSync(path16.join(partsDir, part.filename), part.markdown, "utf8");
11818
+ writeArtifact(partsDir, part.filename, part.markdown);
10511
11819
  }
10512
11820
  }
10513
11821
  if (projectTree !== null) {
10514
- fs14.writeFileSync(path16.join(reportsDir, "project-tree.md"), projectTree, "utf8");
11822
+ writeArtifact(reportsDir, "project-tree.md", projectTree);
10515
11823
  }
10516
- if (artifacts.navigation) {
10517
- fs14.writeFileSync(path16.join(reportsDir, "navigation.md"), generateNavigation(manifest), "utf8");
11824
+ if (navigationText !== null) {
11825
+ writeArtifact(reportsDir, "navigation.md", navigationText);
10518
11826
  }
10519
- if (artifacts.audit) {
10520
- fs14.writeFileSync(
10521
- path16.join(reportsDir, "audit.md"),
10522
- generateAuditReport(manifest, secretFindings, config.secretRules),
10523
- "utf8"
10524
- );
11827
+ if (auditText !== null) {
11828
+ writeArtifact(reportsDir, "audit.md", auditText);
10525
11829
  }
10526
11830
  if (sarifText !== null) {
10527
- fs14.writeFileSync(path16.join(reportsDir, "audit.sarif"), sarifText, "utf8");
11831
+ writeArtifact(reportsDir, "audit.sarif", sarifText);
10528
11832
  }
10529
- if (artifacts.readme) {
10530
- fs14.writeFileSync(path16.join(stagingDir, "README.md"), generateReadme(manifest, artifacts), "utf8");
11833
+ if (readmeText !== null) {
11834
+ writeArtifact(stagingDir, "README.md", readmeText);
10531
11835
  }
10532
11836
  if (artifacts.manifest) {
10533
- fs14.writeFileSync(path16.join(stagingDir, "manifest.json"), JSON.stringify(manifest, null, 2), "utf8");
11837
+ writeArtifact(stagingDir, "manifest.json", JSON.stringify(manifest, null, 2));
10534
11838
  }
10535
11839
  if (monolithJson !== null) {
10536
- fs14.writeFileSync(path16.join(stagingDir, "full-codebase.json"), monolithJson, "utf8");
11840
+ writeArtifact(stagingDir, "full-codebase.json", monolithJson);
10537
11841
  }
10538
11842
  if (monolithMarkdown !== null) {
10539
- fs14.writeFileSync(path16.join(stagingDir, "full-codebase.md"), monolithMarkdown, "utf8");
11843
+ writeArtifact(stagingDir, "full-codebase.md", monolithMarkdown);
10540
11844
  }
10541
- writeOwnershipMarker(stagingDir, markerPayload(stagingDir, "complete", snapshotId, createdAt));
10542
- swapIntoPlace(stagingDir, outDir);
11845
+ writeOwnershipMarker(
11846
+ stagingDir,
11847
+ markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts)
11848
+ );
11849
+ swapIntoPlace(stagingDir, outDir, () => assertReplaceable(outDir, "outDir", config.secretRules));
10543
11850
  stagingDir = null;
10544
11851
  const warningsBeforeHook = manifest.warnings.length;
10545
11852
  const pendingHook = runAfterGenerate(config, manifest);
@@ -10547,8 +11854,12 @@ function generateSnapshot(configInput, options) {
10547
11854
  if (!markerBelongsTo(outDir, snapshotId)) return;
10548
11855
  if (artifacts.manifest && manifest.warnings.length !== warningsBeforeHook) {
10549
11856
  writeManifestAtomically(path16.join(outDir, "manifest.json"), manifest);
11857
+ recordArtifact(outDir, "manifest.json");
10550
11858
  }
10551
- writeOwnershipMarker(outDir, markerPayload(outDir, "complete", snapshotId, createdAt));
11859
+ writeOwnershipMarker(
11860
+ outDir,
11861
+ markerPayload(outDir, "complete", snapshotId, createdAt, writtenArtifacts)
11862
+ );
10552
11863
  };
10553
11864
  if (config.hooks.afterGenerate) shipHookState();
10554
11865
  if (pendingHook) {
@@ -10575,25 +11886,32 @@ function generateSnapshot(configInput, options) {
10575
11886
  if (pendingHooks.get(outDir) === tracked) pendingHooks.delete(outDir);
10576
11887
  });
10577
11888
  pendingHooks.set(outDir, tracked);
11889
+ releaseDeferred = true;
11890
+ void tracked.finally(() => {
11891
+ removeIfEmpty(tmpDir);
11892
+ releaseLock();
11893
+ });
10578
11894
  }
10579
11895
  return manifest;
10580
11896
  } catch (err) {
10581
11897
  if (stagingDir !== null) {
10582
11898
  try {
10583
- fs14.rmSync(stagingDir, { recursive: true, force: true });
11899
+ fs15.rmSync(stagingDir, { recursive: true, force: true });
10584
11900
  } catch {
10585
11901
  }
10586
11902
  }
10587
11903
  throw err;
10588
11904
  } finally {
10589
- removeIfEmpty(tmpDir);
10590
- releaseLock();
11905
+ if (!releaseDeferred) {
11906
+ removeIfEmpty(tmpDir);
11907
+ releaseLock();
11908
+ }
10591
11909
  }
10592
11910
  }
10593
11911
  var pendingHooks = /* @__PURE__ */ new Map();
10594
11912
 
10595
11913
  // src/mcp/tools.ts
10596
- import * as fs16 from "fs";
11914
+ import * as fs17 from "fs";
10597
11915
  import * as path18 from "path";
10598
11916
 
10599
11917
  // src/mcp/part.ts
@@ -10701,7 +12019,7 @@ function windowText(body, fromLine, lineCount) {
10701
12019
  }
10702
12020
 
10703
12021
  // src/mcp/workspace.ts
10704
- import * as fs15 from "fs";
12022
+ import * as fs16 from "fs";
10705
12023
  import * as path17 from "path";
10706
12024
  function foldForComparison(value) {
10707
12025
  return process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
@@ -10709,12 +12027,12 @@ function foldForComparison(value) {
10709
12027
  function canonicalPath(value) {
10710
12028
  const absolute = path17.resolve(value);
10711
12029
  try {
10712
- return fs15.realpathSync(absolute);
12030
+ return fs16.realpathSync(absolute);
10713
12031
  } catch {
10714
12032
  return absolute;
10715
12033
  }
10716
12034
  }
10717
- function isInside2(parent, child) {
12035
+ function isInside3(parent, child) {
10718
12036
  const foldedParent = foldForComparison(parent);
10719
12037
  const foldedChild = foldForComparison(child);
10720
12038
  return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path17.sep}`);
@@ -10722,7 +12040,7 @@ function isInside2(parent, child) {
10722
12040
  function resolveThroughExistingAncestor(target) {
10723
12041
  let existing = target;
10724
12042
  const missing = [];
10725
- while (!fs15.existsSync(existing)) {
12043
+ while (!fs16.existsSync(existing)) {
10726
12044
  missing.unshift(path17.basename(existing));
10727
12045
  const parent = path17.dirname(existing);
10728
12046
  if (parent === existing) break;
@@ -10739,7 +12057,7 @@ function resolveRoot(requested, context) {
10739
12057
  const absolute = path17.resolve(context.cwd, wanted);
10740
12058
  let stats;
10741
12059
  try {
10742
- stats = fs15.statSync(absolute);
12060
+ stats = fs16.statSync(absolute);
10743
12061
  } catch {
10744
12062
  return { ok: false, message: `"${wanted}" does not exist, so it cannot be a repository root.` };
10745
12063
  }
@@ -10748,7 +12066,7 @@ function resolveRoot(requested, context) {
10748
12066
  }
10749
12067
  const resolved = canonicalPath(absolute);
10750
12068
  for (const allowed of context.roots) {
10751
- if (isInside2(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
12069
+ if (isInside3(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
10752
12070
  }
10753
12071
  const shown = context.roots.join(", ");
10754
12072
  return {
@@ -10756,8 +12074,8 @@ function resolveRoot(requested, context) {
10756
12074
  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.`
10757
12075
  };
10758
12076
  }
10759
- async function openWorkspace(root, overrides = {}, allowedRoots) {
10760
- const loaded = await loadConfigFileDetailed(root);
12077
+ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
12078
+ const loaded = await loadConfigFileDetailed(root, options);
10761
12079
  if (loaded.errors.length > 0) {
10762
12080
  return {
10763
12081
  ok: false,
@@ -10792,7 +12110,7 @@ async function openWorkspace(root, overrides = {}, allowedRoots) {
10792
12110
  const requested = overrides.outDir.trim();
10793
12111
  const permitted = allowedRoots !== void 0 && allowedRoots.length > 0 ? allowedRoots : [root];
10794
12112
  const resolved = resolveThroughExistingAncestor(path17.resolve(root, requested));
10795
- if (!permitted.some((allowed) => isInside2(canonicalPath(allowed), resolved))) {
12113
+ if (!permitted.some((allowed) => isInside3(canonicalPath(allowed), resolved))) {
10796
12114
  const shown = permitted.map((allowed) => canonicalPath(allowed)).join(", ");
10797
12115
  return {
10798
12116
  ok: false,
@@ -10821,6 +12139,7 @@ async function openWorkspace(root, overrides = {}, allowedRoots) {
10821
12139
  return { ok: false, message: error instanceof Error ? error.message : String(error) };
10822
12140
  }
10823
12141
  }
12142
+ var MANIFEST_CACHE_LIMIT = 8;
10824
12143
  var manifestCache = /* @__PURE__ */ new Map();
10825
12144
  function manifestPathFor(workspace) {
10826
12145
  return path17.resolve(workspace.root, workspace.config.outDir, "manifest.json");
@@ -10829,8 +12148,20 @@ function partPathFor(workspace, filename) {
10829
12148
  if (filename.length === 0 || filename.includes("\0")) return null;
10830
12149
  const partsDir = path17.resolve(workspace.root, workspace.config.outDir, "parts");
10831
12150
  const resolved = path17.resolve(partsDir, filename);
10832
- const relative12 = path17.relative(partsDir, resolved);
10833
- if (relative12.length === 0 || relative12.includes(path17.sep) || relative12.includes("/") || relative12.includes("\\") || path17.isAbsolute(relative12)) {
12151
+ const relative14 = path17.relative(partsDir, resolved);
12152
+ if (relative14.length === 0 || relative14.includes(path17.sep) || relative14.includes("/") || relative14.includes("\\") || path17.isAbsolute(relative14)) {
12153
+ return null;
12154
+ }
12155
+ let stats;
12156
+ try {
12157
+ stats = fs16.lstatSync(resolved);
12158
+ } catch {
12159
+ return null;
12160
+ }
12161
+ if (!stats.isFile()) return null;
12162
+ try {
12163
+ if (path17.dirname(fs16.realpathSync(resolved)) !== fs16.realpathSync(partsDir)) return null;
12164
+ } catch {
10834
12165
  return null;
10835
12166
  }
10836
12167
  return resolved;
@@ -10840,7 +12171,7 @@ function readManifest3(workspace) {
10840
12171
  const shown = path17.relative(workspace.root, file).split(path17.sep).join("/") || file;
10841
12172
  let stats;
10842
12173
  try {
10843
- stats = fs15.statSync(file);
12174
+ stats = fs16.statSync(file);
10844
12175
  } catch {
10845
12176
  return {
10846
12177
  ok: false,
@@ -10849,12 +12180,12 @@ function readManifest3(workspace) {
10849
12180
  };
10850
12181
  }
10851
12182
  const cached = manifestCache.get(file);
10852
- if (cached && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size) {
12183
+ if (cached && cached.mtimeMs === stats.mtimeMs && cached.ctimeMs === stats.ctimeMs && cached.size === stats.size) {
10853
12184
  return { ok: true, manifest: cached.manifest, file };
10854
12185
  }
10855
12186
  let raw;
10856
12187
  try {
10857
- raw = fs15.readFileSync(file, "utf8");
12188
+ raw = fs16.readFileSync(file, "utf8");
10858
12189
  } catch (error) {
10859
12190
  return {
10860
12191
  ok: false,
@@ -10873,7 +12204,18 @@ function readManifest3(workspace) {
10873
12204
  return { ok: false, missing: false, message: `${shown} is not a snapshot manifest: ${problem}` };
10874
12205
  }
10875
12206
  const manifest = parsed;
10876
- manifestCache.set(file, { mtimeMs: stats.mtimeMs, size: stats.size, manifest });
12207
+ manifestCache.delete(file);
12208
+ manifestCache.set(file, {
12209
+ mtimeMs: stats.mtimeMs,
12210
+ ctimeMs: stats.ctimeMs,
12211
+ size: stats.size,
12212
+ manifest
12213
+ });
12214
+ while (manifestCache.size > MANIFEST_CACHE_LIMIT) {
12215
+ const oldest = manifestCache.keys().next().value;
12216
+ if (oldest === void 0) break;
12217
+ manifestCache.delete(oldest);
12218
+ }
10877
12219
  return { ok: true, manifest, file };
10878
12220
  }
10879
12221
  function forgetManifest(file) {
@@ -10976,11 +12318,11 @@ function toRelativePath(root, value) {
10976
12318
  if (cleaned.length === 0 || cleaned.includes("\0")) return null;
10977
12319
  const resolvedRoot = path18.resolve(root);
10978
12320
  const absolute = path18.resolve(resolvedRoot, cleaned);
10979
- const relative12 = path18.relative(resolvedRoot, absolute);
10980
- if (relative12 === "" || relative12 === ".." || relative12.startsWith(`..${path18.sep}`) || path18.isAbsolute(relative12)) {
12321
+ const relative14 = path18.relative(resolvedRoot, absolute);
12322
+ if (relative14 === "" || relative14 === ".." || relative14.startsWith(`..${path18.sep}`) || path18.isAbsolute(relative14)) {
10981
12323
  return null;
10982
12324
  }
10983
- return relative12.split(path18.sep).join("/");
12325
+ return relative14.split(path18.sep).join("/");
10984
12326
  }
10985
12327
  function symbolsOf(entry) {
10986
12328
  const summary = entry.summary;
@@ -11021,7 +12363,9 @@ function symbolsOf(entry) {
11021
12363
  async function prepare(args, context, overrides = {}) {
11022
12364
  const rootOutcome = resolveRoot(args.root, context);
11023
12365
  if (!rootOutcome.ok) return { ok: false, outcome: failure(rootOutcome.message) };
11024
- const opened = await openWorkspace(rootOutcome.root, overrides, context.roots);
12366
+ const opened = await openWorkspace(rootOutcome.root, overrides, context.roots, {
12367
+ allowExecutableConfig: false
12368
+ });
11025
12369
  if (!opened.ok) return { ok: false, outcome: failure(opened.message) };
11026
12370
  return { ok: true, workspace: opened.workspace };
11027
12371
  }
@@ -11377,10 +12721,12 @@ var locateTool = {
11377
12721
  else if (wants("kind") && entry.kind.toLowerCase().includes(needle)) add(entry, "kind");
11378
12722
  }
11379
12723
  if (wants("route")) {
12724
+ const matchedPaths = new Set(matches.map((match) => match.path));
11380
12725
  for (const route of manifest.indexes.routes) {
11381
12726
  const method = route.methods.find((name) => name.toLowerCase().includes(needle));
11382
12727
  if (!route.path.toLowerCase().includes(needle) && method === void 0) continue;
11383
- if (matches.some((match) => match.path === route.path)) continue;
12728
+ if (matchedPaths.has(route.path)) continue;
12729
+ matchedPaths.add(route.path);
11384
12730
  matches.push({
11385
12731
  path: route.path,
11386
12732
  part: route.part,
@@ -11573,7 +12919,9 @@ var readTool = {
11573
12919
  fromLine: { type: "integer" },
11574
12920
  returnedLines: { type: "integer" },
11575
12921
  totalLines: { type: "integer" },
11576
- nextFromLine: { type: "integer" }
12922
+ nextFromLine: { type: "integer" },
12923
+ pageable: { type: "boolean" },
12924
+ reason: { type: "string" }
11577
12925
  }
11578
12926
  },
11579
12927
  annotations: READ_ONLY,
@@ -11612,7 +12960,7 @@ var readTool = {
11612
12960
  }
11613
12961
  let partText;
11614
12962
  try {
11615
- partText = fs16.readFileSync(partPath, "utf8");
12963
+ partText = fs17.readFileSync(partPath, "utf8");
11616
12964
  } catch {
11617
12965
  return failure(
11618
12966
  `${entry.part} could not be read, so the snapshot is damaged. Run snapshot_generate to rebuild it.`
@@ -11629,15 +12977,20 @@ var readTool = {
11629
12977
  const window = windowText(section.body, fromLine, lineCount);
11630
12978
  let body = window.text;
11631
12979
  let truncatedByBytes = false;
12980
+ let clippedInsideLine = false;
11632
12981
  if (Buffer.byteLength(body, "utf8") > MAX_RESULT_BYTES) {
11633
12982
  const clipped = truncateToBytes(body, MAX_RESULT_BYTES);
11634
- body = clipped.content;
11635
- const lastBreak = body.lastIndexOf("\n");
11636
- body = lastBreak > 0 ? body.slice(0, lastBreak) : body;
12983
+ const lastBreak = clipped.content.lastIndexOf("\n");
12984
+ if (lastBreak > 0) {
12985
+ body = clipped.content.slice(0, lastBreak);
12986
+ } else {
12987
+ body = clipped.content;
12988
+ clippedInsideLine = true;
12989
+ }
11637
12990
  truncatedByBytes = true;
11638
12991
  }
11639
12992
  const returnedLines = body.length === 0 ? 0 : body.split("\n").length;
11640
- const moreRemain = !window.pastEnd && (window.truncated || truncatedByBytes);
12993
+ const moreRemain = !clippedInsideLine && !window.pastEnd && (window.truncated || truncatedByBytes);
11641
12994
  const header = [
11642
12995
  `${entry.relativePath} \u2014 ${entry.part}, ${entry.layer}/${entry.kind}, ${entry.language}`,
11643
12996
  // The line range is the answer to "where am I in this file", and it is computed from the
@@ -11651,12 +13004,17 @@ var readTool = {
11651
13004
  ] : section.inclusion === "signatures" ? [
11652
13005
  "Signatures: function and method bodies were replaced with `{ /* ... */ }` when the snapshot was generated."
11653
13006
  ] : [],
11654
- 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}.`
13007
+ 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}.`
11655
13008
  ];
11656
13009
  const lines = [...header, "", body];
11657
13010
  if (moreRemain) {
11658
13011
  const next = window.fromLine + returnedLines;
11659
13012
  lines.push("", `Truncated. Call snapshot_read with fromLine=${next} for the rest.`);
13013
+ } else if (clippedInsideLine) {
13014
+ lines.push(
13015
+ "",
13016
+ "Truncated. The remainder of this line is not reachable through snapshot_read; read the file from disk to see it."
13017
+ );
11660
13018
  }
11661
13019
  return {
11662
13020
  text: lines.join("\n"),
@@ -11670,7 +13028,9 @@ var readTool = {
11670
13028
  fromLine: window.fromLine,
11671
13029
  returnedLines,
11672
13030
  totalLines: window.totalLines,
11673
- truncated: moreRemain,
13031
+ truncated: moreRemain || clippedInsideLine,
13032
+ pageable: !clippedInsideLine,
13033
+ ...clippedInsideLine ? { reason: "line exceeds the result limit; its remainder is not reachable by fromLine" } : {},
11674
13034
  nextFromLine: moreRemain ? window.fromLine + returnedLines : null,
11675
13035
  sha256: entry.hashSha256
11676
13036
  }
@@ -11828,6 +13188,13 @@ var ERROR_CODES = {
11828
13188
  * invent a partial one.
11829
13189
  */
11830
13190
  resourceTooLarge: -32e3,
13191
+ /**
13192
+ * The server is at its concurrency limit.
13193
+ *
13194
+ * Implementation-defined range, like `resourceTooLarge`. A typed error rather than silent
13195
+ * queueing or a dropped request: the caller can retry, and knows why.
13196
+ */
13197
+ overloaded: -32001,
11831
13198
  unsupportedProtocolVersion: -32022
11832
13199
  };
11833
13200
  var METHOD3 = {
@@ -11964,13 +13331,14 @@ var COMMAND_OPTION_SCOPE = {
11964
13331
  "with-dependents",
11965
13332
  "cwd",
11966
13333
  "out-dir",
11967
- "max-part-bytes",
13334
+ // `--large-file-bytes` changes the inclusion mode `explain` reports, so it belongs here.
13335
+ // `--max-part-bytes`, `--max-monolith-bytes`, `--include-monolith`, `--skip-artifacts` and
13336
+ // `--only-artifacts` were accepted and never read: a per-file answer cannot depend on how the
13337
+ // whole snapshot is partitioned, and none of them changes whether this file is included.
13338
+ // Removed rather than implemented, because a flag that parses and does nothing is the defect
13339
+ // this table exists to prevent.
11968
13340
  "large-file-bytes",
11969
- "max-monolith-bytes",
11970
- "include-monolith",
11971
13341
  "include-sensitive-files",
11972
- "skip-artifacts",
11973
- "only-artifacts",
11974
13342
  "no-config",
11975
13343
  "discovery",
11976
13344
  "no-update-check",
@@ -12318,7 +13686,7 @@ function buildAgentContract() {
12318
13686
  type: "string",
12319
13687
  default: "unset",
12320
13688
  appliesTo: optionAppliesTo("max-part-tokens"),
12321
- summary: "Ceiling on a part expressed in tokens. Narrows --max-part-bytes instead of replacing it; the manifest records both units. Minimum 1024."
13689
+ 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."
12322
13690
  },
12323
13691
  {
12324
13692
  flag: "--large-file-bytes",
@@ -12353,7 +13721,7 @@ function buildAgentContract() {
12353
13721
  type: "string",
12354
13722
  default: "auto",
12355
13723
  appliesTo: optionAppliesTo("discovery"),
12356
- 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)."
13724
+ 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)."
12357
13725
  },
12358
13726
  {
12359
13727
  flag: "--skip-artifacts",
@@ -12374,7 +13742,7 @@ function buildAgentContract() {
12374
13742
  type: "boolean",
12375
13743
  default: false,
12376
13744
  appliesTo: optionAppliesTo("skeleton"),
12377
- 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.'
13745
+ 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.'
12378
13746
  },
12379
13747
  {
12380
13748
  flag: "--sarif",
@@ -12488,7 +13856,7 @@ function buildAgentContract() {
12488
13856
  type: "boolean",
12489
13857
  default: false,
12490
13858
  appliesTo: optionAppliesTo("autopilot"),
12491
- 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)."
13859
+ 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)."
12492
13860
  },
12493
13861
  {
12494
13862
  flag: "--install",
@@ -12523,7 +13891,7 @@ function buildAgentContract() {
12523
13891
  type: "boolean",
12524
13892
  default: false,
12525
13893
  appliesTo: optionAppliesTo("no-update-check"),
12526
- summary: "Skip the once-a-day check for a newer published version. The check is already skipped when stdout is not a terminal, in CI, in a JSON invocation, and in `mcp`, which makes no network requests."
13894
+ summary: "Skip the check for a newer published version. The check is already skipped when stdout is not a terminal, in CI, in a JSON invocation, and in `mcp`, which makes no network requests."
12527
13895
  }
12528
13896
  ],
12529
13897
  presets: PRESETS.map((preset) => ({
@@ -12662,7 +14030,7 @@ function buildAgentContract() {
12662
14030
  }
12663
14031
 
12664
14032
  // src/agent/install-skill.ts
12665
- import * as fs17 from "fs";
14033
+ import * as fs18 from "fs";
12666
14034
  import * as path19 from "path";
12667
14035
 
12668
14036
  // src/agent/skill.ts
@@ -12832,11 +14200,11 @@ function targetPath(cwd, target) {
12832
14200
  }
12833
14201
  }
12834
14202
  function assertWritableInsideRepository(cwd, filePath) {
12835
- const root = fs17.realpathSync(cwd);
14203
+ const root = fs18.realpathSync(cwd);
12836
14204
  const shown = path19.relative(root, filePath) || filePath;
12837
14205
  let stat = null;
12838
14206
  try {
12839
- stat = fs17.lstatSync(filePath);
14207
+ stat = fs18.lstatSync(filePath);
12840
14208
  } catch {
12841
14209
  stat = null;
12842
14210
  }
@@ -12852,13 +14220,13 @@ function assertWritableInsideRepository(cwd, filePath) {
12852
14220
  }
12853
14221
  let existing = filePath;
12854
14222
  const missing = [];
12855
- while (!fs17.existsSync(existing)) {
14223
+ while (!fs18.existsSync(existing)) {
12856
14224
  missing.unshift(path19.basename(existing));
12857
14225
  const parent = path19.dirname(existing);
12858
14226
  if (parent === existing) break;
12859
14227
  existing = parent;
12860
14228
  }
12861
- const realAncestor = fs17.realpathSync(existing);
14229
+ const realAncestor = fs18.realpathSync(existing);
12862
14230
  const resolved = missing.length === 0 ? realAncestor : path19.join(realAncestor, ...missing);
12863
14231
  if (resolved !== root && !resolved.startsWith(`${root}${path19.sep}`)) {
12864
14232
  throw new Error(
@@ -12867,17 +14235,17 @@ function assertWritableInsideRepository(cwd, filePath) {
12867
14235
  }
12868
14236
  }
12869
14237
  function writeIfChanged(target, filePath, content) {
12870
- const existing = fs17.existsSync(filePath) ? fs17.readFileSync(filePath, "utf8") : null;
14238
+ const existing = fs18.existsSync(filePath) ? fs18.readFileSync(filePath, "utf8") : null;
12871
14239
  if (existing === content) return { target, path: filePath, action: "unchanged" };
12872
- fs17.mkdirSync(path19.dirname(filePath), { recursive: true });
12873
- fs17.writeFileSync(filePath, content, "utf8");
14240
+ fs18.mkdirSync(path19.dirname(filePath), { recursive: true });
14241
+ fs18.writeFileSync(filePath, content, "utf8");
12874
14242
  return { target, path: filePath, action: existing === null ? "created" : "updated" };
12875
14243
  }
12876
14244
  function legacyAgentsNote(cwd) {
12877
14245
  const filePath = path19.join(cwd, "AGENTS.md");
12878
14246
  try {
12879
- if (!fs17.existsSync(filePath)) return null;
12880
- if (!fs17.readFileSync(filePath, "utf8").includes(LEGACY_AGENTS_MARKER)) return null;
14247
+ if (!fs18.existsSync(filePath)) return null;
14248
+ if (!fs18.readFileSync(filePath, "utf8").includes(LEGACY_AGENTS_MARKER)) return null;
12881
14249
  } catch {
12882
14250
  return null;
12883
14251
  }
@@ -12889,7 +14257,7 @@ function installSkill(cwd, target = "all") {
12889
14257
  const notes = [];
12890
14258
  const wanted = target === "all" ? ["claude", "cursor"] : [target];
12891
14259
  for (const item of wanted) assertWritableInsideRepository(cwd, targetPath(cwd, item));
12892
- const createsSomething = wanted.some((item) => !fs17.existsSync(targetPath(cwd, item)));
14260
+ const createsSomething = wanted.some((item) => !fs18.existsSync(targetPath(cwd, item)));
12893
14261
  if (createsSomething) {
12894
14262
  assertWritableInsideRepository(cwd, path19.join(cwd, ".gitignore"));
12895
14263
  }
@@ -13005,7 +14373,7 @@ function negotiateLegacyVersion(requested) {
13005
14373
  }
13006
14374
 
13007
14375
  // src/mcp/resources.ts
13008
- import * as fs18 from "fs";
14376
+ import * as fs19 from "fs";
13009
14377
  import * as path20 from "path";
13010
14378
  var MAX_RESOURCE_BYTES = 512 * 1024;
13011
14379
  var ResourceTooLargeError = class extends Error {
@@ -13050,13 +14418,13 @@ function formatBytes2(bytes) {
13050
14418
  async function workspaceFor(context) {
13051
14419
  const root = resolveRoot(void 0, context);
13052
14420
  if (!root.ok) return { error: root.message };
13053
- const opened = await openWorkspace(root.root);
14421
+ const opened = await openWorkspace(root.root, {}, void 0, { allowExecutableConfig: false });
13054
14422
  if (!opened.ok) return { error: opened.message };
13055
14423
  return opened.workspace;
13056
14424
  }
13057
14425
  function readFileIfPresent(file) {
13058
14426
  try {
13059
- return fs18.readFileSync(file, "utf8");
14427
+ return fs19.readFileSync(file, "utf8");
13060
14428
  } catch {
13061
14429
  return null;
13062
14430
  }
@@ -13174,7 +14542,7 @@ function buildResourceProvider() {
13174
14542
  if (partPath === null) return null;
13175
14543
  let partBytes;
13176
14544
  try {
13177
- partBytes = fs18.statSync(partPath).size;
14545
+ partBytes = fs19.statSync(partPath).size;
13178
14546
  } catch {
13179
14547
  return null;
13180
14548
  }
@@ -13592,11 +14960,11 @@ var MAX_LINE_BYTES = 32 * 1024 * 1024;
13592
14960
  function createWriter(output) {
13593
14961
  return {
13594
14962
  write(value) {
13595
- return new Promise((resolve10, reject) => {
14963
+ return new Promise((resolve11, reject) => {
13596
14964
  output.write(`${JSON.stringify(value)}
13597
14965
  `, (error) => {
13598
14966
  if (error) reject(error);
13599
- else resolve10();
14967
+ else resolve11();
13600
14968
  });
13601
14969
  });
13602
14970
  }
@@ -13729,11 +15097,12 @@ async function runStdioServer(options) {
13729
15097
  });
13730
15098
  return writeChain;
13731
15099
  };
15100
+ const MAX_IN_FLIGHT = 4;
13732
15101
  let inFlight = 0;
13733
15102
  let inputEnded = false;
13734
15103
  let resolveDone = () => void 0;
13735
- const finished = new Promise((resolve10) => {
13736
- resolveDone = resolve10;
15104
+ const finished = new Promise((resolve11) => {
15105
+ resolveDone = resolve11;
13737
15106
  });
13738
15107
  const finishIfIdle = () => {
13739
15108
  if (inputEnded && inFlight === 0) resolveDone(0);
@@ -13749,9 +15118,31 @@ async function runStdioServer(options) {
13749
15118
  const response = await server.handle(message);
13750
15119
  if (response) await send(response);
13751
15120
  };
15121
+ const rejectOverloaded = (line) => {
15122
+ let id = null;
15123
+ try {
15124
+ const parsed = JSON.parse(line);
15125
+ if (!isJsonObject(parsed)) return;
15126
+ if (typeof parsed.id === "string" || typeof parsed.id === "number") id = parsed.id;
15127
+ else return;
15128
+ } catch {
15129
+ return;
15130
+ }
15131
+ void send(
15132
+ errorResponse(
15133
+ id,
15134
+ ERROR_CODES.overloaded,
15135
+ `The server is already handling ${MAX_IN_FLIGHT} requests; retry this one when it is free.`
15136
+ )
15137
+ );
15138
+ };
13752
15139
  const stopReading = createLineReader(process.stdin, {
13753
15140
  onOverflow: (bytes) => log(`mcp: discarded an oversized message (${bytes} bytes)`),
13754
15141
  onLine: (line) => {
15142
+ if (inFlight >= MAX_IN_FLIGHT) {
15143
+ rejectOverloaded(line);
15144
+ return;
15145
+ }
13755
15146
  inFlight += 1;
13756
15147
  void handleLine(line).finally(() => {
13757
15148
  inFlight -= 1;
@@ -13918,7 +15309,7 @@ Options:
13918
15309
  --install Write the skill into the repository instead of printing
13919
15310
  --target <name> claude | cursor | all (default: all)
13920
15311
 
13921
- --no-update-check Skip the daily check for a newer published version
15312
+ --no-update-check Skip the check for a newer published version
13922
15313
 
13923
15314
  -h, --help Display this help message
13924
15315
  -v, --version Display version
@@ -14004,10 +15395,10 @@ function parseCliArgs(argv) {
14004
15395
  }
14005
15396
  if (values.cwd !== void 0) {
14006
15397
  const target = String(values.cwd);
14007
- if (!fs19.existsSync(target)) {
15398
+ if (!fs20.existsSync(target)) {
14008
15399
  throw new UsageError(`--cwd directory does not exist: ${target}`);
14009
15400
  }
14010
- if (!fs19.statSync(target).isDirectory()) {
15401
+ if (!fs20.statSync(target).isDirectory()) {
14011
15402
  throw new UsageError(`--cwd is not a directory: ${target}`);
14012
15403
  }
14013
15404
  }
@@ -14111,7 +15502,9 @@ function parseCliArgs(argv) {
14111
15502
  )
14112
15503
  )
14113
15504
  );
14114
- 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)." : "";
15505
+ const setupOnly = ["--preset", "--include", "--exclude", "--install-hook"];
15506
+ const autopilotChose = values.autopilot === true && ignored.some((flag) => setupOnly.includes(flag));
15507
+ 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)." : "";
14115
15508
  throw new UsageError(
14116
15509
  `${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}`
14117
15510
  );
@@ -14233,8 +15626,8 @@ function splitList(value) {
14233
15626
  }
14234
15627
  function displayOutPath(cwd, outDir, ...segments) {
14235
15628
  const absolute = path21.resolve(cwd, outDir, ...segments);
14236
- const relative12 = path21.relative(cwd, absolute);
14237
- if (relative12 && !relative12.startsWith("..") && !path21.isAbsolute(relative12)) return relative12;
15629
+ const relative14 = path21.relative(cwd, absolute);
15630
+ if (relative14 && !relative14.startsWith("..") && !path21.isAbsolute(relative14)) return relative14;
14238
15631
  return absolute;
14239
15632
  }
14240
15633
  function nextStepHint(cwd, scriptsAddedNow) {
@@ -14242,7 +15635,7 @@ function nextStepHint(cwd, scriptsAddedNow) {
14242
15635
  if (!hasScript) {
14243
15636
  try {
14244
15637
  const parsed = JSON.parse(
14245
- stripJsonComments2(fs19.readFileSync(path21.join(cwd, "package.json"), "utf8"))
15638
+ stripJsonComments2(fs20.readFileSync(path21.join(cwd, "package.json"), "utf8"))
14246
15639
  );
14247
15640
  hasScript = typeof parsed.scripts?.snapshot === "string";
14248
15641
  } catch {
@@ -14251,7 +15644,7 @@ function nextStepHint(cwd, scriptsAddedNow) {
14251
15644
  }
14252
15645
  if (!hasScript) return `npx ${GENERATOR_NAME} generate`;
14253
15646
  const bin = path21.join(cwd, "node_modules", ".bin", "codebase-snapshot");
14254
- const installed = fs19.existsSync(bin) || fs19.existsSync(`${bin}.cmd`);
15647
+ const installed = fs20.existsSync(bin) || fs20.existsSync(`${bin}.cmd`);
14255
15648
  return installed ? "npm run snapshot" : "npm install && npm run snapshot";
14256
15649
  }
14257
15650
  function presetSummary(init) {
@@ -14308,16 +15701,25 @@ async function runInitCommand(invocation) {
14308
15701
  }
14309
15702
  }
14310
15703
  function detectPackageManager(cwd) {
14311
- const has = (name) => fs19.existsSync(path21.join(cwd, name));
15704
+ const has = (name) => fs20.existsSync(path21.join(cwd, name));
14312
15705
  if (has("bun.lockb") || has("bun.lock")) return { name: "bun", command: "bun", args: ["install"] };
14313
15706
  if (has("pnpm-lock.yaml")) return { name: "pnpm", command: "pnpm", args: ["install"] };
14314
15707
  if (has("yarn.lock")) return { name: "yarn", command: "yarn", args: ["install"] };
14315
15708
  return { name: "npm", command: "npm", args: ["install"] };
14316
15709
  }
15710
+ var INHERITED_NPM_SETTINGS = /* @__PURE__ */ new Set([
15711
+ "npm_config_registry",
15712
+ "npm_config_proxy",
15713
+ "npm_config_https_proxy",
15714
+ "npm_config_noproxy",
15715
+ "npm_config_cafile",
15716
+ "npm_config_ca",
15717
+ "npm_config_strict_ssl"
15718
+ ]);
14317
15719
  function cleanInstallEnv(env = process.env) {
14318
15720
  const cleaned = {};
14319
15721
  for (const [key, value] of Object.entries(env)) {
14320
- if (/^npm_config_/i.test(key)) continue;
15722
+ if (/^npm_config_/i.test(key) && !INHERITED_NPM_SETTINGS.has(key.toLowerCase())) continue;
14321
15723
  if (key === "npm_lifecycle_event" || key === "npm_lifecycle_script") continue;
14322
15724
  cleaned[key] = value;
14323
15725
  }
@@ -14741,12 +16143,12 @@ ${USAGE}
14741
16143
  }
14742
16144
  if (invocation.command === "report") {
14743
16145
  const manifestPath = path21.resolve(resolved.cwd, resolved.outDir, "manifest.json");
14744
- if (!fs19.existsSync(manifestPath)) {
16146
+ if (!fs20.existsSync(manifestPath)) {
14745
16147
  return fail(invocation.format, `Manifest not found at ${manifestPath}. Run generate first.`);
14746
16148
  }
14747
16149
  let manifest;
14748
16150
  try {
14749
- manifest = JSON.parse(fs19.readFileSync(manifestPath, "utf8"));
16151
+ manifest = JSON.parse(fs20.readFileSync(manifestPath, "utf8"));
14750
16152
  } catch (err) {
14751
16153
  return fail(invocation.format, `Could not read ${manifestPath}: ${err.message}`);
14752
16154
  }
@@ -14922,8 +16324,8 @@ function comparablePath(value) {
14922
16324
  return process.platform === "win32" ? absolute.toLowerCase() : absolute;
14923
16325
  }
14924
16326
  function isSameOrInside(parent, candidate) {
14925
- const relative12 = path21.relative(parent, candidate);
14926
- return relative12 === "" || relative12 !== ".." && !relative12.startsWith(`..${path21.sep}`) && !path21.isAbsolute(relative12);
16327
+ const relative14 = path21.relative(parent, candidate);
16328
+ return relative14 === "" || relative14 !== ".." && !relative14.startsWith(`..${path21.sep}`) && !path21.isAbsolute(relative14);
14927
16329
  }
14928
16330
  function isGeneratedWatchPath(candidate, paths) {
14929
16331
  const absolute = comparablePath(path21.resolve(paths.cwd, candidate));
@@ -15039,7 +16441,7 @@ async function runWatchLoop(invocation, resolved, options) {
15039
16441
  if (!options.generatedAlready) void regenerate();
15040
16442
  let watcher;
15041
16443
  try {
15042
- watcher = fs19.watch(resolved.cwd, { recursive: true }, (_event, filename) => {
16444
+ watcher = fs20.watch(resolved.cwd, { recursive: true }, (_event, filename) => {
15043
16445
  const decision = decideWatchEvent(
15044
16446
  state,
15045
16447
  {
@@ -15069,12 +16471,12 @@ async function runWatchLoop(invocation, resolved, options) {
15069
16471
  info(`\u26A0 Watch error: ${err.message}`);
15070
16472
  info(" The watcher may have missed changes. Restart with Ctrl+C if they stop arriving.");
15071
16473
  });
15072
- await new Promise((resolve10) => {
16474
+ await new Promise((resolve11) => {
15073
16475
  const stop = () => {
15074
16476
  stopped = true;
15075
16477
  if (timer) clearTimeout(timer);
15076
16478
  watcher.close();
15077
- resolve10();
16479
+ resolve11();
15078
16480
  };
15079
16481
  process.once("SIGINT", stop);
15080
16482
  process.once("SIGTERM", stop);