codebase-snapshot 0.9.12 → 0.9.15

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.
@@ -9,11 +9,70 @@ import { createRequire } from 'module';
9
9
  import { pathToFileURL, fileURLToPath } from 'url';
10
10
  import * as childProcess from 'child_process';
11
11
  import { execFileSync } from 'child_process';
12
+ import * as http from 'http';
12
13
  import * as https from 'https';
13
14
  import * as readline from 'readline';
14
15
  import { Worker } from 'worker_threads';
15
16
 
16
17
  // src/index.ts
18
+ var hookStdoutScope = new AsyncLocalStorage();
19
+ var captureScope = new AsyncLocalStorage();
20
+ var installs = 0;
21
+ var underlying = null;
22
+ var router = null;
23
+ var asText = (chunk) => typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
24
+ var callbackIn = (rest) => {
25
+ for (const argument of rest) {
26
+ if (typeof argument === "function") return argument;
27
+ }
28
+ return void 0;
29
+ };
30
+ function installStdoutRouter() {
31
+ if (installs === 0) {
32
+ underlying = process.stdout.write;
33
+ const realStdout = underlying.bind(process.stdout);
34
+ const realStderr = process.stderr.write.bind(process.stderr);
35
+ router = ((...args) => {
36
+ if (hookStdoutScope.getStore() === true) return realStderr(...args);
37
+ const capture = captureScope.getStore();
38
+ if (capture !== void 0) {
39
+ capture.write(asText(args[0]));
40
+ const callback = callbackIn(args.slice(1));
41
+ if (callback) callback(null);
42
+ return true;
43
+ }
44
+ return realStdout(...args);
45
+ });
46
+ process.stdout.write = router;
47
+ }
48
+ installs += 1;
49
+ let released = false;
50
+ return () => {
51
+ if (released) return;
52
+ released = true;
53
+ installs -= 1;
54
+ if (installs === 0) {
55
+ if (process.stdout.write === router && underlying !== null) {
56
+ process.stdout.write = underlying;
57
+ }
58
+ underlying = null;
59
+ router = null;
60
+ }
61
+ };
62
+ }
63
+ async function runWithStdoutCapture(fn) {
64
+ let text2 = "";
65
+ const release = installStdoutRouter();
66
+ try {
67
+ const value = await captureScope.run(
68
+ { write: (chunk) => void (text2 += chunk) },
69
+ fn
70
+ );
71
+ return { value, text: text2 };
72
+ } finally {
73
+ release();
74
+ }
75
+ }
17
76
 
18
77
  // src/ast/profiles/shared.ts
19
78
  var MAX_SUMMARY_CHARS = 1e6;
@@ -69,7 +128,7 @@ function isCapitalizedName(name) {
69
128
  }
70
129
 
71
130
  // src/ast/profiles/cfamily.ts
72
- var INCLUDE = /^#\s*include\s*[<"]([^>"]+)[>"]/;
131
+ var INCLUDE = /^#\s*include\s*([<"])([^>"]+)[>"]/;
73
132
  var DEFINE = /^#\s*define\s+([A-Za-z_]\w*)/;
74
133
  var USING = /^using\s+(?:namespace\s+)?([\w:]+)\s*;/;
75
134
  var TYPE_DECL = /^(?:typedef\s+)?(?:struct|union|class|enum)\s+([A-Za-z_]\w*)/;
@@ -88,7 +147,7 @@ var cfamilyProfile = {
88
147
  }
89
148
  const included = INCLUDE.exec(trimmed);
90
149
  if (included) {
91
- summary.imports.push(included[1]);
150
+ summary.imports.push(included[1] === '"' ? `./${included[2]}` : included[2]);
92
151
  return;
93
152
  }
94
153
  const used = USING.exec(trimmed);
@@ -492,7 +551,15 @@ var pythonProfile = {
492
551
  }
493
552
  const from = FROM_IMPORT.exec(trimmed);
494
553
  if (from) {
495
- summary.imports.push(from[1]);
554
+ const module = from[1];
555
+ if (/^\.+$/.test(module)) {
556
+ for (const name of from[2].split(",")) {
557
+ const imported2 = name.replace(/[()]/g, "").trim().split(/\s+as\s+/)[0].trim();
558
+ if (/^[A-Za-z_]\w*$/.test(imported2)) summary.imports.push(`${module}${imported2}`);
559
+ }
560
+ } else {
561
+ summary.imports.push(module);
562
+ }
496
563
  routePending = false;
497
564
  return;
498
565
  }
@@ -541,7 +608,8 @@ var pythonProfile = {
541
608
  };
542
609
 
543
610
  // src/ast/profiles/ruby.ts
544
- var REQUIRE = /^require(?:_relative)?\s+["']([^"']+)["']/;
611
+ var REQUIRE_RELATIVE = /^require_relative\s+["']([^"']+)["']/;
612
+ var REQUIRE = /^require\s+["']([^"']+)["']/;
545
613
  var CLASS_OR_MODULE = /^(?:class|module)\s+([A-Z][\w:]*)/;
546
614
  var METHOD2 = /^def\s+(?:self\.)?([A-Za-z_]\w*[?!=]?)/;
547
615
  var rubyProfile = {
@@ -552,6 +620,11 @@ var rubyProfile = {
552
620
  eachLine(content, (line) => {
553
621
  const trimmed = line.trim();
554
622
  if (!trimmed || trimmed.startsWith("#")) return;
623
+ const relative8 = REQUIRE_RELATIVE.exec(trimmed);
624
+ if (relative8) {
625
+ summary.imports.push(`./${relative8[1]}`);
626
+ return;
627
+ }
555
628
  const required = REQUIRE.exec(trimmed);
556
629
  if (required) {
557
630
  summary.imports.push(required[1]);
@@ -748,13 +821,23 @@ function summarizeTypeScriptSource(relativePath, content) {
748
821
  if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
749
822
  summary.imports.push(node.moduleSpecifier.text);
750
823
  }
824
+ if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference) && node.moduleReference.expression !== void 0 && ts.isStringLiteral(node.moduleReference.expression)) {
825
+ summary.imports.push(node.moduleReference.expression.text);
826
+ }
827
+ if (ts.isCallExpression(node) && node.arguments.length >= 1) {
828
+ const firstArgument = node.arguments[0];
829
+ if (firstArgument !== void 0 && ts.isStringLiteral(firstArgument)) {
830
+ const isDynamicImport = node.expression.kind === ts.SyntaxKind.ImportKeyword;
831
+ const isRequire = ts.isIdentifier(node.expression) && node.expression.text === "require";
832
+ if (isDynamicImport || isRequire) summary.imports.push(firstArgument.text);
833
+ }
834
+ }
751
835
  if (ts.isExportDeclaration(node)) {
752
836
  if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {
753
837
  summary.imports.push(node.moduleSpecifier.text);
838
+ summary.reExports.push(node.moduleSpecifier.text);
754
839
  if (node.exportClause && ts.isNamespaceExport(node.exportClause)) {
755
840
  summary.exports.push(node.exportClause.name.text);
756
- } else if (!node.exportClause) {
757
- summary.reExports.push(node.moduleSpecifier.text);
758
841
  }
759
842
  }
760
843
  if (node.exportClause && ts.isNamedExports(node.exportClause)) {
@@ -846,7 +929,8 @@ function summarizeTypeScriptSource(relativePath, content) {
846
929
  }
847
930
 
848
931
  // src/ast/profiles/sfc.ts
849
- var SCRIPT_BLOCK = /<script[^>]*>([\s\S]*?)<\/script>/gi;
932
+ var SCRIPT_BLOCK = /<script([^>]*)>([\s\S]*?)<\/script>/gi;
933
+ var JSX_LANG = /\blang\s*=\s*["']?[tj]sx\b/i;
850
934
  var ASTRO_FRONTMATTER = /^\uFEFF?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?=\r?\n|$)/;
851
935
  function componentName(path17) {
852
936
  const base = path17.split("/").pop() ?? path17;
@@ -857,13 +941,15 @@ var sfcProfile = {
857
941
  extensions: [".vue", ".svelte", ".astro"],
858
942
  summarize(path17, content) {
859
943
  let script = "";
944
+ let usesJsx = path17.toLowerCase().endsWith(".astro");
860
945
  if (path17.toLowerCase().endsWith(".astro")) {
861
946
  const frontmatter = ASTRO_FRONTMATTER.exec(content);
862
947
  if (frontmatter) script += `${frontmatter[1]}
863
948
  `;
864
949
  }
865
950
  for (const match of content.matchAll(SCRIPT_BLOCK)) {
866
- script += `${match[1]}
951
+ if (JSX_LANG.test(match[1] ?? "")) usesJsx = true;
952
+ script += `${match[2]}
867
953
  `;
868
954
  }
869
955
  const name = componentName(path17);
@@ -875,7 +961,7 @@ var sfcProfile = {
875
961
  }
876
962
  return { summary: finalizeSummary(summary2), quality: "heuristic" };
877
963
  }
878
- const summary = summarizeTypeScriptSource(`${name}.ts`, script);
964
+ const summary = summarizeTypeScriptSource(`${name}.${usesJsx ? "tsx" : "ts"}`, script);
879
965
  summary.reactComponents.push(name);
880
966
  summary.exports.push(name);
881
967
  return { summary: finalizeSummary(summary), quality: "ast" };
@@ -1067,124 +1153,421 @@ function summarizeWithProfile(path17, content) {
1067
1153
  const profile = profileForPath(path17);
1068
1154
  return profile ? profile.summarize(path17, content) : null;
1069
1155
  }
1070
-
1071
- // src/ast/structured.ts
1072
- function stripJsonComments(content) {
1073
- const text2 = content.replace(/^\uFEFF/, "");
1074
- let out = "";
1075
- let inString = false;
1076
- let inLineComment = false;
1077
- let inBlockComment = false;
1078
- for (let i = 0; i < text2.length; i++) {
1079
- const char = text2[i];
1080
- const next = text2[i + 1];
1081
- if (inLineComment) {
1082
- if (char === "\n") {
1083
- inLineComment = false;
1084
- out += char;
1085
- }
1156
+ var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
1157
+ ".png",
1158
+ ".jpg",
1159
+ ".jpeg",
1160
+ ".gif",
1161
+ ".webp",
1162
+ ".avif",
1163
+ ".ico",
1164
+ ".bmp",
1165
+ ".tiff",
1166
+ ".pdf",
1167
+ ".zip",
1168
+ ".tar",
1169
+ ".gz",
1170
+ ".tgz",
1171
+ ".br",
1172
+ ".bz2",
1173
+ ".xz",
1174
+ ".zst",
1175
+ ".lz4",
1176
+ ".lzma",
1177
+ ".7z",
1178
+ ".rar",
1179
+ ".mp3",
1180
+ ".mp4",
1181
+ ".wav",
1182
+ ".ogg",
1183
+ ".webm",
1184
+ ".mov",
1185
+ ".avi",
1186
+ ".woff",
1187
+ ".woff2",
1188
+ ".ttf",
1189
+ ".otf",
1190
+ ".eot",
1191
+ ".wasm",
1192
+ ".node",
1193
+ ".exe",
1194
+ ".dll",
1195
+ ".dylib",
1196
+ ".so"
1197
+ ]);
1198
+ function isBinaryExtension(filePath) {
1199
+ const ext = path16.extname(filePath).toLowerCase();
1200
+ return BINARY_EXTENSIONS.has(ext);
1201
+ }
1202
+ function isBinaryBuffer(buffer) {
1203
+ return buffer.includes(0);
1204
+ }
1205
+ function countControlBytes(buffer) {
1206
+ let count = 0;
1207
+ for (let index = 0; index < buffer.length; index++) {
1208
+ const byte = buffer[index];
1209
+ if (byte < 32) {
1210
+ if (byte !== 9 && byte !== 10 && byte !== 13) count += 1;
1086
1211
  continue;
1087
1212
  }
1088
- if (inBlockComment) {
1089
- if (char === "*" && next === "/") {
1090
- inBlockComment = false;
1091
- i += 1;
1092
- }
1213
+ if (byte === 127) {
1214
+ count += 1;
1093
1215
  continue;
1094
1216
  }
1095
- if (inString) {
1096
- out += char;
1097
- if (char === "\\") {
1098
- if (next !== void 0) {
1099
- out += next;
1100
- i += 1;
1101
- }
1102
- } else if (char === '"') {
1103
- inString = false;
1217
+ if (byte === 194 && index + 1 < buffer.length) {
1218
+ const next = buffer[index + 1];
1219
+ if (next >= 128 && next <= 159) {
1220
+ count += 1;
1221
+ index += 1;
1104
1222
  }
1223
+ }
1224
+ }
1225
+ return count;
1226
+ }
1227
+ var CONTROL_BYTES_FLOOR = 4;
1228
+ function countInvalidUtf8Bytes(buffer) {
1229
+ let invalid = 0;
1230
+ let index = 0;
1231
+ const length = buffer.length;
1232
+ while (index < length) {
1233
+ const lead = buffer[index];
1234
+ if (lead < 128) {
1235
+ index += 1;
1105
1236
  continue;
1106
1237
  }
1107
- if (char === '"') {
1108
- inString = true;
1109
- out += char;
1238
+ let continuation = 0;
1239
+ let codePoint = 0;
1240
+ let minimum = 0;
1241
+ if ((lead & 224) === 192) {
1242
+ continuation = 1;
1243
+ codePoint = lead & 31;
1244
+ minimum = 128;
1245
+ } else if ((lead & 240) === 224) {
1246
+ continuation = 2;
1247
+ codePoint = lead & 15;
1248
+ minimum = 2048;
1249
+ } else if ((lead & 248) === 240) {
1250
+ continuation = 3;
1251
+ codePoint = lead & 7;
1252
+ minimum = 65536;
1253
+ } else {
1254
+ invalid += 1;
1255
+ index += 1;
1110
1256
  continue;
1111
1257
  }
1112
- if (char === "/" && next === "/") {
1113
- inLineComment = true;
1114
- i += 1;
1258
+ if (index + continuation >= length) {
1259
+ invalid += 1;
1260
+ index += 1;
1115
1261
  continue;
1116
1262
  }
1117
- if (char === "/" && next === "*") {
1118
- inBlockComment = true;
1119
- i += 1;
1263
+ let wellFormed = true;
1264
+ for (let offset = 1; offset <= continuation; offset++) {
1265
+ const next = buffer[index + offset];
1266
+ if ((next & 192) !== 128) {
1267
+ wellFormed = false;
1268
+ break;
1269
+ }
1270
+ codePoint = codePoint << 6 | next & 63;
1271
+ }
1272
+ const isSurrogate = codePoint >= 55296 && codePoint <= 57343;
1273
+ if (!wellFormed || codePoint < minimum || codePoint > 1114111 || isSurrogate) {
1274
+ invalid += 1;
1275
+ index += 1;
1120
1276
  continue;
1121
1277
  }
1122
- out += char;
1278
+ index += continuation + 1;
1123
1279
  }
1124
- return out;
1280
+ return invalid;
1125
1281
  }
1126
- function summarizeJson(content) {
1127
- try {
1128
- const parsed = JSON.parse(stripJsonComments(content));
1129
- if (Array.isArray(parsed)) {
1130
- const sample = parsed[0];
1131
- const sampleKeys = sample && typeof sample === "object" && !Array.isArray(sample) ? Object.keys(sample).slice(0, 10).sort() : [];
1132
- return {
1133
- shape: "array",
1134
- itemCount: parsed.length,
1135
- keys: [],
1136
- sampleKeys
1137
- };
1282
+ function readBomEncoding(buffer) {
1283
+ if (buffer.length >= 2) {
1284
+ if (buffer[0] === 255 && buffer[1] === 254) return "utf-16le";
1285
+ if (buffer[0] === 254 && buffer[1] === 255) return "utf-16be";
1286
+ }
1287
+ return null;
1288
+ }
1289
+ function looksLikeUtf16(buffer) {
1290
+ if (buffer.length < 8 || buffer.length % 2 !== 0) return null;
1291
+ const sample = Math.min(buffer.length, 4096);
1292
+ let nulInLowByte = 0;
1293
+ let nulInHighByte = 0;
1294
+ const units = sample / 2;
1295
+ for (let index = 0; index < sample; index += 2) {
1296
+ if (buffer[index] === 0) nulInLowByte += 1;
1297
+ if (buffer[index + 1] === 0) nulInHighByte += 1;
1298
+ }
1299
+ if (nulInHighByte > units * 0.3 && nulInLowByte < units * 0.05) return "utf-16le";
1300
+ if (nulInLowByte > units * 0.3 && nulInHighByte < units * 0.05) return "utf-16be";
1301
+ return null;
1302
+ }
1303
+ function decodeUtf16(buffer, encoding) {
1304
+ const littleEndian = encoding === "utf-16le" ? buffer : Buffer.from(buffer.subarray(0, buffer.length - buffer.length % 2)).swap16();
1305
+ return new TextDecoder("utf-16le").decode(littleEndian);
1306
+ }
1307
+ function decodeText(buffer) {
1308
+ const bomEncoding = readBomEncoding(buffer);
1309
+ if (bomEncoding) {
1310
+ const text2 = decodeUtf16(buffer.subarray(2), bomEncoding);
1311
+ return { text: text2, encoding: bomEncoding, invalidBytes: 0, binary: false };
1312
+ }
1313
+ if (buffer.includes(0)) {
1314
+ const shape = looksLikeUtf16(buffer);
1315
+ if (shape) {
1316
+ return { text: decodeUtf16(buffer, shape), encoding: shape, invalidBytes: 0, binary: false };
1138
1317
  }
1139
- if (parsed && typeof parsed === "object") {
1140
- const keys = Object.keys(parsed).sort();
1318
+ const offset = buffer.indexOf(0);
1319
+ return {
1320
+ text: "",
1321
+ encoding: "utf-8",
1322
+ invalidBytes: 0,
1323
+ binary: true,
1324
+ binaryReason: `NUL byte at offset ${offset}`
1325
+ };
1326
+ }
1327
+ const invalidBytes = countInvalidUtf8Bytes(buffer);
1328
+ if (invalidBytes === 0) {
1329
+ const controlBytes = countControlBytes(buffer);
1330
+ if (controlBytes > CONTROL_BYTES_FLOOR && controlBytes * 100 > buffer.length) {
1141
1331
  return {
1142
- shape: "object",
1143
- itemCount: keys.length,
1144
- keys: keys.slice(0, 30),
1145
- sampleKeys: []
1332
+ text: "",
1333
+ encoding: "utf-8",
1334
+ invalidBytes: 0,
1335
+ binary: true,
1336
+ binaryReason: `${controlBytes} control byte(s) in ${buffer.length} B; valid UTF-8 but not text`
1146
1337
  };
1147
1338
  }
1148
1339
  return {
1149
- shape: typeof parsed,
1150
- itemCount: null,
1151
- keys: [],
1152
- sampleKeys: []
1340
+ text: new TextDecoder("utf-8").decode(buffer),
1341
+ encoding: "utf-8",
1342
+ invalidBytes: 0,
1343
+ binary: false
1153
1344
  };
1154
- } catch {
1345
+ }
1346
+ if (invalidBytes >= 32 && invalidBytes * 3 >= buffer.length) {
1155
1347
  return {
1156
- shape: "invalid-json",
1157
- itemCount: null,
1158
- keys: [],
1159
- sampleKeys: []
1348
+ text: "",
1349
+ encoding: "utf-8",
1350
+ invalidBytes,
1351
+ binary: true,
1352
+ binaryReason: `${invalidBytes} of ${buffer.length} bytes are not UTF-8; treated as binary`
1160
1353
  };
1161
1354
  }
1355
+ return {
1356
+ text: buffer.toString("utf8"),
1357
+ encoding: "utf-8-lossy",
1358
+ invalidBytes,
1359
+ binary: false
1360
+ };
1162
1361
  }
1163
- function summarizeMarkdown(content) {
1164
- const headings = [];
1165
- const frontmatterKeys = [];
1166
- const lines = content.replace(/^\uFEFF/, "").split("\n");
1167
- let inFrontmatter = false;
1168
- let fence = null;
1169
- let closesFrontmatter = false;
1170
- for (let index = 1; index < lines.length; index++) {
1171
- if (lines[index].trim() === "---") {
1172
- closesFrontmatter = true;
1173
- break;
1174
- }
1175
- }
1362
+ var BINARY_SCAN_BYTES = 8 * 1024 * 1024;
1363
+ var CHUNK = 64 * 1024;
1364
+ var SHAPE_SAMPLE_BYTES = 4096;
1365
+ function isBinaryFile(absolutePath) {
1366
+ if (isBinaryExtension(absolutePath)) return true;
1367
+ let fd;
1368
+ try {
1369
+ fd = fs14.openSync(absolutePath, "r");
1370
+ const buffer = Buffer.alloc(CHUNK);
1371
+ let sample;
1372
+ let position = 0;
1373
+ while (position < BINARY_SCAN_BYTES) {
1374
+ const wanted = Math.min(CHUNK, BINARY_SCAN_BYTES - position);
1375
+ const bytesRead = fs14.readSync(fd, buffer, 0, wanted, position);
1376
+ if (bytesRead === 0) return false;
1377
+ const chunk = buffer.subarray(0, bytesRead);
1378
+ if (sample === void 0) {
1379
+ sample = Buffer.from(chunk.subarray(0, SHAPE_SAMPLE_BYTES));
1380
+ }
1381
+ if (chunk.includes(0)) {
1382
+ const shape = readBomEncoding(sample) ?? looksLikeUtf16(sample);
1383
+ return shape === null;
1384
+ }
1385
+ position += bytesRead;
1386
+ }
1387
+ return false;
1388
+ } catch {
1389
+ return false;
1390
+ } finally {
1391
+ if (fd !== void 0) {
1392
+ try {
1393
+ fs14.closeSync(fd);
1394
+ } catch {
1395
+ }
1396
+ }
1397
+ }
1398
+ }
1399
+
1400
+ // src/ast/imports.ts
1401
+ var SUMMARY_MAX_SOURCE_BYTES = 2 * 1024 * 1024;
1402
+ var TS_SOURCE_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
1403
+ var isTsSource = (relativePath) => {
1404
+ const lower = relativePath.toLowerCase();
1405
+ return TS_SOURCE_EXTENSIONS.some((extension) => lower.endsWith(extension));
1406
+ };
1407
+ function importsOfText(relativePath, text2) {
1408
+ if (Buffer.byteLength(text2, "utf8") > SUMMARY_MAX_SOURCE_BYTES) return [];
1409
+ if (isTsSource(relativePath)) return summarizeTypeScriptSource(relativePath, text2).imports;
1410
+ return summarizeWithProfile(relativePath, text2)?.summary.imports ?? [];
1411
+ }
1412
+ function importsOfFile(relativePath, absolutePath) {
1413
+ let buffer;
1414
+ try {
1415
+ const stats = fs14.statSync(absolutePath);
1416
+ if (!stats.isFile() || stats.size > SUMMARY_MAX_SOURCE_BYTES) return [];
1417
+ buffer = fs14.readFileSync(absolutePath);
1418
+ } catch {
1419
+ return [];
1420
+ }
1421
+ const decoded = decodeText(buffer);
1422
+ if (decoded.binary) return [];
1423
+ return importsOfText(relativePath, decoded.text);
1424
+ }
1425
+
1426
+ // src/ast/structured.ts
1427
+ function stripJsonComments(content) {
1428
+ const text2 = content.replace(/^\uFEFF/, "");
1429
+ const withoutComments = stripComments(text2);
1430
+ return stripTrailingCommas(withoutComments);
1431
+ }
1432
+ function stripComments(text2) {
1433
+ let out = "";
1434
+ let inString = false;
1435
+ let escaped = false;
1436
+ for (let index = 0; index < text2.length; index += 1) {
1437
+ const char = text2[index];
1438
+ if (inString) {
1439
+ out += char;
1440
+ if (escaped) escaped = false;
1441
+ else if (char === "\\") escaped = true;
1442
+ else if (char === '"') inString = false;
1443
+ continue;
1444
+ }
1445
+ if (char === '"') {
1446
+ inString = true;
1447
+ out += char;
1448
+ continue;
1449
+ }
1450
+ if (char === "/" && text2[index + 1] === "/") {
1451
+ while (index < text2.length && text2[index] !== "\n" && text2[index] !== "\r") index += 1;
1452
+ index -= 1;
1453
+ continue;
1454
+ }
1455
+ if (char === "/" && text2[index + 1] === "*") {
1456
+ index += 2;
1457
+ while (index < text2.length && !(text2[index] === "*" && text2[index + 1] === "/")) {
1458
+ if (text2[index] === "\n" || text2[index] === "\r") out += text2[index];
1459
+ index += 1;
1460
+ }
1461
+ index += 1;
1462
+ continue;
1463
+ }
1464
+ out += char;
1465
+ }
1466
+ return out;
1467
+ }
1468
+ function stripTrailingCommas(text2) {
1469
+ let out = "";
1470
+ let inString = false;
1471
+ let escaped = false;
1472
+ for (let index = 0; index < text2.length; index += 1) {
1473
+ const char = text2[index];
1474
+ if (inString) {
1475
+ out += char;
1476
+ if (escaped) escaped = false;
1477
+ else if (char === "\\") escaped = true;
1478
+ else if (char === '"') inString = false;
1479
+ continue;
1480
+ }
1481
+ if (char === '"') {
1482
+ inString = true;
1483
+ out += char;
1484
+ continue;
1485
+ }
1486
+ if (char === ",") {
1487
+ let next = index + 1;
1488
+ while (next < text2.length && /\s/.test(text2[next])) next += 1;
1489
+ if (text2[next] === "}" || text2[next] === "]") continue;
1490
+ }
1491
+ out += char;
1492
+ }
1493
+ return out;
1494
+ }
1495
+ function summarizeJson(content) {
1496
+ try {
1497
+ const parsed = JSON.parse(stripJsonComments(content));
1498
+ if (Array.isArray(parsed)) {
1499
+ const sample = parsed[0];
1500
+ const sampleKeys = sample && typeof sample === "object" && !Array.isArray(sample) ? Object.keys(sample).slice(0, 10).sort() : [];
1501
+ return {
1502
+ shape: "array",
1503
+ itemCount: parsed.length,
1504
+ keys: [],
1505
+ sampleKeys
1506
+ };
1507
+ }
1508
+ if (parsed && typeof parsed === "object") {
1509
+ const keys = Object.keys(parsed).sort();
1510
+ return {
1511
+ shape: "object",
1512
+ itemCount: keys.length,
1513
+ keys: keys.slice(0, 30),
1514
+ sampleKeys: []
1515
+ };
1516
+ }
1517
+ return {
1518
+ shape: typeof parsed,
1519
+ itemCount: null,
1520
+ keys: [],
1521
+ sampleKeys: []
1522
+ };
1523
+ } catch {
1524
+ return {
1525
+ shape: "invalid-json",
1526
+ itemCount: null,
1527
+ keys: [],
1528
+ sampleKeys: []
1529
+ };
1530
+ }
1531
+ }
1532
+ function frontMatterEnd(lines) {
1533
+ if (lines.length < 3 || lines[0].trim() !== "---") return 0;
1534
+ for (let index = 1; index < lines.length; index += 1) {
1535
+ const line = lines[index];
1536
+ const candidate = line.trim();
1537
+ if (candidate === "---" || candidate === "...") {
1538
+ return index > 1 ? index : 0;
1539
+ }
1540
+ if (candidate === "") continue;
1541
+ if (/^#(\s|$)/.test(candidate)) continue;
1542
+ if (/^(`{3,}|~{3,})/.test(candidate)) return 0;
1543
+ if (/^#{1,6}\s+\S/.test(candidate)) return 0;
1544
+ const isYamlMapping = /^[A-Za-z0-9_.-]+\s*:(\s|$)/.test(candidate);
1545
+ const isListItem = /^-(?:(\s|$))/.test(candidate);
1546
+ const isIndented = /^[ \t]/.test(line);
1547
+ if (!isYamlMapping && !isListItem && !isIndented) return 0;
1548
+ }
1549
+ return 0;
1550
+ }
1551
+ function summarizeMarkdown(content) {
1552
+ const headings = [];
1553
+ const frontmatterKeys = [];
1554
+ const lines = content.replace(/^\uFEFF/, "").split(/\r\n|\n|\r/);
1555
+ let inFrontmatter = false;
1556
+ let fence = null;
1557
+ const frontMatterEndLine = frontMatterEnd(lines);
1176
1558
  for (let index = 0; index < lines.length; index++) {
1177
1559
  const line = lines[index];
1178
- if (index === 0 && line.trim() === "---" && closesFrontmatter) {
1560
+ if (index === 0 && frontMatterEndLine > 0) {
1179
1561
  inFrontmatter = true;
1180
1562
  continue;
1181
1563
  }
1182
1564
  if (inFrontmatter) {
1183
- if (line.trim() === "---") {
1565
+ const trimmedFrontmatter = line.trim();
1566
+ if (trimmedFrontmatter === "---" || trimmedFrontmatter === "...") {
1184
1567
  inFrontmatter = false;
1185
1568
  continue;
1186
1569
  }
1187
- const match = /^([a-zA-Z0-9_-]+):/.exec(line);
1570
+ const match = /^([A-Za-z0-9_.-]+)\s*:/.exec(line);
1188
1571
  if (match) frontmatterKeys.push(match[1]);
1189
1572
  continue;
1190
1573
  }
@@ -1217,24 +1600,39 @@ function hasCollapsibleBody(node) {
1217
1600
  return body !== void 0 && ts.isBlock(body);
1218
1601
  }
1219
1602
  function isTsxFileName(fileName) {
1220
- return fileName.toLowerCase().endsWith(".tsx");
1603
+ const lower = fileName.toLowerCase();
1604
+ return lower.endsWith(".tsx") || lower.endsWith(".jsx");
1605
+ }
1606
+ function scriptKindFor(fileName) {
1607
+ const lower = fileName.toLowerCase();
1608
+ if (lower.endsWith(".tsx")) return ts.ScriptKind.TSX;
1609
+ if (lower.endsWith(".jsx")) return ts.ScriptKind.JSX;
1610
+ if (lower.endsWith(".js") || lower.endsWith(".mjs") || lower.endsWith(".cjs")) {
1611
+ return ts.ScriptKind.JS;
1612
+ }
1613
+ return ts.ScriptKind.TS;
1221
1614
  }
1222
1615
  function skeletonizeTypeScript(source, fileName = "file.ts") {
1223
- const scriptKind = isTsxFileName(fileName) ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
1224
1616
  const sourceFile = ts.createSourceFile(
1225
1617
  fileName,
1226
1618
  source,
1227
1619
  ts.ScriptTarget.Latest,
1228
- true,
1229
- scriptKind
1620
+ // `setParentNodes: false`. Nothing here reads `.parent` — the one `getStart` call is given the
1621
+ // source file explicitly, which is the reason that argument exists. Asking for parent pointers
1622
+ // makes the parser run a second full pass over every node in the file to set them, on top of
1623
+ // the summary parse this same file already pays for.
1624
+ false,
1625
+ scriptKindFor(fileName)
1230
1626
  );
1231
1627
  const spans = [];
1232
1628
  const visit = (node) => {
1233
1629
  if ((ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node) || ts.isConstructorDeclaration(node) || ts.isGetAccessorDeclaration(node) || ts.isSetAccessorDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node)) && hasCollapsibleBody(node)) {
1234
1630
  const body = node.body;
1235
- const start = body.getStart(sourceFile);
1236
- const end = body.getEnd();
1237
- if (end > start) spans.push({ start, end });
1631
+ if (body.statements.length > 0) {
1632
+ const start = body.getStart(sourceFile);
1633
+ const end = body.getEnd();
1634
+ if (end > start) spans.push({ start, end });
1635
+ }
1238
1636
  }
1239
1637
  ts.forEachChild(node, visit);
1240
1638
  };
@@ -1246,16 +1644,21 @@ function skeletonizeTypeScript(source, fileName = "file.ts") {
1246
1644
  if (last && span.start < last.end) continue;
1247
1645
  outermost.push(span);
1248
1646
  }
1249
- let text2 = source;
1250
- for (let index = outermost.length - 1; index >= 0; index -= 1) {
1251
- const span = outermost[index];
1252
- text2 = `${text2.slice(0, span.start)}{ /* ... */ }${text2.slice(span.end)}`;
1647
+ const chunks = [];
1648
+ let cursor = 0;
1649
+ for (const span of outermost) {
1650
+ chunks.push(source.slice(cursor, span.start), "{ /* ... */ }");
1651
+ cursor = span.end;
1253
1652
  }
1254
- return { text: text2, collapsed: outermost.length };
1653
+ chunks.push(source.slice(cursor));
1654
+ return { text: chunks.join(""), collapsed: outermost.length };
1255
1655
  }
1256
1656
  function isSkeletonizable(filePath) {
1257
1657
  const lower = filePath.toLowerCase();
1258
- return lower.endsWith(".ts") || lower.endsWith(".tsx") || lower.endsWith(".mts") || lower.endsWith(".cts");
1658
+ if (lower.endsWith(".d.ts") || lower.endsWith(".d.mts") || lower.endsWith(".d.cts")) {
1659
+ return false;
1660
+ }
1661
+ 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");
1259
1662
  }
1260
1663
  var MANIFEST_FILES = [
1261
1664
  "package.json",
@@ -1419,6 +1822,14 @@ function scanWorkspacePackages(cwd, patterns) {
1419
1822
  }
1420
1823
  return { files, dependencies };
1421
1824
  }
1825
+ var SNAPSHOT_MARKER = ".codebase-snapshot";
1826
+ function isToolOwnedDirectory(dir) {
1827
+ try {
1828
+ return fs14.statSync(dir).isDirectory() && fs14.existsSync(path16.join(dir, SNAPSHOT_MARKER));
1829
+ } catch {
1830
+ return false;
1831
+ }
1832
+ }
1422
1833
  function countMarkdownFiles(cwd) {
1423
1834
  let count = 0;
1424
1835
  let directoriesSeen = 0;
@@ -1440,7 +1851,9 @@ function countMarkdownFiles(cwd) {
1440
1851
  }
1441
1852
  if (!entry.isDirectory() || current.depth >= 2) continue;
1442
1853
  if (entry.name.startsWith(".") || SKIPPED_WALK_DIRS.has(entry.name)) continue;
1443
- queue.push({ dir: path16.join(current.dir, entry.name), depth: current.depth + 1 });
1854
+ const child = path16.join(current.dir, entry.name);
1855
+ if (isToolOwnedDirectory(child)) continue;
1856
+ queue.push({ dir: child, depth: current.depth + 1 });
1444
1857
  }
1445
1858
  }
1446
1859
  return count;
@@ -2309,18 +2722,24 @@ function detectPreset(cwd, forced) {
2309
2722
  }
2310
2723
 
2311
2724
  // src/security/patterns.ts
2312
- var STRONG_CREDENTIAL_NAME = "(?:password|passwd|passphrase|pwd|api[_-]?key|api[_-]?secret|secret[_-]?access[_-]?key|secret[_-]?key|client[_-]?secret[_-]?key|client[_-]?secret|private[_-]?key|aws[_-]?secret[_-]?access[_-]?key|access[_-]?token|refresh[_-]?token|auth[_-]?token|session[_-]?token|secret|token)";
2313
- var WEAK_CREDENTIAL_NAME = "(?:pass|id[_-]?token|credentials?)";
2725
+ var STRONG_CREDENTIAL_NAME = "(?:password|passwd|passphrase|pwd|api[_-]?key|api[_-]?secret|access[_-]?key|secret[_-]?access[_-]?key|secret[_-]?key|client[_-]?secret[_-]?key|client[_-]?secret|private[_-]?key|aws[_-]?secret[_-]?access[_-]?key|access[_-]?token|refresh[_-]?token|auth[_-]?token|session[_-]?token|session[_-]?key|secret|token)";
2726
+ var WEAK_CREDENTIAL_NAME = "(?:pass|credentials?)";
2314
2727
  var NOT_A_LITERAL_VALUE = "(?!(?:string|number|boolean|bigint|symbol|unknown|any|never|void|null|undefined|true|false|await|async|new|this|typeof|delete|yield|function|return|process\\.env|Buffer|Record|object)\\b)";
2315
2728
  var UNQUOTED_MIN_LENGTH = 2;
2316
2729
  var PROSE_CONTINUATION = String.raw`(?!\s+[a-z])`;
2317
- var UNQUOTED_LITERAL = String.raw`(?![0-9]+(?![A-Za-z0-9_+=/%:.~-]))([A-Za-z0-9_][A-Za-z0-9_+=/%:~-]{${UNQUOTED_MIN_LENGTH - 1},511})(?![A-Za-z0-9_+=/%:.~-]|[({[])` + PROSE_CONTINUATION;
2318
- var UNQUOTED_AMBIGUOUS_LITERAL = String.raw`(?![0-9]+(?![A-Za-z0-9_+=/%:.~-]))([A-Za-z0-9_][A-Za-z0-9_+=/%:~-]{7,511})(?![A-Za-z0-9_+=/%:.~-]|[({[])` + PROSE_CONTINUATION;
2730
+ var UNQUOTED_VALUE_CHARS = String.raw`A-Za-z0-9_+=/%:~$!@#^*?-`;
2731
+ var UNQUOTED_VALUE_END = String.raw`[A-Za-z0-9_+=/%:.~$!@#^*?-]`;
2732
+ var UNQUOTED_VALUE_START = String.raw`[$!@#%^&*~+]`;
2733
+ var UNQUOTED_LITERAL = String.raw`(` + // one capture, whichever branch matched: valueGroup is 1
2734
+ String.raw`(?![0-9]+(?!${UNQUOTED_VALUE_END}))[A-Za-z0-9_][${UNQUOTED_VALUE_CHARS}]{${UNQUOTED_MIN_LENGTH - 1},511}(?!${UNQUOTED_VALUE_END}|[({[]|[<>|\\])` + String.raw`|(?=${UNQUOTED_VALUE_START}[^ \t]{0,62}(?:[0-9]|${UNQUOTED_VALUE_START}))${UNQUOTED_VALUE_START}[${UNQUOTED_VALUE_CHARS}]{2,511}(?!${UNQUOTED_VALUE_END}|[({[]|[<>|\\])` + String.raw`|\([^()\s]{1,510}\)|\[[^\[\]\s]{1,510}\]|\{[^{}\s]{1,510}\}` + String.raw`)` + PROSE_CONTINUATION;
2735
+ var UNQUOTED_AMBIGUOUS_LITERAL = String.raw`(?![0-9]+(?!${UNQUOTED_VALUE_END}))([A-Za-z0-9_][${UNQUOTED_VALUE_CHARS}]{7,511})(?!${UNQUOTED_VALUE_END}|[({[]|[<>|\\])` + PROSE_CONTINUATION;
2319
2736
  var ASSIGN = String.raw`(?<![=!<>])[:=](?!=)`;
2320
2737
  var NOT_AFTER_QUOTE = String.raw`(?<!["'])`;
2321
2738
  var NOT_A_NAMESPACED_IDENTIFIER = String.raw`(?![a-z][a-z0-9]*(?:\.[a-z][a-z0-9-]*)+/)`;
2739
+ var QUOTED_CREDENTIAL_KEY = `["'](?!id[-_]token["'])[A-Za-z0-9_$-]{0,64}${STRONG_CREDENTIAL_NAME}["']`;
2322
2740
  var QUOTED_VALUE = String.raw`((?:[^"'\\\n]|\\\\["'](?=[A-Za-z0-9_])|\\.){1,512})`;
2323
2741
  var UNQUOTED_STRONG_NAME = `(?<!id[-_])${STRONG_CREDENTIAL_NAME}`;
2742
+ var CREDENTIAL_KEY_TAIL = new RegExp(`(?:${STRONG_CREDENTIAL_NAME})$`, "i");
2324
2743
  var DEFAULT_SECRET_PATTERNS = [
2325
2744
  {
2326
2745
  rule: "private-key-header",
@@ -2387,13 +2806,28 @@ var DEFAULT_SECRET_PATTERNS = [
2387
2806
  pattern: /xox[baprsdc]-[0-9A-Za-z-]{10,250}/
2388
2807
  },
2389
2808
  {
2390
- // Prefix-only vendors. Each prefix below is documented, globally unique and
2391
- // cannot collide with an ordinary identifier, which is what makes a bare
2392
- // prefix rule cheap and safe: `glpat-` (GitLab), `hvs.`/`s.` (Vault service
2393
- // and batch tokens), `whsec_` (Stripe webhook secret), `dckr_pat_` (Docker
2394
- // Hub), `hf_` (HuggingFace), `ya29.` (Google OAuth access token).
2809
+ // Known vendor token shapes: prefix-unique tokens, plus the few fixed layouts whose format is
2810
+ // documented and cannot collide with an ordinary identifier.
2811
+ //
2812
+ // Each prefix below is globally unique, which is what makes a bare prefix rule cheap and
2813
+ // safe: `glpat-` (GitLab), `hvs.`/`s.` (Vault service and batch tokens), `whsec_`
2814
+ // (Stripe webhook secret), `dckr_pat_` (Docker Hub), `hf_` (HuggingFace), `ya29.`
2815
+ // (Google OAuth access token), `shpat_`/`shpca_`/`shppa_`/`shpss_` (Shopify admin and
2816
+ // storefront tokens).
2817
+ //
2818
+ // The fixed shapes have no prefix to anchor on and were each emitted in clear:
2819
+ // - Telegram bot token: `<8-10 digit bot id>:<35-character secret>`.
2820
+ // - Discord bot token: `<base64 user id>.<6-8 char hmac>.<25-45 char signature>`; demanding
2821
+ // all three segments keeps ordinary dotted identifiers out.
2822
+ // - Azure DevOps personal access token: exactly 52 alphanumerics that always mix case and
2823
+ // digits, so a hash, a UUID or a plain identifier — all single-case or a different length —
2824
+ // does not match.
2825
+ //
2826
+ // The rule name still says "prefix" because that is how the catalogue began; it is the
2827
+ // vendor-token rule, and growing a new named rule per vendor would make the documented
2828
+ // pattern count drift on every release.
2395
2829
  rule: "known-vendor-token-prefix",
2396
- pattern: /\b(?:glpat-[A-Za-z0-9_-]{20,64}|glrt-[A-Za-z0-9_-]{20,64}|hvs\.[A-Za-z0-9_-]{20,128}|hvb\.[A-Za-z0-9_-]{20,128}|s\.[A-Za-z0-9]{20,64}|whsec_[A-Za-z0-9]{20,64}|dckr_pat_[A-Za-z0-9_-]{20,64}|hf_[A-Za-z0-9]{30,64}|ya29\.[A-Za-z0-9_-]{20,128}|sk_test_[A-Za-z0-9]{16,64}|1\/\/0[A-Za-z0-9_-]{20,64})/
2830
+ pattern: /\b(?:glpat-[A-Za-z0-9_-]{20,64}|glrt-[A-Za-z0-9_-]{20,64}|hvs\.[A-Za-z0-9_-]{20,128}|hvb\.[A-Za-z0-9_-]{20,128}|s\.[A-Za-z0-9]{20,64}|whsec_[A-Za-z0-9]{20,64}|dckr_pat_[A-Za-z0-9_-]{20,64}|hf_[A-Za-z0-9]{30,64}|ya29\.[A-Za-z0-9_-]{20,128}|sk_test_[A-Za-z0-9]{16,64}|1\/\/0[A-Za-z0-9_-]{20,64}|shpat_[A-Za-z0-9]{20,64}|shpca_[A-Za-z0-9]{20,64}|shppa_[A-Za-z0-9]{20,64}|shpss_[A-Za-z0-9]{20,64}|[0-9]{8,10}:[A-Za-z0-9_-]{35}|[A-Za-z0-9]{20,30}\.[A-Za-z0-9_-]{5,8}\.[A-Za-z0-9_-]{25,45}|(?=[A-Za-z0-9]{0,51}[a-z])(?=[A-Za-z0-9]{0,51}[A-Z])(?=[A-Za-z0-9]{0,51}[0-9])[A-Za-z0-9]{52})(?![A-Za-z0-9])/
2397
2831
  },
2398
2832
  {
2399
2833
  rule: "slack-webhook-url",
@@ -2448,39 +2882,52 @@ var DEFAULT_SECRET_PATTERNS = [
2448
2882
  // (including one invented tomorrow) is covered, provided the `//` is followed
2449
2883
  // immediately by the userinfo: `// see the docs` and a bare reminder comment
2450
2884
  // never match, because a space or the comment wording breaks the shape.
2885
+ //
2886
+ // Three shapes joined it, all the same fact — a URL carries the credential in plain sight —
2887
+ // and each cost a leak while it was elsewhere:
2888
+ // - The user part may be **empty**: Redis, SMTP, AMQP and FTP URLs routinely omit the username
2889
+ // (`redis://:password@host`), and a `{1,128}` prefix made every one of those invisible.
2890
+ // - `curl -u user:password` sends the same userinfo without a scheme; the lookbehind
2891
+ // consumes the flag so the match is the credential alone.
2892
+ // - An Azure SAS link authenticates with `?sig=`; the signature *is* the credential.
2451
2893
  rule: "uri-credentials",
2452
- pattern: /\/\/[^\s:/@"'`;()<>,]{1,128}:[^\s:/@"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/
2894
+ 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%._=~-])/
2453
2895
  },
2454
2896
  {
2455
2897
  // The host tail stops at quotes, `;`, `)`, `<`, `>` and `,`: an unbounded
2456
2898
  // `[^\s/]` used to swallow the closing quote and the statement separator of
2457
2899
  // the string the URL was written in.
2900
+ // The user part may be empty here too: `redis://:password@host` and `amqp://:password@host`
2901
+ // are how those services are configured when the account is the server's default.
2458
2902
  rule: "database-uri-credentials",
2459
- pattern: /(?:mongodb(?:\+srv)?|postgres(?:ql)?|mysql|maria(?:db)?|redis(?:s)?|amqp(?:s)?|clickhouse|mssql|sqlserver|oracle):\/\/[^\s:@/"'`;()<>,]{1,128}:[^\s@/"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/
2903
+ pattern: /(?:mongodb(?:\+srv)?|postgres(?:ql)?|mysql|maria(?:db)?|redis(?:s)?|amqp(?:s)?|clickhouse|mssql|sqlserver|oracle):\/\/[^\s:@/"'`;()<>,]{0,128}:[^\s@/"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/
2460
2904
  },
2461
2905
  {
2906
+ // An empty user part is valid userinfo (`smtp://:password@host`: the account is the server's
2907
+ // default), and it used to be the one shape every scheme-listed rule refused.
2462
2908
  rule: "basic-auth-url",
2463
- pattern: /(?:https?|ftp|sftp|ssh|git|smtp|smtps|ldap|ldaps):\/\/[^\s:@/"'`;()<>,]{1,128}:[^\s@/"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/i
2909
+ pattern: /(?:https?|ftp|sftp|ssh|git|smtp|smtps|ldap|ldaps):\/\/[^\s:@/"'`;()<>,]{0,128}:[^\s@/"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/i
2464
2910
  },
2465
2911
  {
2466
2912
  // Quoted credentials in any common key spelling. The value may be as short
2467
2913
  // as one character: `password: "hunter2"` is a credential whatever its
2468
2914
  // entropy, and a length floor was exactly how it survived into `parts`.
2469
2915
  //
2470
- // The key is either bare (`dbPassword:`) or wholly quoted (`"dbPassword":`).
2916
+ // The key is bare (`dbPassword:`), wholly quoted (`"password":`), or quoted with a
2917
+ // camelCase prefix (`"dbPassword":`) — the last one is {@link QUOTED_CREDENTIAL_KEY}.
2471
2918
  // There is deliberately no optional quote *before* the separator: that let a
2472
2919
  // previous string's closing quote stand in for the key's, so
2473
2920
  // ``${pass ? " PASS" : " FAIL"}`` had `" FAIL"` masked as if `PASS` were
2474
2921
  // the key name.
2475
2922
  rule: "credential-assignment",
2476
2923
  pattern: new RegExp(
2477
- `(?:["']${STRONG_CREDENTIAL_NAME}["']|${NOT_AFTER_QUOTE}${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_NAMESPACED_IDENTIFIER}(["'\`])${QUOTED_VALUE}\\1`,
2924
+ `(?:${QUOTED_CREDENTIAL_KEY}|${NOT_AFTER_QUOTE}(?<!id[-_])${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_NAMESPACED_IDENTIFIER}(["'\`])${QUOTED_VALUE}\\1`,
2478
2925
  "i"
2479
2926
  ),
2480
2927
  valueGroup: 2
2481
2928
  },
2482
2929
  {
2483
- // `pass`, `id-token` and `credentials` are ambiguous on their own, so they
2930
+ // `pass` and `credentials` are ambiguous on their own, so they
2484
2931
  // are accepted only against a quoted value long enough to be a credential.
2485
2932
  rule: "credential-assignment-weak",
2486
2933
  pattern: new RegExp(
@@ -2493,9 +2940,40 @@ var DEFAULT_SECRET_PATTERNS = [
2493
2940
  // The unquoted twin for YAML, docker-compose and `.env`: those formats never
2494
2941
  // quote their values, so the rules above cannot see them. `valueGroup` keeps
2495
2942
  // `POSTGRES_PASSWORD:` in the output.
2943
+ //
2944
+ // This is the one unquoted rule without `NOT_AFTER_QUOTE`, and the lookbehind is a
2945
+ // string-literal guard rather than a precision rule: a credential assignment *inside* a
2946
+ // literal — `const dsn = "password=hunter2;host=db"`, `curl -d "password=hunter2"` — was
2947
+ // rejected before it could be considered, and a DSN is a credential in a string. What made the
2948
+ // lookbehind redundant is the shape of `UNQUOTED_LITERAL`: a value has to start with a word
2949
+ // character, so `["awsSecret:", "apiKey:"]` — the list of key names the lookbehind was added
2950
+ // for — cannot match here anyway. `redact.ts` still refuses a match whose separator is inside
2951
+ // the literal, which is the case that list actually is.
2952
+ //
2953
+ // The name may also be a *quoted* key: YAML allows `"dbPassword": hunter2`, and JSON cannot
2954
+ // spell a key any other way, so the same {@link QUOTED_CREDENTIAL_KEY} fragment is used here.
2955
+ // Without it a quoted key whose value was not quoted emitted the value in clear.
2956
+ //
2957
+ // A colon-form assignment in a data file masks the whole remainder of the value to
2958
+ // end-of-line, whatever punctuation it holds. A strong credential name is the evidence that
2959
+ // the thing after it is a value, and the character classes above cannot cover every symbol a
2960
+ // password may contain — `password: pa&ss` used to stop at the `&`. This branch is a
2961
+ // lookbehind, so the match is the value alone, and `redact.ts` only applies it to a data or
2962
+ // shell file: in source code the same shape is an expression and stays untouched, and an `URL`
2963
+ // query string keeps its `&` separators because they are not a colon form.
2964
+ //
2965
+ // The `KEY=value` twin does the same for the `=` form, which INI, .properties and shell files
2966
+ // use: with a credential key the whole value is masked whatever symbols it contains
2967
+ // (`password=pa&ss`, `token=a<b`, `client_secret=x|y`). The value is bounded by whitespace
2968
+ // (end of line, or the space before a `# comment`), not by a symbol class — `envpass!@#$%^&*()` used
2969
+ // to stop before the parenthesis and leave the tail in clear. The lookbehind matches the value
2970
+ // alone and `redact.ts` decides, from the file and from the key, whether the line is an
2971
+ // assignment (it must be a data/shell file, the key must end in a credential name, and a URL
2972
+ // query parameter or `$VARIABLE` reference is not an assignment).
2496
2973
  rule: "credential-assignment-unquoted",
2497
2974
  pattern: new RegExp(
2498
- `${NOT_AFTER_QUOTE}${UNQUOTED_STRONG_NAME}\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_LITERAL_VALUE}${UNQUOTED_LITERAL}`,
2975
+ `(?:${QUOTED_CREDENTIAL_KEY}|${UNQUOTED_STRONG_NAME})\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_LITERAL_VALUE}${UNQUOTED_LITERAL}|(?<=${UNQUOTED_STRONG_NAME}\\s{0,8}=(?!=)\\s{0,8})(?![\\s#$"'\`])[^\\s]{1,512}|(?<=${UNQUOTED_STRONG_NAME}\\s{0,8}:[ ]{1,8})(?![ ]*["'\`])(?![ ]*[|>])${NOT_A_LITERAL_VALUE}[^\r
2976
+ #]{1,300}`,
2499
2977
  "i"
2500
2978
  ),
2501
2979
  valueGroup: 1
@@ -2518,8 +2996,14 @@ var DEFAULT_SECRET_PATTERNS = [
2518
2996
  // needs no `valueGroup`. A lone `Bearer`/`Basic`, and a word after it that
2519
2997
  // cannot be a credential (`Bearer authentication`), stay readable: the value
2520
2998
  // must contain a digit, be at least 32 chars, or carry base64 `=` padding.
2999
+ //
3000
+ // A fourth shape was leaking: `Basic dXNlcjpwYXNz` is the base64 of `user:pass` — 12
3001
+ // characters, no digit, no padding — and the three tests above all said "not a
3002
+ // credential", so it reached the parts in clear. Mixed case is the discriminator: a base64
3003
+ // rendering of textual userinfo mixes cases, while the prose the earlier rules were
3004
+ // protecting (`Bearer authentication`) is a lowercase word.
2521
3005
  rule: "authorization-header",
2522
- 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_.+/=-])/
3006
+ 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_.+/=-])/
2523
3007
  },
2524
3008
  {
2525
3009
  // Broader names than before (`apiKey`, `clientSecret`, `privateKey` were
@@ -2530,6 +3014,27 @@ var DEFAULT_SECRET_PATTERNS = [
2530
3014
  pattern: /(?<!["'])(?:api[_-]?key|secret[_-]?key|auth[_-]?token|client[_-]?secret|access[_-]?token|refresh[_-]?token|private[_-]?key|password|passwd|pwd)["']?\s*(?<![=!<>])[:=](?!=)\s*["']([^"'\s]{8,256})["']/i,
2531
3015
  valueGroup: 1
2532
3016
  },
3017
+ {
3018
+ // `${VAR:-fallback}` — a default value in a shell script, a `.env`, docker-compose or a
3019
+ // GitHub Actions workflow.
3020
+ //
3021
+ // This shape defeated every rule above it, and each refusal was individually reasonable:
3022
+ // the quoted rules need a quote after the separator, and the unquoted ones need the value to
3023
+ // begin with a word character — a fallback begins with `$`. So
3024
+ // `POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-MyProdPassword123!}` was emitted whole, `.env` files
3025
+ // and compose files included, which is where that idiom is the norm.
3026
+ //
3027
+ // The **fallback** is what gets masked, not the whole expansion: the variable name is the
3028
+ // readable context, exactly as `POSTGRES_PASSWORD:` is kept by the rule above. A single
3029
+ // interpolation with no operator (`${DB_PASSWORD}`) still does not match — there is nothing
3030
+ // between the braces to mask, and `isTemplateInterpolation` keeps such a value readable.
3031
+ rule: "interpolation-fallback-secret",
3032
+ pattern: new RegExp(
3033
+ `(?:["']${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})\\}["'\`]?`,
3034
+ "i"
3035
+ ),
3036
+ valueGroup: 1
3037
+ },
2533
3038
  {
2534
3039
  // Covers `.env` / shell assignment syntax, which never quotes its values and
2535
3040
  // was therefore invisible to the rule above. Anchored to the line start and
@@ -2557,8 +3062,8 @@ var DEFAULT_SECRET_PATTERNS = [
2557
3062
  valueGroup: 1
2558
3063
  }
2559
3064
  ];
2560
- var PEM_BLOCK_PATTERN = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----/g;
2561
- var PEM_UNTERMINATED_PATTERN = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----(?:\r?\n[A-Za-z0-9+/=]{4,}[ A-Za-z0-9+/=]*)+/g;
3065
+ var PEM_BLOCK_PATTERN = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----(?:(?!-----BEGIN)[\s\S])*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----/g;
3066
+ var PEM_UNTERMINATED_PATTERN = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----(?:\r\n|\n|\r)(?:(?:[ \t]*(?:Proc-Type|DEK-Info|Comment|Version):[^\r\n]*|[ \t]*)(?:\r\n|\n|\r))*(?:[ \t]*[A-Za-z0-9+/=]{8,}[ \t]*(?:\r\n|\n|\r|$))+/g;
2562
3067
 
2563
3068
  // src/security/redact.ts
2564
3069
  var REDACTION_MARKER = "[REDACTED: potential secret-like value omitted from snapshot]";
@@ -2652,6 +3157,20 @@ function toGlobal(rule) {
2652
3157
  return new RegExp(rule.pattern.source, [...flags].join(""));
2653
3158
  }
2654
3159
  var LINE_BREAK = /(\r\n|\n|\r)/;
3160
+ var LINE_TERMINATOR = /\r\n|\n|\r/g;
3161
+ var COMPILED_RULES = /* @__PURE__ */ new WeakMap();
3162
+ function compiledRuleFor(rule) {
3163
+ let compiled = COMPILED_RULES.get(rule);
3164
+ if (compiled === void 0) {
3165
+ compiled = {
3166
+ rule: rule.rule,
3167
+ pattern: toGlobal(rule),
3168
+ ...rule.valueGroup === void 0 ? {} : { valueGroup: rule.valueGroup }
3169
+ };
3170
+ COMPILED_RULES.set(rule, compiled);
3171
+ }
3172
+ return compiled;
3173
+ }
2655
3174
  function scanAndRedactSecrets(content, rules, filePath) {
2656
3175
  const findings = [];
2657
3176
  let redacted = content;
@@ -2663,18 +3182,15 @@ function scanAndRedactSecrets(content, rules, filePath) {
2663
3182
  blockPattern.lastIndex += 1;
2664
3183
  continue;
2665
3184
  }
2666
- const line = redacted.slice(0, match.index).split("\n").length;
2667
- const newlines = (match[0].match(/\n/g) ?? []).length;
3185
+ const before = redacted.slice(0, match.index);
3186
+ const line = (before.match(LINE_TERMINATOR) ?? []).length + 1;
3187
+ const newlines = (match[0].match(LINE_TERMINATOR) ?? []).length;
2668
3188
  findings.push({ rules: ["private-key-block"], line, path: filePath });
2669
- redacted = redacted.slice(0, match.index) + PEM_REDACTION_MARKER + "\n".repeat(newlines) + redacted.slice(match.index + match[0].length);
3189
+ redacted = before + PEM_REDACTION_MARKER + "\n".repeat(newlines) + redacted.slice(match.index + match[0].length);
2670
3190
  blockPattern.lastIndex = match.index + PEM_REDACTION_MARKER.length + newlines;
2671
3191
  }
2672
3192
  }
2673
- const compiled = rules.map((rule) => ({
2674
- rule: rule.rule,
2675
- pattern: toGlobal(rule),
2676
- ...rule.valueGroup === void 0 ? {} : { valueGroup: rule.valueGroup }
2677
- }));
3193
+ const compiled = rules.map(compiledRuleFor);
2678
3194
  const segments = redacted.split(LINE_BREAK);
2679
3195
  let lineNumber = 1;
2680
3196
  for (let index = 0; index < segments.length; index += 2) {
@@ -2692,11 +3208,39 @@ function scanAndRedactSecrets(content, rules, filePath) {
2692
3208
  }
2693
3209
  const group = valueGroup === void 0 ? void 0 : match.indices?.[valueGroup];
2694
3210
  if (group && isSelfNamingConstant(line, group[0], group[1])) continue;
2695
- if (valueGroup !== void 0 && startsInsideStringLiteral(line, match.index)) continue;
2696
- if (group && isUnquotedValue(line, group[0]) && isDeclaredBinding(line, match.index)) {
3211
+ if (valueGroup !== void 0 && startsInsideStringLiteral(line, match.index, group?.[0])) {
3212
+ continue;
3213
+ }
3214
+ if (group && isUnquotedValue(line, group[0]) && isDeclaredBinding(line, match.index, filePath)) {
2697
3215
  continue;
2698
3216
  }
2699
3217
  if (group && isTemplateInterpolation(line, group[0], group[1])) continue;
3218
+ if (group && isUnquotedValue(line, group[0]) && TRUNCATING_VALUE_CHARS.test(line[group[1]] ?? "")) {
3219
+ continue;
3220
+ }
3221
+ if (valueGroup !== void 0 && group === void 0) {
3222
+ if (!isAssignmentFile(filePath)) continue;
3223
+ const assignment = assignmentAround(line, match.index);
3224
+ if (assignment.form === "=" && (assignment.reference || assignment.key === null || !CREDENTIAL_KEY_TAIL.test(assignment.key))) {
3225
+ continue;
3226
+ }
3227
+ }
3228
+ if (group && isUnquotedValue(line, group[0]) && OPENER_LED_VALUE.test(line.slice(group[0], group[1])) && !isAssignmentFile(filePath)) {
3229
+ continue;
3230
+ }
3231
+ if (group && isUnquotedValue(line, group[0])) {
3232
+ const assignment = assignmentAround(line, group[0]);
3233
+ const wholeValue = isAssignmentFile(filePath) && assignment.form !== null && !assignment.reference && !assignment.urlValue;
3234
+ if (wholeValue) {
3235
+ spans.push({
3236
+ start: group[0],
3237
+ end: Math.max(group[1], tokenEnd(line, group[0])),
3238
+ rule
3239
+ });
3240
+ matchedRules.add(rule);
3241
+ continue;
3242
+ }
3243
+ }
2700
3244
  spans.push(
2701
3245
  group ? { start: group[0], end: group[1], rule } : { start: match.index, end: match.index + match[0].length, rule }
2702
3246
  );
@@ -2714,6 +3258,8 @@ function scanAndRedactSecrets(content, rules, filePath) {
2714
3258
  }
2715
3259
  var TOKEN_CHARS_LEFT = /[A-Za-z0-9_+/-]/;
2716
3260
  var TOKEN_CHARS_RIGHT = /[A-Za-z0-9_+/=-]/;
3261
+ var TRUNCATING_VALUE_CHARS = /[<>|\\]/;
3262
+ var OPENER_LED_VALUE = /^[(\\[{]/;
2717
3263
  function expandOverToken(line, start, end) {
2718
3264
  let left = start;
2719
3265
  let right = end;
@@ -2726,14 +3272,20 @@ function expandOverToken(line, start, end) {
2726
3272
  while (right < line.length && TOKEN_CHARS_RIGHT.test(line[right])) right += 1;
2727
3273
  return { start: left, end: right };
2728
3274
  }
2729
- function startsInsideStringLiteral(line, matchIndex) {
3275
+ function startsInsideStringLiteral(line, matchIndex, valueStart) {
2730
3276
  let runStart = matchIndex;
2731
3277
  while (runStart > 0 && /[A-Za-z0-9_-]/.test(line[runStart - 1])) runStart -= 1;
2732
3278
  const before = runStart > 0 ? line[runStart - 1] : "";
2733
- return before === '"' || before === "'" || before === "`";
3279
+ if (before !== '"' && before !== "'" && before !== "`") return false;
3280
+ if (valueStart === void 0) return true;
3281
+ return /["'`]/.test(line.slice(matchIndex, valueStart));
2734
3282
  }
2735
3283
  function isTemplateInterpolation(line, start, end) {
2736
- return line[start] === "$" && line[start + 1] === "{" && line[end - 1] === "}";
3284
+ if (line[start] !== "$" || line[start + 1] !== "{" || line[end - 1] !== "}") {
3285
+ return false;
3286
+ }
3287
+ const inner = line.slice(start + 2, end - 1).trim();
3288
+ return /^[A-Za-z_$][A-Za-z0-9_$.()[\]]*$/.test(inner);
2737
3289
  }
2738
3290
  function isSelfNamingConstant(line, start, end) {
2739
3291
  const value = line.slice(start, end);
@@ -2754,13 +3306,48 @@ function isSelfNamingConstant(line, start, end) {
2754
3306
  }
2755
3307
  return line.endsWith(value, index);
2756
3308
  }
3309
+ function assignmentAround(line, valueStart) {
3310
+ let index = valueStart;
3311
+ while (index > 0 && (line[index - 1] === " " || line[index - 1] === " ")) index -= 1;
3312
+ const separator = index > 0 ? line[index - 1] : "";
3313
+ if (separator !== ":" && separator !== "=") {
3314
+ return { form: null, key: null, reference: false, rhsStart: -1, urlValue: false };
3315
+ }
3316
+ const separatorIndex = index - 1;
3317
+ index = separatorIndex;
3318
+ while (index > 0 && (line[index - 1] === " " || line[index - 1] === " ")) index -= 1;
3319
+ const keyEnd = index;
3320
+ while (index > 0 && /[A-Za-z0-9_$.-]/.test(line[index - 1])) index -= 1;
3321
+ const key = line.slice(index, keyEnd).replace(/^-+/, "");
3322
+ const before = index > 0 ? line[index - 1] : "";
3323
+ const reference = before === "?" || before === "&" || before === "$" || before === '"' || before === "'" || before === "`";
3324
+ let rhsStart = separatorIndex + 1;
3325
+ while (rhsStart < line.length && (line[rhsStart] === " " || line[rhsStart] === " ")) rhsStart += 1;
3326
+ const urlValue = /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(line.slice(rhsStart, tokenEnd(line, rhsStart)));
3327
+ return { form: separator === ":" ? ":" : "=", key, reference, rhsStart, urlValue };
3328
+ }
3329
+ function tokenEnd(line, start) {
3330
+ let end = start;
3331
+ while (end < line.length && !/\s/.test(line[end])) end += 1;
3332
+ return end;
3333
+ }
2757
3334
  function isUnquotedValue(line, start) {
2758
3335
  const before = start > 0 ? line[start - 1] : "";
2759
3336
  return before !== '"' && before !== "'" && before !== "`";
2760
3337
  }
2761
- var DECLARATION_KEYWORDS = /\b(?:const|let|var|readonly|public|private|protected|static|declare|export|using)\s+$/;
3338
+ var DECLARATION_KEYWORDS = /\b(?:const|let|var|readonly|public|private|protected|static|using)\s+$/;
3339
+ var ASSIGNMENT_FILE = /\.(?:sh|bash|zsh|ksh|fish|env|ya?ml|toml|ini|conf|cfg|properties|tf|tfvars|service)$/i;
3340
+ var ASSIGNMENT_BASENAME = /^(?:\.env(?:\.[^/]*)?|\.envrc|\.profile|\.bashrc|\.zshrc|\.bash_profile)$/i;
3341
+ function isAssignmentFile(filePath) {
3342
+ if (filePath === void 0) return false;
3343
+ const normalised = filePath.replace(/\\/g, "/");
3344
+ if (ASSIGNMENT_FILE.test(normalised)) return true;
3345
+ const base = normalised.slice(normalised.lastIndexOf("/") + 1);
3346
+ return ASSIGNMENT_BASENAME.test(base);
3347
+ }
2762
3348
  var DECLARATION_WINDOW = 40;
2763
- function isDeclaredBinding(line, matchIndex) {
3349
+ function isDeclaredBinding(line, matchIndex, filePath) {
3350
+ if (isAssignmentFile(filePath)) return false;
2764
3351
  let runStart = matchIndex;
2765
3352
  while (runStart > 0 && /[A-Za-z0-9_$]/.test(line[runStart - 1])) runStart -= 1;
2766
3353
  const from = Math.max(0, runStart - DECLARATION_WINDOW);
@@ -2802,6 +3389,15 @@ function readLinkTarget(linkPath, fallback) {
2802
3389
  return fallback;
2803
3390
  }
2804
3391
  }
3392
+ function brokenLinkRecord(linkPath, relativePath, rootReal) {
3393
+ const rawTarget = readLinkTarget(linkPath, linkPath);
3394
+ const resolvedFallback = path16.resolve(path16.dirname(linkPath), rawTarget);
3395
+ return isInside(rootReal, resolvedFallback) ? { path: relativePath, reason: "read-error", detail: "broken symlink" } : {
3396
+ path: relativePath,
3397
+ reason: "outside-root",
3398
+ detail: `link target resolves outside the scanned root (target: ${rawTarget}); not followed`
3399
+ };
3400
+ }
2805
3401
  function isInside(root, candidate) {
2806
3402
  const relative8 = path16.relative(root, candidate);
2807
3403
  return relative8 === "" || !relative8.startsWith(`..${path16.sep}`) && relative8 !== ".." && !path16.isAbsolute(relative8);
@@ -2891,6 +3487,13 @@ function isSensitivePath(relativePath) {
2891
3487
  return matchesSensitiveList(posixPath, base);
2892
3488
  }
2893
3489
  var GLOBAL_PATTERNS = /* @__PURE__ */ new WeakMap();
3490
+ var GLOB_REGEX_CACHE = /* @__PURE__ */ new Map();
3491
+ var GITIGNORE_REGEX_CACHE = /* @__PURE__ */ new Map();
3492
+ var REGEX_CACHE_LIMIT = 4096;
3493
+ function rememberCompiled(cache, key, value) {
3494
+ if (cache.size >= REGEX_CACHE_LIMIT) cache.clear();
3495
+ cache.set(key, value);
3496
+ }
2894
3497
  function globalPattern(pattern) {
2895
3498
  let compiled = GLOBAL_PATTERNS.get(pattern);
2896
3499
  if (compiled === void 0) {
@@ -2901,8 +3504,8 @@ function globalPattern(pattern) {
2901
3504
  }
2902
3505
  var DEFAULT_PATH_RULES = [...DEFAULT_SECRET_PATTERNS];
2903
3506
  function pathScanRules(extraRules) {
2904
- if (extraRules === void 0 || extraRules.length === 0) return DEFAULT_PATH_RULES;
2905
- return [...DEFAULT_SECRET_PATTERNS, ...extraRules];
3507
+ if (extraRules === void 0) return DEFAULT_PATH_RULES;
3508
+ return extraRules;
2906
3509
  }
2907
3510
  function findSecretInPath(relativePath, extraRules) {
2908
3511
  const posixPath = relativePath.replace(/\\/g, "/");
@@ -2951,11 +3554,22 @@ function maskSkipPaths(records, extraRules) {
2951
3554
  });
2952
3555
  }
2953
3556
  function globToRegExp(glob) {
3557
+ const cached = GLOB_REGEX_CACHE.get(glob);
3558
+ if (cached !== void 0) return cached;
2954
3559
  const normalized = glob.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
2955
3560
  const anchored = normalized.startsWith("/");
2956
3561
  const body = anchored ? normalized.slice(1) : normalized;
2957
3562
  const prefix = anchored || body.includes("/") ? "^" : "(?:^|.*/)";
2958
- return new RegExp(`${prefix}${globBodyToRegExp(body, true)}(?:/.*)?$`);
3563
+ let compiled;
3564
+ try {
3565
+ compiled = new RegExp(`${prefix}${globBodyToRegExp(body, true)}(?:/.*)?$`);
3566
+ } catch (error) {
3567
+ throw new Error(
3568
+ `"${glob}" is not a valid glob: ${error.message}. A character class must be ascending, as in "[a-z]".`
3569
+ );
3570
+ }
3571
+ rememberCompiled(GLOB_REGEX_CACHE, glob, compiled);
3572
+ return compiled;
2959
3573
  }
2960
3574
  function globBodyToRegExp(body, allowBraces) {
2961
3575
  let out = "";
@@ -3067,6 +3681,14 @@ function escapeRegExpChar(character) {
3067
3681
  return /[\\^$.*+?()[\]{}|/]/.test(character) ? `\\${character}` : character;
3068
3682
  }
3069
3683
  function matchGitignorePattern(target, pattern) {
3684
+ let compiled = GITIGNORE_REGEX_CACHE.get(pattern);
3685
+ if (compiled === void 0) {
3686
+ compiled = compileGitignorePattern(pattern);
3687
+ rememberCompiled(GITIGNORE_REGEX_CACHE, pattern, compiled);
3688
+ }
3689
+ return compiled.test(target);
3690
+ }
3691
+ function compileGitignorePattern(pattern) {
3070
3692
  const anchored = pattern.startsWith("/");
3071
3693
  const body = anchored ? pattern.slice(1) : pattern;
3072
3694
  let source = "";
@@ -3115,7 +3737,11 @@ function matchGitignorePattern(target, pattern) {
3115
3737
  source += escapeRegExpChar(character);
3116
3738
  }
3117
3739
  const prefix = anchored || body.includes("/") ? "^" : "(?:^|.*/)";
3118
- return new RegExp(`${prefix}${source}(?:/.*)?$`).test(target);
3740
+ try {
3741
+ return new RegExp(`${prefix}${source}(?:/.*)?$`);
3742
+ } catch {
3743
+ return /$^/;
3744
+ }
3119
3745
  }
3120
3746
  function matchesGitignoreRule(rule, scoped, isDirectory) {
3121
3747
  if (!rule.dirOnly) return matchGitignorePattern(scoped, rule.pattern);
@@ -3145,14 +3771,31 @@ function gitignoreVerdict(layers, relativePath, isDirectory) {
3145
3771
  }
3146
3772
  return verdict;
3147
3773
  }
3148
- function defaultIgnoreReason(relativePath) {
3774
+ var DEFAULT_TOOL_DIR_NAMES = ["snapshot"];
3775
+ function toolDirNamesFor(toolOwnedPaths) {
3776
+ const names = new Set(DEFAULT_TOOL_DIR_NAMES);
3777
+ for (const entry of toolOwnedPaths) {
3778
+ const base = entry.replace(/\\/g, "/").replace(/\/+$/, "").split("/").pop();
3779
+ if (base !== void 0 && base.length > 0) names.add(base);
3780
+ }
3781
+ return [...names];
3782
+ }
3783
+ function isToolLeftoverName(name, dirNames) {
3784
+ for (const dirName of dirNames) {
3785
+ if (name.startsWith(`${dirName}.backup-`) || name.startsWith(`${dirName}.partial-`)) {
3786
+ return true;
3787
+ }
3788
+ }
3789
+ return false;
3790
+ }
3791
+ function defaultIgnoreReason(relativePath, toolDirNames = DEFAULT_TOOL_DIR_NAMES) {
3149
3792
  const posixPath = relativePath.replace(/\\/g, "/");
3150
3793
  const parts = posixPath.split("/");
3151
3794
  for (let i = 0; i < parts.length - 1; i++) {
3152
3795
  if (DEFAULT_IGNORED_DIRS.includes(parts[i])) {
3153
3796
  return `built-in ignore: directory "${parts[i]}"`;
3154
3797
  }
3155
- if (parts[i].startsWith("snapshot.backup-")) {
3798
+ if (isToolLeftoverName(parts[i], toolDirNames)) {
3156
3799
  return `built-in ignore: leftover snapshot backup "${parts[i]}"`;
3157
3800
  }
3158
3801
  }
@@ -3160,6 +3803,9 @@ function defaultIgnoreReason(relativePath) {
3160
3803
  if (DEFAULT_IGNORED_FILES.includes(base)) {
3161
3804
  return `built-in ignore: filename "${base}"`;
3162
3805
  }
3806
+ if (isToolLeftoverName(base, toolDirNames)) {
3807
+ return `built-in ignore: leftover snapshot backup "${base}"`;
3808
+ }
3163
3809
  return null;
3164
3810
  }
3165
3811
  function listIgnoredPaths(cwd) {
@@ -3228,46 +3874,77 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
3228
3874
  }
3229
3875
  const reported = /* @__PURE__ */ new Set();
3230
3876
  const kept = [];
3877
+ const report = (linkedPath, record) => {
3878
+ if (reported.has(linkedPath)) return;
3879
+ reported.add(linkedPath);
3880
+ skipped.push(record);
3881
+ };
3231
3882
  for (const candidate of candidates) {
3232
3883
  const parts = candidate.split("/");
3233
- let linkedDir = null;
3884
+ let linkedPath = null;
3234
3885
  for (let depth = 1; depth <= parts.length; depth += 1) {
3235
3886
  const prefix = parts.slice(0, depth).join("/");
3236
3887
  if (isLink(path16.join(cwd, prefix))) {
3237
- linkedDir = prefix;
3888
+ linkedPath = prefix;
3238
3889
  break;
3239
3890
  }
3240
3891
  }
3241
- if (linkedDir === null) {
3892
+ if (linkedPath === null) {
3242
3893
  kept.push(candidate);
3243
3894
  continue;
3244
3895
  }
3245
- if (reported.has(linkedDir)) continue;
3246
- reported.add(linkedDir);
3247
- const absolute = path16.join(cwd, linkedDir);
3248
- let targetReal = absolute;
3896
+ const absolute = path16.join(cwd, linkedPath);
3897
+ const rawTarget = readLinkTarget(absolute, absolute);
3898
+ let targetReal = null;
3249
3899
  try {
3250
3900
  targetReal = fs14.realpathSync(absolute);
3251
3901
  } catch {
3902
+ targetReal = null;
3252
3903
  }
3253
- const target = readLinkTarget(absolute, targetReal);
3254
- const what = linkedDir === candidate ? "symbolic link" : "directory link";
3255
- skipped.push(
3256
- isInside(rootReal, targetReal) ? {
3257
- path: linkedDir,
3258
- reason: "symlink",
3259
- detail: `${what} not followed (target: ${target})`
3260
- } : {
3261
- path: linkedDir,
3904
+ if (targetReal === null) {
3905
+ report(linkedPath, brokenLinkRecord(absolute, linkedPath, rootReal));
3906
+ continue;
3907
+ }
3908
+ if (!isInside(rootReal, targetReal)) {
3909
+ report(linkedPath, {
3910
+ path: linkedPath,
3262
3911
  reason: "outside-root",
3263
- detail: `link target resolves outside the scanned root (target: ${target}); not followed`
3264
- }
3265
- );
3266
- }
3267
- return kept;
3268
- }
3269
- function listGitCandidates(cwd, skipped, isToolOwned) {
3270
- const stdout = childProcess.execFileSync(
3912
+ detail: `link target resolves outside the scanned root (target: ${rawTarget}); not followed`
3913
+ });
3914
+ continue;
3915
+ }
3916
+ let stats = null;
3917
+ try {
3918
+ stats = fs14.statSync(absolute);
3919
+ } catch {
3920
+ stats = null;
3921
+ }
3922
+ if (stats === null) {
3923
+ report(linkedPath, { path: linkedPath, reason: "read-error", detail: "unreadable symlink" });
3924
+ continue;
3925
+ }
3926
+ if (linkedPath !== candidate || stats.isDirectory()) {
3927
+ report(linkedPath, {
3928
+ path: linkedPath,
3929
+ reason: "symlink",
3930
+ detail: `directory link not followed (target: ${rawTarget})`
3931
+ });
3932
+ continue;
3933
+ }
3934
+ if (!stats.isFile()) {
3935
+ report(linkedPath, {
3936
+ path: linkedPath,
3937
+ reason: "symlink",
3938
+ detail: `link to neither a file nor a directory (target: ${rawTarget})`
3939
+ });
3940
+ continue;
3941
+ }
3942
+ kept.push(candidate);
3943
+ }
3944
+ return kept;
3945
+ }
3946
+ function listGitCandidates(cwd, skipped, isToolOwned) {
3947
+ const stdout = childProcess.execFileSync(
3271
3948
  "git",
3272
3949
  ["ls-files", "-z", "--cached", "--others", "--exclude-standard"],
3273
3950
  {
@@ -3309,6 +3986,7 @@ function collectFiles(cwd, options = {}) {
3309
3986
  (options.toolOwnedPaths ?? []).map((entry) => entry.replace(/\\/g, "/"))
3310
3987
  );
3311
3988
  const isToolOwned = makeToolOwnedDecider(cwd, [...toolOwnedPaths]);
3989
+ const toolDirNames = toolDirNamesFor(toolOwnedPaths);
3312
3990
  let candidates;
3313
3991
  const skipped = [];
3314
3992
  const discovery = options.discovery ?? "auto";
@@ -3337,7 +4015,7 @@ function collectFiles(cwd, options = {}) {
3337
4015
  }
3338
4016
  const files = candidates.filter((file) => {
3339
4017
  if (isToolOwned(file)) return false;
3340
- const ignored = defaultIgnoreReason(file);
4018
+ const ignored = defaultIgnoreReason(file, toolDirNames);
3341
4019
  if (ignored) {
3342
4020
  skipped.push({ path: file, reason: "default-ignore", detail: ignored });
3343
4021
  return false;
@@ -3392,6 +4070,7 @@ function rootRealFor(root) {
3392
4070
  function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PURE__ */ new Set(), parentGitignoreLayers = []) {
3393
4071
  const results = { files: [], skipped: [] };
3394
4072
  const stack = [];
4073
+ const toolDirNames = toolDirNamesFor(reservedPaths);
3395
4074
  const relativeToBase = (target) => path16.relative(baseDir, target).replace(/\\/g, "/") || ".";
3396
4075
  const enter = (current, layers) => {
3397
4076
  if (visited.has(current)) return false;
@@ -3436,11 +4115,11 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
3436
4115
  });
3437
4116
  continue;
3438
4117
  }
3439
- if (DEFAULT_IGNORED_FILES.includes(entry.name) || entry.name.startsWith("snapshot.backup-")) {
4118
+ if (DEFAULT_IGNORED_FILES.includes(entry.name) || isToolLeftoverName(entry.name, toolDirNames)) {
3440
4119
  results.skipped.push({
3441
4120
  path: relPath,
3442
4121
  reason: "default-ignore",
3443
- detail: "built-in ignore: filename"
4122
+ detail: isToolLeftoverName(entry.name, toolDirNames) ? `built-in ignore: leftover snapshot backup "${entry.name}" (not descended)` : "built-in ignore: filename"
3444
4123
  });
3445
4124
  continue;
3446
4125
  }
@@ -3461,7 +4140,7 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
3461
4140
  try {
3462
4141
  targetReal = fs14.realpathSync(fullPath);
3463
4142
  } catch {
3464
- results.skipped.push({ path: relPath, reason: "read-error", detail: "broken symlink" });
4143
+ results.skipped.push(brokenLinkRecord(fullPath, relPath, rootReal));
3465
4144
  continue;
3466
4145
  }
3467
4146
  let stats;
@@ -3549,8 +4228,9 @@ function findConfigFile(cwd) {
3549
4228
  const pkgJsonPath = path16.join(cwd, "package.json");
3550
4229
  if (!fs14.existsSync(pkgJsonPath)) return null;
3551
4230
  try {
3552
- const parsed = JSON.parse(fs14.readFileSync(pkgJsonPath, "utf8"));
3553
- return parsed.snapshot === void 0 ? null : pkgJsonPath;
4231
+ const parsed = JSON.parse(stripJsonComments2(fs14.readFileSync(pkgJsonPath, "utf8")));
4232
+ const snapshot = parsed?.snapshot;
4233
+ return typeof snapshot === "object" && snapshot !== null && !Array.isArray(snapshot) ? pkgJsonPath : null;
3554
4234
  } catch {
3555
4235
  return null;
3556
4236
  }
@@ -3600,15 +4280,19 @@ function normalizeBudgets(budgets, maxPartBytes) {
3600
4280
  }
3601
4281
  function normalizeResolvedConfig(config) {
3602
4282
  const discovery = isDiscoveryMode(config.discovery) ? config.discovery : "auto";
4283
+ const monolithWanted = config.includeMonolith === true || config.artifacts?.monolith === true;
4284
+ const artifacts = resolveArtifacts(
4285
+ config.artifacts,
4286
+ void 0,
4287
+ monolithWanted,
4288
+ monolithWanted
4289
+ );
3603
4290
  return markResolvedConfig({
3604
4291
  ...config,
3605
4292
  discovery,
4293
+ includeMonolith: artifacts.monolith,
3606
4294
  secretRules: compileSecretRules(config.secretRules),
3607
- artifacts: resolveArtifacts(
3608
- config.artifacts,
3609
- void 0,
3610
- config.includeMonolith === true
3611
- ),
4295
+ artifacts,
3612
4296
  include: resolveInclude(config.include),
3613
4297
  preset: typeof config.preset === "string" ? config.preset : "generic",
3614
4298
  presetExclude: [
@@ -3687,9 +4371,9 @@ function stripJsonComments2(raw) {
3687
4371
  }
3688
4372
  out += char;
3689
4373
  }
3690
- return stripTrailingCommas(out);
4374
+ return stripTrailingCommas2(out);
3691
4375
  }
3692
- function stripTrailingCommas(text2) {
4376
+ function stripTrailingCommas2(text2) {
3693
4377
  let out = "";
3694
4378
  let inString = false;
3695
4379
  let escaped = false;
@@ -3817,6 +4501,16 @@ async function importConfigModule(fullPath) {
3817
4501
  url.searchParams.set("codebaseSnapshotLoad", String(moduleConfigLoadToken));
3818
4502
  return await import(url.href);
3819
4503
  }
4504
+ function attachConfigDir(config, filePath) {
4505
+ if (typeof config === "object" && config !== null) {
4506
+ Object.defineProperty(config, CONFIG_DIR_SYMBOL, {
4507
+ value: path16.dirname(filePath),
4508
+ enumerable: false,
4509
+ configurable: true
4510
+ });
4511
+ }
4512
+ return config;
4513
+ }
3820
4514
  async function loadConfigFileDetailed(cwd) {
3821
4515
  const warnings = [];
3822
4516
  const errors = [];
@@ -3832,7 +4526,7 @@ async function loadConfigFileDetailed(cwd) {
3832
4526
  );
3833
4527
  }
3834
4528
  assertKnownConfigKeys(config, fullPath);
3835
- return { config, file: fullPath, warnings, errors };
4529
+ return { config: attachConfigDir(config, fullPath), file: fullPath, warnings, errors };
3836
4530
  } catch (err) {
3837
4531
  const raw = err.message;
3838
4532
  const message = raw.includes(fullPath) ? raw : `${fullPath}: ${raw}`;
@@ -3851,7 +4545,7 @@ async function loadConfigFileDetailed(cwd) {
3851
4545
  const imported = await importConfigModule(fullPath);
3852
4546
  const hasDefault = Object.prototype.hasOwnProperty.call(imported, "default");
3853
4547
  const config = readConfigExport(hasDefault ? imported.default : imported, fullPath);
3854
- return { config, file: fullPath, warnings, errors };
4548
+ return { config: attachConfigDir(config, fullPath), file: fullPath, warnings, errors };
3855
4549
  } catch (err) {
3856
4550
  const message = `Could not load ${fullPath}: ${err.message}`;
3857
4551
  warnings.push(message);
@@ -3869,7 +4563,12 @@ async function loadConfigFileDetailed(cwd) {
3869
4563
  snapshotKey,
3870
4564
  `${pkgJsonPath} (the "snapshot" key)`
3871
4565
  );
3872
- return { config: snapshotKey, file: pkgJsonPath, warnings, errors };
4566
+ return {
4567
+ config: attachConfigDir(snapshotKey, pkgJsonPath),
4568
+ file: pkgJsonPath,
4569
+ warnings,
4570
+ errors
4571
+ };
3873
4572
  }
3874
4573
  if (snapshotKey !== void 0) {
3875
4574
  const kind = Array.isArray(snapshotKey) ? "array" : typeof snapshotKey;
@@ -3887,13 +4586,6 @@ async function loadConfigFileDetailed(cwd) {
3887
4586
  }
3888
4587
  async function loadConfigFile(cwd) {
3889
4588
  const loaded = await loadConfigFileDetailed(cwd);
3890
- if (loaded.config && loaded.file && typeof loaded.config === "object") {
3891
- Object.defineProperty(loaded.config, CONFIG_DIR_SYMBOL, {
3892
- value: path16.dirname(loaded.file),
3893
- enumerable: false,
3894
- configurable: true
3895
- });
3896
- }
3897
4589
  if (loaded.errors.length > 0) {
3898
4590
  throw new Error(`The config file could not be read: ${loaded.errors.join("; ")}`);
3899
4591
  }
@@ -3922,7 +4614,7 @@ var DEFAULT_ARTIFACTS = {
3922
4614
  function isArtifactName(value) {
3923
4615
  return ARTIFACT_NAMES.includes(value);
3924
4616
  }
3925
- function resolveArtifacts(requested, skipped, includeMonolith, monolithOverride) {
4617
+ function resolveArtifacts(requested, skipped, includeMonolith, monolithOverride, only) {
3926
4618
  const artifacts = {
3927
4619
  ...DEFAULT_ARTIFACTS,
3928
4620
  // `includeMonolith` predates this selection and stays the switch for it.
@@ -3947,6 +4639,21 @@ function resolveArtifacts(requested, skipped, includeMonolith, monolithOverride)
3947
4639
  if (monolithOverride !== void 0) {
3948
4640
  artifacts.monolith = monolithOverride;
3949
4641
  }
4642
+ if (only !== void 0 && only.length > 0) {
4643
+ const keep = /* @__PURE__ */ new Set();
4644
+ for (const name of only) {
4645
+ if (!isArtifactName(name)) {
4646
+ throw new Error(
4647
+ `Unknown artifact "${name}". Expected one of: ${ARTIFACT_NAMES.join(", ")}.`
4648
+ );
4649
+ }
4650
+ keep.add(name);
4651
+ }
4652
+ for (const name of ARTIFACT_NAMES) {
4653
+ artifacts[name] = keep.has(name);
4654
+ }
4655
+ return artifacts;
4656
+ }
3950
4657
  for (const name of skipped ?? []) {
3951
4658
  if (!isArtifactName(name)) {
3952
4659
  throw new Error(
@@ -4247,7 +4954,8 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
4247
4954
  userConfig?.artifacts,
4248
4955
  cliOptions?.skipArtifacts,
4249
4956
  includeMonolith,
4250
- cliMonolith
4957
+ cliMonolith,
4958
+ cliOptions?.onlyArtifacts
4251
4959
  );
4252
4960
  const explicitMaxPartBytes = cliOptions?.maxPartBytes ?? userConfig?.maxPartBytes;
4253
4961
  const maxPartBytes = boundedBytes(
@@ -4421,7 +5129,18 @@ function configDigest(config) {
4421
5129
  excludePatterns: config.excludePatterns,
4422
5130
  preset: config.preset,
4423
5131
  layersMode: config.layersMode,
4424
- budgets: config.budgets,
5132
+ // `budgets.byLayer` is a plain object, and `JSON.stringify` preserves insertion order — so
5133
+ // `{ docs, api }` and `{ api, docs }` hashed differently despite being the same settings, and
5134
+ // `validate` reported configuration drift for a snapshot nobody had changed. The keys are
5135
+ // canonicalised here; nothing else about the object is order-dependent.
5136
+ budgets: {
5137
+ default: config.budgets.default,
5138
+ byLayer: Object.fromEntries(
5139
+ Object.entries(config.budgets.byLayer).sort(
5140
+ ([left], [right]) => left < right ? -1 : left > right ? 1 : 0
5141
+ )
5142
+ )
5143
+ },
4425
5144
  // The matcher is what makes a layer a layer. Hashing only the names meant that
4426
5145
  // moving `{ name: "api", match: "src/api/**" }` to `"src/v2/**"` produced the same
4427
5146
  // digest, so `validate` reported "valid and up to date" for a snapshot whose files
@@ -4705,9 +5424,21 @@ function generateSarifReport(manifest, findings, rules, toolVersion) {
4705
5424
  }
4706
5425
 
4707
5426
  // src/partitioner/preview.ts
5427
+ var LINE_ENDINGS = /\r\n|\r/g;
5428
+ var normaliseLineEndings = (content) => content.replace(LINE_ENDINGS, "\n");
4708
5429
  function countLines(content) {
4709
5430
  if (content.length === 0) return 0;
4710
- return content.split("\n").length - (content.endsWith("\n") ? 1 : 0);
5431
+ let breaks = 0;
5432
+ for (let index = 0; index < content.length; index += 1) {
5433
+ const code = content.charCodeAt(index);
5434
+ if (code === 10) {
5435
+ breaks += 1;
5436
+ continue;
5437
+ }
5438
+ if (code === 13 && content.charCodeAt(index + 1) !== 10) breaks += 1;
5439
+ }
5440
+ const last = content.charCodeAt(content.length - 1);
5441
+ return last === 10 || last === 13 ? breaks : breaks + 1;
4711
5442
  }
4712
5443
  function truncateToBytes(content, maxBytes) {
4713
5444
  if (maxBytes <= 0) return { content: "", isTruncated: content.length > 0 };
@@ -4718,17 +5449,18 @@ function truncateToBytes(content, maxBytes) {
4718
5449
  return { content: slice, isTruncated: true };
4719
5450
  }
4720
5451
  function truncatePreview(content, headLines, tailLines) {
4721
- const lines = content.split("\n");
4722
- const total = countLines(content);
5452
+ const normalised = normaliseLineEndings(content);
5453
+ const lines = normalised.split("\n");
5454
+ const total = countLines(normalised);
4723
5455
  if (total <= headLines + tailLines) {
4724
5456
  return {
4725
- content,
5457
+ content: normalised,
4726
5458
  isTruncated: false,
4727
5459
  originalLines: total,
4728
5460
  includedLines: total
4729
5461
  };
4730
5462
  }
4731
- const window = content.endsWith("\n") ? lines.slice(0, -1) : lines;
5463
+ const window = normalised.endsWith("\n") ? lines.slice(0, -1) : lines;
4732
5464
  const head = window.slice(0, headLines);
4733
5465
  const tail = tailLines > 0 ? window.slice(window.length - tailLines) : [];
4734
5466
  const omitted = total - head.length - tail.length;
@@ -4782,23 +5514,55 @@ function truncateWithBudgetMarker(content, maxBytes, budget, originalLines) {
4782
5514
  };
4783
5515
  }
4784
5516
  function partitionFiles(files, maxPartBytes, contentFingerprint) {
4785
- if (files.length === 0) return [];
4786
- const budget = Math.max(MIN_SECTION_BUDGET_BYTES + HEADER_RESERVE_BYTES, maxPartBytes);
4787
- const sectionBudget = budget - HEADER_RESERVE_BYTES;
4788
- const prepared = files.map((file) => prepareSection(file, sectionBudget));
4789
- let groups = greedyGroups(prepared, budget);
5517
+ return partitionFilesForBuckets([{ files, budgetBytes: maxPartBytes }], contentFingerprint);
5518
+ }
5519
+ function partitionFilesForBuckets(buckets, contentFingerprint) {
5520
+ const groups = [];
5521
+ for (const bucket of buckets) {
5522
+ if (bucket.files.length === 0) continue;
5523
+ const budget = Math.max(
5524
+ MIN_SECTION_BUDGET_BYTES + HEADER_RESERVE_BYTES,
5525
+ bucket.budgetBytes
5526
+ );
5527
+ const sectionBudget = budget - HEADER_RESERVE_BYTES;
5528
+ const prepared = bucket.files.map((file) => prepareSection(file, sectionBudget, budget));
5529
+ for (const sections of greedyGroups(prepared, budget)) groups.push({ sections, budget });
5530
+ }
5531
+ if (groups.length === 0) return [];
5532
+ const measurements = /* @__PURE__ */ new Map();
5533
+ const widthOf = (total) => Math.max(3, String(total).length);
5534
+ const measure = (group, index, total) => {
5535
+ const cached = measurements.get(group);
5536
+ const width = widthOf(total);
5537
+ if (cached !== void 0 && cached.index === index && cached.width === width) {
5538
+ return cached.size;
5539
+ }
5540
+ const { content } = assembleGroup(group, index, total, contentFingerprint);
5541
+ const size2 = Buffer.byteLength(content, "utf8");
5542
+ measurements.set(group, { index, width, size: size2 });
5543
+ return size2;
5544
+ };
4790
5545
  for (let pass = 0; pass < MAX_SPLIT_PASSES; pass++) {
4791
- const rendered = renderGroups(groups, budget, contentFingerprint);
4792
- const oversized = rendered.findIndex((part) => part.metadata.byteSize > budget);
4793
- if (oversized === -1) return rendered;
5546
+ const total = groups.length;
5547
+ let oversized = -1;
5548
+ for (let index = 0; index < total; index += 1) {
5549
+ const group2 = groups[index];
5550
+ if (measure(group2, index, total) > group2.budget) {
5551
+ oversized = index;
5552
+ break;
5553
+ }
5554
+ }
5555
+ if (oversized === -1) return renderGroups(groups, contentFingerprint);
4794
5556
  const group = groups[oversized];
4795
- if (group.length > 1) {
4796
- const moved = group.pop();
4797
- groups.splice(oversized + 1, 0, [moved]);
5557
+ if (group.sections.length > 1) {
5558
+ const moved = group.sections.pop();
5559
+ groups.splice(oversized + 1, 0, { sections: [moved], budget: group.budget });
5560
+ measurements.delete(group);
4798
5561
  continue;
4799
5562
  }
4800
- const [section] = group;
4801
- const overflow = rendered[oversized].metadata.byteSize - budget;
5563
+ const [section] = group.sections;
5564
+ if (section === void 0) return renderGroups(groups, contentFingerprint);
5565
+ const overflow = measure(group, oversized, total) - group.budget;
4802
5566
  const currentContent = section.file.content ?? "";
4803
5567
  const shrinkTo = Math.max(
4804
5568
  0,
@@ -4807,26 +5571,33 @@ function partitionFiles(files, maxPartBytes, contentFingerprint) {
4807
5571
  const shrunk = truncateWithBudgetMarker(
4808
5572
  currentContent,
4809
5573
  shrinkTo,
4810
- budget,
5574
+ group.budget,
4811
5575
  section.file.originalLines
4812
5576
  );
4813
5577
  if (shrunk.isTruncated) {
4814
5578
  applyTruncatedContent(section.file, shrunk.content);
4815
5579
  section.text = renderFileSection(section.file);
4816
5580
  section.byteSize = Buffer.byteLength(section.text, "utf8");
5581
+ measurements.delete(group);
4817
5582
  continue;
4818
5583
  }
5584
+ const rendered = renderGroups(groups, contentFingerprint);
4819
5585
  const marker2 = TRUNCATION_MARKER;
4820
- assertBudgetHoldsMarker(budget);
5586
+ assertBudgetHoldsMarker(group.budget);
4821
5587
  const target = Math.max(
4822
5588
  0,
4823
- budget - Buffer.byteLength(marker2, "utf8") - TOKEN_LINE_SLACK
5589
+ group.budget - Buffer.byteLength(marker2, "utf8") - TOKEN_LINE_SLACK
4824
5590
  );
4825
5591
  const clipped = truncateToBytes(rendered[oversized].markdown, target);
4826
- rendered[oversized] = rehashPart(rendered[oversized], clipped.content + marker2);
5592
+ rendered[oversized] = rehashPart(
5593
+ rendered[oversized],
5594
+ clipped.content + marker2
5595
+ );
4827
5596
  return rendered;
4828
5597
  }
4829
- return enforceBudget(renderGroups(groups, budget, contentFingerprint), budget);
5598
+ return renderGroups(groups, contentFingerprint).flatMap(
5599
+ (part) => enforceBudget([part], part.metadata.budgetBytes)
5600
+ );
4830
5601
  }
4831
5602
  var TRUNCATION_MARKER = "\n... [part truncated: cannot fit budget] ...\n";
4832
5603
  function assertBudgetHoldsMarker(budget) {
@@ -4911,7 +5682,7 @@ function renumberParts(parts, contentFingerprint) {
4911
5682
  (part) => enforceBudget([part], part.metadata.budgetBytes)[0] ?? part
4912
5683
  );
4913
5684
  }
4914
- var SECTION_TRUNCATION_NOTICE = "\n... [section truncated: metadata alone exceeds the part budget] ...\n";
5685
+ var SECTION_TRUNCATION_NOTICE = "... [section truncated: the fixed metadata and a code fence did not fit the part budget] ...";
4915
5686
  var METADATA_VALUE_MAX = 200;
4916
5687
  var DISPLAY_PATH_MAX = 300;
4917
5688
  function capValue(value, max) {
@@ -4924,7 +5695,7 @@ var displayPath = (value) => capValue(escapeControls(value), DISPLAY_PATH_MAX);
4924
5695
  function topEntries(counts, limit) {
4925
5696
  return Object.entries(counts).sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).slice(0, limit).map(([key, value]) => `${capMetadata(key)} (${value})`).join(", ");
4926
5697
  }
4927
- function prepareSection(file, sectionBudget) {
5698
+ function prepareSection(file, sectionBudget, partBudget) {
4928
5699
  let text2 = renderFileSection(file);
4929
5700
  let byteSize = Buffer.byteLength(text2, "utf8");
4930
5701
  if (byteSize <= sectionBudget) return { file, text: text2, byteSize };
@@ -4936,7 +5707,7 @@ function prepareSection(file, sectionBudget) {
4936
5707
  const truncated = truncateWithBudgetMarker(
4937
5708
  content,
4938
5709
  allowed,
4939
- sectionBudget,
5710
+ partBudget,
4940
5711
  file.originalLines
4941
5712
  );
4942
5713
  if (!truncated.isTruncated) return;
@@ -4953,13 +5724,57 @@ function prepareSection(file, sectionBudget) {
4953
5724
  shrinkBody();
4954
5725
  }
4955
5726
  if (byteSize > sectionBudget) {
4956
- const target = sectionBudget - Buffer.byteLength(SECTION_TRUNCATION_NOTICE, "utf8");
4957
- const truncated = truncateToBytes(text2, Math.max(0, target));
4958
- text2 = truncated.content + SECTION_TRUNCATION_NOTICE;
5727
+ applyTruncatedContent(file, SECTION_TRUNCATION_NOTICE);
5728
+ file.summary = void 0;
5729
+ file.summaryOmitted = true;
5730
+ text2 = renderFileSection(file);
4959
5731
  byteSize = Buffer.byteLength(text2, "utf8");
5732
+ if (byteSize > sectionBudget) {
5733
+ text2 = truncateRenderedSection(text2, sectionBudget, fenceForContent(file.content ?? ""));
5734
+ byteSize = Buffer.byteLength(text2, "utf8");
5735
+ }
4960
5736
  }
4961
5737
  return { file, text: text2, byteSize };
4962
5738
  }
5739
+ function truncateRenderedSection(text2, sectionBudget, fence) {
5740
+ const closing = `
5741
+ ${SECTION_TRUNCATION_NOTICE}
5742
+ ${fence}
5743
+ `;
5744
+ const bodyRoom = sectionBudget - Buffer.byteLength(closing, "utf8");
5745
+ if (bodyRoom > 0) {
5746
+ const cut2 = truncateToBytes(text2, bodyRoom).content;
5747
+ const lastBreak2 = cut2.lastIndexOf("\n");
5748
+ const kept = lastBreak2 >= 0 ? cut2.slice(0, lastBreak2 + 1) : "";
5749
+ if (fenceIsOpen(kept, fence)) return `${kept}${closing}`;
5750
+ }
5751
+ const probe = text2.slice(0, 512);
5752
+ const emptyFence = fenceForText(probe.slice(0, Math.max(0, probe.lastIndexOf("\n") + 1)), 4);
5753
+ const block = `
5754
+ ${emptyFence}
5755
+ ${SECTION_TRUNCATION_NOTICE}
5756
+ ${emptyFence}
5757
+ `;
5758
+ const prefixRoom = sectionBudget - Buffer.byteLength(block, "utf8");
5759
+ const cut = prefixRoom > 0 ? truncateToBytes(text2, prefixRoom).content : "";
5760
+ const lastBreak = cut.lastIndexOf("\n");
5761
+ const prefix = lastBreak >= 0 ? cut.slice(0, lastBreak + 1) : "";
5762
+ return `${dropTrailingOpenFence(prefix, fence)}${block}`;
5763
+ }
5764
+ function dropTrailingOpenFence(text2, fence) {
5765
+ if (!fenceIsOpen(text2, fence)) return text2;
5766
+ const lines = text2.split("\n");
5767
+ const opening = lines.findIndex((line) => line.startsWith(fence));
5768
+ if (opening < 0) return text2;
5769
+ return lines.slice(0, opening).join("\n") + (opening > 0 ? "\n" : "");
5770
+ }
5771
+ function fenceIsOpen(text2, fence) {
5772
+ let open = false;
5773
+ for (const line of text2.split("\n")) {
5774
+ if (line.startsWith(fence)) open = !open;
5775
+ }
5776
+ return open;
5777
+ }
4963
5778
  function applyTruncatedContent(file, content) {
4964
5779
  file.content = content;
4965
5780
  file.isPreviewTruncated = true;
@@ -5007,52 +5822,64 @@ function greedyGroups(sections, budget) {
5007
5822
  if (current.length > 0) groups.push(current);
5008
5823
  return groups;
5009
5824
  }
5010
- function renderGroups(groups, budget, contentFingerprint) {
5825
+ function assembleGroup(group, index, total, contentFingerprint) {
5826
+ const width = Math.max(3, String(total).length);
5827
+ const zeroPad = (value) => String(value).padStart(width, "0");
5828
+ const filename = `part-${zeroPad(index + 1)}.md`;
5829
+ const prev = index === 0 ? "none" : `part-${zeroPad(index)}.md`;
5830
+ const next = index === total - 1 ? "none" : `part-${zeroPad(index + 2)}.md`;
5831
+ for (const section of group.sections) {
5832
+ section.file.part = filename;
5833
+ }
5834
+ const layerCounts = {};
5835
+ const kindCounts = {};
5836
+ for (const section of group.sections) {
5837
+ layerCounts[section.file.layer] = (layerCounts[section.file.layer] || 0) + 1;
5838
+ kindCounts[section.file.kind] = (kindCounts[section.file.kind] || 0) + 1;
5839
+ }
5840
+ const pathLines = group.sections.map((s) => displayPath(s.file.relativePath));
5841
+ const listFence = fenceForText(pathLines.join("\n"), 3);
5842
+ const header = [
5843
+ `# Codebase Snapshot Part ${zeroPad(index + 1)} of ${zeroPad(total)}`,
5844
+ "",
5845
+ `- Previous: ${prev}`,
5846
+ `- Next: ${next}`,
5847
+ `- Files: ${group.sections.length}`,
5848
+ `- Content Fingerprint: ${contentFingerprint || "none"}`,
5849
+ `- Layers: ${topEntries(layerCounts, 6) || "none"}`,
5850
+ `- Kinds: ${topEntries(kindCounts, 8) || "none"}`,
5851
+ "",
5852
+ UNTRUSTED_CONTENT_NOTICE,
5853
+ "",
5854
+ "## Files",
5855
+ "",
5856
+ `${listFence}text`,
5857
+ ...pathLines,
5858
+ listFence,
5859
+ "",
5860
+ "## Contents",
5861
+ ""
5862
+ ].join("\n");
5863
+ const assembled = (header + group.sections.map((s) => s.text).join("")).replace(
5864
+ /\r\n|\r/g,
5865
+ "\n"
5866
+ );
5867
+ const estimatedTokens = estimateTokens(assembled);
5868
+ return { filename, content: insertTokenLine(assembled, estimatedTokens), estimatedTokens };
5869
+ }
5870
+ function renderGroups(groups, contentFingerprint) {
5011
5871
  const total = groups.length;
5012
- const zeroPad = (index) => String(index).padStart(Math.max(3, String(total).length), "0");
5013
5872
  return groups.map((group, index) => {
5014
- const filename = `part-${zeroPad(index + 1)}.md`;
5015
- const prev = index === 0 ? "none" : `part-${zeroPad(index)}.md`;
5016
- const next = index === total - 1 ? "none" : `part-${zeroPad(index + 2)}.md`;
5017
- for (const section of group) {
5018
- section.file.part = filename;
5019
- }
5020
- const layersCovered = Array.from(new Set(group.map((s) => s.file.layer))).sort();
5021
- const layerCounts = {};
5022
- const kindCounts = {};
5023
- for (const section of group) {
5024
- layerCounts[section.file.layer] = (layerCounts[section.file.layer] || 0) + 1;
5025
- kindCounts[section.file.kind] = (kindCounts[section.file.kind] || 0) + 1;
5026
- }
5027
- const pathLines = group.map((s) => displayPath(s.file.relativePath));
5028
- const listFence = fenceForText(pathLines.join("\n"), 3);
5029
- const header = [
5030
- `# Codebase Snapshot Part ${zeroPad(index + 1)} of ${zeroPad(total)}`,
5031
- "",
5032
- `- Previous: ${prev}`,
5033
- `- Next: ${next}`,
5034
- `- Files: ${group.length}`,
5035
- `- Content Fingerprint: ${contentFingerprint || "none"}`,
5036
- `- Layers: ${topEntries(layerCounts, 6) || "none"}`,
5037
- `- Kinds: ${topEntries(kindCounts, 8) || "none"}`,
5038
- "",
5039
- UNTRUSTED_CONTENT_NOTICE,
5040
- "",
5041
- "## Files",
5042
- "",
5043
- `${listFence}text`,
5044
- ...pathLines,
5045
- listFence,
5046
- "",
5047
- "## Contents",
5048
- ""
5049
- ].join("\n");
5050
- const assembled = (header + group.map((s) => s.text).join("")).replace(/\r\n/g, "\n");
5051
- const estimatedTokens = estimateTokens(assembled);
5052
- const content = insertTokenLine(assembled, estimatedTokens);
5873
+ const { filename, content, estimatedTokens } = assembleGroup(
5874
+ group,
5875
+ index,
5876
+ total,
5877
+ contentFingerprint
5878
+ );
5053
5879
  const byteSize = Buffer.byteLength(content, "utf8");
5054
5880
  const sha256 = crypto2.createHash("sha256").update(content).digest("hex");
5055
- const includedFiles = group.map(({ file }) => ({
5881
+ const layersCovered = Array.from(new Set(group.sections.map((s) => s.file.layer))).sort();
5882
+ const includedFiles = group.sections.map(({ file }) => ({
5056
5883
  relativePath: file.relativePath,
5057
5884
  sourceBytes: file.sizeBytes,
5058
5885
  includedBytes: file.includedBytes,
@@ -5065,10 +5892,10 @@ function renderGroups(groups, budget, contentFingerprint) {
5065
5892
  filename,
5066
5893
  byteSize,
5067
5894
  estimatedTokens,
5068
- budgetBytes: budget,
5895
+ budgetBytes: group.budget,
5069
5896
  sha256,
5070
5897
  lines: countLines(content),
5071
- fileCount: group.length,
5898
+ fileCount: group.sections.length,
5072
5899
  layersCovered,
5073
5900
  includedFiles
5074
5901
  };
@@ -5076,7 +5903,7 @@ function renderGroups(groups, budget, contentFingerprint) {
5076
5903
  });
5077
5904
  }
5078
5905
  function emittedBody(content) {
5079
- const normalised = content.replace(/\r\n/g, "\n");
5906
+ const normalised = content.replace(/\r\n|\r/g, "\n");
5080
5907
  return normalised.endsWith("\n") ? normalised.slice(0, -1) : normalised;
5081
5908
  }
5082
5909
  function compactMetadata(file) {
@@ -5144,7 +5971,7 @@ function generateMonolithJson(manifest, filesWithContent) {
5144
5971
  }
5145
5972
  function generateMonolithMarkdown(manifest, filesWithContent) {
5146
5973
  const sections = filesWithContent.map((file) => {
5147
- const content = (file.content ?? "").replace(/\r\n/g, "\n");
5974
+ const content = (file.content ?? "").replace(/\r\n|\r/g, "\n");
5148
5975
  const fence = fenceForContent(content);
5149
5976
  return [
5150
5977
  `## File: ${escapeControls(file.relativePath)}`,
@@ -5358,273 +6185,30 @@ function generateProjectTree(filePaths) {
5358
6185
  const isDirectory = child.children.size > 0;
5359
6186
  const label = escapeControls(key);
5360
6187
  lines.push(`${frame.prefix}${isLast ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 "}${label}${isDirectory ? "/" : ""}`);
5361
- if (lines.length >= MAX_TREE_LINES) {
5362
- truncatedAt = lines.length;
5363
- break;
5364
- }
5365
- if (!isDirectory) continue;
5366
- if (frame.depth + 1 > MAX_TREE_DEPTH) {
5367
- depthTruncated = true;
5368
- continue;
5369
- }
5370
- stack.push({
5371
- node: child,
5372
- prefix: frame.prefix + (isLast ? " " : "\u2502 "),
5373
- depth: frame.depth + 1,
5374
- keys: childKeys(child),
5375
- index: 0
5376
- });
5377
- }
5378
- if (truncatedAt !== -1) {
5379
- lines.push(`... [tree truncated at ${MAX_TREE_LINES} lines] ...`);
5380
- } else if (depthTruncated) {
5381
- lines.push(`... [tree truncated at ${MAX_TREE_DEPTH} levels] ...`);
5382
- }
5383
- const fence = fenceForText(lines.join("\n"), 3);
5384
- return ["# Project Tree", "", `${fence}text`, ...lines, fence, ""].join("\n");
5385
- }
5386
- var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
5387
- ".png",
5388
- ".jpg",
5389
- ".jpeg",
5390
- ".gif",
5391
- ".webp",
5392
- ".avif",
5393
- ".ico",
5394
- ".bmp",
5395
- ".tiff",
5396
- ".pdf",
5397
- ".zip",
5398
- ".tar",
5399
- ".gz",
5400
- ".tgz",
5401
- ".br",
5402
- ".bz2",
5403
- ".xz",
5404
- ".zst",
5405
- ".lz4",
5406
- ".lzma",
5407
- ".7z",
5408
- ".rar",
5409
- ".mp3",
5410
- ".mp4",
5411
- ".wav",
5412
- ".ogg",
5413
- ".webm",
5414
- ".mov",
5415
- ".avi",
5416
- ".woff",
5417
- ".woff2",
5418
- ".ttf",
5419
- ".otf",
5420
- ".eot",
5421
- ".wasm",
5422
- ".node",
5423
- ".exe",
5424
- ".dll",
5425
- ".dylib",
5426
- ".so"
5427
- ]);
5428
- function isBinaryExtension(filePath) {
5429
- const ext = path16.extname(filePath).toLowerCase();
5430
- return BINARY_EXTENSIONS.has(ext);
5431
- }
5432
- function isBinaryBuffer(buffer) {
5433
- return buffer.includes(0);
5434
- }
5435
- function countControlBytes(buffer) {
5436
- let count = 0;
5437
- for (let index = 0; index < buffer.length; index++) {
5438
- const byte = buffer[index];
5439
- if (byte < 32) {
5440
- if (byte !== 9 && byte !== 10 && byte !== 13) count += 1;
5441
- continue;
5442
- }
5443
- if (byte === 127) {
5444
- count += 1;
5445
- continue;
5446
- }
5447
- if (byte === 194 && index + 1 < buffer.length) {
5448
- const next = buffer[index + 1];
5449
- if (next >= 128 && next <= 159) {
5450
- count += 1;
5451
- index += 1;
5452
- }
5453
- }
5454
- }
5455
- return count;
5456
- }
5457
- var CONTROL_BYTES_FLOOR = 4;
5458
- function countInvalidUtf8Bytes(buffer) {
5459
- let invalid = 0;
5460
- let index = 0;
5461
- const length = buffer.length;
5462
- while (index < length) {
5463
- const lead = buffer[index];
5464
- if (lead < 128) {
5465
- index += 1;
5466
- continue;
5467
- }
5468
- let continuation = 0;
5469
- let codePoint = 0;
5470
- let minimum = 0;
5471
- if ((lead & 224) === 192) {
5472
- continuation = 1;
5473
- codePoint = lead & 31;
5474
- minimum = 128;
5475
- } else if ((lead & 240) === 224) {
5476
- continuation = 2;
5477
- codePoint = lead & 15;
5478
- minimum = 2048;
5479
- } else if ((lead & 248) === 240) {
5480
- continuation = 3;
5481
- codePoint = lead & 7;
5482
- minimum = 65536;
5483
- } else {
5484
- invalid += 1;
5485
- index += 1;
5486
- continue;
5487
- }
5488
- if (index + continuation >= length) {
5489
- invalid += 1;
5490
- index += 1;
5491
- continue;
5492
- }
5493
- let wellFormed = true;
5494
- for (let offset = 1; offset <= continuation; offset++) {
5495
- const next = buffer[index + offset];
5496
- if ((next & 192) !== 128) {
5497
- wellFormed = false;
5498
- break;
5499
- }
5500
- codePoint = codePoint << 6 | next & 63;
5501
- }
5502
- const isSurrogate = codePoint >= 55296 && codePoint <= 57343;
5503
- if (!wellFormed || codePoint < minimum || codePoint > 1114111 || isSurrogate) {
5504
- invalid += 1;
5505
- index += 1;
5506
- continue;
5507
- }
5508
- index += continuation + 1;
5509
- }
5510
- return invalid;
5511
- }
5512
- function readBomEncoding(buffer) {
5513
- if (buffer.length >= 2) {
5514
- if (buffer[0] === 255 && buffer[1] === 254) return "utf-16le";
5515
- if (buffer[0] === 254 && buffer[1] === 255) return "utf-16be";
5516
- }
5517
- return null;
5518
- }
5519
- function looksLikeUtf16(buffer) {
5520
- if (buffer.length < 8 || buffer.length % 2 !== 0) return null;
5521
- const sample = Math.min(buffer.length, 4096);
5522
- let nulInLowByte = 0;
5523
- let nulInHighByte = 0;
5524
- const units = sample / 2;
5525
- for (let index = 0; index < sample; index += 2) {
5526
- if (buffer[index] === 0) nulInLowByte += 1;
5527
- if (buffer[index + 1] === 0) nulInHighByte += 1;
5528
- }
5529
- if (nulInHighByte > units * 0.3 && nulInLowByte < units * 0.05) return "utf-16le";
5530
- if (nulInLowByte > units * 0.3 && nulInHighByte < units * 0.05) return "utf-16be";
5531
- return null;
5532
- }
5533
- function decodeUtf16(buffer, encoding) {
5534
- const littleEndian = encoding === "utf-16le" ? buffer : Buffer.from(buffer.subarray(0, buffer.length - buffer.length % 2)).swap16();
5535
- return new TextDecoder("utf-16le").decode(littleEndian);
5536
- }
5537
- function decodeText(buffer) {
5538
- const bomEncoding = readBomEncoding(buffer);
5539
- if (bomEncoding) {
5540
- const text2 = decodeUtf16(buffer.subarray(2), bomEncoding);
5541
- return { text: text2, encoding: bomEncoding, invalidBytes: 0, binary: false };
5542
- }
5543
- if (buffer.includes(0)) {
5544
- const shape = looksLikeUtf16(buffer);
5545
- if (shape) {
5546
- return { text: decodeUtf16(buffer, shape), encoding: shape, invalidBytes: 0, binary: false };
5547
- }
5548
- const offset = buffer.indexOf(0);
5549
- return {
5550
- text: "",
5551
- encoding: "utf-8",
5552
- invalidBytes: 0,
5553
- binary: true,
5554
- binaryReason: `NUL byte at offset ${offset}`
5555
- };
5556
- }
5557
- const invalidBytes = countInvalidUtf8Bytes(buffer);
5558
- if (invalidBytes === 0) {
5559
- const controlBytes = countControlBytes(buffer);
5560
- if (controlBytes > CONTROL_BYTES_FLOOR && controlBytes * 100 > buffer.length) {
5561
- return {
5562
- text: "",
5563
- encoding: "utf-8",
5564
- invalidBytes: 0,
5565
- binary: true,
5566
- binaryReason: `${controlBytes} control byte(s) in ${buffer.length} B; valid UTF-8 but not text`
5567
- };
5568
- }
5569
- return {
5570
- text: new TextDecoder("utf-8").decode(buffer),
5571
- encoding: "utf-8",
5572
- invalidBytes: 0,
5573
- binary: false
5574
- };
5575
- }
5576
- if (invalidBytes >= 32 && invalidBytes * 3 >= buffer.length) {
5577
- return {
5578
- text: "",
5579
- encoding: "utf-8",
5580
- invalidBytes,
5581
- binary: true,
5582
- binaryReason: `${invalidBytes} of ${buffer.length} bytes are not UTF-8; treated as binary`
5583
- };
5584
- }
5585
- return {
5586
- text: buffer.toString("utf8"),
5587
- encoding: "utf-8-lossy",
5588
- invalidBytes,
5589
- binary: false
5590
- };
5591
- }
5592
- var BINARY_SCAN_BYTES = 8 * 1024 * 1024;
5593
- var CHUNK = 64 * 1024;
5594
- var SHAPE_SAMPLE_BYTES = 4096;
5595
- function isBinaryFile(absolutePath) {
5596
- if (isBinaryExtension(absolutePath)) return true;
5597
- let fd;
5598
- try {
5599
- fd = fs14.openSync(absolutePath, "r");
5600
- const buffer = Buffer.alloc(CHUNK);
5601
- let sample;
5602
- let position = 0;
5603
- while (position < BINARY_SCAN_BYTES) {
5604
- const wanted = Math.min(CHUNK, BINARY_SCAN_BYTES - position);
5605
- const bytesRead = fs14.readSync(fd, buffer, 0, wanted, position);
5606
- if (bytesRead === 0) return false;
5607
- const chunk = buffer.subarray(0, bytesRead);
5608
- if (sample === void 0) {
5609
- sample = Buffer.from(chunk.subarray(0, SHAPE_SAMPLE_BYTES));
5610
- }
5611
- if (chunk.includes(0)) {
5612
- const shape = readBomEncoding(sample) ?? looksLikeUtf16(sample);
5613
- return shape === null;
5614
- }
5615
- position += bytesRead;
6188
+ if (lines.length >= MAX_TREE_LINES) {
6189
+ truncatedAt = lines.length;
6190
+ break;
5616
6191
  }
5617
- return false;
5618
- } catch {
5619
- return false;
5620
- } finally {
5621
- if (fd !== void 0) {
5622
- try {
5623
- fs14.closeSync(fd);
5624
- } catch {
5625
- }
6192
+ if (!isDirectory) continue;
6193
+ if (frame.depth + 1 > MAX_TREE_DEPTH) {
6194
+ depthTruncated = true;
6195
+ continue;
5626
6196
  }
6197
+ stack.push({
6198
+ node: child,
6199
+ prefix: frame.prefix + (isLast ? " " : "\u2502 "),
6200
+ depth: frame.depth + 1,
6201
+ keys: childKeys(child),
6202
+ index: 0
6203
+ });
6204
+ }
6205
+ if (truncatedAt !== -1) {
6206
+ lines.push(`... [tree truncated at ${MAX_TREE_LINES} lines] ...`);
6207
+ } else if (depthTruncated) {
6208
+ lines.push(`... [tree truncated at ${MAX_TREE_DEPTH} levels] ...`);
5627
6209
  }
6210
+ const fence = fenceForText(lines.join("\n"), 3);
6211
+ return ["# Project Tree", "", `${fence}text`, ...lines, fence, ""].join("\n");
5628
6212
  }
5629
6213
  function gitPaths(cwd, args) {
5630
6214
  let output;
@@ -5711,6 +6295,10 @@ var SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
5711
6295
  ".mjs",
5712
6296
  ".cjs"
5713
6297
  ]);
6298
+ var PYTHON_EXTENSIONS = /* @__PURE__ */ new Set([".py", ".pyi"]);
6299
+ var RUBY_EXTENSIONS = /* @__PURE__ */ new Set([".rb", ".rake", ".gemspec"]);
6300
+ var C_EXTENSIONS = /* @__PURE__ */ new Set([".c", ".h", ".cc", ".cpp", ".cxx", ".hpp", ".hxx", ".m", ".mm"]);
6301
+ var PYTHON_SUFFIXES = [".py", ".pyi", "/__init__.py", "/__init__.pyi"];
5714
6302
  function buildImportResolver(files) {
5715
6303
  const byPath = /* @__PURE__ */ new Map();
5716
6304
  const byPathFolded = /* @__PURE__ */ new Map();
@@ -5737,11 +6325,45 @@ function buildImportResolver(files) {
5737
6325
  return { byPath, byPathFolded, byStem, byStemFolded };
5738
6326
  }
5739
6327
  function resolveSpecifier(fromFile, specifier, resolver) {
6328
+ const extension = path16.posix.extname(fromFile).toLowerCase();
6329
+ const exact = (key) => resolver.byPath.get(key) ?? resolver.byPathFolded.get(key.toLowerCase()) ?? null;
6330
+ const firstOf = (candidates) => {
6331
+ for (const candidate of candidates) {
6332
+ const hit = exact(candidate);
6333
+ if (hit) return hit;
6334
+ }
6335
+ return null;
6336
+ };
6337
+ if (PYTHON_EXTENSIONS.has(extension) && specifier.startsWith(".")) {
6338
+ const dots = /^\.+/.exec(specifier)?.[0].length ?? 0;
6339
+ const rest = specifier.slice(dots).replace(/\./g, "/");
6340
+ let base = path16.posix.dirname(fromFile);
6341
+ for (let up = 1; up < dots; up += 1) base = path16.posix.dirname(base);
6342
+ const joined2 = rest ? path16.posix.normalize(path16.posix.join(base, rest)) : base;
6343
+ return firstOf([joined2, ...PYTHON_SUFFIXES.map((suffix) => `${joined2}${suffix}`)]);
6344
+ }
6345
+ if (RUBY_EXTENSIONS.has(extension) && specifier.startsWith("./")) {
6346
+ const joined2 = path16.posix.normalize(
6347
+ path16.posix.join(path16.posix.dirname(fromFile), specifier)
6348
+ );
6349
+ return firstOf([`${joined2}.rb`, joined2]);
6350
+ }
6351
+ if (C_EXTENSIONS.has(extension) && specifier.startsWith("./")) {
6352
+ const joined2 = path16.posix.normalize(
6353
+ path16.posix.join(path16.posix.dirname(fromFile), specifier)
6354
+ );
6355
+ return exact(joined2);
6356
+ }
6357
+ if (extension === ".dart" && !specifier.includes(":")) {
6358
+ const joined2 = path16.posix.normalize(
6359
+ path16.posix.join(path16.posix.dirname(fromFile), specifier)
6360
+ );
6361
+ return firstOf([joined2, `${joined2}.dart`]);
6362
+ }
5740
6363
  if (!RELATIVE_SPECIFIER.test(specifier)) return null;
5741
6364
  const joined = path16.posix.normalize(
5742
6365
  path16.posix.join(path16.posix.dirname(fromFile), specifier)
5743
6366
  );
5744
- const exact = (key) => resolver.byPath.get(key) ?? resolver.byPathFolded.get(key.toLowerCase()) ?? null;
5745
6367
  const direct = exact(joined);
5746
6368
  if (direct) return direct;
5747
6369
  for (const suffix of IMPORT_CANDIDATE_SUFFIXES) {
@@ -5822,28 +6444,6 @@ function detectLanguage(filePath) {
5822
6444
  const ext = path16.posix.extname(base).toLowerCase();
5823
6445
  return LANGUAGE_BY_EXTENSION[ext] ?? "text";
5824
6446
  }
5825
- var TS_SOURCE_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
5826
- var isTsSource = (relativePath) => {
5827
- const lower = relativePath.toLowerCase();
5828
- return TS_SOURCE_EXTENSIONS.some((extension) => lower.endsWith(extension));
5829
- };
5830
- function importsOfText(relativePath, text2) {
5831
- if (isTsSource(relativePath)) return summarizeTypeScriptSource(relativePath, text2).imports;
5832
- return summarizeWithProfile(relativePath, text2)?.summary.imports ?? [];
5833
- }
5834
- function importsOfFile(relativePath, absolutePath) {
5835
- let buffer;
5836
- try {
5837
- buffer = fs14.readFileSync(absolutePath);
5838
- } catch {
5839
- return [];
5840
- }
5841
- const decoded = decodeText(buffer);
5842
- if (decoded.binary) return [];
5843
- return importsOfText(relativePath, decoded.text);
5844
- }
5845
-
5846
- // src/validator/validate.ts
5847
6447
  function maskedPath(value, secretRules) {
5848
6448
  return findSecretInPath(value, secretRules)?.masked ?? value;
5849
6449
  }
@@ -5909,16 +6509,14 @@ function emptyDrift() {
5909
6509
  function sha256Hex(buffer) {
5910
6510
  return crypto2.createHash("sha256").update(buffer).digest("hex");
5911
6511
  }
5912
- var VERIFY_SNIFF_MAX_BYTES = 8 * 1024 * 1024;
5913
6512
  function wouldNowBeIncluded(cwd, relativePath) {
5914
6513
  const absolutePath = path16.join(cwd, relativePath);
5915
6514
  try {
5916
6515
  const stats = fs14.statSync(absolutePath);
5917
6516
  if (!stats.isFile()) return false;
5918
- if (stats.size <= VERIFY_SNIFF_MAX_BYTES) {
5919
- return !decodeText(fs14.readFileSync(absolutePath)).binary;
5920
- }
5921
- return !isBinaryFile(absolutePath);
6517
+ if (isBinaryExtension(absolutePath)) return false;
6518
+ if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) return false;
6519
+ return !decodeText(fs14.readFileSync(absolutePath)).binary;
5922
6520
  } catch {
5923
6521
  return false;
5924
6522
  }
@@ -5964,9 +6562,13 @@ function describeManifestShapeProblem(value) {
5964
6562
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
5965
6563
  return 'a "parts" entry is not an object';
5966
6564
  }
5967
- if (typeof entry.filename !== "string") {
6565
+ const filename = entry.filename;
6566
+ if (typeof filename !== "string" || filename.trim() === "") {
5968
6567
  return 'a "parts" entry has no "filename"';
5969
6568
  }
6569
+ if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path16.isAbsolute(filename)) {
6570
+ return 'a "parts" entry "filename" must be a bare filename inside parts/';
6571
+ }
5970
6572
  }
5971
6573
  if (!candidate.layers || typeof candidate.layers !== "object" || Array.isArray(candidate.layers)) {
5972
6574
  return 'missing "layers" object';
@@ -6077,7 +6679,7 @@ function validateSnapshot(configInput) {
6077
6679
  });
6078
6680
  for (const diskFile of collection.files) {
6079
6681
  const snapshotHash = manifestFileMap.get(diskFile);
6080
- if (!snapshotHash) {
6682
+ if (snapshotHash === void 0) {
6081
6683
  const skipReason = skippedReasonOnDisk(diskFile);
6082
6684
  if (skipReason === "unchanged") {
6083
6685
  if (unchangedScope !== null) {
@@ -6091,6 +6693,11 @@ function validateSnapshot(configInput) {
6091
6693
  drift.missingInSnapshot.push(diskFile);
6092
6694
  continue;
6093
6695
  }
6696
+ if (unchangedScope !== null && !unchangedScope.has(diskFile) && !becameDependent(diskFile)) {
6697
+ drift.configMismatches.push(
6698
+ `scope: ${maskedPath(diskFile, config.secretRules)} is in the snapshot but is no longer in the changed-files scope`
6699
+ );
6700
+ }
6094
6701
  let diskHash;
6095
6702
  try {
6096
6703
  diskHash = sha256Hex(fs14.readFileSync(path16.join(config.cwd, diskFile)));
@@ -6231,6 +6838,41 @@ function validateSnapshot(configInput) {
6231
6838
  `includeSensitiveFiles: manifest ${recorded.includeSensitiveFiles} vs current ${config.includeSensitiveFiles}`
6232
6839
  );
6233
6840
  }
6841
+ if ((recorded.maxPartTokens ?? void 0) !== (config.maxPartTokens ?? void 0)) {
6842
+ drift.configMismatches.push(
6843
+ `maxPartTokens: manifest ${String(recorded.maxPartTokens ?? "unset")} vs current ${String(config.maxPartTokens ?? "unset")}`
6844
+ );
6845
+ }
6846
+ if ((recorded.maxMonolithBytes ?? null) !== (config.maxMonolithBytes ?? null)) {
6847
+ drift.configMismatches.push(
6848
+ `maxMonolithBytes: manifest ${String(recorded.maxMonolithBytes ?? null)} vs current ${String(config.maxMonolithBytes ?? null)}`
6849
+ );
6850
+ }
6851
+ if (Boolean(recorded.skeleton) !== Boolean(config.skeleton)) {
6852
+ drift.configMismatches.push(
6853
+ `skeleton: manifest ${Boolean(recorded.skeleton)} vs current ${Boolean(config.skeleton)}`
6854
+ );
6855
+ }
6856
+ if (Boolean(recorded.sarif) !== Boolean(config.sarif)) {
6857
+ drift.configMismatches.push(
6858
+ `sarif: manifest ${Boolean(recorded.sarif)} vs current ${Boolean(config.sarif)}`
6859
+ );
6860
+ }
6861
+ if ((recorded.changedSince ?? void 0) !== (config.changedSince ?? void 0)) {
6862
+ drift.configMismatches.push(
6863
+ `changedSince: manifest ${String(recorded.changedSince ?? "unset")} vs current ${String(config.changedSince ?? "unset")}`
6864
+ );
6865
+ }
6866
+ if (Boolean(recorded.staged) !== Boolean(config.staged)) {
6867
+ drift.configMismatches.push(
6868
+ `staged: manifest ${Boolean(recorded.staged)} vs current ${Boolean(config.staged)}`
6869
+ );
6870
+ }
6871
+ if (Boolean(recorded.withDependents) !== Boolean(config.withDependents)) {
6872
+ drift.configMismatches.push(
6873
+ `withDependents: manifest ${Boolean(recorded.withDependents)} vs current ${Boolean(config.withDependents)}`
6874
+ );
6875
+ }
6234
6876
  const effectiveDiscovery = config.discovery ?? "auto";
6235
6877
  const recordedDiscovery = recorded.discovery;
6236
6878
  if (recordedDiscovery !== void 0 && recordedDiscovery !== effectiveDiscovery) {
@@ -6451,7 +7093,7 @@ function validateSnapshot(configInput) {
6451
7093
 
6452
7094
  // src/version.ts
6453
7095
  var GENERATOR_NAME = "codebase-snapshot";
6454
- var GENERATOR_VERSION = "0.9.12";
7096
+ var GENERATOR_VERSION = "0.9.15";
6455
7097
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
6456
7098
  function isOurGeneratorName(name) {
6457
7099
  if (typeof name !== "string") return false;
@@ -6478,22 +7120,28 @@ function updateCommand(kind) {
6478
7120
  if (kind === "local") return "npm install codebase-snapshot@latest";
6479
7121
  return "npm install -g codebase-snapshot";
6480
7122
  }
6481
- function versionParts(value) {
6482
- const core = value.trim().replace(/^v/i, "").split("-")[0];
6483
- return core.split(".").map((part) => {
7123
+ function parseSemver(value) {
7124
+ const cleaned = value.trim().replace(/^v/i, "").split("+")[0] ?? "";
7125
+ const dash = cleaned.indexOf("-");
7126
+ const corePart = dash === -1 ? cleaned : cleaned.slice(0, dash);
7127
+ const prerelease = dash === -1 ? null : cleaned.slice(dash + 1);
7128
+ const core = corePart.split(".").map((part) => {
6484
7129
  const parsed = Number(part);
6485
7130
  return Number.isFinite(parsed) ? parsed : 0;
6486
7131
  });
7132
+ return { core, prerelease };
6487
7133
  }
6488
7134
  function isNewer(candidate, current) {
6489
- const left = versionParts(candidate);
6490
- const right = versionParts(current);
6491
- const length = Math.max(left.length, right.length);
7135
+ const left = parseSemver(candidate);
7136
+ const right = parseSemver(current);
7137
+ if (left.prerelease !== null && right.prerelease === null) return false;
7138
+ const length = Math.max(left.core.length, right.core.length);
6492
7139
  for (let index = 0; index < length; index += 1) {
6493
- const a = left[index] ?? 0;
6494
- const b = right[index] ?? 0;
7140
+ const a = left.core[index] ?? 0;
7141
+ const b = right.core[index] ?? 0;
6495
7142
  if (a !== b) return a > b;
6496
7143
  }
7144
+ if (left.prerelease === null && right.prerelease !== null) return true;
6497
7145
  return false;
6498
7146
  }
6499
7147
  function cacheDirectory(env = process.env, platform = process.platform) {
@@ -6561,14 +7209,22 @@ function writeCache(file, entry) {
6561
7209
  }
6562
7210
  }
6563
7211
  function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOUT_MS) {
6564
- return new Promise((resolve5) => {
7212
+ return new Promise((resolve6) => {
6565
7213
  let settled = false;
7214
+ let request = null;
6566
7215
  const finish = (value) => {
6567
7216
  if (settled) return;
6568
7217
  settled = true;
6569
- resolve5(value);
7218
+ clearTimeout(deadline);
7219
+ resolve6(value);
6570
7220
  };
6571
- const request = https.get(
7221
+ const deadline = setTimeout(() => {
7222
+ request?.destroy();
7223
+ finish(null);
7224
+ }, timeoutMs);
7225
+ deadline.unref();
7226
+ const transport = url.startsWith("http:") ? http : https;
7227
+ request = transport.get(
6572
7228
  url,
6573
7229
  {
6574
7230
  headers: {
@@ -6587,7 +7243,7 @@ function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOU
6587
7243
  response.on("data", (chunk) => {
6588
7244
  body += chunk;
6589
7245
  if (body.length > 64 * 1024) {
6590
- request.destroy();
7246
+ request?.destroy();
6591
7247
  finish(null);
6592
7248
  }
6593
7249
  });
@@ -6602,10 +7258,6 @@ function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOU
6602
7258
  }
6603
7259
  );
6604
7260
  request.on("error", () => finish(null));
6605
- request.setTimeout(timeoutMs, () => {
6606
- request.destroy();
6607
- finish(null);
6608
- });
6609
7261
  });
6610
7262
  }
6611
7263
  async function checkForUpdate(options) {
@@ -6649,10 +7301,13 @@ function describeMatcher(matcher) {
6649
7301
  return String(matcher);
6650
7302
  }
6651
7303
  function normalizeTarget(cwd, target) {
6652
- const absolute = path16.resolve(cwd, target);
6653
- const relative8 = path16.relative(cwd, absolute);
6654
- if (relative8.startsWith("..") || path16.isAbsolute(relative8)) return target;
6655
- return relative8.split(path16.sep).join("/");
7304
+ const resolvedCwd = path16.resolve(cwd);
7305
+ const absolute = path16.resolve(resolvedCwd, target);
7306
+ const relative8 = path16.relative(resolvedCwd, absolute);
7307
+ if (relative8 === "" || relative8 === ".." || relative8.startsWith(`..${path16.sep}`) || path16.isAbsolute(relative8)) {
7308
+ return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
7309
+ }
7310
+ return { relative: relative8.split(path16.sep).join("/"), outsideRoot: false };
6656
7311
  }
6657
7312
  function findRuleMatch(rules, relativePath) {
6658
7313
  return rules.find(
@@ -6679,9 +7334,19 @@ function readManifest2(config) {
6679
7334
  }
6680
7335
  }
6681
7336
  function explainPath(config, target) {
6682
- const relative8 = normalizeTarget(config.cwd, target);
6683
- const absolute = path16.join(config.cwd, relative8);
7337
+ const normalized = normalizeTarget(config.cwd, target);
7338
+ const relative8 = normalized.relative;
6684
7339
  const maskedPath2 = findSecretInPath(relative8, config.secretRules)?.masked ?? relative8;
7340
+ if (normalized.outsideRoot) {
7341
+ return {
7342
+ path: maskedPath2,
7343
+ exists: false,
7344
+ included: false,
7345
+ reason: "outside-root",
7346
+ detail: "path resolves outside the configured repository root and was not inspected"
7347
+ };
7348
+ }
7349
+ const absolute = path16.join(config.cwd, relative8);
6685
7350
  const result = {
6686
7351
  path: maskedPath2,
6687
7352
  exists: fs14.existsSync(absolute),
@@ -6755,6 +7420,12 @@ function explainPath(config, target) {
6755
7420
  return result;
6756
7421
  }
6757
7422
  }
7423
+ if (isBinaryExtension(absolute)) {
7424
+ result.included = false;
7425
+ result.reason = "binary";
7426
+ result.detail = "binary extension; generate skips it without reading and records `binary` in manifest.skipped[]";
7427
+ return result;
7428
+ }
6758
7429
  let sizeOnDisk = null;
6759
7430
  try {
6760
7431
  sizeOnDisk = fs14.statSync(absolute).size;
@@ -6767,13 +7438,6 @@ function explainPath(config, target) {
6767
7438
  result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
6768
7439
  return result;
6769
7440
  }
6770
- result.layer = classifyLayer(relative8, config.layers);
6771
- result.kind = classifyKind(relative8, config.kinds);
6772
- result.language = detectLanguage(relative8);
6773
- const layerRule = findRuleMatch(config.layers, relative8);
6774
- if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
6775
- const kindRule = findRuleMatch(config.kinds, relative8);
6776
- if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
6777
7441
  if (fs14.existsSync(absolute) && fs14.statSync(absolute).isFile()) {
6778
7442
  const buffer = fs14.readFileSync(absolute);
6779
7443
  const decoded = decodeText(buffer);
@@ -6791,6 +7455,13 @@ function explainPath(config, target) {
6791
7455
  result.secretCount = findings.length;
6792
7456
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
6793
7457
  }
7458
+ result.layer = classifyLayer(relative8, config.layers);
7459
+ result.kind = classifyKind(relative8, config.kinds);
7460
+ result.language = detectLanguage(relative8);
7461
+ const layerRule = findRuleMatch(config.layers, relative8);
7462
+ if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
7463
+ const kindRule = findRuleMatch(config.kinds, relative8);
7464
+ if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
6794
7465
  const manifest = readManifest2(config);
6795
7466
  const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative8) : void 0;
6796
7467
  result.part = entry?.part ?? null;
@@ -6928,7 +7599,7 @@ function describePayloadDiff(before, after, sourceFilesIdentical) {
6928
7599
  }
6929
7600
  if (fingerprintDiffers && (sourceFilesIdentical || configurationDiffers)) {
6930
7601
  reasons.push(
6931
- `content fingerprint ${shortDigest(before.fingerprint)} \u2192 ${shortDigest(after.fingerprint)}` + (sourceFilesIdentical ? " (same source files, packed differently)" : "")
7602
+ `content fingerprint ${shortDigest(before.fingerprint)} \u2192 ${shortDigest(after.fingerprint)}` + (sourceFilesIdentical ? " (same source files, packed or configured differently)" : "")
6932
7603
  );
6933
7604
  }
6934
7605
  if (partsDiffer) {
@@ -7203,7 +7874,8 @@ function renderConfig(answers) {
7203
7874
  // matched value is never included \u2014 only the path, the line and the rule.
7204
7875
  sarif: ${answers.sarif},
7205
7876
  // Snapshot only the files that differ from a git ref (for example "main"),
7206
- // plus untracked ones. null and false both mean "snapshot everything".
7877
+ // plus untracked ones. null means "snapshot everything"; any other value must
7878
+ // be a git ref string, and anything else is a configuration error.
7207
7879
  changedSince: null,
7208
7880
  // Snapshot only what is staged in the index: the pre-commit counterpart.
7209
7881
  staged: false,
@@ -7319,6 +7991,24 @@ function displayWidth(line) {
7319
7991
  return width;
7320
7992
  }
7321
7993
  var GUTTER_PATTERN = /^[ \t]*(?:[❯◆◻◼▏✖][ \t]+)*/;
7994
+ function sliceByDisplayWidth(text2, maxCells) {
7995
+ let cells = 0;
7996
+ let lastSpace = -1;
7997
+ let index = 0;
7998
+ for (const character of text2) {
7999
+ const width = isWideCodePoint(character.codePointAt(0) ?? 0) ? 2 : 1;
8000
+ if (cells + width > maxCells) break;
8001
+ if (character === " ") lastSpace = index;
8002
+ cells += width;
8003
+ index += character.length;
8004
+ }
8005
+ if (index >= text2.length) return { head: text2, tail: "" };
8006
+ if (lastSpace > 0) {
8007
+ return { head: text2.slice(0, lastSpace), tail: text2.slice(lastSpace + 1).trimStart() };
8008
+ }
8009
+ const safeIndex = index > 0 ? index : Array.from(text2)[0]?.length ?? 1;
8010
+ return { head: text2.slice(0, safeIndex), tail: text2.slice(safeIndex).trimStart() };
8011
+ }
7322
8012
  function wrapOneLine(line, limit) {
7323
8013
  if (displayWidth(line) <= limit) return [line];
7324
8014
  const gutter = GUTTER_PATTERN.exec(line)?.[0] ?? "";
@@ -7333,12 +8023,11 @@ function wrapOneLine(line, limit) {
7333
8023
  rows.push(prefix + rest);
7334
8024
  break;
7335
8025
  }
7336
- let cut = room;
7337
- const space = rest.slice(0, room).lastIndexOf(" ");
7338
- if (space > 0) cut = space;
7339
- const taken = rest.slice(0, cut).trimEnd();
7340
- rows.push(`${prefix}${taken.length > 0 ? taken : rest.slice(0, cut)}`);
7341
- rest = rest.slice(cut).trimStart();
8026
+ const { head, tail } = sliceByDisplayWidth(rest, room);
8027
+ rows.push(
8028
+ `${prefix}${head.length > 0 ? head : rest.slice(0, 1)}`
8029
+ );
8030
+ rest = tail;
7342
8031
  prefix = continuation;
7343
8032
  }
7344
8033
  return rows;
@@ -7409,7 +8098,7 @@ function keyReader(input) {
7409
8098
  next() {
7410
8099
  const queued = queue.shift();
7411
8100
  if (queued) return Promise.resolve(queued);
7412
- return new Promise((resolve5) => waiters.push(resolve5));
8101
+ return new Promise((resolve6) => waiters.push(resolve6));
7413
8102
  },
7414
8103
  close() {
7415
8104
  input.off("keypress", onKey);
@@ -7626,17 +8315,25 @@ var CONFIG_CANDIDATES = [
7626
8315
  ".snapshotrc.json",
7627
8316
  ".snapshotrc"
7628
8317
  ];
7629
- function chooseConfigFileName(cwd) {
7630
- if (!supportsTypeScriptImports()) return "snapshot.config.mjs";
7631
- const pkgPath = path16.join(cwd, "package.json");
7632
- if (!fs14.existsSync(pkgPath)) return "snapshot.config.mjs";
8318
+ function parsePackageJson(raw) {
8319
+ const parsed = JSON.parse(stripJsonComments(raw));
8320
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
8321
+ throw new Error("package.json is not a JSON object");
8322
+ }
8323
+ return parsed;
8324
+ }
8325
+ function readPackageJson(cwd) {
7633
8326
  try {
7634
- const parsed = JSON.parse(fs14.readFileSync(pkgPath, "utf8"));
7635
- return parsed.type === "module" ? "snapshot.config.ts" : "snapshot.config.mjs";
8327
+ return parsePackageJson(fs14.readFileSync(path16.join(cwd, "package.json"), "utf8"));
7636
8328
  } catch {
7637
- return "snapshot.config.mjs";
8329
+ return null;
7638
8330
  }
7639
8331
  }
8332
+ function chooseConfigFileName(cwd) {
8333
+ if (!supportsTypeScriptImports()) return "snapshot.config.mjs";
8334
+ const parsed = readPackageJson(cwd);
8335
+ return parsed?.type === "module" ? "snapshot.config.ts" : "snapshot.config.mjs";
8336
+ }
7640
8337
  var SIZE_CHOICES = [
7641
8338
  { value: "60k", label: "Small", hint: "60 KB \xB7 ~15k tokens \xB7 tight context windows" },
7642
8339
  { value: "120k", label: "Medium", hint: "120 KB \xB7 ~30k tokens \xB7 recommended" },
@@ -7644,12 +8341,9 @@ var SIZE_CHOICES = [
7644
8341
  { value: "custom", label: "Custom\u2026", hint: "type a size like 150k or 1.5mb" }
7645
8342
  ];
7646
8343
  function packageJsonHasConfig(cwd) {
7647
- try {
7648
- const parsed = JSON.parse(fs14.readFileSync(path16.join(cwd, "package.json"), "utf8"));
7649
- return typeof parsed.snapshot === "object" && parsed.snapshot !== null && !Array.isArray(parsed.snapshot);
7650
- } catch {
7651
- return false;
7652
- }
8344
+ const parsed = readPackageJson(cwd);
8345
+ if (parsed === null) return false;
8346
+ return typeof parsed.snapshot === "object" && parsed.snapshot !== null && !Array.isArray(parsed.snapshot);
7653
8347
  }
7654
8348
  function artifactAnswers(options) {
7655
8349
  const artifacts = { ...DEFAULT_ANSWERS.artifacts };
@@ -7690,12 +8384,7 @@ function writeFileOrExplain(target, content) {
7690
8384
  function canWriteModuleConfig(name, cwd) {
7691
8385
  if (name.endsWith(".mjs") || name.endsWith(".ts")) return true;
7692
8386
  if (!name.endsWith(".js")) return false;
7693
- try {
7694
- const parsed = JSON.parse(fs14.readFileSync(path16.join(cwd, "package.json"), "utf8"));
7695
- return parsed.type === "module";
7696
- } catch {
7697
- return false;
7698
- }
8387
+ return readPackageJson(cwd)?.type === "module";
7699
8388
  }
7700
8389
  function configFormatLabel(name) {
7701
8390
  if (name.endsWith(".js")) return 'CommonJS `.js` (package.json has no "type": "module")';
@@ -7723,7 +8412,8 @@ function serializePackageJson(raw, value) {
7723
8412
  const crlf = raw.includes("\r\n");
7724
8413
  const body = JSON.stringify(value, null, spacing);
7725
8414
  const text2 = crlf ? body.replace(/\n/g, "\r\n") : body;
7726
- return `${text2}${raw.endsWith("\n") ? crlf ? "\r\n" : "\n" : ""}`;
8415
+ const bom = raw.startsWith("\uFEFF") ? "\uFEFF" : "";
8416
+ return `${bom}${text2}${raw.endsWith("\n") ? crlf ? "\r\n" : "\n" : ""}`;
7727
8417
  }
7728
8418
  function updatePackageJson(cwd, notes) {
7729
8419
  const packagePath = path16.join(cwd, "package.json");
@@ -7739,7 +8429,7 @@ function updatePackageJson(cwd, notes) {
7739
8429
  let parsed;
7740
8430
  try {
7741
8431
  raw = fs14.readFileSync(packagePath, "utf8");
7742
- parsed = JSON.parse(raw);
8432
+ parsed = parsePackageJson(raw);
7743
8433
  } catch {
7744
8434
  notes.push("Could not parse package.json; npm scripts and the devDependency were not added.");
7745
8435
  return unchanged;
@@ -8278,7 +8968,10 @@ const { parentPort, workerData } = require("node:worker_threads");
8278
8968
  parentPort.postMessage({ ok: false, message: loaded.errors.join("; ") });
8279
8969
  return;
8280
8970
  }
8281
- const config = mod.resolveConfig(loaded.config, workerData.cliOptions, workerData.cwd);
8971
+ // \`hooks: {}\` is a value, not an absence: the config is applied with the hook list emptied,
8972
+ // so the run is the documented MCP run rather than the CLI run with one setting removed.
8973
+ const base = loaded.config ? { ...loaded.config, hooks: {} } : null;
8974
+ const config = mod.resolveConfig(base, workerData.cliOptions, workerData.cwd);
8282
8975
  const manifest = mod.generateSnapshot(config);
8283
8976
  parentPort.postMessage({
8284
8977
  ok: true,
@@ -8301,14 +8994,15 @@ const { parentPort, workerData } = require("node:worker_threads");
8301
8994
  })();
8302
8995
  `;
8303
8996
  function generateInWorker(cwd, cliOptions) {
8304
- return new Promise((resolve5) => {
8997
+ return new Promise((resolve6) => {
8305
8998
  let settled = false;
8999
+ let worker = null;
8306
9000
  const finish = (result) => {
8307
9001
  if (settled) return;
8308
9002
  settled = true;
8309
- resolve5(result);
9003
+ if (worker !== null) void worker.terminate();
9004
+ resolve6(result);
8310
9005
  };
8311
- let worker;
8312
9006
  const isCjs = typeof __dirname !== "undefined";
8313
9007
  const directory = isCjs ? __dirname : path16.dirname(fileURLToPath(import.meta.url));
8314
9008
  try {
@@ -8341,7 +9035,100 @@ function generateInWorker(cwd, cliOptions) {
8341
9035
 
8342
9036
  // src/index.ts
8343
9037
  var SCHEMA_VERSION = "3.0.0";
8344
- var SUMMARY_MAX_SOURCE_BYTES = 2 * 1024 * 1024;
9038
+ var SUMMARY_MAX_SOURCE_BYTES2 = SUMMARY_MAX_SOURCE_BYTES;
9039
+ var FILE_DERIVATIONS = /* @__PURE__ */ new Map();
9040
+ var FILE_DERIVATION_LIMIT_BYTES = 64 * 1024 * 1024;
9041
+ var fileDerivationBytes = 0;
9042
+ function takeDerivation(path17, hash, settings) {
9043
+ const cached = FILE_DERIVATIONS.get(path17);
9044
+ if (cached === void 0 || cached.hash !== hash || cached.settings !== settings) return void 0;
9045
+ return cached;
9046
+ }
9047
+ function rememberDerivation(path17, hash, settings, derivation) {
9048
+ const bodyBytes = derivation.finalContent === derivation.redacted ? derivation.redacted.length : derivation.redacted.length + derivation.finalContent.length;
9049
+ const bytes = bodyBytes * 2 + 512;
9050
+ if (bytes > FILE_DERIVATION_LIMIT_BYTES / 4) return;
9051
+ while (fileDerivationBytes + bytes > FILE_DERIVATION_LIMIT_BYTES) {
9052
+ const oldest = FILE_DERIVATIONS.keys().next();
9053
+ if (oldest.done === true) break;
9054
+ const evicted = FILE_DERIVATIONS.get(oldest.value);
9055
+ FILE_DERIVATIONS.delete(oldest.value);
9056
+ if (evicted !== void 0) fileDerivationBytes -= evicted.bytes;
9057
+ }
9058
+ FILE_DERIVATIONS.set(path17, { ...derivation, hash, settings, bytes });
9059
+ fileDerivationBytes += bytes;
9060
+ }
9061
+ function derivationSettings(config) {
9062
+ const rules = config.secretRules.map(
9063
+ (rule) => `${rule.rule}\0${rule.pattern.source}\0${rule.pattern.flags}\0${rule.valueGroup ?? ""}`
9064
+ ).join("");
9065
+ return `${GENERATOR_VERSION}${configDigest(config)}${sha256Hex2(rules)}`;
9066
+ }
9067
+ function deriveFile(relativePath, rawContent, sizeBytes, config) {
9068
+ const lineCount = countLines(rawContent);
9069
+ const { redacted, findings } = scanAndRedactSecrets(rawContent, config.secretRules, relativePath);
9070
+ const isLarge = sizeBytes > config.largeFileBytes;
9071
+ let finalContent = redacted;
9072
+ let isPreviewTruncated = false;
9073
+ let includedLines = lineCount;
9074
+ let inclusionMode = "full";
9075
+ if (config.skeleton === true && isSkeletonizable(relativePath)) {
9076
+ const skeleton = skeletonizeTypeScript(redacted, relativePath);
9077
+ if (skeleton.collapsed > 0) {
9078
+ finalContent = skeleton.text;
9079
+ inclusionMode = "signatures";
9080
+ includedLines = countLines(skeleton.text);
9081
+ }
9082
+ }
9083
+ if (isLarge && inclusionMode !== "signatures") {
9084
+ const preview = truncatePreview(redacted, config.previewHeadLines, config.previewTailLines);
9085
+ finalContent = preview.content;
9086
+ isPreviewTruncated = preview.isTruncated;
9087
+ includedLines = preview.includedLines;
9088
+ inclusionMode = isPreviewTruncated ? "preview" : "full";
9089
+ }
9090
+ let summary;
9091
+ let summaryQuality;
9092
+ let summarySkip = null;
9093
+ let summaryWarning = null;
9094
+ let dependentImports = null;
9095
+ if (Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES2) {
9096
+ summarySkip = "oversize";
9097
+ dependentImports = [];
9098
+ } else if (isPreviewTruncated && hasStructuralSummary(relativePath)) {
9099
+ summarySkip = "preview";
9100
+ dependentImports = importsOfText(relativePath, rawContent);
9101
+ } else {
9102
+ try {
9103
+ const outcome = summarizeFile(relativePath, rawContent);
9104
+ summary = outcome?.summary ? maskSummaryStrings(outcome.summary, config.secretRules) : void 0;
9105
+ summaryQuality = outcome?.quality;
9106
+ if (isSourceSummary(summary) && summary.parseErrors) {
9107
+ summaryWarning = `Parse errors in ${maskPathText(relativePath, config.secretRules)} (${summary.parseErrors}); its summary is incomplete.`;
9108
+ }
9109
+ } catch (err) {
9110
+ summaryWarning = `Summary skipped for ${maskPathText(relativePath, config.secretRules)}: ${err.message}`.replace(
9111
+ /\s+/g,
9112
+ " "
9113
+ );
9114
+ }
9115
+ }
9116
+ return {
9117
+ redacted,
9118
+ findings,
9119
+ lineCount,
9120
+ finalContent,
9121
+ inclusionMode,
9122
+ isPreviewTruncated,
9123
+ includedLines,
9124
+ isLarge,
9125
+ summary,
9126
+ summaryQuality,
9127
+ summarySkip,
9128
+ summaryWarning,
9129
+ dependentImports
9130
+ };
9131
+ }
8345
9132
  function sha256Hex2(input) {
8346
9133
  return crypto2.createHash("sha256").update(input).digest("hex");
8347
9134
  }
@@ -8530,6 +9317,7 @@ function isProcessAlive(pid) {
8530
9317
  var OWNERSHIP_MARKER = ".codebase-snapshot";
8531
9318
  var SUPPORTED_MARKER_SCHEMAS = /* @__PURE__ */ new Set([SCHEMA_VERSION]);
8532
9319
  var SNAPSHOT_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
9320
+ var SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/;
8533
9321
  function listEntries(dir) {
8534
9322
  const entries = [];
8535
9323
  const walk = (absolute, prefix) => {
@@ -8548,7 +9336,32 @@ function listEntries(dir) {
8548
9336
  walk(dir, "");
8549
9337
  return entries.sort();
8550
9338
  }
9339
+ function markerInventory(dir) {
9340
+ const entries = listEntries(dir);
9341
+ const files = [];
9342
+ for (const entry of entries) {
9343
+ if (entry === OWNERSHIP_MARKER) continue;
9344
+ if (IGNORABLE_ENTRIES.has(entry.slice(entry.lastIndexOf("/") + 1))) continue;
9345
+ const full = path16.join(dir, ...entry.split("/"));
9346
+ let stats;
9347
+ try {
9348
+ stats = fs14.lstatSync(full);
9349
+ } catch {
9350
+ continue;
9351
+ }
9352
+ if (!stats.isFile()) continue;
9353
+ let digest;
9354
+ try {
9355
+ digest = sha256Hex2(fs14.readFileSync(full));
9356
+ } catch {
9357
+ continue;
9358
+ }
9359
+ files.push({ path: entry, bytes: stats.size, sha256: digest });
9360
+ }
9361
+ return { entries, files };
9362
+ }
8551
9363
  function markerPayload(dir, state, id, createdAt) {
9364
+ const { entries, files } = markerInventory(dir);
8552
9365
  const marker2 = {
8553
9366
  generator: GENERATOR_NAME,
8554
9367
  version: GENERATOR_VERSION,
@@ -8557,7 +9370,8 @@ function markerPayload(dir, state, id, createdAt) {
8557
9370
  state,
8558
9371
  id,
8559
9372
  pid: process.pid,
8560
- entries: listEntries(dir)
9373
+ entries,
9374
+ files
8561
9375
  };
8562
9376
  const manifestPath = path16.join(dir, "manifest.json");
8563
9377
  if (fs14.existsSync(manifestPath)) {
@@ -8617,6 +9431,33 @@ function readOwnershipMarker(dir) {
8617
9431
  if (candidate.state !== "staging" && candidate.state !== "complete") {
8618
9432
  return { marker: null, problem: "its .codebase-snapshot marker records no run state" };
8619
9433
  }
9434
+ const rawFiles = candidate.files;
9435
+ let files;
9436
+ if (rawFiles !== void 0) {
9437
+ if (!Array.isArray(rawFiles)) {
9438
+ return {
9439
+ marker: null,
9440
+ problem: "its .codebase-snapshot marker's file inventory is not an array"
9441
+ };
9442
+ }
9443
+ files = [];
9444
+ for (const item of rawFiles) {
9445
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
9446
+ return {
9447
+ marker: null,
9448
+ problem: "its .codebase-snapshot marker's file inventory holds an entry that is not an object"
9449
+ };
9450
+ }
9451
+ const record = item;
9452
+ if (typeof record.path !== "string" || typeof record.bytes !== "number" || !Number.isInteger(record.bytes) || record.bytes < 0 || typeof record.sha256 !== "string" || !SHA256_HEX_PATTERN.test(record.sha256)) {
9453
+ return {
9454
+ marker: null,
9455
+ problem: "its .codebase-snapshot marker's file inventory holds an entry this build cannot read"
9456
+ };
9457
+ }
9458
+ files.push({ path: record.path, bytes: record.bytes, sha256: record.sha256 });
9459
+ }
9460
+ }
8620
9461
  return {
8621
9462
  marker: {
8622
9463
  generator: GENERATOR_NAME,
@@ -8627,7 +9468,8 @@ function readOwnershipMarker(dir) {
8627
9468
  id: candidate.id,
8628
9469
  pid: typeof candidate.pid === "number" ? candidate.pid : void 0,
8629
9470
  manifestSha256: typeof candidate.manifestSha256 === "string" ? candidate.manifestSha256 : void 0,
8630
- entries: Array.isArray(candidate.entries) && candidate.entries.every((entry) => typeof entry === "string") ? candidate.entries : void 0
9471
+ entries: Array.isArray(candidate.entries) && candidate.entries.every((entry) => typeof entry === "string") ? candidate.entries : void 0,
9472
+ files
8631
9473
  },
8632
9474
  problem: null
8633
9475
  };
@@ -8642,6 +9484,59 @@ function describeManifestProblem(value) {
8642
9484
  if (!Array.isArray(candidate.files)) return "has no files array";
8643
9485
  return null;
8644
9486
  }
9487
+ function verifyMarkerInventory(dir, entries, files) {
9488
+ const diskEntries = new Set(entries);
9489
+ const recorded = /* @__PURE__ */ new Map();
9490
+ for (const record of files) {
9491
+ if (recorded.has(record.path)) {
9492
+ return `its .codebase-snapshot inventory records ${record.path} twice`;
9493
+ }
9494
+ if (!diskEntries.has(record.path)) {
9495
+ return `its .codebase-snapshot inventory records ${record.path}, which is missing from the directory`;
9496
+ }
9497
+ recorded.set(record.path, record);
9498
+ }
9499
+ for (const entry of entries) {
9500
+ if (entry === OWNERSHIP_MARKER) continue;
9501
+ if (IGNORABLE_ENTRIES.has(entry.slice(entry.lastIndexOf("/") + 1))) continue;
9502
+ const full = path16.join(dir, ...entry.split("/"));
9503
+ let stats;
9504
+ try {
9505
+ stats = fs14.lstatSync(full);
9506
+ } catch {
9507
+ return `its .codebase-snapshot inventory lists ${entry}, which cannot be read`;
9508
+ }
9509
+ if (stats.isDirectory()) {
9510
+ if (recorded.has(entry)) {
9511
+ return `its .codebase-snapshot inventory records the directory ${entry} as a file`;
9512
+ }
9513
+ continue;
9514
+ }
9515
+ if (!stats.isFile()) {
9516
+ if (recorded.has(entry)) {
9517
+ return `its .codebase-snapshot inventory records ${entry} as a regular file, but it is not one`;
9518
+ }
9519
+ continue;
9520
+ }
9521
+ const record = recorded.get(entry);
9522
+ if (record === void 0) {
9523
+ return `its .codebase-snapshot inventory does not record the file ${entry}`;
9524
+ }
9525
+ if (record.bytes !== stats.size) {
9526
+ return `its .codebase-snapshot inventory records ${entry} as ${record.bytes} B, but it is ${stats.size} B`;
9527
+ }
9528
+ let digest;
9529
+ try {
9530
+ digest = sha256Hex2(fs14.readFileSync(full));
9531
+ } catch {
9532
+ return `its .codebase-snapshot inventory cannot verify ${entry}: the file could not be read`;
9533
+ }
9534
+ if (digest !== record.sha256) {
9535
+ return `its .codebase-snapshot inventory's digest for ${entry} does not match the file`;
9536
+ }
9537
+ }
9538
+ return null;
9539
+ }
8645
9540
  function assessSnapshotDirectory(dir) {
8646
9541
  const { marker: marker2, problem } = readOwnershipMarker(dir);
8647
9542
  if (!marker2) return { owned: false, problem, foreignEntries: [], marker: null };
@@ -8654,7 +9549,8 @@ function assessSnapshotDirectory(dir) {
8654
9549
  };
8655
9550
  }
8656
9551
  const manifestPath = path16.join(dir, "manifest.json");
8657
- if (fs14.existsSync(manifestPath)) {
9552
+ const hasManifest = fs14.existsSync(manifestPath);
9553
+ if (hasManifest) {
8658
9554
  let raw;
8659
9555
  try {
8660
9556
  raw = fs14.readFileSync(manifestPath, "utf8");
@@ -8710,6 +9606,14 @@ function assessSnapshotDirectory(dir) {
8710
9606
  marker: marker2
8711
9607
  };
8712
9608
  }
9609
+ if (marker2.files === void 0 && !hasManifest) {
9610
+ return {
9611
+ owned: false,
9612
+ problem: "its .codebase-snapshot marker records neither per-file digests nor a manifest digest, so it cannot prove this generator wrote the directory",
9613
+ foreignEntries: [],
9614
+ marker: marker2
9615
+ };
9616
+ }
8713
9617
  const recorded = new Set(marker2.entries ?? []);
8714
9618
  if (recorded.size === 0) {
8715
9619
  return {
@@ -8719,13 +9623,18 @@ function assessSnapshotDirectory(dir) {
8719
9623
  marker: marker2
8720
9624
  };
8721
9625
  }
8722
- const foreignEntries = listEntries(dir).filter(
9626
+ const entries = listEntries(dir);
9627
+ const foreignEntries = entries.filter(
8723
9628
  (entry) => !recorded.has(entry) && !IGNORABLE_ENTRIES.has(entry)
8724
9629
  );
9630
+ if (foreignEntries.length > 0) {
9631
+ return { owned: false, problem: null, foreignEntries, marker: marker2 };
9632
+ }
9633
+ const inventoryProblem = marker2.files === void 0 ? null : verifyMarkerInventory(dir, entries, marker2.files);
8725
9634
  return {
8726
- owned: foreignEntries.length === 0,
8727
- problem: null,
8728
- foreignEntries,
9635
+ owned: inventoryProblem === null,
9636
+ problem: inventoryProblem,
9637
+ foreignEntries: [],
8729
9638
  marker: marker2
8730
9639
  };
8731
9640
  }
@@ -8885,10 +9794,7 @@ function acquireRunLock(stagingRoot) {
8885
9794
  };
8886
9795
  } catch (err) {
8887
9796
  if (err.code !== "EEXIST") throw err;
8888
- if (attempt === 0 && lockOwnerIsGone(lockPath)) {
8889
- fs14.rmSync(lockPath, { force: true });
8890
- continue;
8891
- }
9797
+ if (attempt === 0 && reclaimStaleLock(lockPath)) continue;
8892
9798
  throw new Error(
8893
9799
  `Another generate run is already using the staging directory ${stagingRoot}. Wait for it to finish, or delete ${lockPath} if no other run is active.`
8894
9800
  );
@@ -8897,14 +9803,25 @@ function acquireRunLock(stagingRoot) {
8897
9803
  throw new Error(`Could not acquire the generate lock for ${stagingRoot}.`);
8898
9804
  }
8899
9805
  function lockKeyFor(stagingRoot) {
8900
- let key = stagingRoot;
8901
- try {
8902
- key = fs14.realpathSync(stagingRoot);
8903
- } catch {
8904
- }
9806
+ let key = canonicalLockTarget(stagingRoot);
8905
9807
  if (process.platform === "win32" || process.platform === "darwin") key = key.toLowerCase();
8906
9808
  return sha256Hex2(key).slice(0, 16);
8907
9809
  }
9810
+ function canonicalLockTarget(targetPath) {
9811
+ const resolved = path16.resolve(targetPath);
9812
+ let existing = resolved;
9813
+ const tail = [];
9814
+ for (; ; ) {
9815
+ try {
9816
+ return path16.join(fs14.realpathSync(existing), ...tail);
9817
+ } catch {
9818
+ const parent = path16.dirname(existing);
9819
+ if (parent === existing) return resolved;
9820
+ tail.unshift(path16.basename(existing));
9821
+ existing = parent;
9822
+ }
9823
+ }
9824
+ }
8908
9825
  function lockPathFor(stagingRoot) {
8909
9826
  return path16.join(os.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
8910
9827
  }
@@ -8929,6 +9846,24 @@ function lockOwnerIsGone(lockPath) {
8929
9846
  return err.code === "ESRCH";
8930
9847
  }
8931
9848
  }
9849
+ function reclaimStaleLock(lockPath) {
9850
+ let before;
9851
+ try {
9852
+ before = fs14.statSync(lockPath);
9853
+ } catch {
9854
+ return true;
9855
+ }
9856
+ if (!lockOwnerIsGone(lockPath)) return false;
9857
+ try {
9858
+ const current = fs14.statSync(lockPath);
9859
+ const sameFile = current.ino === before.ino && current.birthtimeMs === before.birthtimeMs && current.mtimeMs === before.mtimeMs;
9860
+ if (!sameFile) return false;
9861
+ fs14.rmSync(lockPath, { force: true });
9862
+ return true;
9863
+ } catch {
9864
+ return false;
9865
+ }
9866
+ }
8932
9867
  function lockFileIsAncient(lockPath) {
8933
9868
  try {
8934
9869
  return Date.now() - fs14.statSync(lockPath).mtimeMs > STALE_RUN_MS;
@@ -8986,7 +9921,6 @@ function swapOnce(stagingDir, outDir) {
8986
9921
  throw copyErr;
8987
9922
  }
8988
9923
  }
8989
- if (hadPrevious) fs14.rmSync(backupDir, { recursive: true, force: true });
8990
9924
  } catch (err) {
8991
9925
  if (hadPrevious && fs14.existsSync(backupDir)) {
8992
9926
  if (fs14.existsSync(outDir)) fs14.rmSync(outDir, { recursive: true, force: true });
@@ -8994,6 +9928,16 @@ function swapOnce(stagingDir, outDir) {
8994
9928
  }
8995
9929
  throw err;
8996
9930
  }
9931
+ if (hadPrevious) {
9932
+ try {
9933
+ fs14.rmSync(backupDir, { recursive: true, force: true });
9934
+ } catch (err) {
9935
+ process.stderr.write(
9936
+ `\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.
9937
+ `
9938
+ );
9939
+ }
9940
+ }
8997
9941
  }
8998
9942
  function sleepSync(milliseconds) {
8999
9943
  const buffer = new Int32Array(new SharedArrayBuffer(4));
@@ -9016,22 +9960,18 @@ function artifactWarnings(artifacts, sarif) {
9016
9960
  }
9017
9961
  return messages;
9018
9962
  }
9963
+ function installHookStdoutRedirect() {
9964
+ return installStdoutRouter();
9965
+ }
9019
9966
  function runAfterGenerate(config, manifest) {
9020
9967
  const hook = config.hooks.afterGenerate;
9021
9968
  if (!hook) return null;
9022
- const stdoutWrite = process.stdout.write.bind(process.stdout);
9023
- const stderrWrite = process.stderr.write.bind(process.stderr);
9024
- const hookScope = new AsyncLocalStorage();
9025
- const patchedWrite = ((...args) => hookScope.getStore() === true ? stderrWrite(...args) : stdoutWrite(...args));
9026
- const restoreStdout = () => {
9027
- if (process.stdout.write === patchedWrite) process.stdout.write = stdoutWrite;
9028
- };
9969
+ const releaseRedirect = installHookStdoutRedirect();
9029
9970
  let returned;
9030
9971
  try {
9031
- process.stdout.write = patchedWrite;
9032
- returned = hookScope.run(true, () => hook(manifest));
9972
+ returned = hookStdoutScope.run(true, () => hook(manifest));
9033
9973
  } catch (err) {
9034
- restoreStdout();
9974
+ releaseRedirect();
9035
9975
  const message = maskPathText(err.message, config.secretRules);
9036
9976
  manifest.warnings.push(`hooks.afterGenerate failed: ${message}`);
9037
9977
  manifest.totals.warningCount = manifest.warnings.length;
@@ -9039,10 +9979,10 @@ function runAfterGenerate(config, manifest) {
9039
9979
  }
9040
9980
  const thenable = returned;
9041
9981
  if (!thenable || typeof thenable.then !== "function") {
9042
- restoreStdout();
9982
+ releaseRedirect();
9043
9983
  return null;
9044
9984
  }
9045
- return Promise.resolve(returned).finally(restoreStdout);
9985
+ return Promise.resolve(returned).finally(releaseRedirect);
9046
9986
  }
9047
9987
  function partitionByBudget(files, config, fingerprint) {
9048
9988
  const budgetFor = (file) => config.budgets.byLayer[file.layer] ?? config.budgets.default;
@@ -9053,23 +9993,14 @@ function partitionByBudget(files, config, fingerprint) {
9053
9993
  if (bucket) bucket.push(file);
9054
9994
  else buckets.set(budget, [file]);
9055
9995
  }
9056
- if (buckets.size <= 1) {
9057
- const only = buckets.size === 1 ? Array.from(buckets.keys())[0] : config.maxPartBytes;
9058
- return partitionFiles(files, only, fingerprint);
9996
+ if (buckets.size === 0) return [];
9997
+ if (buckets.size === 1) {
9998
+ return partitionFiles(files, Array.from(buckets.keys())[0], fingerprint);
9059
9999
  }
9060
- const parts = [];
9061
- for (const budget of Array.from(buckets.keys()).sort((a, b) => a - b)) {
9062
- parts.push(...partitionFiles(buckets.get(budget) ?? [], budget, fingerprint));
9063
- }
9064
- const merged = renumberParts(parts, fingerprint);
9065
- const byPath = new Map(files.map((file) => [file.relativePath, file]));
9066
- for (const part of merged) {
9067
- for (const included of part.metadata.includedFiles) {
9068
- const file = byPath.get(included.relativePath);
9069
- if (file) file.part = part.filename;
9070
- }
9071
- }
9072
- return merged;
10000
+ return partitionFilesForBuckets(
10001
+ Array.from(buckets.entries()).sort(([left], [right]) => left - right).map(([budgetBytes, bucketFiles]) => ({ files: bucketFiles, budgetBytes })),
10002
+ fingerprint
10003
+ );
9073
10004
  }
9074
10005
  function generateSnapshot(configInput, options) {
9075
10006
  assertUsableConfigInput(configInput);
@@ -9101,6 +10032,7 @@ function generateSnapshot(configInput, options) {
9101
10032
  return false;
9102
10033
  }) : collection.files;
9103
10034
  const files = [];
10035
+ const derivationKey = derivationSettings(config);
9104
10036
  const monolithBodies = /* @__PURE__ */ new Map();
9105
10037
  const skipped = maskSkipRecords([...collection.skipped], config.secretRules);
9106
10038
  const secretFindings = [];
@@ -9113,6 +10045,7 @@ function generateSnapshot(configInput, options) {
9113
10045
  const fileWarnings = [];
9114
10046
  const oversizeSummaryPaths = [];
9115
10047
  const previewSummaryPaths = [];
10048
+ const skippedSummaryImports = /* @__PURE__ */ new Map();
9116
10049
  const layerCounts = {};
9117
10050
  const kindCounts = {};
9118
10051
  let totalLines = 0;
@@ -9177,8 +10110,6 @@ function generateSnapshot(configInput, options) {
9177
10110
  }
9178
10111
  const hashSha256 = sha256Hex2(buffer);
9179
10112
  const rawContent = decoded.text;
9180
- const lineCount = countLines(rawContent);
9181
- totalLines += lineCount;
9182
10113
  totalSizeBytes += stats.size;
9183
10114
  if (decoded.encoding !== "utf-8") {
9184
10115
  encodingNotes.push({
@@ -9192,66 +10123,25 @@ function generateSnapshot(configInput, options) {
9192
10123
  const language = detectLanguage(relativePath);
9193
10124
  bump(layerCounts, layer2);
9194
10125
  bump(kindCounts, kind);
9195
- const { redacted, findings } = scanAndRedactSecrets(
9196
- rawContent,
9197
- config.secretRules,
9198
- relativePath
9199
- );
9200
- secretFindings.push(...findings);
9201
- const isLarge = stats.size > config.largeFileBytes;
9202
- if (isLarge) largeFileCount += 1;
9203
- let finalContent = redacted;
9204
- let isPreviewTruncated = false;
9205
- let includedLines = lineCount;
9206
- let inclusionMode = "full";
9207
- if (config.skeleton === true && isSkeletonizable(relativePath)) {
9208
- const skeleton = skeletonizeTypeScript(redacted, relativePath);
9209
- if (skeleton.collapsed > 0) {
9210
- finalContent = skeleton.text;
9211
- inclusionMode = "signatures";
9212
- includedLines = countLines(skeleton.text);
9213
- }
9214
- }
9215
- if (isLarge && inclusionMode !== "signatures") {
9216
- const preview = truncatePreview(
9217
- redacted,
9218
- config.previewHeadLines,
9219
- config.previewTailLines
9220
- );
9221
- finalContent = preview.content;
9222
- isPreviewTruncated = preview.isTruncated;
9223
- includedLines = preview.includedLines;
9224
- inclusionMode = isPreviewTruncated ? "preview" : "full";
9225
- }
9226
- if (config.includeMonolith && (isPreviewTruncated || inclusionMode === "signatures")) {
9227
- monolithBodies.set(relativePath, redacted);
9228
- }
9229
- let summary;
9230
- let summaryQuality;
9231
- if (Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES) {
9232
- oversizeSummaryPaths.push(relativePath);
9233
- } else if (isPreviewTruncated && hasStructuralSummary(relativePath)) {
9234
- previewSummaryPaths.push(relativePath);
9235
- } else {
9236
- try {
9237
- const outcome = summarizeFile(relativePath, rawContent);
9238
- summary = outcome?.summary ? maskSummaryStrings(outcome.summary, config.secretRules) : void 0;
9239
- summaryQuality = outcome?.quality;
9240
- if (isSourceSummary(summary) && summary.parseErrors) {
9241
- fileWarnings.push({
9242
- path: relativePath,
9243
- message: `Parse errors in ${maskPathText(relativePath, config.secretRules)} (${summary.parseErrors}); its summary is incomplete.`
9244
- });
9245
- }
9246
- } catch (err) {
9247
- fileWarnings.push({
9248
- path: relativePath,
9249
- message: `Summary skipped for ${maskPathText(relativePath, config.secretRules)}: ${err.message}`.replace(
9250
- /\s+/g,
9251
- " "
9252
- )
9253
- });
9254
- }
10126
+ const derivation = takeDerivation(absolutePath, hashSha256, derivationKey) ?? (() => {
10127
+ const fresh = deriveFile(relativePath, rawContent, stats.size, config);
10128
+ rememberDerivation(absolutePath, hashSha256, derivationKey, fresh);
10129
+ return fresh;
10130
+ })();
10131
+ const { lineCount } = derivation;
10132
+ totalLines += lineCount;
10133
+ secretFindings.push(...derivation.findings);
10134
+ if (derivation.isLarge) largeFileCount += 1;
10135
+ if (derivation.summarySkip === "oversize") oversizeSummaryPaths.push(relativePath);
10136
+ else if (derivation.summarySkip === "preview") previewSummaryPaths.push(relativePath);
10137
+ if (derivation.dependentImports !== null) {
10138
+ skippedSummaryImports.set(relativePath, derivation.dependentImports);
10139
+ }
10140
+ if (derivation.summaryWarning !== null) {
10141
+ fileWarnings.push({ path: relativePath, message: derivation.summaryWarning });
10142
+ }
10143
+ if (config.includeMonolith && (derivation.isPreviewTruncated || derivation.inclusionMode === "signatures")) {
10144
+ monolithBodies.set(relativePath, derivation.redacted);
9255
10145
  }
9256
10146
  files.push({
9257
10147
  relativePath,
@@ -9262,24 +10152,25 @@ function generateSnapshot(configInput, options) {
9262
10152
  layer: layer2,
9263
10153
  kind,
9264
10154
  language,
9265
- inclusionMode,
9266
- isLarge,
9267
- isPreviewTruncated,
10155
+ inclusionMode: derivation.inclusionMode,
10156
+ isLarge: derivation.isLarge,
10157
+ isPreviewTruncated: derivation.isPreviewTruncated,
9268
10158
  originalLines: lineCount,
9269
- includedLines,
9270
- includedBytes: Buffer.byteLength(finalContent, "utf8"),
9271
- summary,
9272
- summaryQuality,
10159
+ includedLines: derivation.includedLines,
10160
+ includedBytes: Buffer.byteLength(derivation.finalContent, "utf8"),
10161
+ summary: derivation.summary,
10162
+ summaryQuality: derivation.summaryQuality,
9273
10163
  ...decoded.encoding === "utf-8" ? {} : { encoding: decoded.encoding },
9274
- content: finalContent
10164
+ content: derivation.finalContent
9275
10165
  });
9276
10166
  }
9277
10167
  if (changedScope !== null && changedPaths !== null && config.withDependents === true) {
9278
10168
  const keep = new Set(changedPaths);
9279
10169
  const resolver = buildImportResolver(files);
9280
10170
  for (const file of files) {
9281
- if (!isSourceSummary(file.summary)) continue;
9282
- if (importsChangedFile(file.relativePath, file.summary.imports, changedPaths, resolver)) {
10171
+ const fileImports = isSourceSummary(file.summary) ? file.summary.imports : skippedSummaryImports.get(file.relativePath) ?? [];
10172
+ if (fileImports.length === 0) continue;
10173
+ if (importsChangedFile(file.relativePath, fileImports, changedPaths, resolver)) {
9283
10174
  keep.add(file.relativePath);
9284
10175
  }
9285
10176
  }
@@ -9310,6 +10201,9 @@ function generateSnapshot(configInput, options) {
9310
10201
  for (const path17 of [...monolithBodies.keys()]) {
9311
10202
  if (!keep.has(path17)) monolithBodies.delete(path17);
9312
10203
  }
10204
+ for (const path17 of [...skippedSummaryImports.keys()]) {
10205
+ if (!keep.has(path17)) skippedSummaryImports.delete(path17);
10206
+ }
9313
10207
  }
9314
10208
  if (changedScope !== null) {
9315
10209
  for (const relativePath of unchangedPaths) {
@@ -9345,7 +10239,7 @@ function generateSnapshot(configInput, options) {
9345
10239
  const shown = oversizeSummaryPaths.slice(0, ENCODING_PATHS_SHOWN).map((entry) => maskPathText(entry, config.secretRules));
9346
10240
  const hidden = oversizeSummaryPaths.length - ENCODING_PATHS_SHOWN;
9347
10241
  warnings.push(
9348
- `${oversizeSummaryPaths.length} file(s) exceed ${Math.round(SUMMARY_MAX_SOURCE_BYTES / (1024 * 1024))} MB and were not parsed for a structural summary: ${shown.join(", ")}${hidden > 0 ? ` and ${hidden} more` : ""}. Their bodies are emitted as head/tail previews.`
10242
+ `${oversizeSummaryPaths.length} file(s) exceed ${Math.round(SUMMARY_MAX_SOURCE_BYTES2 / (1024 * 1024))} MB and were not parsed for a structural summary: ${shown.join(", ")}${hidden > 0 ? ` and ${hidden} more` : ""}. Their bodies are emitted as head/tail previews.`
9349
10243
  );
9350
10244
  }
9351
10245
  for (const [encoding, bucket] of encodingBuckets) {
@@ -9364,16 +10258,21 @@ function generateSnapshot(configInput, options) {
9364
10258
  }
9365
10259
  }
9366
10260
  const fingerprint = sha256Hex2(
9367
- files.map(
9368
- (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
9369
- ).join("\n")
10261
+ [
10262
+ ...files.map(
10263
+ (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
10264
+ ),
10265
+ `settings:${configDigest(config)}`
10266
+ ].join("\n")
9370
10267
  );
9371
10268
  const fullContents = /* @__PURE__ */ new Map();
9372
- for (const file of files) {
9373
- fullContents.set(
9374
- file.relativePath,
9375
- monolithBodies.get(file.relativePath) ?? file.content ?? ""
9376
- );
10269
+ if (config.includeMonolith) {
10270
+ for (const file of files) {
10271
+ fullContents.set(
10272
+ file.relativePath,
10273
+ monolithBodies.get(file.relativePath) ?? file.content ?? ""
10274
+ );
10275
+ }
9377
10276
  }
9378
10277
  const parts = partitionByBudget(files, config, fingerprint);
9379
10278
  const truncatedPreviewCount = files.filter((file) => file.isPreviewTruncated).length;
@@ -9632,9 +10531,9 @@ function generateSnapshot(configInput, options) {
9632
10531
  }
9633
10532
  writeOwnershipMarker(outDir, markerPayload(outDir, "complete", snapshotId, createdAt));
9634
10533
  };
9635
- shipHookState();
10534
+ if (config.hooks.afterGenerate) shipHookState();
9636
10535
  if (pendingHook) {
9637
- pendingHook.then(
10536
+ const tracked = pendingHook.then(
9638
10537
  () => {
9639
10538
  try {
9640
10539
  shipHookState();
@@ -9653,8 +10552,10 @@ function generateSnapshot(configInput, options) {
9653
10552
  } catch {
9654
10553
  }
9655
10554
  }
9656
- );
9657
- pendingHooks.set(outDir, pendingHook);
10555
+ ).finally(() => {
10556
+ if (pendingHooks.get(outDir) === tracked) pendingHooks.delete(outDir);
10557
+ });
10558
+ pendingHooks.set(outDir, tracked);
9658
10559
  }
9659
10560
  return manifest;
9660
10561
  } catch (err) {
@@ -9672,15 +10573,15 @@ function generateSnapshot(configInput, options) {
9672
10573
  }
9673
10574
  var pendingHooks = /* @__PURE__ */ new Map();
9674
10575
  async function generateSnapshotAsync(configInput, options) {
9675
- const manifest = generateSnapshot(configInput, options);
10576
+ assertUsableConfigInput(configInput);
9676
10577
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput ?? null);
10578
+ const manifest = generateSnapshot(config, options);
9677
10579
  const { outDir } = resolveSafeOutputDirs(config);
9678
10580
  const pending = pendingHooks.get(outDir);
9679
10581
  if (pending !== void 0) {
9680
- pendingHooks.delete(outDir);
9681
10582
  await pending.catch(() => void 0);
9682
10583
  }
9683
10584
  return manifest;
9684
10585
  }
9685
10586
 
9686
- export { ARTIFACT_NAMES, CHECK_INTERVAL_MS, CONFIG_KEYS, DEFAULT_ANSWERS, DEFAULT_SECRET_PATTERNS, FAILURE_INTERVAL_MS, GENERATOR_NAME, GENERATOR_VERSION, HOOK_MARKER, LANGUAGE_PROFILES, MIN_MAX_PART_BYTES, MIN_MAX_PART_TOKENS, PACKAGE_LATEST_URL, PRESETS, PromptBack, PromptCancelled, REQUEST_TIMEOUT_MS, SCHEMA_VERSION, anchorForPath, appendGitignoreEntries, assertReplaceable, assertUsableConfigInput, buildImportResolver, bytesForTokens, cacheDirectory, cacheFilePath, checkForUpdate, classifyKind, classifyLayer, collectFiles, compareManifests, configDigest, countInvalidUtf8Bytes, countLines, decodeText, defaultIO, defineConfig, describeManifestShapeProblem, detectLanguage, detectPreset, displayPath, displayWidth, enforceBudget, escapeControls, estimateTokens, explainPath, fenceForContent, fenceForText, fetchLatestVersion, findConfigFile, findSecretInPath, firstRunMessage, formatNumber, formatTokens, formatUpdateNotice, generateInWorker, generateProjectTree, generateSarifReport, generateSnapshot, generateSnapshotAsync, getGitInfo, getPreset, gitignorePath, globToRegExp, hasPriorSnapshot, importsChangedFile, importsOfFile, importsOfText, installKind, installPreCommitHook, isBinaryBuffer, isBinaryExtension, isBinaryFile, isDiscoveryMode, isEffectivelyEmpty, isInteractive, isNewer, isResolvedConfig, isSensitivePath, isSkeletonizable, isTsxFileName, listPresetNames, loadConfigFile, loadConfigFileDetailed, loadManifest, lockPathFor, markResolvedConfig, matchRule, matchesExclude, normalizeResolvedConfig, parseByteSize, partitionFiles, planFirstRun, profileForPath, renderConfig, renderDiffText, renderExplainText, renumberParts, resolveChangedScope, resolveConfig, resolveSafeOutputDirs, resolveSpecifier, runInit, scanAndRedactSecrets, shouldCheck, skeletonizeTypeScript, stripJsonComments, summarizeJson, summarizeMarkdown, summarizeTypeScriptSource, summarizeWithProfile, supportsTypeScriptImports, truncatePreview, truncateToBytes, unknownPresetMessage, updateCommand, validateSnapshot, workerEntry, wrapLines };
10587
+ export { ARTIFACT_NAMES, CHECK_INTERVAL_MS, CONFIG_KEYS, DEFAULT_ANSWERS, DEFAULT_SECRET_PATTERNS, FAILURE_INTERVAL_MS, GENERATOR_NAME, GENERATOR_VERSION, HOOK_MARKER, LANGUAGE_PROFILES, MIN_MAX_PART_BYTES, MIN_MAX_PART_TOKENS, PACKAGE_LATEST_URL, PRESETS, PromptBack, PromptCancelled, REQUEST_TIMEOUT_MS, SCHEMA_VERSION, anchorForPath, appendGitignoreEntries, assertReplaceable, assertUsableConfigInput, buildImportResolver, bytesForTokens, cacheDirectory, cacheFilePath, checkForUpdate, classifyKind, classifyLayer, collectFiles, compareManifests, configDigest, countInvalidUtf8Bytes, countLines, decodeText, defaultIO, defineConfig, describeManifestShapeProblem, detectLanguage, detectPreset, displayPath, displayWidth, enforceBudget, escapeControls, estimateTokens, explainPath, fenceForContent, fenceForText, fetchLatestVersion, findConfigFile, findSecretInPath, firstRunMessage, formatNumber, formatTokens, formatUpdateNotice, generateInWorker, generateProjectTree, generateSarifReport, generateSnapshot, generateSnapshotAsync, getGitInfo, getPreset, gitignorePath, globToRegExp, hasPriorSnapshot, importsChangedFile, importsOfFile, importsOfText, installKind, installPreCommitHook, isBinaryBuffer, isBinaryExtension, isBinaryFile, isDiscoveryMode, isEffectivelyEmpty, isInteractive, isNewer, isResolvedConfig, isSensitivePath, isSkeletonizable, isTsxFileName, listPresetNames, loadConfigFile, loadConfigFileDetailed, loadManifest, lockPathFor, markResolvedConfig, matchRule, matchesExclude, normalizeResolvedConfig, parseByteSize, partitionFiles, planFirstRun, profileForPath, renderConfig, renderDiffText, renderExplainText, renumberParts, resolveChangedScope, resolveConfig, resolveSafeOutputDirs, resolveSpecifier, runInit, runWithStdoutCapture, scanAndRedactSecrets, shouldCheck, skeletonizeTypeScript, stripJsonComments, summarizeJson, summarizeMarkdown, summarizeTypeScriptSource, summarizeWithProfile, supportsTypeScriptImports, truncatePreview, truncateToBytes, unknownPresetMessage, updateCommand, validateSnapshot, workerEntry, wrapLines };