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.
package/dist/index.cjs CHANGED
@@ -9,6 +9,7 @@ var ts = require('typescript');
9
9
  var module$1 = require('module');
10
10
  var url = require('url');
11
11
  var childProcess = require('child_process');
12
+ var http = require('http');
12
13
  var https = require('https');
13
14
  var readline = require('readline');
14
15
  require('worker_threads');
@@ -39,10 +40,56 @@ var os__namespace = /*#__PURE__*/_interopNamespace(os);
39
40
  var path16__namespace = /*#__PURE__*/_interopNamespace(path16);
40
41
  var ts__default = /*#__PURE__*/_interopDefault(ts);
41
42
  var childProcess__namespace = /*#__PURE__*/_interopNamespace(childProcess);
43
+ var http__namespace = /*#__PURE__*/_interopNamespace(http);
42
44
  var https__namespace = /*#__PURE__*/_interopNamespace(https);
43
45
  var readline__namespace = /*#__PURE__*/_interopNamespace(readline);
44
46
 
45
47
  // src/index.ts
48
+ var hookStdoutScope = new async_hooks.AsyncLocalStorage();
49
+ var captureScope = new async_hooks.AsyncLocalStorage();
50
+ var installs = 0;
51
+ var underlying = null;
52
+ var router = null;
53
+ var asText = (chunk) => typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
54
+ var callbackIn = (rest) => {
55
+ for (const argument of rest) {
56
+ if (typeof argument === "function") return argument;
57
+ }
58
+ return void 0;
59
+ };
60
+ function installStdoutRouter() {
61
+ if (installs === 0) {
62
+ underlying = process.stdout.write;
63
+ const realStdout = underlying.bind(process.stdout);
64
+ const realStderr = process.stderr.write.bind(process.stderr);
65
+ router = ((...args) => {
66
+ if (hookStdoutScope.getStore() === true) return realStderr(...args);
67
+ const capture = captureScope.getStore();
68
+ if (capture !== void 0) {
69
+ capture.write(asText(args[0]));
70
+ const callback = callbackIn(args.slice(1));
71
+ if (callback) callback(null);
72
+ return true;
73
+ }
74
+ return realStdout(...args);
75
+ });
76
+ process.stdout.write = router;
77
+ }
78
+ installs += 1;
79
+ let released = false;
80
+ return () => {
81
+ if (released) return;
82
+ released = true;
83
+ installs -= 1;
84
+ if (installs === 0) {
85
+ if (process.stdout.write === router && underlying !== null) {
86
+ process.stdout.write = underlying;
87
+ }
88
+ underlying = null;
89
+ router = null;
90
+ }
91
+ };
92
+ }
46
93
 
47
94
  // src/ast/profiles/shared.ts
48
95
  var MAX_SUMMARY_CHARS = 1e6;
@@ -98,7 +145,7 @@ function isCapitalizedName(name) {
98
145
  }
99
146
 
100
147
  // src/ast/profiles/cfamily.ts
101
- var INCLUDE = /^#\s*include\s*[<"]([^>"]+)[>"]/;
148
+ var INCLUDE = /^#\s*include\s*([<"])([^>"]+)[>"]/;
102
149
  var DEFINE = /^#\s*define\s+([A-Za-z_]\w*)/;
103
150
  var USING = /^using\s+(?:namespace\s+)?([\w:]+)\s*;/;
104
151
  var TYPE_DECL = /^(?:typedef\s+)?(?:struct|union|class|enum)\s+([A-Za-z_]\w*)/;
@@ -117,7 +164,7 @@ var cfamilyProfile = {
117
164
  }
118
165
  const included = INCLUDE.exec(trimmed);
119
166
  if (included) {
120
- summary.imports.push(included[1]);
167
+ summary.imports.push(included[1] === '"' ? `./${included[2]}` : included[2]);
121
168
  return;
122
169
  }
123
170
  const used = USING.exec(trimmed);
@@ -521,7 +568,15 @@ var pythonProfile = {
521
568
  }
522
569
  const from = FROM_IMPORT.exec(trimmed);
523
570
  if (from) {
524
- summary.imports.push(from[1]);
571
+ const module = from[1];
572
+ if (/^\.+$/.test(module)) {
573
+ for (const name of from[2].split(",")) {
574
+ const imported2 = name.replace(/[()]/g, "").trim().split(/\s+as\s+/)[0].trim();
575
+ if (/^[A-Za-z_]\w*$/.test(imported2)) summary.imports.push(`${module}${imported2}`);
576
+ }
577
+ } else {
578
+ summary.imports.push(module);
579
+ }
525
580
  routePending = false;
526
581
  return;
527
582
  }
@@ -570,7 +625,8 @@ var pythonProfile = {
570
625
  };
571
626
 
572
627
  // src/ast/profiles/ruby.ts
573
- var REQUIRE = /^require(?:_relative)?\s+["']([^"']+)["']/;
628
+ var REQUIRE_RELATIVE = /^require_relative\s+["']([^"']+)["']/;
629
+ var REQUIRE = /^require\s+["']([^"']+)["']/;
574
630
  var CLASS_OR_MODULE = /^(?:class|module)\s+([A-Z][\w:]*)/;
575
631
  var METHOD2 = /^def\s+(?:self\.)?([A-Za-z_]\w*[?!=]?)/;
576
632
  var rubyProfile = {
@@ -581,6 +637,11 @@ var rubyProfile = {
581
637
  eachLine(content, (line) => {
582
638
  const trimmed = line.trim();
583
639
  if (!trimmed || trimmed.startsWith("#")) return;
640
+ const relative8 = REQUIRE_RELATIVE.exec(trimmed);
641
+ if (relative8) {
642
+ summary.imports.push(`./${relative8[1]}`);
643
+ return;
644
+ }
584
645
  const required = REQUIRE.exec(trimmed);
585
646
  if (required) {
586
647
  summary.imports.push(required[1]);
@@ -777,13 +838,23 @@ function summarizeTypeScriptSource(relativePath, content) {
777
838
  if (ts__default.default.isImportDeclaration(node) && ts__default.default.isStringLiteral(node.moduleSpecifier)) {
778
839
  summary.imports.push(node.moduleSpecifier.text);
779
840
  }
841
+ if (ts__default.default.isImportEqualsDeclaration(node) && ts__default.default.isExternalModuleReference(node.moduleReference) && node.moduleReference.expression !== void 0 && ts__default.default.isStringLiteral(node.moduleReference.expression)) {
842
+ summary.imports.push(node.moduleReference.expression.text);
843
+ }
844
+ if (ts__default.default.isCallExpression(node) && node.arguments.length >= 1) {
845
+ const firstArgument = node.arguments[0];
846
+ if (firstArgument !== void 0 && ts__default.default.isStringLiteral(firstArgument)) {
847
+ const isDynamicImport = node.expression.kind === ts__default.default.SyntaxKind.ImportKeyword;
848
+ const isRequire = ts__default.default.isIdentifier(node.expression) && node.expression.text === "require";
849
+ if (isDynamicImport || isRequire) summary.imports.push(firstArgument.text);
850
+ }
851
+ }
780
852
  if (ts__default.default.isExportDeclaration(node)) {
781
853
  if (node.moduleSpecifier && ts__default.default.isStringLiteral(node.moduleSpecifier)) {
782
854
  summary.imports.push(node.moduleSpecifier.text);
855
+ summary.reExports.push(node.moduleSpecifier.text);
783
856
  if (node.exportClause && ts__default.default.isNamespaceExport(node.exportClause)) {
784
857
  summary.exports.push(node.exportClause.name.text);
785
- } else if (!node.exportClause) {
786
- summary.reExports.push(node.moduleSpecifier.text);
787
858
  }
788
859
  }
789
860
  if (node.exportClause && ts__default.default.isNamedExports(node.exportClause)) {
@@ -875,7 +946,8 @@ function summarizeTypeScriptSource(relativePath, content) {
875
946
  }
876
947
 
877
948
  // src/ast/profiles/sfc.ts
878
- var SCRIPT_BLOCK = /<script[^>]*>([\s\S]*?)<\/script>/gi;
949
+ var SCRIPT_BLOCK = /<script([^>]*)>([\s\S]*?)<\/script>/gi;
950
+ var JSX_LANG = /\blang\s*=\s*["']?[tj]sx\b/i;
879
951
  var ASTRO_FRONTMATTER = /^\uFEFF?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?=\r?\n|$)/;
880
952
  function componentName(path17) {
881
953
  const base = path17.split("/").pop() ?? path17;
@@ -886,13 +958,15 @@ var sfcProfile = {
886
958
  extensions: [".vue", ".svelte", ".astro"],
887
959
  summarize(path17, content) {
888
960
  let script = "";
961
+ let usesJsx = path17.toLowerCase().endsWith(".astro");
889
962
  if (path17.toLowerCase().endsWith(".astro")) {
890
963
  const frontmatter = ASTRO_FRONTMATTER.exec(content);
891
964
  if (frontmatter) script += `${frontmatter[1]}
892
965
  `;
893
966
  }
894
967
  for (const match of content.matchAll(SCRIPT_BLOCK)) {
895
- script += `${match[1]}
968
+ if (JSX_LANG.test(match[1] ?? "")) usesJsx = true;
969
+ script += `${match[2]}
896
970
  `;
897
971
  }
898
972
  const name = componentName(path17);
@@ -904,7 +978,7 @@ var sfcProfile = {
904
978
  }
905
979
  return { summary: finalizeSummary(summary2), quality: "heuristic" };
906
980
  }
907
- const summary = summarizeTypeScriptSource(`${name}.ts`, script);
981
+ const summary = summarizeTypeScriptSource(`${name}.${usesJsx ? "tsx" : "ts"}`, script);
908
982
  summary.reactComponents.push(name);
909
983
  summary.exports.push(name);
910
984
  return { summary: finalizeSummary(summary), quality: "ast" };
@@ -1096,124 +1170,421 @@ function summarizeWithProfile(path17, content) {
1096
1170
  const profile = profileForPath(path17);
1097
1171
  return profile ? profile.summarize(path17, content) : null;
1098
1172
  }
1099
-
1100
- // src/ast/structured.ts
1101
- function stripJsonComments(content) {
1102
- const text2 = content.replace(/^\uFEFF/, "");
1103
- let out = "";
1104
- let inString = false;
1105
- let inLineComment = false;
1106
- let inBlockComment = false;
1107
- for (let i = 0; i < text2.length; i++) {
1108
- const char = text2[i];
1109
- const next = text2[i + 1];
1110
- if (inLineComment) {
1111
- if (char === "\n") {
1112
- inLineComment = false;
1113
- out += char;
1114
- }
1173
+ var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
1174
+ ".png",
1175
+ ".jpg",
1176
+ ".jpeg",
1177
+ ".gif",
1178
+ ".webp",
1179
+ ".avif",
1180
+ ".ico",
1181
+ ".bmp",
1182
+ ".tiff",
1183
+ ".pdf",
1184
+ ".zip",
1185
+ ".tar",
1186
+ ".gz",
1187
+ ".tgz",
1188
+ ".br",
1189
+ ".bz2",
1190
+ ".xz",
1191
+ ".zst",
1192
+ ".lz4",
1193
+ ".lzma",
1194
+ ".7z",
1195
+ ".rar",
1196
+ ".mp3",
1197
+ ".mp4",
1198
+ ".wav",
1199
+ ".ogg",
1200
+ ".webm",
1201
+ ".mov",
1202
+ ".avi",
1203
+ ".woff",
1204
+ ".woff2",
1205
+ ".ttf",
1206
+ ".otf",
1207
+ ".eot",
1208
+ ".wasm",
1209
+ ".node",
1210
+ ".exe",
1211
+ ".dll",
1212
+ ".dylib",
1213
+ ".so"
1214
+ ]);
1215
+ function isBinaryExtension(filePath) {
1216
+ const ext = path16__namespace.extname(filePath).toLowerCase();
1217
+ return BINARY_EXTENSIONS.has(ext);
1218
+ }
1219
+ function isBinaryBuffer(buffer) {
1220
+ return buffer.includes(0);
1221
+ }
1222
+ function countControlBytes(buffer) {
1223
+ let count = 0;
1224
+ for (let index = 0; index < buffer.length; index++) {
1225
+ const byte = buffer[index];
1226
+ if (byte < 32) {
1227
+ if (byte !== 9 && byte !== 10 && byte !== 13) count += 1;
1115
1228
  continue;
1116
1229
  }
1117
- if (inBlockComment) {
1118
- if (char === "*" && next === "/") {
1119
- inBlockComment = false;
1120
- i += 1;
1121
- }
1230
+ if (byte === 127) {
1231
+ count += 1;
1122
1232
  continue;
1123
1233
  }
1124
- if (inString) {
1125
- out += char;
1126
- if (char === "\\") {
1127
- if (next !== void 0) {
1128
- out += next;
1129
- i += 1;
1130
- }
1131
- } else if (char === '"') {
1132
- inString = false;
1234
+ if (byte === 194 && index + 1 < buffer.length) {
1235
+ const next = buffer[index + 1];
1236
+ if (next >= 128 && next <= 159) {
1237
+ count += 1;
1238
+ index += 1;
1133
1239
  }
1240
+ }
1241
+ }
1242
+ return count;
1243
+ }
1244
+ var CONTROL_BYTES_FLOOR = 4;
1245
+ function countInvalidUtf8Bytes(buffer) {
1246
+ let invalid = 0;
1247
+ let index = 0;
1248
+ const length = buffer.length;
1249
+ while (index < length) {
1250
+ const lead = buffer[index];
1251
+ if (lead < 128) {
1252
+ index += 1;
1134
1253
  continue;
1135
1254
  }
1136
- if (char === '"') {
1137
- inString = true;
1138
- out += char;
1255
+ let continuation = 0;
1256
+ let codePoint = 0;
1257
+ let minimum = 0;
1258
+ if ((lead & 224) === 192) {
1259
+ continuation = 1;
1260
+ codePoint = lead & 31;
1261
+ minimum = 128;
1262
+ } else if ((lead & 240) === 224) {
1263
+ continuation = 2;
1264
+ codePoint = lead & 15;
1265
+ minimum = 2048;
1266
+ } else if ((lead & 248) === 240) {
1267
+ continuation = 3;
1268
+ codePoint = lead & 7;
1269
+ minimum = 65536;
1270
+ } else {
1271
+ invalid += 1;
1272
+ index += 1;
1139
1273
  continue;
1140
1274
  }
1141
- if (char === "/" && next === "/") {
1142
- inLineComment = true;
1143
- i += 1;
1275
+ if (index + continuation >= length) {
1276
+ invalid += 1;
1277
+ index += 1;
1144
1278
  continue;
1145
1279
  }
1146
- if (char === "/" && next === "*") {
1147
- inBlockComment = true;
1148
- i += 1;
1280
+ let wellFormed = true;
1281
+ for (let offset = 1; offset <= continuation; offset++) {
1282
+ const next = buffer[index + offset];
1283
+ if ((next & 192) !== 128) {
1284
+ wellFormed = false;
1285
+ break;
1286
+ }
1287
+ codePoint = codePoint << 6 | next & 63;
1288
+ }
1289
+ const isSurrogate = codePoint >= 55296 && codePoint <= 57343;
1290
+ if (!wellFormed || codePoint < minimum || codePoint > 1114111 || isSurrogate) {
1291
+ invalid += 1;
1292
+ index += 1;
1149
1293
  continue;
1150
1294
  }
1151
- out += char;
1295
+ index += continuation + 1;
1152
1296
  }
1153
- return out;
1297
+ return invalid;
1154
1298
  }
1155
- function summarizeJson(content) {
1156
- try {
1157
- const parsed = JSON.parse(stripJsonComments(content));
1158
- if (Array.isArray(parsed)) {
1159
- const sample = parsed[0];
1160
- const sampleKeys = sample && typeof sample === "object" && !Array.isArray(sample) ? Object.keys(sample).slice(0, 10).sort() : [];
1161
- return {
1162
- shape: "array",
1163
- itemCount: parsed.length,
1164
- keys: [],
1165
- sampleKeys
1166
- };
1299
+ function readBomEncoding(buffer) {
1300
+ if (buffer.length >= 2) {
1301
+ if (buffer[0] === 255 && buffer[1] === 254) return "utf-16le";
1302
+ if (buffer[0] === 254 && buffer[1] === 255) return "utf-16be";
1303
+ }
1304
+ return null;
1305
+ }
1306
+ function looksLikeUtf16(buffer) {
1307
+ if (buffer.length < 8 || buffer.length % 2 !== 0) return null;
1308
+ const sample = Math.min(buffer.length, 4096);
1309
+ let nulInLowByte = 0;
1310
+ let nulInHighByte = 0;
1311
+ const units = sample / 2;
1312
+ for (let index = 0; index < sample; index += 2) {
1313
+ if (buffer[index] === 0) nulInLowByte += 1;
1314
+ if (buffer[index + 1] === 0) nulInHighByte += 1;
1315
+ }
1316
+ if (nulInHighByte > units * 0.3 && nulInLowByte < units * 0.05) return "utf-16le";
1317
+ if (nulInLowByte > units * 0.3 && nulInHighByte < units * 0.05) return "utf-16be";
1318
+ return null;
1319
+ }
1320
+ function decodeUtf16(buffer, encoding) {
1321
+ const littleEndian = encoding === "utf-16le" ? buffer : Buffer.from(buffer.subarray(0, buffer.length - buffer.length % 2)).swap16();
1322
+ return new TextDecoder("utf-16le").decode(littleEndian);
1323
+ }
1324
+ function decodeText(buffer) {
1325
+ const bomEncoding = readBomEncoding(buffer);
1326
+ if (bomEncoding) {
1327
+ const text2 = decodeUtf16(buffer.subarray(2), bomEncoding);
1328
+ return { text: text2, encoding: bomEncoding, invalidBytes: 0, binary: false };
1329
+ }
1330
+ if (buffer.includes(0)) {
1331
+ const shape = looksLikeUtf16(buffer);
1332
+ if (shape) {
1333
+ return { text: decodeUtf16(buffer, shape), encoding: shape, invalidBytes: 0, binary: false };
1167
1334
  }
1168
- if (parsed && typeof parsed === "object") {
1169
- const keys = Object.keys(parsed).sort();
1335
+ const offset = buffer.indexOf(0);
1336
+ return {
1337
+ text: "",
1338
+ encoding: "utf-8",
1339
+ invalidBytes: 0,
1340
+ binary: true,
1341
+ binaryReason: `NUL byte at offset ${offset}`
1342
+ };
1343
+ }
1344
+ const invalidBytes = countInvalidUtf8Bytes(buffer);
1345
+ if (invalidBytes === 0) {
1346
+ const controlBytes = countControlBytes(buffer);
1347
+ if (controlBytes > CONTROL_BYTES_FLOOR && controlBytes * 100 > buffer.length) {
1170
1348
  return {
1171
- shape: "object",
1172
- itemCount: keys.length,
1173
- keys: keys.slice(0, 30),
1174
- sampleKeys: []
1349
+ text: "",
1350
+ encoding: "utf-8",
1351
+ invalidBytes: 0,
1352
+ binary: true,
1353
+ binaryReason: `${controlBytes} control byte(s) in ${buffer.length} B; valid UTF-8 but not text`
1175
1354
  };
1176
1355
  }
1177
1356
  return {
1178
- shape: typeof parsed,
1179
- itemCount: null,
1180
- keys: [],
1181
- sampleKeys: []
1357
+ text: new TextDecoder("utf-8").decode(buffer),
1358
+ encoding: "utf-8",
1359
+ invalidBytes: 0,
1360
+ binary: false
1182
1361
  };
1183
- } catch {
1362
+ }
1363
+ if (invalidBytes >= 32 && invalidBytes * 3 >= buffer.length) {
1184
1364
  return {
1185
- shape: "invalid-json",
1186
- itemCount: null,
1187
- keys: [],
1188
- sampleKeys: []
1365
+ text: "",
1366
+ encoding: "utf-8",
1367
+ invalidBytes,
1368
+ binary: true,
1369
+ binaryReason: `${invalidBytes} of ${buffer.length} bytes are not UTF-8; treated as binary`
1189
1370
  };
1190
1371
  }
1372
+ return {
1373
+ text: buffer.toString("utf8"),
1374
+ encoding: "utf-8-lossy",
1375
+ invalidBytes,
1376
+ binary: false
1377
+ };
1191
1378
  }
1192
- function summarizeMarkdown(content) {
1193
- const headings = [];
1194
- const frontmatterKeys = [];
1195
- const lines = content.replace(/^\uFEFF/, "").split("\n");
1196
- let inFrontmatter = false;
1197
- let fence = null;
1198
- let closesFrontmatter = false;
1199
- for (let index = 1; index < lines.length; index++) {
1200
- if (lines[index].trim() === "---") {
1201
- closesFrontmatter = true;
1202
- break;
1203
- }
1204
- }
1205
- for (let index = 0; index < lines.length; index++) {
1206
- const line = lines[index];
1207
- if (index === 0 && line.trim() === "---" && closesFrontmatter) {
1208
- inFrontmatter = true;
1209
- continue;
1210
- }
1379
+ var BINARY_SCAN_BYTES = 8 * 1024 * 1024;
1380
+ var CHUNK = 64 * 1024;
1381
+ var SHAPE_SAMPLE_BYTES = 4096;
1382
+ function isBinaryFile(absolutePath) {
1383
+ if (isBinaryExtension(absolutePath)) return true;
1384
+ let fd;
1385
+ try {
1386
+ fd = fs14__namespace.openSync(absolutePath, "r");
1387
+ const buffer = Buffer.alloc(CHUNK);
1388
+ let sample;
1389
+ let position = 0;
1390
+ while (position < BINARY_SCAN_BYTES) {
1391
+ const wanted = Math.min(CHUNK, BINARY_SCAN_BYTES - position);
1392
+ const bytesRead = fs14__namespace.readSync(fd, buffer, 0, wanted, position);
1393
+ if (bytesRead === 0) return false;
1394
+ const chunk = buffer.subarray(0, bytesRead);
1395
+ if (sample === void 0) {
1396
+ sample = Buffer.from(chunk.subarray(0, SHAPE_SAMPLE_BYTES));
1397
+ }
1398
+ if (chunk.includes(0)) {
1399
+ const shape = readBomEncoding(sample) ?? looksLikeUtf16(sample);
1400
+ return shape === null;
1401
+ }
1402
+ position += bytesRead;
1403
+ }
1404
+ return false;
1405
+ } catch {
1406
+ return false;
1407
+ } finally {
1408
+ if (fd !== void 0) {
1409
+ try {
1410
+ fs14__namespace.closeSync(fd);
1411
+ } catch {
1412
+ }
1413
+ }
1414
+ }
1415
+ }
1416
+
1417
+ // src/ast/imports.ts
1418
+ var SUMMARY_MAX_SOURCE_BYTES = 2 * 1024 * 1024;
1419
+ var TS_SOURCE_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
1420
+ var isTsSource = (relativePath) => {
1421
+ const lower = relativePath.toLowerCase();
1422
+ return TS_SOURCE_EXTENSIONS.some((extension) => lower.endsWith(extension));
1423
+ };
1424
+ function importsOfText(relativePath, text2) {
1425
+ if (Buffer.byteLength(text2, "utf8") > SUMMARY_MAX_SOURCE_BYTES) return [];
1426
+ if (isTsSource(relativePath)) return summarizeTypeScriptSource(relativePath, text2).imports;
1427
+ return summarizeWithProfile(relativePath, text2)?.summary.imports ?? [];
1428
+ }
1429
+ function importsOfFile(relativePath, absolutePath) {
1430
+ let buffer;
1431
+ try {
1432
+ const stats = fs14__namespace.statSync(absolutePath);
1433
+ if (!stats.isFile() || stats.size > SUMMARY_MAX_SOURCE_BYTES) return [];
1434
+ buffer = fs14__namespace.readFileSync(absolutePath);
1435
+ } catch {
1436
+ return [];
1437
+ }
1438
+ const decoded = decodeText(buffer);
1439
+ if (decoded.binary) return [];
1440
+ return importsOfText(relativePath, decoded.text);
1441
+ }
1442
+
1443
+ // src/ast/structured.ts
1444
+ function stripJsonComments(content) {
1445
+ const text2 = content.replace(/^\uFEFF/, "");
1446
+ const withoutComments = stripComments(text2);
1447
+ return stripTrailingCommas(withoutComments);
1448
+ }
1449
+ function stripComments(text2) {
1450
+ let out = "";
1451
+ let inString = false;
1452
+ let escaped = false;
1453
+ for (let index = 0; index < text2.length; index += 1) {
1454
+ const char = text2[index];
1455
+ if (inString) {
1456
+ out += char;
1457
+ if (escaped) escaped = false;
1458
+ else if (char === "\\") escaped = true;
1459
+ else if (char === '"') inString = false;
1460
+ continue;
1461
+ }
1462
+ if (char === '"') {
1463
+ inString = true;
1464
+ out += char;
1465
+ continue;
1466
+ }
1467
+ if (char === "/" && text2[index + 1] === "/") {
1468
+ while (index < text2.length && text2[index] !== "\n" && text2[index] !== "\r") index += 1;
1469
+ index -= 1;
1470
+ continue;
1471
+ }
1472
+ if (char === "/" && text2[index + 1] === "*") {
1473
+ index += 2;
1474
+ while (index < text2.length && !(text2[index] === "*" && text2[index + 1] === "/")) {
1475
+ if (text2[index] === "\n" || text2[index] === "\r") out += text2[index];
1476
+ index += 1;
1477
+ }
1478
+ index += 1;
1479
+ continue;
1480
+ }
1481
+ out += char;
1482
+ }
1483
+ return out;
1484
+ }
1485
+ function stripTrailingCommas(text2) {
1486
+ let out = "";
1487
+ let inString = false;
1488
+ let escaped = false;
1489
+ for (let index = 0; index < text2.length; index += 1) {
1490
+ const char = text2[index];
1491
+ if (inString) {
1492
+ out += char;
1493
+ if (escaped) escaped = false;
1494
+ else if (char === "\\") escaped = true;
1495
+ else if (char === '"') inString = false;
1496
+ continue;
1497
+ }
1498
+ if (char === '"') {
1499
+ inString = true;
1500
+ out += char;
1501
+ continue;
1502
+ }
1503
+ if (char === ",") {
1504
+ let next = index + 1;
1505
+ while (next < text2.length && /\s/.test(text2[next])) next += 1;
1506
+ if (text2[next] === "}" || text2[next] === "]") continue;
1507
+ }
1508
+ out += char;
1509
+ }
1510
+ return out;
1511
+ }
1512
+ function summarizeJson(content) {
1513
+ try {
1514
+ const parsed = JSON.parse(stripJsonComments(content));
1515
+ if (Array.isArray(parsed)) {
1516
+ const sample = parsed[0];
1517
+ const sampleKeys = sample && typeof sample === "object" && !Array.isArray(sample) ? Object.keys(sample).slice(0, 10).sort() : [];
1518
+ return {
1519
+ shape: "array",
1520
+ itemCount: parsed.length,
1521
+ keys: [],
1522
+ sampleKeys
1523
+ };
1524
+ }
1525
+ if (parsed && typeof parsed === "object") {
1526
+ const keys = Object.keys(parsed).sort();
1527
+ return {
1528
+ shape: "object",
1529
+ itemCount: keys.length,
1530
+ keys: keys.slice(0, 30),
1531
+ sampleKeys: []
1532
+ };
1533
+ }
1534
+ return {
1535
+ shape: typeof parsed,
1536
+ itemCount: null,
1537
+ keys: [],
1538
+ sampleKeys: []
1539
+ };
1540
+ } catch {
1541
+ return {
1542
+ shape: "invalid-json",
1543
+ itemCount: null,
1544
+ keys: [],
1545
+ sampleKeys: []
1546
+ };
1547
+ }
1548
+ }
1549
+ function frontMatterEnd(lines) {
1550
+ if (lines.length < 3 || lines[0].trim() !== "---") return 0;
1551
+ for (let index = 1; index < lines.length; index += 1) {
1552
+ const line = lines[index];
1553
+ const candidate = line.trim();
1554
+ if (candidate === "---" || candidate === "...") {
1555
+ return index > 1 ? index : 0;
1556
+ }
1557
+ if (candidate === "") continue;
1558
+ if (/^#(\s|$)/.test(candidate)) continue;
1559
+ if (/^(`{3,}|~{3,})/.test(candidate)) return 0;
1560
+ if (/^#{1,6}\s+\S/.test(candidate)) return 0;
1561
+ const isYamlMapping = /^[A-Za-z0-9_.-]+\s*:(\s|$)/.test(candidate);
1562
+ const isListItem = /^-(?:(\s|$))/.test(candidate);
1563
+ const isIndented = /^[ \t]/.test(line);
1564
+ if (!isYamlMapping && !isListItem && !isIndented) return 0;
1565
+ }
1566
+ return 0;
1567
+ }
1568
+ function summarizeMarkdown(content) {
1569
+ const headings = [];
1570
+ const frontmatterKeys = [];
1571
+ const lines = content.replace(/^\uFEFF/, "").split(/\r\n|\n|\r/);
1572
+ let inFrontmatter = false;
1573
+ let fence = null;
1574
+ const frontMatterEndLine = frontMatterEnd(lines);
1575
+ for (let index = 0; index < lines.length; index++) {
1576
+ const line = lines[index];
1577
+ if (index === 0 && frontMatterEndLine > 0) {
1578
+ inFrontmatter = true;
1579
+ continue;
1580
+ }
1211
1581
  if (inFrontmatter) {
1212
- if (line.trim() === "---") {
1582
+ const trimmedFrontmatter = line.trim();
1583
+ if (trimmedFrontmatter === "---" || trimmedFrontmatter === "...") {
1213
1584
  inFrontmatter = false;
1214
1585
  continue;
1215
1586
  }
1216
- const match = /^([a-zA-Z0-9_-]+):/.exec(line);
1587
+ const match = /^([A-Za-z0-9_.-]+)\s*:/.exec(line);
1217
1588
  if (match) frontmatterKeys.push(match[1]);
1218
1589
  continue;
1219
1590
  }
@@ -1246,24 +1617,39 @@ function hasCollapsibleBody(node) {
1246
1617
  return body !== void 0 && ts__default.default.isBlock(body);
1247
1618
  }
1248
1619
  function isTsxFileName(fileName) {
1249
- return fileName.toLowerCase().endsWith(".tsx");
1620
+ const lower = fileName.toLowerCase();
1621
+ return lower.endsWith(".tsx") || lower.endsWith(".jsx");
1622
+ }
1623
+ function scriptKindFor(fileName) {
1624
+ const lower = fileName.toLowerCase();
1625
+ if (lower.endsWith(".tsx")) return ts__default.default.ScriptKind.TSX;
1626
+ if (lower.endsWith(".jsx")) return ts__default.default.ScriptKind.JSX;
1627
+ if (lower.endsWith(".js") || lower.endsWith(".mjs") || lower.endsWith(".cjs")) {
1628
+ return ts__default.default.ScriptKind.JS;
1629
+ }
1630
+ return ts__default.default.ScriptKind.TS;
1250
1631
  }
1251
1632
  function skeletonizeTypeScript(source, fileName = "file.ts") {
1252
- const scriptKind = isTsxFileName(fileName) ? ts__default.default.ScriptKind.TSX : ts__default.default.ScriptKind.TS;
1253
1633
  const sourceFile = ts__default.default.createSourceFile(
1254
1634
  fileName,
1255
1635
  source,
1256
1636
  ts__default.default.ScriptTarget.Latest,
1257
- true,
1258
- scriptKind
1637
+ // `setParentNodes: false`. Nothing here reads `.parent` — the one `getStart` call is given the
1638
+ // source file explicitly, which is the reason that argument exists. Asking for parent pointers
1639
+ // makes the parser run a second full pass over every node in the file to set them, on top of
1640
+ // the summary parse this same file already pays for.
1641
+ false,
1642
+ scriptKindFor(fileName)
1259
1643
  );
1260
1644
  const spans = [];
1261
1645
  const visit = (node) => {
1262
1646
  if ((ts__default.default.isFunctionDeclaration(node) || ts__default.default.isMethodDeclaration(node) || ts__default.default.isConstructorDeclaration(node) || ts__default.default.isGetAccessorDeclaration(node) || ts__default.default.isSetAccessorDeclaration(node) || ts__default.default.isFunctionExpression(node) || ts__default.default.isArrowFunction(node)) && hasCollapsibleBody(node)) {
1263
1647
  const body = node.body;
1264
- const start = body.getStart(sourceFile);
1265
- const end = body.getEnd();
1266
- if (end > start) spans.push({ start, end });
1648
+ if (body.statements.length > 0) {
1649
+ const start = body.getStart(sourceFile);
1650
+ const end = body.getEnd();
1651
+ if (end > start) spans.push({ start, end });
1652
+ }
1267
1653
  }
1268
1654
  ts__default.default.forEachChild(node, visit);
1269
1655
  };
@@ -1275,16 +1661,21 @@ function skeletonizeTypeScript(source, fileName = "file.ts") {
1275
1661
  if (last && span.start < last.end) continue;
1276
1662
  outermost.push(span);
1277
1663
  }
1278
- let text2 = source;
1279
- for (let index = outermost.length - 1; index >= 0; index -= 1) {
1280
- const span = outermost[index];
1281
- text2 = `${text2.slice(0, span.start)}{ /* ... */ }${text2.slice(span.end)}`;
1664
+ const chunks = [];
1665
+ let cursor = 0;
1666
+ for (const span of outermost) {
1667
+ chunks.push(source.slice(cursor, span.start), "{ /* ... */ }");
1668
+ cursor = span.end;
1282
1669
  }
1283
- return { text: text2, collapsed: outermost.length };
1670
+ chunks.push(source.slice(cursor));
1671
+ return { text: chunks.join(""), collapsed: outermost.length };
1284
1672
  }
1285
1673
  function isSkeletonizable(filePath) {
1286
1674
  const lower = filePath.toLowerCase();
1287
- return lower.endsWith(".ts") || lower.endsWith(".tsx") || lower.endsWith(".mts") || lower.endsWith(".cts");
1675
+ if (lower.endsWith(".d.ts") || lower.endsWith(".d.mts") || lower.endsWith(".d.cts")) {
1676
+ return false;
1677
+ }
1678
+ 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");
1288
1679
  }
1289
1680
  var MANIFEST_FILES = [
1290
1681
  "package.json",
@@ -1448,6 +1839,14 @@ function scanWorkspacePackages(cwd, patterns) {
1448
1839
  }
1449
1840
  return { files, dependencies };
1450
1841
  }
1842
+ var SNAPSHOT_MARKER = ".codebase-snapshot";
1843
+ function isToolOwnedDirectory(dir) {
1844
+ try {
1845
+ return fs14__namespace.statSync(dir).isDirectory() && fs14__namespace.existsSync(path16__namespace.join(dir, SNAPSHOT_MARKER));
1846
+ } catch {
1847
+ return false;
1848
+ }
1849
+ }
1451
1850
  function countMarkdownFiles(cwd) {
1452
1851
  let count = 0;
1453
1852
  let directoriesSeen = 0;
@@ -1469,7 +1868,9 @@ function countMarkdownFiles(cwd) {
1469
1868
  }
1470
1869
  if (!entry.isDirectory() || current.depth >= 2) continue;
1471
1870
  if (entry.name.startsWith(".") || SKIPPED_WALK_DIRS.has(entry.name)) continue;
1472
- queue.push({ dir: path16__namespace.join(current.dir, entry.name), depth: current.depth + 1 });
1871
+ const child = path16__namespace.join(current.dir, entry.name);
1872
+ if (isToolOwnedDirectory(child)) continue;
1873
+ queue.push({ dir: child, depth: current.depth + 1 });
1473
1874
  }
1474
1875
  }
1475
1876
  return count;
@@ -2338,18 +2739,24 @@ function detectPreset(cwd, forced) {
2338
2739
  }
2339
2740
 
2340
2741
  // src/security/patterns.ts
2341
- 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)";
2342
- var WEAK_CREDENTIAL_NAME = "(?:pass|id[_-]?token|credentials?)";
2742
+ 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)";
2743
+ var WEAK_CREDENTIAL_NAME = "(?:pass|credentials?)";
2343
2744
  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)";
2344
2745
  var UNQUOTED_MIN_LENGTH = 2;
2345
2746
  var PROSE_CONTINUATION = String.raw`(?!\s+[a-z])`;
2346
- 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;
2347
- 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;
2747
+ var UNQUOTED_VALUE_CHARS = String.raw`A-Za-z0-9_+=/%:~$!@#^*?-`;
2748
+ var UNQUOTED_VALUE_END = String.raw`[A-Za-z0-9_+=/%:.~$!@#^*?-]`;
2749
+ var UNQUOTED_VALUE_START = String.raw`[$!@#%^&*~+]`;
2750
+ var UNQUOTED_LITERAL = String.raw`(` + // one capture, whichever branch matched: valueGroup is 1
2751
+ 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;
2752
+ 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;
2348
2753
  var ASSIGN = String.raw`(?<![=!<>])[:=](?!=)`;
2349
2754
  var NOT_AFTER_QUOTE = String.raw`(?<!["'])`;
2350
2755
  var NOT_A_NAMESPACED_IDENTIFIER = String.raw`(?![a-z][a-z0-9]*(?:\.[a-z][a-z0-9-]*)+/)`;
2756
+ var QUOTED_CREDENTIAL_KEY = `["'](?!id[-_]token["'])[A-Za-z0-9_$-]{0,64}${STRONG_CREDENTIAL_NAME}["']`;
2351
2757
  var QUOTED_VALUE = String.raw`((?:[^"'\\\n]|\\\\["'](?=[A-Za-z0-9_])|\\.){1,512})`;
2352
2758
  var UNQUOTED_STRONG_NAME = `(?<!id[-_])${STRONG_CREDENTIAL_NAME}`;
2759
+ var CREDENTIAL_KEY_TAIL = new RegExp(`(?:${STRONG_CREDENTIAL_NAME})$`, "i");
2353
2760
  var DEFAULT_SECRET_PATTERNS = [
2354
2761
  {
2355
2762
  rule: "private-key-header",
@@ -2416,13 +2823,28 @@ var DEFAULT_SECRET_PATTERNS = [
2416
2823
  pattern: /xox[baprsdc]-[0-9A-Za-z-]{10,250}/
2417
2824
  },
2418
2825
  {
2419
- // Prefix-only vendors. Each prefix below is documented, globally unique and
2420
- // cannot collide with an ordinary identifier, which is what makes a bare
2421
- // prefix rule cheap and safe: `glpat-` (GitLab), `hvs.`/`s.` (Vault service
2422
- // and batch tokens), `whsec_` (Stripe webhook secret), `dckr_pat_` (Docker
2423
- // Hub), `hf_` (HuggingFace), `ya29.` (Google OAuth access token).
2826
+ // Known vendor token shapes: prefix-unique tokens, plus the few fixed layouts whose format is
2827
+ // documented and cannot collide with an ordinary identifier.
2828
+ //
2829
+ // Each prefix below is globally unique, which is what makes a bare prefix rule cheap and
2830
+ // safe: `glpat-` (GitLab), `hvs.`/`s.` (Vault service and batch tokens), `whsec_`
2831
+ // (Stripe webhook secret), `dckr_pat_` (Docker Hub), `hf_` (HuggingFace), `ya29.`
2832
+ // (Google OAuth access token), `shpat_`/`shpca_`/`shppa_`/`shpss_` (Shopify admin and
2833
+ // storefront tokens).
2834
+ //
2835
+ // The fixed shapes have no prefix to anchor on and were each emitted in clear:
2836
+ // - Telegram bot token: `<8-10 digit bot id>:<35-character secret>`.
2837
+ // - Discord bot token: `<base64 user id>.<6-8 char hmac>.<25-45 char signature>`; demanding
2838
+ // all three segments keeps ordinary dotted identifiers out.
2839
+ // - Azure DevOps personal access token: exactly 52 alphanumerics that always mix case and
2840
+ // digits, so a hash, a UUID or a plain identifier — all single-case or a different length —
2841
+ // does not match.
2842
+ //
2843
+ // The rule name still says "prefix" because that is how the catalogue began; it is the
2844
+ // vendor-token rule, and growing a new named rule per vendor would make the documented
2845
+ // pattern count drift on every release.
2424
2846
  rule: "known-vendor-token-prefix",
2425
- 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})/
2847
+ 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])/
2426
2848
  },
2427
2849
  {
2428
2850
  rule: "slack-webhook-url",
@@ -2477,39 +2899,52 @@ var DEFAULT_SECRET_PATTERNS = [
2477
2899
  // (including one invented tomorrow) is covered, provided the `//` is followed
2478
2900
  // immediately by the userinfo: `// see the docs` and a bare reminder comment
2479
2901
  // never match, because a space or the comment wording breaks the shape.
2902
+ //
2903
+ // Three shapes joined it, all the same fact — a URL carries the credential in plain sight —
2904
+ // and each cost a leak while it was elsewhere:
2905
+ // - The user part may be **empty**: Redis, SMTP, AMQP and FTP URLs routinely omit the username
2906
+ // (`redis://:password@host`), and a `{1,128}` prefix made every one of those invisible.
2907
+ // - `curl -u user:password` sends the same userinfo without a scheme; the lookbehind
2908
+ // consumes the flag so the match is the credential alone.
2909
+ // - An Azure SAS link authenticates with `?sig=`; the signature *is* the credential.
2480
2910
  rule: "uri-credentials",
2481
- pattern: /\/\/[^\s:/@"'`;()<>,]{1,128}:[^\s:/@"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/
2911
+ 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%._=~-])/
2482
2912
  },
2483
2913
  {
2484
2914
  // The host tail stops at quotes, `;`, `)`, `<`, `>` and `,`: an unbounded
2485
2915
  // `[^\s/]` used to swallow the closing quote and the statement separator of
2486
2916
  // the string the URL was written in.
2917
+ // The user part may be empty here too: `redis://:password@host` and `amqp://:password@host`
2918
+ // are how those services are configured when the account is the server's default.
2487
2919
  rule: "database-uri-credentials",
2488
- 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}/
2920
+ 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}/
2489
2921
  },
2490
2922
  {
2923
+ // An empty user part is valid userinfo (`smtp://:password@host`: the account is the server's
2924
+ // default), and it used to be the one shape every scheme-listed rule refused.
2491
2925
  rule: "basic-auth-url",
2492
- pattern: /(?:https?|ftp|sftp|ssh|git|smtp|smtps|ldap|ldaps):\/\/[^\s:@/"'`;()<>,]{1,128}:[^\s@/"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/i
2926
+ pattern: /(?:https?|ftp|sftp|ssh|git|smtp|smtps|ldap|ldaps):\/\/[^\s:@/"'`;()<>,]{0,128}:[^\s@/"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/i
2493
2927
  },
2494
2928
  {
2495
2929
  // Quoted credentials in any common key spelling. The value may be as short
2496
2930
  // as one character: `password: "hunter2"` is a credential whatever its
2497
2931
  // entropy, and a length floor was exactly how it survived into `parts`.
2498
2932
  //
2499
- // The key is either bare (`dbPassword:`) or wholly quoted (`"dbPassword":`).
2933
+ // The key is bare (`dbPassword:`), wholly quoted (`"password":`), or quoted with a
2934
+ // camelCase prefix (`"dbPassword":`) — the last one is {@link QUOTED_CREDENTIAL_KEY}.
2500
2935
  // There is deliberately no optional quote *before* the separator: that let a
2501
2936
  // previous string's closing quote stand in for the key's, so
2502
2937
  // ``${pass ? " PASS" : " FAIL"}`` had `" FAIL"` masked as if `PASS` were
2503
2938
  // the key name.
2504
2939
  rule: "credential-assignment",
2505
2940
  pattern: new RegExp(
2506
- `(?:["']${STRONG_CREDENTIAL_NAME}["']|${NOT_AFTER_QUOTE}${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_NAMESPACED_IDENTIFIER}(["'\`])${QUOTED_VALUE}\\1`,
2941
+ `(?:${QUOTED_CREDENTIAL_KEY}|${NOT_AFTER_QUOTE}(?<!id[-_])${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_NAMESPACED_IDENTIFIER}(["'\`])${QUOTED_VALUE}\\1`,
2507
2942
  "i"
2508
2943
  ),
2509
2944
  valueGroup: 2
2510
2945
  },
2511
2946
  {
2512
- // `pass`, `id-token` and `credentials` are ambiguous on their own, so they
2947
+ // `pass` and `credentials` are ambiguous on their own, so they
2513
2948
  // are accepted only against a quoted value long enough to be a credential.
2514
2949
  rule: "credential-assignment-weak",
2515
2950
  pattern: new RegExp(
@@ -2522,9 +2957,40 @@ var DEFAULT_SECRET_PATTERNS = [
2522
2957
  // The unquoted twin for YAML, docker-compose and `.env`: those formats never
2523
2958
  // quote their values, so the rules above cannot see them. `valueGroup` keeps
2524
2959
  // `POSTGRES_PASSWORD:` in the output.
2960
+ //
2961
+ // This is the one unquoted rule without `NOT_AFTER_QUOTE`, and the lookbehind is a
2962
+ // string-literal guard rather than a precision rule: a credential assignment *inside* a
2963
+ // literal — `const dsn = "password=hunter2;host=db"`, `curl -d "password=hunter2"` — was
2964
+ // rejected before it could be considered, and a DSN is a credential in a string. What made the
2965
+ // lookbehind redundant is the shape of `UNQUOTED_LITERAL`: a value has to start with a word
2966
+ // character, so `["awsSecret:", "apiKey:"]` — the list of key names the lookbehind was added
2967
+ // for — cannot match here anyway. `redact.ts` still refuses a match whose separator is inside
2968
+ // the literal, which is the case that list actually is.
2969
+ //
2970
+ // The name may also be a *quoted* key: YAML allows `"dbPassword": hunter2`, and JSON cannot
2971
+ // spell a key any other way, so the same {@link QUOTED_CREDENTIAL_KEY} fragment is used here.
2972
+ // Without it a quoted key whose value was not quoted emitted the value in clear.
2973
+ //
2974
+ // A colon-form assignment in a data file masks the whole remainder of the value to
2975
+ // end-of-line, whatever punctuation it holds. A strong credential name is the evidence that
2976
+ // the thing after it is a value, and the character classes above cannot cover every symbol a
2977
+ // password may contain — `password: pa&ss` used to stop at the `&`. This branch is a
2978
+ // lookbehind, so the match is the value alone, and `redact.ts` only applies it to a data or
2979
+ // shell file: in source code the same shape is an expression and stays untouched, and an `URL`
2980
+ // query string keeps its `&` separators because they are not a colon form.
2981
+ //
2982
+ // The `KEY=value` twin does the same for the `=` form, which INI, .properties and shell files
2983
+ // use: with a credential key the whole value is masked whatever symbols it contains
2984
+ // (`password=pa&ss`, `token=a<b`, `client_secret=x|y`). The value is bounded by whitespace
2985
+ // (end of line, or the space before a `# comment`), not by a symbol class — `envpass!@#$%^&*()` used
2986
+ // to stop before the parenthesis and leave the tail in clear. The lookbehind matches the value
2987
+ // alone and `redact.ts` decides, from the file and from the key, whether the line is an
2988
+ // assignment (it must be a data/shell file, the key must end in a credential name, and a URL
2989
+ // query parameter or `$VARIABLE` reference is not an assignment).
2525
2990
  rule: "credential-assignment-unquoted",
2526
2991
  pattern: new RegExp(
2527
- `${NOT_AFTER_QUOTE}${UNQUOTED_STRONG_NAME}\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_LITERAL_VALUE}${UNQUOTED_LITERAL}`,
2992
+ `(?:${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
2993
+ #]{1,300}`,
2528
2994
  "i"
2529
2995
  ),
2530
2996
  valueGroup: 1
@@ -2547,8 +3013,14 @@ var DEFAULT_SECRET_PATTERNS = [
2547
3013
  // needs no `valueGroup`. A lone `Bearer`/`Basic`, and a word after it that
2548
3014
  // cannot be a credential (`Bearer authentication`), stay readable: the value
2549
3015
  // must contain a digit, be at least 32 chars, or carry base64 `=` padding.
3016
+ //
3017
+ // A fourth shape was leaking: `Basic dXNlcjpwYXNz` is the base64 of `user:pass` — 12
3018
+ // characters, no digit, no padding — and the three tests above all said "not a
3019
+ // credential", so it reached the parts in clear. Mixed case is the discriminator: a base64
3020
+ // rendering of textual userinfo mixes cases, while the prose the earlier rules were
3021
+ // protecting (`Bearer authentication`) is a lowercase word.
2550
3022
  rule: "authorization-header",
2551
- 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_.+/=-])/
3023
+ 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_.+/=-])/
2552
3024
  },
2553
3025
  {
2554
3026
  // Broader names than before (`apiKey`, `clientSecret`, `privateKey` were
@@ -2559,6 +3031,27 @@ var DEFAULT_SECRET_PATTERNS = [
2559
3031
  pattern: /(?<!["'])(?:api[_-]?key|secret[_-]?key|auth[_-]?token|client[_-]?secret|access[_-]?token|refresh[_-]?token|private[_-]?key|password|passwd|pwd)["']?\s*(?<![=!<>])[:=](?!=)\s*["']([^"'\s]{8,256})["']/i,
2560
3032
  valueGroup: 1
2561
3033
  },
3034
+ {
3035
+ // `${VAR:-fallback}` — a default value in a shell script, a `.env`, docker-compose or a
3036
+ // GitHub Actions workflow.
3037
+ //
3038
+ // This shape defeated every rule above it, and each refusal was individually reasonable:
3039
+ // the quoted rules need a quote after the separator, and the unquoted ones need the value to
3040
+ // begin with a word character — a fallback begins with `$`. So
3041
+ // `POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-MyProdPassword123!}` was emitted whole, `.env` files
3042
+ // and compose files included, which is where that idiom is the norm.
3043
+ //
3044
+ // The **fallback** is what gets masked, not the whole expansion: the variable name is the
3045
+ // readable context, exactly as `POSTGRES_PASSWORD:` is kept by the rule above. A single
3046
+ // interpolation with no operator (`${DB_PASSWORD}`) still does not match — there is nothing
3047
+ // between the braces to mask, and `isTemplateInterpolation` keeps such a value readable.
3048
+ rule: "interpolation-fallback-secret",
3049
+ pattern: new RegExp(
3050
+ `(?:["']${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})\\}["'\`]?`,
3051
+ "i"
3052
+ ),
3053
+ valueGroup: 1
3054
+ },
2562
3055
  {
2563
3056
  // Covers `.env` / shell assignment syntax, which never quotes its values and
2564
3057
  // was therefore invisible to the rule above. Anchored to the line start and
@@ -2586,8 +3079,8 @@ var DEFAULT_SECRET_PATTERNS = [
2586
3079
  valueGroup: 1
2587
3080
  }
2588
3081
  ];
2589
- var PEM_BLOCK_PATTERN = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----/g;
2590
- var PEM_UNTERMINATED_PATTERN = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----(?:\r?\n[A-Za-z0-9+/=]{4,}[ A-Za-z0-9+/=]*)+/g;
3082
+ var PEM_BLOCK_PATTERN = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----(?:(?!-----BEGIN)[\s\S])*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----/g;
3083
+ 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;
2591
3084
 
2592
3085
  // src/security/redact.ts
2593
3086
  var REDACTION_MARKER = "[REDACTED: potential secret-like value omitted from snapshot]";
@@ -2681,6 +3174,20 @@ function toGlobal(rule) {
2681
3174
  return new RegExp(rule.pattern.source, [...flags].join(""));
2682
3175
  }
2683
3176
  var LINE_BREAK = /(\r\n|\n|\r)/;
3177
+ var LINE_TERMINATOR = /\r\n|\n|\r/g;
3178
+ var COMPILED_RULES = /* @__PURE__ */ new WeakMap();
3179
+ function compiledRuleFor(rule) {
3180
+ let compiled = COMPILED_RULES.get(rule);
3181
+ if (compiled === void 0) {
3182
+ compiled = {
3183
+ rule: rule.rule,
3184
+ pattern: toGlobal(rule),
3185
+ ...rule.valueGroup === void 0 ? {} : { valueGroup: rule.valueGroup }
3186
+ };
3187
+ COMPILED_RULES.set(rule, compiled);
3188
+ }
3189
+ return compiled;
3190
+ }
2684
3191
  function scanAndRedactSecrets(content, rules, filePath) {
2685
3192
  const findings = [];
2686
3193
  let redacted = content;
@@ -2692,18 +3199,15 @@ function scanAndRedactSecrets(content, rules, filePath) {
2692
3199
  blockPattern.lastIndex += 1;
2693
3200
  continue;
2694
3201
  }
2695
- const line = redacted.slice(0, match.index).split("\n").length;
2696
- const newlines = (match[0].match(/\n/g) ?? []).length;
3202
+ const before = redacted.slice(0, match.index);
3203
+ const line = (before.match(LINE_TERMINATOR) ?? []).length + 1;
3204
+ const newlines = (match[0].match(LINE_TERMINATOR) ?? []).length;
2697
3205
  findings.push({ rules: ["private-key-block"], line, path: filePath });
2698
- redacted = redacted.slice(0, match.index) + PEM_REDACTION_MARKER + "\n".repeat(newlines) + redacted.slice(match.index + match[0].length);
3206
+ redacted = before + PEM_REDACTION_MARKER + "\n".repeat(newlines) + redacted.slice(match.index + match[0].length);
2699
3207
  blockPattern.lastIndex = match.index + PEM_REDACTION_MARKER.length + newlines;
2700
3208
  }
2701
3209
  }
2702
- const compiled = rules.map((rule) => ({
2703
- rule: rule.rule,
2704
- pattern: toGlobal(rule),
2705
- ...rule.valueGroup === void 0 ? {} : { valueGroup: rule.valueGroup }
2706
- }));
3210
+ const compiled = rules.map(compiledRuleFor);
2707
3211
  const segments = redacted.split(LINE_BREAK);
2708
3212
  let lineNumber = 1;
2709
3213
  for (let index = 0; index < segments.length; index += 2) {
@@ -2721,11 +3225,39 @@ function scanAndRedactSecrets(content, rules, filePath) {
2721
3225
  }
2722
3226
  const group = valueGroup === void 0 ? void 0 : match.indices?.[valueGroup];
2723
3227
  if (group && isSelfNamingConstant(line, group[0], group[1])) continue;
2724
- if (valueGroup !== void 0 && startsInsideStringLiteral(line, match.index)) continue;
2725
- if (group && isUnquotedValue(line, group[0]) && isDeclaredBinding(line, match.index)) {
3228
+ if (valueGroup !== void 0 && startsInsideStringLiteral(line, match.index, group?.[0])) {
3229
+ continue;
3230
+ }
3231
+ if (group && isUnquotedValue(line, group[0]) && isDeclaredBinding(line, match.index, filePath)) {
2726
3232
  continue;
2727
3233
  }
2728
3234
  if (group && isTemplateInterpolation(line, group[0], group[1])) continue;
3235
+ if (group && isUnquotedValue(line, group[0]) && TRUNCATING_VALUE_CHARS.test(line[group[1]] ?? "")) {
3236
+ continue;
3237
+ }
3238
+ if (valueGroup !== void 0 && group === void 0) {
3239
+ if (!isAssignmentFile(filePath)) continue;
3240
+ const assignment = assignmentAround(line, match.index);
3241
+ if (assignment.form === "=" && (assignment.reference || assignment.key === null || !CREDENTIAL_KEY_TAIL.test(assignment.key))) {
3242
+ continue;
3243
+ }
3244
+ }
3245
+ if (group && isUnquotedValue(line, group[0]) && OPENER_LED_VALUE.test(line.slice(group[0], group[1])) && !isAssignmentFile(filePath)) {
3246
+ continue;
3247
+ }
3248
+ if (group && isUnquotedValue(line, group[0])) {
3249
+ const assignment = assignmentAround(line, group[0]);
3250
+ const wholeValue = isAssignmentFile(filePath) && assignment.form !== null && !assignment.reference && !assignment.urlValue;
3251
+ if (wholeValue) {
3252
+ spans.push({
3253
+ start: group[0],
3254
+ end: Math.max(group[1], tokenEnd(line, group[0])),
3255
+ rule
3256
+ });
3257
+ matchedRules.add(rule);
3258
+ continue;
3259
+ }
3260
+ }
2729
3261
  spans.push(
2730
3262
  group ? { start: group[0], end: group[1], rule } : { start: match.index, end: match.index + match[0].length, rule }
2731
3263
  );
@@ -2743,6 +3275,8 @@ function scanAndRedactSecrets(content, rules, filePath) {
2743
3275
  }
2744
3276
  var TOKEN_CHARS_LEFT = /[A-Za-z0-9_+/-]/;
2745
3277
  var TOKEN_CHARS_RIGHT = /[A-Za-z0-9_+/=-]/;
3278
+ var TRUNCATING_VALUE_CHARS = /[<>|\\]/;
3279
+ var OPENER_LED_VALUE = /^[(\\[{]/;
2746
3280
  function expandOverToken(line, start, end) {
2747
3281
  let left = start;
2748
3282
  let right = end;
@@ -2755,14 +3289,20 @@ function expandOverToken(line, start, end) {
2755
3289
  while (right < line.length && TOKEN_CHARS_RIGHT.test(line[right])) right += 1;
2756
3290
  return { start: left, end: right };
2757
3291
  }
2758
- function startsInsideStringLiteral(line, matchIndex) {
3292
+ function startsInsideStringLiteral(line, matchIndex, valueStart) {
2759
3293
  let runStart = matchIndex;
2760
3294
  while (runStart > 0 && /[A-Za-z0-9_-]/.test(line[runStart - 1])) runStart -= 1;
2761
3295
  const before = runStart > 0 ? line[runStart - 1] : "";
2762
- return before === '"' || before === "'" || before === "`";
3296
+ if (before !== '"' && before !== "'" && before !== "`") return false;
3297
+ if (valueStart === void 0) return true;
3298
+ return /["'`]/.test(line.slice(matchIndex, valueStart));
2763
3299
  }
2764
3300
  function isTemplateInterpolation(line, start, end) {
2765
- return line[start] === "$" && line[start + 1] === "{" && line[end - 1] === "}";
3301
+ if (line[start] !== "$" || line[start + 1] !== "{" || line[end - 1] !== "}") {
3302
+ return false;
3303
+ }
3304
+ const inner = line.slice(start + 2, end - 1).trim();
3305
+ return /^[A-Za-z_$][A-Za-z0-9_$.()[\]]*$/.test(inner);
2766
3306
  }
2767
3307
  function isSelfNamingConstant(line, start, end) {
2768
3308
  const value = line.slice(start, end);
@@ -2783,13 +3323,48 @@ function isSelfNamingConstant(line, start, end) {
2783
3323
  }
2784
3324
  return line.endsWith(value, index);
2785
3325
  }
3326
+ function assignmentAround(line, valueStart) {
3327
+ let index = valueStart;
3328
+ while (index > 0 && (line[index - 1] === " " || line[index - 1] === " ")) index -= 1;
3329
+ const separator = index > 0 ? line[index - 1] : "";
3330
+ if (separator !== ":" && separator !== "=") {
3331
+ return { form: null, key: null, reference: false, rhsStart: -1, urlValue: false };
3332
+ }
3333
+ const separatorIndex = index - 1;
3334
+ index = separatorIndex;
3335
+ while (index > 0 && (line[index - 1] === " " || line[index - 1] === " ")) index -= 1;
3336
+ const keyEnd = index;
3337
+ while (index > 0 && /[A-Za-z0-9_$.-]/.test(line[index - 1])) index -= 1;
3338
+ const key = line.slice(index, keyEnd).replace(/^-+/, "");
3339
+ const before = index > 0 ? line[index - 1] : "";
3340
+ const reference = before === "?" || before === "&" || before === "$" || before === '"' || before === "'" || before === "`";
3341
+ let rhsStart = separatorIndex + 1;
3342
+ while (rhsStart < line.length && (line[rhsStart] === " " || line[rhsStart] === " ")) rhsStart += 1;
3343
+ const urlValue = /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(line.slice(rhsStart, tokenEnd(line, rhsStart)));
3344
+ return { form: separator === ":" ? ":" : "=", key, reference, rhsStart, urlValue };
3345
+ }
3346
+ function tokenEnd(line, start) {
3347
+ let end = start;
3348
+ while (end < line.length && !/\s/.test(line[end])) end += 1;
3349
+ return end;
3350
+ }
2786
3351
  function isUnquotedValue(line, start) {
2787
3352
  const before = start > 0 ? line[start - 1] : "";
2788
3353
  return before !== '"' && before !== "'" && before !== "`";
2789
3354
  }
2790
- var DECLARATION_KEYWORDS = /\b(?:const|let|var|readonly|public|private|protected|static|declare|export|using)\s+$/;
3355
+ var DECLARATION_KEYWORDS = /\b(?:const|let|var|readonly|public|private|protected|static|using)\s+$/;
3356
+ var ASSIGNMENT_FILE = /\.(?:sh|bash|zsh|ksh|fish|env|ya?ml|toml|ini|conf|cfg|properties|tf|tfvars|service)$/i;
3357
+ var ASSIGNMENT_BASENAME = /^(?:\.env(?:\.[^/]*)?|\.envrc|\.profile|\.bashrc|\.zshrc|\.bash_profile)$/i;
3358
+ function isAssignmentFile(filePath) {
3359
+ if (filePath === void 0) return false;
3360
+ const normalised = filePath.replace(/\\/g, "/");
3361
+ if (ASSIGNMENT_FILE.test(normalised)) return true;
3362
+ const base = normalised.slice(normalised.lastIndexOf("/") + 1);
3363
+ return ASSIGNMENT_BASENAME.test(base);
3364
+ }
2791
3365
  var DECLARATION_WINDOW = 40;
2792
- function isDeclaredBinding(line, matchIndex) {
3366
+ function isDeclaredBinding(line, matchIndex, filePath) {
3367
+ if (isAssignmentFile(filePath)) return false;
2793
3368
  let runStart = matchIndex;
2794
3369
  while (runStart > 0 && /[A-Za-z0-9_$]/.test(line[runStart - 1])) runStart -= 1;
2795
3370
  const from = Math.max(0, runStart - DECLARATION_WINDOW);
@@ -2831,6 +3406,15 @@ function readLinkTarget(linkPath, fallback) {
2831
3406
  return fallback;
2832
3407
  }
2833
3408
  }
3409
+ function brokenLinkRecord(linkPath, relativePath, rootReal) {
3410
+ const rawTarget = readLinkTarget(linkPath, linkPath);
3411
+ const resolvedFallback = path16__namespace.resolve(path16__namespace.dirname(linkPath), rawTarget);
3412
+ return isInside(rootReal, resolvedFallback) ? { path: relativePath, reason: "read-error", detail: "broken symlink" } : {
3413
+ path: relativePath,
3414
+ reason: "outside-root",
3415
+ detail: `link target resolves outside the scanned root (target: ${rawTarget}); not followed`
3416
+ };
3417
+ }
2834
3418
  function isInside(root, candidate) {
2835
3419
  const relative8 = path16__namespace.relative(root, candidate);
2836
3420
  return relative8 === "" || !relative8.startsWith(`..${path16__namespace.sep}`) && relative8 !== ".." && !path16__namespace.isAbsolute(relative8);
@@ -2920,6 +3504,13 @@ function isSensitivePath(relativePath) {
2920
3504
  return matchesSensitiveList(posixPath, base);
2921
3505
  }
2922
3506
  var GLOBAL_PATTERNS = /* @__PURE__ */ new WeakMap();
3507
+ var GLOB_REGEX_CACHE = /* @__PURE__ */ new Map();
3508
+ var GITIGNORE_REGEX_CACHE = /* @__PURE__ */ new Map();
3509
+ var REGEX_CACHE_LIMIT = 4096;
3510
+ function rememberCompiled(cache, key, value) {
3511
+ if (cache.size >= REGEX_CACHE_LIMIT) cache.clear();
3512
+ cache.set(key, value);
3513
+ }
2923
3514
  function globalPattern(pattern) {
2924
3515
  let compiled = GLOBAL_PATTERNS.get(pattern);
2925
3516
  if (compiled === void 0) {
@@ -2930,8 +3521,8 @@ function globalPattern(pattern) {
2930
3521
  }
2931
3522
  var DEFAULT_PATH_RULES = [...DEFAULT_SECRET_PATTERNS];
2932
3523
  function pathScanRules(extraRules) {
2933
- if (extraRules === void 0 || extraRules.length === 0) return DEFAULT_PATH_RULES;
2934
- return [...DEFAULT_SECRET_PATTERNS, ...extraRules];
3524
+ if (extraRules === void 0) return DEFAULT_PATH_RULES;
3525
+ return extraRules;
2935
3526
  }
2936
3527
  function findSecretInPath(relativePath, extraRules) {
2937
3528
  const posixPath = relativePath.replace(/\\/g, "/");
@@ -2980,11 +3571,22 @@ function maskSkipPaths(records, extraRules) {
2980
3571
  });
2981
3572
  }
2982
3573
  function globToRegExp(glob) {
3574
+ const cached = GLOB_REGEX_CACHE.get(glob);
3575
+ if (cached !== void 0) return cached;
2983
3576
  const normalized = glob.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
2984
3577
  const anchored = normalized.startsWith("/");
2985
3578
  const body = anchored ? normalized.slice(1) : normalized;
2986
3579
  const prefix = anchored || body.includes("/") ? "^" : "(?:^|.*/)";
2987
- return new RegExp(`${prefix}${globBodyToRegExp(body, true)}(?:/.*)?$`);
3580
+ let compiled;
3581
+ try {
3582
+ compiled = new RegExp(`${prefix}${globBodyToRegExp(body, true)}(?:/.*)?$`);
3583
+ } catch (error) {
3584
+ throw new Error(
3585
+ `"${glob}" is not a valid glob: ${error.message}. A character class must be ascending, as in "[a-z]".`
3586
+ );
3587
+ }
3588
+ rememberCompiled(GLOB_REGEX_CACHE, glob, compiled);
3589
+ return compiled;
2988
3590
  }
2989
3591
  function globBodyToRegExp(body, allowBraces) {
2990
3592
  let out = "";
@@ -3096,6 +3698,14 @@ function escapeRegExpChar(character) {
3096
3698
  return /[\\^$.*+?()[\]{}|/]/.test(character) ? `\\${character}` : character;
3097
3699
  }
3098
3700
  function matchGitignorePattern(target, pattern) {
3701
+ let compiled = GITIGNORE_REGEX_CACHE.get(pattern);
3702
+ if (compiled === void 0) {
3703
+ compiled = compileGitignorePattern(pattern);
3704
+ rememberCompiled(GITIGNORE_REGEX_CACHE, pattern, compiled);
3705
+ }
3706
+ return compiled.test(target);
3707
+ }
3708
+ function compileGitignorePattern(pattern) {
3099
3709
  const anchored = pattern.startsWith("/");
3100
3710
  const body = anchored ? pattern.slice(1) : pattern;
3101
3711
  let source = "";
@@ -3144,7 +3754,11 @@ function matchGitignorePattern(target, pattern) {
3144
3754
  source += escapeRegExpChar(character);
3145
3755
  }
3146
3756
  const prefix = anchored || body.includes("/") ? "^" : "(?:^|.*/)";
3147
- return new RegExp(`${prefix}${source}(?:/.*)?$`).test(target);
3757
+ try {
3758
+ return new RegExp(`${prefix}${source}(?:/.*)?$`);
3759
+ } catch {
3760
+ return /$^/;
3761
+ }
3148
3762
  }
3149
3763
  function matchesGitignoreRule(rule, scoped, isDirectory) {
3150
3764
  if (!rule.dirOnly) return matchGitignorePattern(scoped, rule.pattern);
@@ -3174,14 +3788,31 @@ function gitignoreVerdict(layers, relativePath, isDirectory) {
3174
3788
  }
3175
3789
  return verdict;
3176
3790
  }
3177
- function defaultIgnoreReason(relativePath) {
3791
+ var DEFAULT_TOOL_DIR_NAMES = ["snapshot"];
3792
+ function toolDirNamesFor(toolOwnedPaths) {
3793
+ const names = new Set(DEFAULT_TOOL_DIR_NAMES);
3794
+ for (const entry of toolOwnedPaths) {
3795
+ const base = entry.replace(/\\/g, "/").replace(/\/+$/, "").split("/").pop();
3796
+ if (base !== void 0 && base.length > 0) names.add(base);
3797
+ }
3798
+ return [...names];
3799
+ }
3800
+ function isToolLeftoverName(name, dirNames) {
3801
+ for (const dirName of dirNames) {
3802
+ if (name.startsWith(`${dirName}.backup-`) || name.startsWith(`${dirName}.partial-`)) {
3803
+ return true;
3804
+ }
3805
+ }
3806
+ return false;
3807
+ }
3808
+ function defaultIgnoreReason(relativePath, toolDirNames = DEFAULT_TOOL_DIR_NAMES) {
3178
3809
  const posixPath = relativePath.replace(/\\/g, "/");
3179
3810
  const parts = posixPath.split("/");
3180
3811
  for (let i = 0; i < parts.length - 1; i++) {
3181
3812
  if (DEFAULT_IGNORED_DIRS.includes(parts[i])) {
3182
3813
  return `built-in ignore: directory "${parts[i]}"`;
3183
3814
  }
3184
- if (parts[i].startsWith("snapshot.backup-")) {
3815
+ if (isToolLeftoverName(parts[i], toolDirNames)) {
3185
3816
  return `built-in ignore: leftover snapshot backup "${parts[i]}"`;
3186
3817
  }
3187
3818
  }
@@ -3189,6 +3820,9 @@ function defaultIgnoreReason(relativePath) {
3189
3820
  if (DEFAULT_IGNORED_FILES.includes(base)) {
3190
3821
  return `built-in ignore: filename "${base}"`;
3191
3822
  }
3823
+ if (isToolLeftoverName(base, toolDirNames)) {
3824
+ return `built-in ignore: leftover snapshot backup "${base}"`;
3825
+ }
3192
3826
  return null;
3193
3827
  }
3194
3828
  function listIgnoredPaths(cwd) {
@@ -3257,41 +3891,72 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
3257
3891
  }
3258
3892
  const reported = /* @__PURE__ */ new Set();
3259
3893
  const kept = [];
3894
+ const report = (linkedPath, record) => {
3895
+ if (reported.has(linkedPath)) return;
3896
+ reported.add(linkedPath);
3897
+ skipped.push(record);
3898
+ };
3260
3899
  for (const candidate of candidates) {
3261
3900
  const parts = candidate.split("/");
3262
- let linkedDir = null;
3901
+ let linkedPath = null;
3263
3902
  for (let depth = 1; depth <= parts.length; depth += 1) {
3264
3903
  const prefix = parts.slice(0, depth).join("/");
3265
3904
  if (isLink(path16__namespace.join(cwd, prefix))) {
3266
- linkedDir = prefix;
3905
+ linkedPath = prefix;
3267
3906
  break;
3268
3907
  }
3269
3908
  }
3270
- if (linkedDir === null) {
3909
+ if (linkedPath === null) {
3271
3910
  kept.push(candidate);
3272
3911
  continue;
3273
3912
  }
3274
- if (reported.has(linkedDir)) continue;
3275
- reported.add(linkedDir);
3276
- const absolute = path16__namespace.join(cwd, linkedDir);
3277
- let targetReal = absolute;
3913
+ const absolute = path16__namespace.join(cwd, linkedPath);
3914
+ const rawTarget = readLinkTarget(absolute, absolute);
3915
+ let targetReal = null;
3278
3916
  try {
3279
3917
  targetReal = fs14__namespace.realpathSync(absolute);
3280
3918
  } catch {
3919
+ targetReal = null;
3281
3920
  }
3282
- const target = readLinkTarget(absolute, targetReal);
3283
- const what = linkedDir === candidate ? "symbolic link" : "directory link";
3284
- skipped.push(
3285
- isInside(rootReal, targetReal) ? {
3286
- path: linkedDir,
3287
- reason: "symlink",
3288
- detail: `${what} not followed (target: ${target})`
3289
- } : {
3290
- path: linkedDir,
3921
+ if (targetReal === null) {
3922
+ report(linkedPath, brokenLinkRecord(absolute, linkedPath, rootReal));
3923
+ continue;
3924
+ }
3925
+ if (!isInside(rootReal, targetReal)) {
3926
+ report(linkedPath, {
3927
+ path: linkedPath,
3291
3928
  reason: "outside-root",
3292
- detail: `link target resolves outside the scanned root (target: ${target}); not followed`
3293
- }
3294
- );
3929
+ detail: `link target resolves outside the scanned root (target: ${rawTarget}); not followed`
3930
+ });
3931
+ continue;
3932
+ }
3933
+ let stats = null;
3934
+ try {
3935
+ stats = fs14__namespace.statSync(absolute);
3936
+ } catch {
3937
+ stats = null;
3938
+ }
3939
+ if (stats === null) {
3940
+ report(linkedPath, { path: linkedPath, reason: "read-error", detail: "unreadable symlink" });
3941
+ continue;
3942
+ }
3943
+ if (linkedPath !== candidate || stats.isDirectory()) {
3944
+ report(linkedPath, {
3945
+ path: linkedPath,
3946
+ reason: "symlink",
3947
+ detail: `directory link not followed (target: ${rawTarget})`
3948
+ });
3949
+ continue;
3950
+ }
3951
+ if (!stats.isFile()) {
3952
+ report(linkedPath, {
3953
+ path: linkedPath,
3954
+ reason: "symlink",
3955
+ detail: `link to neither a file nor a directory (target: ${rawTarget})`
3956
+ });
3957
+ continue;
3958
+ }
3959
+ kept.push(candidate);
3295
3960
  }
3296
3961
  return kept;
3297
3962
  }
@@ -3338,6 +4003,7 @@ function collectFiles(cwd, options = {}) {
3338
4003
  (options.toolOwnedPaths ?? []).map((entry) => entry.replace(/\\/g, "/"))
3339
4004
  );
3340
4005
  const isToolOwned = makeToolOwnedDecider(cwd, [...toolOwnedPaths]);
4006
+ const toolDirNames = toolDirNamesFor(toolOwnedPaths);
3341
4007
  let candidates;
3342
4008
  const skipped = [];
3343
4009
  const discovery = options.discovery ?? "auto";
@@ -3366,7 +4032,7 @@ function collectFiles(cwd, options = {}) {
3366
4032
  }
3367
4033
  const files = candidates.filter((file) => {
3368
4034
  if (isToolOwned(file)) return false;
3369
- const ignored = defaultIgnoreReason(file);
4035
+ const ignored = defaultIgnoreReason(file, toolDirNames);
3370
4036
  if (ignored) {
3371
4037
  skipped.push({ path: file, reason: "default-ignore", detail: ignored });
3372
4038
  return false;
@@ -3421,6 +4087,7 @@ function rootRealFor(root) {
3421
4087
  function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PURE__ */ new Set(), parentGitignoreLayers = []) {
3422
4088
  const results = { files: [], skipped: [] };
3423
4089
  const stack = [];
4090
+ const toolDirNames = toolDirNamesFor(reservedPaths);
3424
4091
  const relativeToBase = (target) => path16__namespace.relative(baseDir, target).replace(/\\/g, "/") || ".";
3425
4092
  const enter = (current, layers) => {
3426
4093
  if (visited.has(current)) return false;
@@ -3465,11 +4132,11 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
3465
4132
  });
3466
4133
  continue;
3467
4134
  }
3468
- if (DEFAULT_IGNORED_FILES.includes(entry.name) || entry.name.startsWith("snapshot.backup-")) {
4135
+ if (DEFAULT_IGNORED_FILES.includes(entry.name) || isToolLeftoverName(entry.name, toolDirNames)) {
3469
4136
  results.skipped.push({
3470
4137
  path: relPath,
3471
4138
  reason: "default-ignore",
3472
- detail: "built-in ignore: filename"
4139
+ detail: isToolLeftoverName(entry.name, toolDirNames) ? `built-in ignore: leftover snapshot backup "${entry.name}" (not descended)` : "built-in ignore: filename"
3473
4140
  });
3474
4141
  continue;
3475
4142
  }
@@ -3490,7 +4157,7 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
3490
4157
  try {
3491
4158
  targetReal = fs14__namespace.realpathSync(fullPath);
3492
4159
  } catch {
3493
- results.skipped.push({ path: relPath, reason: "read-error", detail: "broken symlink" });
4160
+ results.skipped.push(brokenLinkRecord(fullPath, relPath, rootReal));
3494
4161
  continue;
3495
4162
  }
3496
4163
  let stats;
@@ -3615,15 +4282,19 @@ function normalizeBudgets(budgets, maxPartBytes) {
3615
4282
  }
3616
4283
  function normalizeResolvedConfig(config) {
3617
4284
  const discovery = isDiscoveryMode(config.discovery) ? config.discovery : "auto";
4285
+ const monolithWanted = config.includeMonolith === true || config.artifacts?.monolith === true;
4286
+ const artifacts = resolveArtifacts(
4287
+ config.artifacts,
4288
+ void 0,
4289
+ monolithWanted,
4290
+ monolithWanted
4291
+ );
3618
4292
  return markResolvedConfig({
3619
4293
  ...config,
3620
4294
  discovery,
4295
+ includeMonolith: artifacts.monolith,
3621
4296
  secretRules: compileSecretRules(config.secretRules),
3622
- artifacts: resolveArtifacts(
3623
- config.artifacts,
3624
- void 0,
3625
- config.includeMonolith === true
3626
- ),
4297
+ artifacts,
3627
4298
  include: resolveInclude(config.include),
3628
4299
  preset: typeof config.preset === "string" ? config.preset : "generic",
3629
4300
  presetExclude: [
@@ -3702,9 +4373,9 @@ function stripJsonComments2(raw) {
3702
4373
  }
3703
4374
  out += char;
3704
4375
  }
3705
- return stripTrailingCommas(out);
4376
+ return stripTrailingCommas2(out);
3706
4377
  }
3707
- function stripTrailingCommas(text2) {
4378
+ function stripTrailingCommas2(text2) {
3708
4379
  let out = "";
3709
4380
  let inString = false;
3710
4381
  let escaped = false;
@@ -3832,6 +4503,16 @@ async function importConfigModule(fullPath) {
3832
4503
  url$1.searchParams.set("codebaseSnapshotLoad", String(moduleConfigLoadToken));
3833
4504
  return await import(url$1.href);
3834
4505
  }
4506
+ function attachConfigDir(config, filePath) {
4507
+ if (typeof config === "object" && config !== null) {
4508
+ Object.defineProperty(config, CONFIG_DIR_SYMBOL, {
4509
+ value: path16__namespace.dirname(filePath),
4510
+ enumerable: false,
4511
+ configurable: true
4512
+ });
4513
+ }
4514
+ return config;
4515
+ }
3835
4516
  async function loadConfigFileDetailed(cwd) {
3836
4517
  const warnings = [];
3837
4518
  const errors = [];
@@ -3847,7 +4528,7 @@ async function loadConfigFileDetailed(cwd) {
3847
4528
  );
3848
4529
  }
3849
4530
  assertKnownConfigKeys(config, fullPath);
3850
- return { config, file: fullPath, warnings, errors };
4531
+ return { config: attachConfigDir(config, fullPath), file: fullPath, warnings, errors };
3851
4532
  } catch (err) {
3852
4533
  const raw = err.message;
3853
4534
  const message = raw.includes(fullPath) ? raw : `${fullPath}: ${raw}`;
@@ -3866,7 +4547,7 @@ async function loadConfigFileDetailed(cwd) {
3866
4547
  const imported = await importConfigModule(fullPath);
3867
4548
  const hasDefault = Object.prototype.hasOwnProperty.call(imported, "default");
3868
4549
  const config = readConfigExport(hasDefault ? imported.default : imported, fullPath);
3869
- return { config, file: fullPath, warnings, errors };
4550
+ return { config: attachConfigDir(config, fullPath), file: fullPath, warnings, errors };
3870
4551
  } catch (err) {
3871
4552
  const message = `Could not load ${fullPath}: ${err.message}`;
3872
4553
  warnings.push(message);
@@ -3884,7 +4565,12 @@ async function loadConfigFileDetailed(cwd) {
3884
4565
  snapshotKey,
3885
4566
  `${pkgJsonPath} (the "snapshot" key)`
3886
4567
  );
3887
- return { config: snapshotKey, file: pkgJsonPath, warnings, errors };
4568
+ return {
4569
+ config: attachConfigDir(snapshotKey, pkgJsonPath),
4570
+ file: pkgJsonPath,
4571
+ warnings,
4572
+ errors
4573
+ };
3888
4574
  }
3889
4575
  if (snapshotKey !== void 0) {
3890
4576
  const kind = Array.isArray(snapshotKey) ? "array" : typeof snapshotKey;
@@ -3902,13 +4588,6 @@ async function loadConfigFileDetailed(cwd) {
3902
4588
  }
3903
4589
  async function loadConfigFile(cwd) {
3904
4590
  const loaded = await loadConfigFileDetailed(cwd);
3905
- if (loaded.config && loaded.file && typeof loaded.config === "object") {
3906
- Object.defineProperty(loaded.config, CONFIG_DIR_SYMBOL, {
3907
- value: path16__namespace.dirname(loaded.file),
3908
- enumerable: false,
3909
- configurable: true
3910
- });
3911
- }
3912
4591
  if (loaded.errors.length > 0) {
3913
4592
  throw new Error(`The config file could not be read: ${loaded.errors.join("; ")}`);
3914
4593
  }
@@ -3937,7 +4616,7 @@ var DEFAULT_ARTIFACTS = {
3937
4616
  function isArtifactName(value) {
3938
4617
  return ARTIFACT_NAMES.includes(value);
3939
4618
  }
3940
- function resolveArtifacts(requested, skipped, includeMonolith, monolithOverride) {
4619
+ function resolveArtifacts(requested, skipped, includeMonolith, monolithOverride, only) {
3941
4620
  const artifacts = {
3942
4621
  ...DEFAULT_ARTIFACTS,
3943
4622
  // `includeMonolith` predates this selection and stays the switch for it.
@@ -3962,6 +4641,21 @@ function resolveArtifacts(requested, skipped, includeMonolith, monolithOverride)
3962
4641
  if (monolithOverride !== void 0) {
3963
4642
  artifacts.monolith = monolithOverride;
3964
4643
  }
4644
+ if (only !== void 0 && only.length > 0) {
4645
+ const keep = /* @__PURE__ */ new Set();
4646
+ for (const name of only) {
4647
+ if (!isArtifactName(name)) {
4648
+ throw new Error(
4649
+ `Unknown artifact "${name}". Expected one of: ${ARTIFACT_NAMES.join(", ")}.`
4650
+ );
4651
+ }
4652
+ keep.add(name);
4653
+ }
4654
+ for (const name of ARTIFACT_NAMES) {
4655
+ artifacts[name] = keep.has(name);
4656
+ }
4657
+ return artifacts;
4658
+ }
3965
4659
  for (const name of skipped ?? []) {
3966
4660
  if (!isArtifactName(name)) {
3967
4661
  throw new Error(
@@ -4262,7 +4956,8 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
4262
4956
  userConfig?.artifacts,
4263
4957
  cliOptions?.skipArtifacts,
4264
4958
  includeMonolith,
4265
- cliMonolith
4959
+ cliMonolith,
4960
+ cliOptions?.onlyArtifacts
4266
4961
  );
4267
4962
  const explicitMaxPartBytes = cliOptions?.maxPartBytes ?? userConfig?.maxPartBytes;
4268
4963
  const maxPartBytes = boundedBytes(
@@ -4436,7 +5131,18 @@ function configDigest(config) {
4436
5131
  excludePatterns: config.excludePatterns,
4437
5132
  preset: config.preset,
4438
5133
  layersMode: config.layersMode,
4439
- budgets: config.budgets,
5134
+ // `budgets.byLayer` is a plain object, and `JSON.stringify` preserves insertion order — so
5135
+ // `{ docs, api }` and `{ api, docs }` hashed differently despite being the same settings, and
5136
+ // `validate` reported configuration drift for a snapshot nobody had changed. The keys are
5137
+ // canonicalised here; nothing else about the object is order-dependent.
5138
+ budgets: {
5139
+ default: config.budgets.default,
5140
+ byLayer: Object.fromEntries(
5141
+ Object.entries(config.budgets.byLayer).sort(
5142
+ ([left], [right]) => left < right ? -1 : left > right ? 1 : 0
5143
+ )
5144
+ )
5145
+ },
4440
5146
  // The matcher is what makes a layer a layer. Hashing only the names meant that
4441
5147
  // moving `{ name: "api", match: "src/api/**" }` to `"src/v2/**"` produced the same
4442
5148
  // digest, so `validate` reported "valid and up to date" for a snapshot whose files
@@ -4720,9 +5426,21 @@ function generateSarifReport(manifest, findings, rules, toolVersion) {
4720
5426
  }
4721
5427
 
4722
5428
  // src/partitioner/preview.ts
5429
+ var LINE_ENDINGS = /\r\n|\r/g;
5430
+ var normaliseLineEndings = (content) => content.replace(LINE_ENDINGS, "\n");
4723
5431
  function countLines(content) {
4724
5432
  if (content.length === 0) return 0;
4725
- return content.split("\n").length - (content.endsWith("\n") ? 1 : 0);
5433
+ let breaks = 0;
5434
+ for (let index = 0; index < content.length; index += 1) {
5435
+ const code = content.charCodeAt(index);
5436
+ if (code === 10) {
5437
+ breaks += 1;
5438
+ continue;
5439
+ }
5440
+ if (code === 13 && content.charCodeAt(index + 1) !== 10) breaks += 1;
5441
+ }
5442
+ const last = content.charCodeAt(content.length - 1);
5443
+ return last === 10 || last === 13 ? breaks : breaks + 1;
4726
5444
  }
4727
5445
  function truncateToBytes(content, maxBytes) {
4728
5446
  if (maxBytes <= 0) return { content: "", isTruncated: content.length > 0 };
@@ -4733,17 +5451,18 @@ function truncateToBytes(content, maxBytes) {
4733
5451
  return { content: slice, isTruncated: true };
4734
5452
  }
4735
5453
  function truncatePreview(content, headLines, tailLines) {
4736
- const lines = content.split("\n");
4737
- const total = countLines(content);
5454
+ const normalised = normaliseLineEndings(content);
5455
+ const lines = normalised.split("\n");
5456
+ const total = countLines(normalised);
4738
5457
  if (total <= headLines + tailLines) {
4739
5458
  return {
4740
- content,
5459
+ content: normalised,
4741
5460
  isTruncated: false,
4742
5461
  originalLines: total,
4743
5462
  includedLines: total
4744
5463
  };
4745
5464
  }
4746
- const window = content.endsWith("\n") ? lines.slice(0, -1) : lines;
5465
+ const window = normalised.endsWith("\n") ? lines.slice(0, -1) : lines;
4747
5466
  const head = window.slice(0, headLines);
4748
5467
  const tail = tailLines > 0 ? window.slice(window.length - tailLines) : [];
4749
5468
  const omitted = total - head.length - tail.length;
@@ -4797,23 +5516,55 @@ function truncateWithBudgetMarker(content, maxBytes, budget, originalLines) {
4797
5516
  };
4798
5517
  }
4799
5518
  function partitionFiles(files, maxPartBytes, contentFingerprint) {
4800
- if (files.length === 0) return [];
4801
- const budget = Math.max(MIN_SECTION_BUDGET_BYTES + HEADER_RESERVE_BYTES, maxPartBytes);
4802
- const sectionBudget = budget - HEADER_RESERVE_BYTES;
4803
- const prepared = files.map((file) => prepareSection(file, sectionBudget));
4804
- let groups = greedyGroups(prepared, budget);
5519
+ return partitionFilesForBuckets([{ files, budgetBytes: maxPartBytes }], contentFingerprint);
5520
+ }
5521
+ function partitionFilesForBuckets(buckets, contentFingerprint) {
5522
+ const groups = [];
5523
+ for (const bucket of buckets) {
5524
+ if (bucket.files.length === 0) continue;
5525
+ const budget = Math.max(
5526
+ MIN_SECTION_BUDGET_BYTES + HEADER_RESERVE_BYTES,
5527
+ bucket.budgetBytes
5528
+ );
5529
+ const sectionBudget = budget - HEADER_RESERVE_BYTES;
5530
+ const prepared = bucket.files.map((file) => prepareSection(file, sectionBudget, budget));
5531
+ for (const sections of greedyGroups(prepared, budget)) groups.push({ sections, budget });
5532
+ }
5533
+ if (groups.length === 0) return [];
5534
+ const measurements = /* @__PURE__ */ new Map();
5535
+ const widthOf = (total) => Math.max(3, String(total).length);
5536
+ const measure = (group, index, total) => {
5537
+ const cached = measurements.get(group);
5538
+ const width = widthOf(total);
5539
+ if (cached !== void 0 && cached.index === index && cached.width === width) {
5540
+ return cached.size;
5541
+ }
5542
+ const { content } = assembleGroup(group, index, total, contentFingerprint);
5543
+ const size2 = Buffer.byteLength(content, "utf8");
5544
+ measurements.set(group, { index, width, size: size2 });
5545
+ return size2;
5546
+ };
4805
5547
  for (let pass = 0; pass < MAX_SPLIT_PASSES; pass++) {
4806
- const rendered = renderGroups(groups, budget, contentFingerprint);
4807
- const oversized = rendered.findIndex((part) => part.metadata.byteSize > budget);
4808
- if (oversized === -1) return rendered;
5548
+ const total = groups.length;
5549
+ let oversized = -1;
5550
+ for (let index = 0; index < total; index += 1) {
5551
+ const group2 = groups[index];
5552
+ if (measure(group2, index, total) > group2.budget) {
5553
+ oversized = index;
5554
+ break;
5555
+ }
5556
+ }
5557
+ if (oversized === -1) return renderGroups(groups, contentFingerprint);
4809
5558
  const group = groups[oversized];
4810
- if (group.length > 1) {
4811
- const moved = group.pop();
4812
- groups.splice(oversized + 1, 0, [moved]);
5559
+ if (group.sections.length > 1) {
5560
+ const moved = group.sections.pop();
5561
+ groups.splice(oversized + 1, 0, { sections: [moved], budget: group.budget });
5562
+ measurements.delete(group);
4813
5563
  continue;
4814
5564
  }
4815
- const [section] = group;
4816
- const overflow = rendered[oversized].metadata.byteSize - budget;
5565
+ const [section] = group.sections;
5566
+ if (section === void 0) return renderGroups(groups, contentFingerprint);
5567
+ const overflow = measure(group, oversized, total) - group.budget;
4817
5568
  const currentContent = section.file.content ?? "";
4818
5569
  const shrinkTo = Math.max(
4819
5570
  0,
@@ -4822,26 +5573,33 @@ function partitionFiles(files, maxPartBytes, contentFingerprint) {
4822
5573
  const shrunk = truncateWithBudgetMarker(
4823
5574
  currentContent,
4824
5575
  shrinkTo,
4825
- budget,
5576
+ group.budget,
4826
5577
  section.file.originalLines
4827
5578
  );
4828
5579
  if (shrunk.isTruncated) {
4829
5580
  applyTruncatedContent(section.file, shrunk.content);
4830
5581
  section.text = renderFileSection(section.file);
4831
5582
  section.byteSize = Buffer.byteLength(section.text, "utf8");
5583
+ measurements.delete(group);
4832
5584
  continue;
4833
5585
  }
5586
+ const rendered = renderGroups(groups, contentFingerprint);
4834
5587
  const marker2 = TRUNCATION_MARKER;
4835
- assertBudgetHoldsMarker(budget);
5588
+ assertBudgetHoldsMarker(group.budget);
4836
5589
  const target = Math.max(
4837
5590
  0,
4838
- budget - Buffer.byteLength(marker2, "utf8") - TOKEN_LINE_SLACK
5591
+ group.budget - Buffer.byteLength(marker2, "utf8") - TOKEN_LINE_SLACK
4839
5592
  );
4840
5593
  const clipped = truncateToBytes(rendered[oversized].markdown, target);
4841
- rendered[oversized] = rehashPart(rendered[oversized], clipped.content + marker2);
5594
+ rendered[oversized] = rehashPart(
5595
+ rendered[oversized],
5596
+ clipped.content + marker2
5597
+ );
4842
5598
  return rendered;
4843
5599
  }
4844
- return enforceBudget(renderGroups(groups, budget, contentFingerprint), budget);
5600
+ return renderGroups(groups, contentFingerprint).flatMap(
5601
+ (part) => enforceBudget([part], part.metadata.budgetBytes)
5602
+ );
4845
5603
  }
4846
5604
  var TRUNCATION_MARKER = "\n... [part truncated: cannot fit budget] ...\n";
4847
5605
  function assertBudgetHoldsMarker(budget) {
@@ -4926,7 +5684,7 @@ function renumberParts(parts, contentFingerprint) {
4926
5684
  (part) => enforceBudget([part], part.metadata.budgetBytes)[0] ?? part
4927
5685
  );
4928
5686
  }
4929
- var SECTION_TRUNCATION_NOTICE = "\n... [section truncated: metadata alone exceeds the part budget] ...\n";
5687
+ var SECTION_TRUNCATION_NOTICE = "... [section truncated: the fixed metadata and a code fence did not fit the part budget] ...";
4930
5688
  var METADATA_VALUE_MAX = 200;
4931
5689
  var DISPLAY_PATH_MAX = 300;
4932
5690
  function capValue(value, max) {
@@ -4939,7 +5697,7 @@ var displayPath = (value) => capValue(escapeControls(value), DISPLAY_PATH_MAX);
4939
5697
  function topEntries(counts, limit) {
4940
5698
  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(", ");
4941
5699
  }
4942
- function prepareSection(file, sectionBudget) {
5700
+ function prepareSection(file, sectionBudget, partBudget) {
4943
5701
  let text2 = renderFileSection(file);
4944
5702
  let byteSize = Buffer.byteLength(text2, "utf8");
4945
5703
  if (byteSize <= sectionBudget) return { file, text: text2, byteSize };
@@ -4951,7 +5709,7 @@ function prepareSection(file, sectionBudget) {
4951
5709
  const truncated = truncateWithBudgetMarker(
4952
5710
  content,
4953
5711
  allowed,
4954
- sectionBudget,
5712
+ partBudget,
4955
5713
  file.originalLines
4956
5714
  );
4957
5715
  if (!truncated.isTruncated) return;
@@ -4968,13 +5726,57 @@ function prepareSection(file, sectionBudget) {
4968
5726
  shrinkBody();
4969
5727
  }
4970
5728
  if (byteSize > sectionBudget) {
4971
- const target = sectionBudget - Buffer.byteLength(SECTION_TRUNCATION_NOTICE, "utf8");
4972
- const truncated = truncateToBytes(text2, Math.max(0, target));
4973
- text2 = truncated.content + SECTION_TRUNCATION_NOTICE;
5729
+ applyTruncatedContent(file, SECTION_TRUNCATION_NOTICE);
5730
+ file.summary = void 0;
5731
+ file.summaryOmitted = true;
5732
+ text2 = renderFileSection(file);
4974
5733
  byteSize = Buffer.byteLength(text2, "utf8");
5734
+ if (byteSize > sectionBudget) {
5735
+ text2 = truncateRenderedSection(text2, sectionBudget, fenceForContent(file.content ?? ""));
5736
+ byteSize = Buffer.byteLength(text2, "utf8");
5737
+ }
4975
5738
  }
4976
5739
  return { file, text: text2, byteSize };
4977
5740
  }
5741
+ function truncateRenderedSection(text2, sectionBudget, fence) {
5742
+ const closing = `
5743
+ ${SECTION_TRUNCATION_NOTICE}
5744
+ ${fence}
5745
+ `;
5746
+ const bodyRoom = sectionBudget - Buffer.byteLength(closing, "utf8");
5747
+ if (bodyRoom > 0) {
5748
+ const cut2 = truncateToBytes(text2, bodyRoom).content;
5749
+ const lastBreak2 = cut2.lastIndexOf("\n");
5750
+ const kept = lastBreak2 >= 0 ? cut2.slice(0, lastBreak2 + 1) : "";
5751
+ if (fenceIsOpen(kept, fence)) return `${kept}${closing}`;
5752
+ }
5753
+ const probe = text2.slice(0, 512);
5754
+ const emptyFence = fenceForText(probe.slice(0, Math.max(0, probe.lastIndexOf("\n") + 1)), 4);
5755
+ const block = `
5756
+ ${emptyFence}
5757
+ ${SECTION_TRUNCATION_NOTICE}
5758
+ ${emptyFence}
5759
+ `;
5760
+ const prefixRoom = sectionBudget - Buffer.byteLength(block, "utf8");
5761
+ const cut = prefixRoom > 0 ? truncateToBytes(text2, prefixRoom).content : "";
5762
+ const lastBreak = cut.lastIndexOf("\n");
5763
+ const prefix = lastBreak >= 0 ? cut.slice(0, lastBreak + 1) : "";
5764
+ return `${dropTrailingOpenFence(prefix, fence)}${block}`;
5765
+ }
5766
+ function dropTrailingOpenFence(text2, fence) {
5767
+ if (!fenceIsOpen(text2, fence)) return text2;
5768
+ const lines = text2.split("\n");
5769
+ const opening = lines.findIndex((line) => line.startsWith(fence));
5770
+ if (opening < 0) return text2;
5771
+ return lines.slice(0, opening).join("\n") + (opening > 0 ? "\n" : "");
5772
+ }
5773
+ function fenceIsOpen(text2, fence) {
5774
+ let open = false;
5775
+ for (const line of text2.split("\n")) {
5776
+ if (line.startsWith(fence)) open = !open;
5777
+ }
5778
+ return open;
5779
+ }
4978
5780
  function applyTruncatedContent(file, content) {
4979
5781
  file.content = content;
4980
5782
  file.isPreviewTruncated = true;
@@ -5022,52 +5824,64 @@ function greedyGroups(sections, budget) {
5022
5824
  if (current.length > 0) groups.push(current);
5023
5825
  return groups;
5024
5826
  }
5025
- function renderGroups(groups, budget, contentFingerprint) {
5827
+ function assembleGroup(group, index, total, contentFingerprint) {
5828
+ const width = Math.max(3, String(total).length);
5829
+ const zeroPad = (value) => String(value).padStart(width, "0");
5830
+ const filename = `part-${zeroPad(index + 1)}.md`;
5831
+ const prev = index === 0 ? "none" : `part-${zeroPad(index)}.md`;
5832
+ const next = index === total - 1 ? "none" : `part-${zeroPad(index + 2)}.md`;
5833
+ for (const section of group.sections) {
5834
+ section.file.part = filename;
5835
+ }
5836
+ const layerCounts = {};
5837
+ const kindCounts = {};
5838
+ for (const section of group.sections) {
5839
+ layerCounts[section.file.layer] = (layerCounts[section.file.layer] || 0) + 1;
5840
+ kindCounts[section.file.kind] = (kindCounts[section.file.kind] || 0) + 1;
5841
+ }
5842
+ const pathLines = group.sections.map((s) => displayPath(s.file.relativePath));
5843
+ const listFence = fenceForText(pathLines.join("\n"), 3);
5844
+ const header = [
5845
+ `# Codebase Snapshot Part ${zeroPad(index + 1)} of ${zeroPad(total)}`,
5846
+ "",
5847
+ `- Previous: ${prev}`,
5848
+ `- Next: ${next}`,
5849
+ `- Files: ${group.sections.length}`,
5850
+ `- Content Fingerprint: ${contentFingerprint || "none"}`,
5851
+ `- Layers: ${topEntries(layerCounts, 6) || "none"}`,
5852
+ `- Kinds: ${topEntries(kindCounts, 8) || "none"}`,
5853
+ "",
5854
+ UNTRUSTED_CONTENT_NOTICE,
5855
+ "",
5856
+ "## Files",
5857
+ "",
5858
+ `${listFence}text`,
5859
+ ...pathLines,
5860
+ listFence,
5861
+ "",
5862
+ "## Contents",
5863
+ ""
5864
+ ].join("\n");
5865
+ const assembled = (header + group.sections.map((s) => s.text).join("")).replace(
5866
+ /\r\n|\r/g,
5867
+ "\n"
5868
+ );
5869
+ const estimatedTokens = estimateTokens(assembled);
5870
+ return { filename, content: insertTokenLine(assembled, estimatedTokens), estimatedTokens };
5871
+ }
5872
+ function renderGroups(groups, contentFingerprint) {
5026
5873
  const total = groups.length;
5027
- const zeroPad = (index) => String(index).padStart(Math.max(3, String(total).length), "0");
5028
5874
  return groups.map((group, index) => {
5029
- const filename = `part-${zeroPad(index + 1)}.md`;
5030
- const prev = index === 0 ? "none" : `part-${zeroPad(index)}.md`;
5031
- const next = index === total - 1 ? "none" : `part-${zeroPad(index + 2)}.md`;
5032
- for (const section of group) {
5033
- section.file.part = filename;
5034
- }
5035
- const layersCovered = Array.from(new Set(group.map((s) => s.file.layer))).sort();
5036
- const layerCounts = {};
5037
- const kindCounts = {};
5038
- for (const section of group) {
5039
- layerCounts[section.file.layer] = (layerCounts[section.file.layer] || 0) + 1;
5040
- kindCounts[section.file.kind] = (kindCounts[section.file.kind] || 0) + 1;
5041
- }
5042
- const pathLines = group.map((s) => displayPath(s.file.relativePath));
5043
- const listFence = fenceForText(pathLines.join("\n"), 3);
5044
- const header = [
5045
- `# Codebase Snapshot Part ${zeroPad(index + 1)} of ${zeroPad(total)}`,
5046
- "",
5047
- `- Previous: ${prev}`,
5048
- `- Next: ${next}`,
5049
- `- Files: ${group.length}`,
5050
- `- Content Fingerprint: ${contentFingerprint || "none"}`,
5051
- `- Layers: ${topEntries(layerCounts, 6) || "none"}`,
5052
- `- Kinds: ${topEntries(kindCounts, 8) || "none"}`,
5053
- "",
5054
- UNTRUSTED_CONTENT_NOTICE,
5055
- "",
5056
- "## Files",
5057
- "",
5058
- `${listFence}text`,
5059
- ...pathLines,
5060
- listFence,
5061
- "",
5062
- "## Contents",
5063
- ""
5064
- ].join("\n");
5065
- const assembled = (header + group.map((s) => s.text).join("")).replace(/\r\n/g, "\n");
5066
- const estimatedTokens = estimateTokens(assembled);
5067
- const content = insertTokenLine(assembled, estimatedTokens);
5875
+ const { filename, content, estimatedTokens } = assembleGroup(
5876
+ group,
5877
+ index,
5878
+ total,
5879
+ contentFingerprint
5880
+ );
5068
5881
  const byteSize = Buffer.byteLength(content, "utf8");
5069
5882
  const sha256 = crypto2__namespace.createHash("sha256").update(content).digest("hex");
5070
- const includedFiles = group.map(({ file }) => ({
5883
+ const layersCovered = Array.from(new Set(group.sections.map((s) => s.file.layer))).sort();
5884
+ const includedFiles = group.sections.map(({ file }) => ({
5071
5885
  relativePath: file.relativePath,
5072
5886
  sourceBytes: file.sizeBytes,
5073
5887
  includedBytes: file.includedBytes,
@@ -5080,10 +5894,10 @@ function renderGroups(groups, budget, contentFingerprint) {
5080
5894
  filename,
5081
5895
  byteSize,
5082
5896
  estimatedTokens,
5083
- budgetBytes: budget,
5897
+ budgetBytes: group.budget,
5084
5898
  sha256,
5085
5899
  lines: countLines(content),
5086
- fileCount: group.length,
5900
+ fileCount: group.sections.length,
5087
5901
  layersCovered,
5088
5902
  includedFiles
5089
5903
  };
@@ -5091,7 +5905,7 @@ function renderGroups(groups, budget, contentFingerprint) {
5091
5905
  });
5092
5906
  }
5093
5907
  function emittedBody(content) {
5094
- const normalised = content.replace(/\r\n/g, "\n");
5908
+ const normalised = content.replace(/\r\n|\r/g, "\n");
5095
5909
  return normalised.endsWith("\n") ? normalised.slice(0, -1) : normalised;
5096
5910
  }
5097
5911
  function compactMetadata(file) {
@@ -5159,7 +5973,7 @@ function generateMonolithJson(manifest, filesWithContent) {
5159
5973
  }
5160
5974
  function generateMonolithMarkdown(manifest, filesWithContent) {
5161
5975
  const sections = filesWithContent.map((file) => {
5162
- const content = (file.content ?? "").replace(/\r\n/g, "\n");
5976
+ const content = (file.content ?? "").replace(/\r\n|\r/g, "\n");
5163
5977
  const fence = fenceForContent(content);
5164
5978
  return [
5165
5979
  `## File: ${escapeControls(file.relativePath)}`,
@@ -5373,273 +6187,30 @@ function generateProjectTree(filePaths) {
5373
6187
  const isDirectory = child.children.size > 0;
5374
6188
  const label = escapeControls(key);
5375
6189
  lines.push(`${frame.prefix}${isLast ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 "}${label}${isDirectory ? "/" : ""}`);
5376
- if (lines.length >= MAX_TREE_LINES) {
5377
- truncatedAt = lines.length;
5378
- break;
5379
- }
5380
- if (!isDirectory) continue;
5381
- if (frame.depth + 1 > MAX_TREE_DEPTH) {
5382
- depthTruncated = true;
5383
- continue;
5384
- }
5385
- stack.push({
5386
- node: child,
5387
- prefix: frame.prefix + (isLast ? " " : "\u2502 "),
5388
- depth: frame.depth + 1,
5389
- keys: childKeys(child),
5390
- index: 0
5391
- });
5392
- }
5393
- if (truncatedAt !== -1) {
5394
- lines.push(`... [tree truncated at ${MAX_TREE_LINES} lines] ...`);
5395
- } else if (depthTruncated) {
5396
- lines.push(`... [tree truncated at ${MAX_TREE_DEPTH} levels] ...`);
5397
- }
5398
- const fence = fenceForText(lines.join("\n"), 3);
5399
- return ["# Project Tree", "", `${fence}text`, ...lines, fence, ""].join("\n");
5400
- }
5401
- var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
5402
- ".png",
5403
- ".jpg",
5404
- ".jpeg",
5405
- ".gif",
5406
- ".webp",
5407
- ".avif",
5408
- ".ico",
5409
- ".bmp",
5410
- ".tiff",
5411
- ".pdf",
5412
- ".zip",
5413
- ".tar",
5414
- ".gz",
5415
- ".tgz",
5416
- ".br",
5417
- ".bz2",
5418
- ".xz",
5419
- ".zst",
5420
- ".lz4",
5421
- ".lzma",
5422
- ".7z",
5423
- ".rar",
5424
- ".mp3",
5425
- ".mp4",
5426
- ".wav",
5427
- ".ogg",
5428
- ".webm",
5429
- ".mov",
5430
- ".avi",
5431
- ".woff",
5432
- ".woff2",
5433
- ".ttf",
5434
- ".otf",
5435
- ".eot",
5436
- ".wasm",
5437
- ".node",
5438
- ".exe",
5439
- ".dll",
5440
- ".dylib",
5441
- ".so"
5442
- ]);
5443
- function isBinaryExtension(filePath) {
5444
- const ext = path16__namespace.extname(filePath).toLowerCase();
5445
- return BINARY_EXTENSIONS.has(ext);
5446
- }
5447
- function isBinaryBuffer(buffer) {
5448
- return buffer.includes(0);
5449
- }
5450
- function countControlBytes(buffer) {
5451
- let count = 0;
5452
- for (let index = 0; index < buffer.length; index++) {
5453
- const byte = buffer[index];
5454
- if (byte < 32) {
5455
- if (byte !== 9 && byte !== 10 && byte !== 13) count += 1;
5456
- continue;
5457
- }
5458
- if (byte === 127) {
5459
- count += 1;
5460
- continue;
5461
- }
5462
- if (byte === 194 && index + 1 < buffer.length) {
5463
- const next = buffer[index + 1];
5464
- if (next >= 128 && next <= 159) {
5465
- count += 1;
5466
- index += 1;
5467
- }
5468
- }
5469
- }
5470
- return count;
5471
- }
5472
- var CONTROL_BYTES_FLOOR = 4;
5473
- function countInvalidUtf8Bytes(buffer) {
5474
- let invalid = 0;
5475
- let index = 0;
5476
- const length = buffer.length;
5477
- while (index < length) {
5478
- const lead = buffer[index];
5479
- if (lead < 128) {
5480
- index += 1;
5481
- continue;
5482
- }
5483
- let continuation = 0;
5484
- let codePoint = 0;
5485
- let minimum = 0;
5486
- if ((lead & 224) === 192) {
5487
- continuation = 1;
5488
- codePoint = lead & 31;
5489
- minimum = 128;
5490
- } else if ((lead & 240) === 224) {
5491
- continuation = 2;
5492
- codePoint = lead & 15;
5493
- minimum = 2048;
5494
- } else if ((lead & 248) === 240) {
5495
- continuation = 3;
5496
- codePoint = lead & 7;
5497
- minimum = 65536;
5498
- } else {
5499
- invalid += 1;
5500
- index += 1;
5501
- continue;
5502
- }
5503
- if (index + continuation >= length) {
5504
- invalid += 1;
5505
- index += 1;
5506
- continue;
5507
- }
5508
- let wellFormed = true;
5509
- for (let offset = 1; offset <= continuation; offset++) {
5510
- const next = buffer[index + offset];
5511
- if ((next & 192) !== 128) {
5512
- wellFormed = false;
5513
- break;
5514
- }
5515
- codePoint = codePoint << 6 | next & 63;
5516
- }
5517
- const isSurrogate = codePoint >= 55296 && codePoint <= 57343;
5518
- if (!wellFormed || codePoint < minimum || codePoint > 1114111 || isSurrogate) {
5519
- invalid += 1;
5520
- index += 1;
5521
- continue;
5522
- }
5523
- index += continuation + 1;
5524
- }
5525
- return invalid;
5526
- }
5527
- function readBomEncoding(buffer) {
5528
- if (buffer.length >= 2) {
5529
- if (buffer[0] === 255 && buffer[1] === 254) return "utf-16le";
5530
- if (buffer[0] === 254 && buffer[1] === 255) return "utf-16be";
5531
- }
5532
- return null;
5533
- }
5534
- function looksLikeUtf16(buffer) {
5535
- if (buffer.length < 8 || buffer.length % 2 !== 0) return null;
5536
- const sample = Math.min(buffer.length, 4096);
5537
- let nulInLowByte = 0;
5538
- let nulInHighByte = 0;
5539
- const units = sample / 2;
5540
- for (let index = 0; index < sample; index += 2) {
5541
- if (buffer[index] === 0) nulInLowByte += 1;
5542
- if (buffer[index + 1] === 0) nulInHighByte += 1;
5543
- }
5544
- if (nulInHighByte > units * 0.3 && nulInLowByte < units * 0.05) return "utf-16le";
5545
- if (nulInLowByte > units * 0.3 && nulInHighByte < units * 0.05) return "utf-16be";
5546
- return null;
5547
- }
5548
- function decodeUtf16(buffer, encoding) {
5549
- const littleEndian = encoding === "utf-16le" ? buffer : Buffer.from(buffer.subarray(0, buffer.length - buffer.length % 2)).swap16();
5550
- return new TextDecoder("utf-16le").decode(littleEndian);
5551
- }
5552
- function decodeText(buffer) {
5553
- const bomEncoding = readBomEncoding(buffer);
5554
- if (bomEncoding) {
5555
- const text2 = decodeUtf16(buffer.subarray(2), bomEncoding);
5556
- return { text: text2, encoding: bomEncoding, invalidBytes: 0, binary: false };
5557
- }
5558
- if (buffer.includes(0)) {
5559
- const shape = looksLikeUtf16(buffer);
5560
- if (shape) {
5561
- return { text: decodeUtf16(buffer, shape), encoding: shape, invalidBytes: 0, binary: false };
5562
- }
5563
- const offset = buffer.indexOf(0);
5564
- return {
5565
- text: "",
5566
- encoding: "utf-8",
5567
- invalidBytes: 0,
5568
- binary: true,
5569
- binaryReason: `NUL byte at offset ${offset}`
5570
- };
5571
- }
5572
- const invalidBytes = countInvalidUtf8Bytes(buffer);
5573
- if (invalidBytes === 0) {
5574
- const controlBytes = countControlBytes(buffer);
5575
- if (controlBytes > CONTROL_BYTES_FLOOR && controlBytes * 100 > buffer.length) {
5576
- return {
5577
- text: "",
5578
- encoding: "utf-8",
5579
- invalidBytes: 0,
5580
- binary: true,
5581
- binaryReason: `${controlBytes} control byte(s) in ${buffer.length} B; valid UTF-8 but not text`
5582
- };
5583
- }
5584
- return {
5585
- text: new TextDecoder("utf-8").decode(buffer),
5586
- encoding: "utf-8",
5587
- invalidBytes: 0,
5588
- binary: false
5589
- };
5590
- }
5591
- if (invalidBytes >= 32 && invalidBytes * 3 >= buffer.length) {
5592
- return {
5593
- text: "",
5594
- encoding: "utf-8",
5595
- invalidBytes,
5596
- binary: true,
5597
- binaryReason: `${invalidBytes} of ${buffer.length} bytes are not UTF-8; treated as binary`
5598
- };
5599
- }
5600
- return {
5601
- text: buffer.toString("utf8"),
5602
- encoding: "utf-8-lossy",
5603
- invalidBytes,
5604
- binary: false
5605
- };
5606
- }
5607
- var BINARY_SCAN_BYTES = 8 * 1024 * 1024;
5608
- var CHUNK = 64 * 1024;
5609
- var SHAPE_SAMPLE_BYTES = 4096;
5610
- function isBinaryFile(absolutePath) {
5611
- if (isBinaryExtension(absolutePath)) return true;
5612
- let fd;
5613
- try {
5614
- fd = fs14__namespace.openSync(absolutePath, "r");
5615
- const buffer = Buffer.alloc(CHUNK);
5616
- let sample;
5617
- let position = 0;
5618
- while (position < BINARY_SCAN_BYTES) {
5619
- const wanted = Math.min(CHUNK, BINARY_SCAN_BYTES - position);
5620
- const bytesRead = fs14__namespace.readSync(fd, buffer, 0, wanted, position);
5621
- if (bytesRead === 0) return false;
5622
- const chunk = buffer.subarray(0, bytesRead);
5623
- if (sample === void 0) {
5624
- sample = Buffer.from(chunk.subarray(0, SHAPE_SAMPLE_BYTES));
5625
- }
5626
- if (chunk.includes(0)) {
5627
- const shape = readBomEncoding(sample) ?? looksLikeUtf16(sample);
5628
- return shape === null;
5629
- }
5630
- position += bytesRead;
6190
+ if (lines.length >= MAX_TREE_LINES) {
6191
+ truncatedAt = lines.length;
6192
+ break;
5631
6193
  }
5632
- return false;
5633
- } catch {
5634
- return false;
5635
- } finally {
5636
- if (fd !== void 0) {
5637
- try {
5638
- fs14__namespace.closeSync(fd);
5639
- } catch {
5640
- }
6194
+ if (!isDirectory) continue;
6195
+ if (frame.depth + 1 > MAX_TREE_DEPTH) {
6196
+ depthTruncated = true;
6197
+ continue;
5641
6198
  }
6199
+ stack.push({
6200
+ node: child,
6201
+ prefix: frame.prefix + (isLast ? " " : "\u2502 "),
6202
+ depth: frame.depth + 1,
6203
+ keys: childKeys(child),
6204
+ index: 0
6205
+ });
6206
+ }
6207
+ if (truncatedAt !== -1) {
6208
+ lines.push(`... [tree truncated at ${MAX_TREE_LINES} lines] ...`);
6209
+ } else if (depthTruncated) {
6210
+ lines.push(`... [tree truncated at ${MAX_TREE_DEPTH} levels] ...`);
5642
6211
  }
6212
+ const fence = fenceForText(lines.join("\n"), 3);
6213
+ return ["# Project Tree", "", `${fence}text`, ...lines, fence, ""].join("\n");
5643
6214
  }
5644
6215
  function gitPaths(cwd, args) {
5645
6216
  let output;
@@ -5726,6 +6297,10 @@ var SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
5726
6297
  ".mjs",
5727
6298
  ".cjs"
5728
6299
  ]);
6300
+ var PYTHON_EXTENSIONS = /* @__PURE__ */ new Set([".py", ".pyi"]);
6301
+ var RUBY_EXTENSIONS = /* @__PURE__ */ new Set([".rb", ".rake", ".gemspec"]);
6302
+ var C_EXTENSIONS = /* @__PURE__ */ new Set([".c", ".h", ".cc", ".cpp", ".cxx", ".hpp", ".hxx", ".m", ".mm"]);
6303
+ var PYTHON_SUFFIXES = [".py", ".pyi", "/__init__.py", "/__init__.pyi"];
5729
6304
  function buildImportResolver(files) {
5730
6305
  const byPath = /* @__PURE__ */ new Map();
5731
6306
  const byPathFolded = /* @__PURE__ */ new Map();
@@ -5752,11 +6327,45 @@ function buildImportResolver(files) {
5752
6327
  return { byPath, byPathFolded, byStem, byStemFolded };
5753
6328
  }
5754
6329
  function resolveSpecifier(fromFile, specifier, resolver) {
6330
+ const extension = path16__namespace.posix.extname(fromFile).toLowerCase();
6331
+ const exact = (key) => resolver.byPath.get(key) ?? resolver.byPathFolded.get(key.toLowerCase()) ?? null;
6332
+ const firstOf = (candidates) => {
6333
+ for (const candidate of candidates) {
6334
+ const hit = exact(candidate);
6335
+ if (hit) return hit;
6336
+ }
6337
+ return null;
6338
+ };
6339
+ if (PYTHON_EXTENSIONS.has(extension) && specifier.startsWith(".")) {
6340
+ const dots = /^\.+/.exec(specifier)?.[0].length ?? 0;
6341
+ const rest = specifier.slice(dots).replace(/\./g, "/");
6342
+ let base = path16__namespace.posix.dirname(fromFile);
6343
+ for (let up = 1; up < dots; up += 1) base = path16__namespace.posix.dirname(base);
6344
+ const joined2 = rest ? path16__namespace.posix.normalize(path16__namespace.posix.join(base, rest)) : base;
6345
+ return firstOf([joined2, ...PYTHON_SUFFIXES.map((suffix) => `${joined2}${suffix}`)]);
6346
+ }
6347
+ if (RUBY_EXTENSIONS.has(extension) && specifier.startsWith("./")) {
6348
+ const joined2 = path16__namespace.posix.normalize(
6349
+ path16__namespace.posix.join(path16__namespace.posix.dirname(fromFile), specifier)
6350
+ );
6351
+ return firstOf([`${joined2}.rb`, joined2]);
6352
+ }
6353
+ if (C_EXTENSIONS.has(extension) && specifier.startsWith("./")) {
6354
+ const joined2 = path16__namespace.posix.normalize(
6355
+ path16__namespace.posix.join(path16__namespace.posix.dirname(fromFile), specifier)
6356
+ );
6357
+ return exact(joined2);
6358
+ }
6359
+ if (extension === ".dart" && !specifier.includes(":")) {
6360
+ const joined2 = path16__namespace.posix.normalize(
6361
+ path16__namespace.posix.join(path16__namespace.posix.dirname(fromFile), specifier)
6362
+ );
6363
+ return firstOf([joined2, `${joined2}.dart`]);
6364
+ }
5755
6365
  if (!RELATIVE_SPECIFIER.test(specifier)) return null;
5756
6366
  const joined = path16__namespace.posix.normalize(
5757
6367
  path16__namespace.posix.join(path16__namespace.posix.dirname(fromFile), specifier)
5758
6368
  );
5759
- const exact = (key) => resolver.byPath.get(key) ?? resolver.byPathFolded.get(key.toLowerCase()) ?? null;
5760
6369
  const direct = exact(joined);
5761
6370
  if (direct) return direct;
5762
6371
  for (const suffix of IMPORT_CANDIDATE_SUFFIXES) {
@@ -5837,28 +6446,6 @@ function detectLanguage(filePath) {
5837
6446
  const ext = path16__namespace.posix.extname(base).toLowerCase();
5838
6447
  return LANGUAGE_BY_EXTENSION[ext] ?? "text";
5839
6448
  }
5840
- var TS_SOURCE_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
5841
- var isTsSource = (relativePath) => {
5842
- const lower = relativePath.toLowerCase();
5843
- return TS_SOURCE_EXTENSIONS.some((extension) => lower.endsWith(extension));
5844
- };
5845
- function importsOfText(relativePath, text2) {
5846
- if (isTsSource(relativePath)) return summarizeTypeScriptSource(relativePath, text2).imports;
5847
- return summarizeWithProfile(relativePath, text2)?.summary.imports ?? [];
5848
- }
5849
- function importsOfFile(relativePath, absolutePath) {
5850
- let buffer;
5851
- try {
5852
- buffer = fs14__namespace.readFileSync(absolutePath);
5853
- } catch {
5854
- return [];
5855
- }
5856
- const decoded = decodeText(buffer);
5857
- if (decoded.binary) return [];
5858
- return importsOfText(relativePath, decoded.text);
5859
- }
5860
-
5861
- // src/validator/validate.ts
5862
6449
  function maskedPath(value, secretRules) {
5863
6450
  return findSecretInPath(value, secretRules)?.masked ?? value;
5864
6451
  }
@@ -5924,16 +6511,14 @@ function emptyDrift() {
5924
6511
  function sha256Hex(buffer) {
5925
6512
  return crypto2__namespace.createHash("sha256").update(buffer).digest("hex");
5926
6513
  }
5927
- var VERIFY_SNIFF_MAX_BYTES = 8 * 1024 * 1024;
5928
6514
  function wouldNowBeIncluded(cwd, relativePath) {
5929
6515
  const absolutePath = path16__namespace.join(cwd, relativePath);
5930
6516
  try {
5931
6517
  const stats = fs14__namespace.statSync(absolutePath);
5932
6518
  if (!stats.isFile()) return false;
5933
- if (stats.size <= VERIFY_SNIFF_MAX_BYTES) {
5934
- return !decodeText(fs14__namespace.readFileSync(absolutePath)).binary;
5935
- }
5936
- return !isBinaryFile(absolutePath);
6519
+ if (isBinaryExtension(absolutePath)) return false;
6520
+ if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) return false;
6521
+ return !decodeText(fs14__namespace.readFileSync(absolutePath)).binary;
5937
6522
  } catch {
5938
6523
  return false;
5939
6524
  }
@@ -5979,9 +6564,13 @@ function describeManifestShapeProblem(value) {
5979
6564
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
5980
6565
  return 'a "parts" entry is not an object';
5981
6566
  }
5982
- if (typeof entry.filename !== "string") {
6567
+ const filename = entry.filename;
6568
+ if (typeof filename !== "string" || filename.trim() === "") {
5983
6569
  return 'a "parts" entry has no "filename"';
5984
6570
  }
6571
+ if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path16__namespace.isAbsolute(filename)) {
6572
+ return 'a "parts" entry "filename" must be a bare filename inside parts/';
6573
+ }
5985
6574
  }
5986
6575
  if (!candidate.layers || typeof candidate.layers !== "object" || Array.isArray(candidate.layers)) {
5987
6576
  return 'missing "layers" object';
@@ -6092,7 +6681,7 @@ function validateSnapshot(configInput) {
6092
6681
  });
6093
6682
  for (const diskFile of collection.files) {
6094
6683
  const snapshotHash = manifestFileMap.get(diskFile);
6095
- if (!snapshotHash) {
6684
+ if (snapshotHash === void 0) {
6096
6685
  const skipReason = skippedReasonOnDisk(diskFile);
6097
6686
  if (skipReason === "unchanged") {
6098
6687
  if (unchangedScope !== null) {
@@ -6106,6 +6695,11 @@ function validateSnapshot(configInput) {
6106
6695
  drift.missingInSnapshot.push(diskFile);
6107
6696
  continue;
6108
6697
  }
6698
+ if (unchangedScope !== null && !unchangedScope.has(diskFile) && !becameDependent(diskFile)) {
6699
+ drift.configMismatches.push(
6700
+ `scope: ${maskedPath(diskFile, config.secretRules)} is in the snapshot but is no longer in the changed-files scope`
6701
+ );
6702
+ }
6109
6703
  let diskHash;
6110
6704
  try {
6111
6705
  diskHash = sha256Hex(fs14__namespace.readFileSync(path16__namespace.join(config.cwd, diskFile)));
@@ -6246,6 +6840,41 @@ function validateSnapshot(configInput) {
6246
6840
  `includeSensitiveFiles: manifest ${recorded.includeSensitiveFiles} vs current ${config.includeSensitiveFiles}`
6247
6841
  );
6248
6842
  }
6843
+ if ((recorded.maxPartTokens ?? void 0) !== (config.maxPartTokens ?? void 0)) {
6844
+ drift.configMismatches.push(
6845
+ `maxPartTokens: manifest ${String(recorded.maxPartTokens ?? "unset")} vs current ${String(config.maxPartTokens ?? "unset")}`
6846
+ );
6847
+ }
6848
+ if ((recorded.maxMonolithBytes ?? null) !== (config.maxMonolithBytes ?? null)) {
6849
+ drift.configMismatches.push(
6850
+ `maxMonolithBytes: manifest ${String(recorded.maxMonolithBytes ?? null)} vs current ${String(config.maxMonolithBytes ?? null)}`
6851
+ );
6852
+ }
6853
+ if (Boolean(recorded.skeleton) !== Boolean(config.skeleton)) {
6854
+ drift.configMismatches.push(
6855
+ `skeleton: manifest ${Boolean(recorded.skeleton)} vs current ${Boolean(config.skeleton)}`
6856
+ );
6857
+ }
6858
+ if (Boolean(recorded.sarif) !== Boolean(config.sarif)) {
6859
+ drift.configMismatches.push(
6860
+ `sarif: manifest ${Boolean(recorded.sarif)} vs current ${Boolean(config.sarif)}`
6861
+ );
6862
+ }
6863
+ if ((recorded.changedSince ?? void 0) !== (config.changedSince ?? void 0)) {
6864
+ drift.configMismatches.push(
6865
+ `changedSince: manifest ${String(recorded.changedSince ?? "unset")} vs current ${String(config.changedSince ?? "unset")}`
6866
+ );
6867
+ }
6868
+ if (Boolean(recorded.staged) !== Boolean(config.staged)) {
6869
+ drift.configMismatches.push(
6870
+ `staged: manifest ${Boolean(recorded.staged)} vs current ${Boolean(config.staged)}`
6871
+ );
6872
+ }
6873
+ if (Boolean(recorded.withDependents) !== Boolean(config.withDependents)) {
6874
+ drift.configMismatches.push(
6875
+ `withDependents: manifest ${Boolean(recorded.withDependents)} vs current ${Boolean(config.withDependents)}`
6876
+ );
6877
+ }
6249
6878
  const effectiveDiscovery = config.discovery ?? "auto";
6250
6879
  const recordedDiscovery = recorded.discovery;
6251
6880
  if (recordedDiscovery !== void 0 && recordedDiscovery !== effectiveDiscovery) {
@@ -6466,7 +7095,7 @@ function validateSnapshot(configInput) {
6466
7095
 
6467
7096
  // src/version.ts
6468
7097
  var GENERATOR_NAME = "codebase-snapshot";
6469
- var GENERATOR_VERSION = "0.9.12";
7098
+ var GENERATOR_VERSION = "0.9.15";
6470
7099
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
6471
7100
  function isOurGeneratorName(name) {
6472
7101
  if (typeof name !== "string") return false;
@@ -6493,22 +7122,28 @@ function updateCommand(kind) {
6493
7122
  if (kind === "local") return "npm install codebase-snapshot@latest";
6494
7123
  return "npm install -g codebase-snapshot";
6495
7124
  }
6496
- function versionParts(value) {
6497
- const core = value.trim().replace(/^v/i, "").split("-")[0];
6498
- return core.split(".").map((part) => {
7125
+ function parseSemver(value) {
7126
+ const cleaned = value.trim().replace(/^v/i, "").split("+")[0] ?? "";
7127
+ const dash = cleaned.indexOf("-");
7128
+ const corePart = dash === -1 ? cleaned : cleaned.slice(0, dash);
7129
+ const prerelease = dash === -1 ? null : cleaned.slice(dash + 1);
7130
+ const core = corePart.split(".").map((part) => {
6499
7131
  const parsed = Number(part);
6500
7132
  return Number.isFinite(parsed) ? parsed : 0;
6501
7133
  });
7134
+ return { core, prerelease };
6502
7135
  }
6503
7136
  function isNewer(candidate, current) {
6504
- const left = versionParts(candidate);
6505
- const right = versionParts(current);
6506
- const length = Math.max(left.length, right.length);
7137
+ const left = parseSemver(candidate);
7138
+ const right = parseSemver(current);
7139
+ if (left.prerelease !== null && right.prerelease === null) return false;
7140
+ const length = Math.max(left.core.length, right.core.length);
6507
7141
  for (let index = 0; index < length; index += 1) {
6508
- const a = left[index] ?? 0;
6509
- const b = right[index] ?? 0;
7142
+ const a = left.core[index] ?? 0;
7143
+ const b = right.core[index] ?? 0;
6510
7144
  if (a !== b) return a > b;
6511
7145
  }
7146
+ if (left.prerelease === null && right.prerelease !== null) return true;
6512
7147
  return false;
6513
7148
  }
6514
7149
  function cacheDirectory(env = process.env, platform = process.platform) {
@@ -6576,14 +7211,22 @@ function writeCache(file, entry) {
6576
7211
  }
6577
7212
  }
6578
7213
  function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOUT_MS) {
6579
- return new Promise((resolve5) => {
7214
+ return new Promise((resolve6) => {
6580
7215
  let settled = false;
7216
+ let request = null;
6581
7217
  const finish = (value) => {
6582
7218
  if (settled) return;
6583
7219
  settled = true;
6584
- resolve5(value);
7220
+ clearTimeout(deadline);
7221
+ resolve6(value);
6585
7222
  };
6586
- const request = https__namespace.get(
7223
+ const deadline = setTimeout(() => {
7224
+ request?.destroy();
7225
+ finish(null);
7226
+ }, timeoutMs);
7227
+ deadline.unref();
7228
+ const transport = url.startsWith("http:") ? http__namespace : https__namespace;
7229
+ request = transport.get(
6587
7230
  url,
6588
7231
  {
6589
7232
  headers: {
@@ -6602,7 +7245,7 @@ function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOU
6602
7245
  response.on("data", (chunk) => {
6603
7246
  body += chunk;
6604
7247
  if (body.length > 64 * 1024) {
6605
- request.destroy();
7248
+ request?.destroy();
6606
7249
  finish(null);
6607
7250
  }
6608
7251
  });
@@ -6617,10 +7260,6 @@ function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOU
6617
7260
  }
6618
7261
  );
6619
7262
  request.on("error", () => finish(null));
6620
- request.setTimeout(timeoutMs, () => {
6621
- request.destroy();
6622
- finish(null);
6623
- });
6624
7263
  });
6625
7264
  }
6626
7265
  async function checkForUpdate(options) {
@@ -6664,10 +7303,13 @@ function describeMatcher(matcher) {
6664
7303
  return String(matcher);
6665
7304
  }
6666
7305
  function normalizeTarget(cwd, target) {
6667
- const absolute = path16__namespace.resolve(cwd, target);
6668
- const relative8 = path16__namespace.relative(cwd, absolute);
6669
- if (relative8.startsWith("..") || path16__namespace.isAbsolute(relative8)) return target;
6670
- return relative8.split(path16__namespace.sep).join("/");
7306
+ const resolvedCwd = path16__namespace.resolve(cwd);
7307
+ const absolute = path16__namespace.resolve(resolvedCwd, target);
7308
+ const relative8 = path16__namespace.relative(resolvedCwd, absolute);
7309
+ if (relative8 === "" || relative8 === ".." || relative8.startsWith(`..${path16__namespace.sep}`) || path16__namespace.isAbsolute(relative8)) {
7310
+ return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
7311
+ }
7312
+ return { relative: relative8.split(path16__namespace.sep).join("/"), outsideRoot: false };
6671
7313
  }
6672
7314
  function findRuleMatch(rules, relativePath) {
6673
7315
  return rules.find(
@@ -6694,9 +7336,19 @@ function readManifest2(config) {
6694
7336
  }
6695
7337
  }
6696
7338
  function explainPath(config, target) {
6697
- const relative8 = normalizeTarget(config.cwd, target);
6698
- const absolute = path16__namespace.join(config.cwd, relative8);
7339
+ const normalized = normalizeTarget(config.cwd, target);
7340
+ const relative8 = normalized.relative;
6699
7341
  const maskedPath2 = findSecretInPath(relative8, config.secretRules)?.masked ?? relative8;
7342
+ if (normalized.outsideRoot) {
7343
+ return {
7344
+ path: maskedPath2,
7345
+ exists: false,
7346
+ included: false,
7347
+ reason: "outside-root",
7348
+ detail: "path resolves outside the configured repository root and was not inspected"
7349
+ };
7350
+ }
7351
+ const absolute = path16__namespace.join(config.cwd, relative8);
6700
7352
  const result = {
6701
7353
  path: maskedPath2,
6702
7354
  exists: fs14__namespace.existsSync(absolute),
@@ -6770,6 +7422,12 @@ function explainPath(config, target) {
6770
7422
  return result;
6771
7423
  }
6772
7424
  }
7425
+ if (isBinaryExtension(absolute)) {
7426
+ result.included = false;
7427
+ result.reason = "binary";
7428
+ result.detail = "binary extension; generate skips it without reading and records `binary` in manifest.skipped[]";
7429
+ return result;
7430
+ }
6773
7431
  let sizeOnDisk = null;
6774
7432
  try {
6775
7433
  sizeOnDisk = fs14__namespace.statSync(absolute).size;
@@ -6782,13 +7440,6 @@ function explainPath(config, target) {
6782
7440
  result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
6783
7441
  return result;
6784
7442
  }
6785
- result.layer = classifyLayer(relative8, config.layers);
6786
- result.kind = classifyKind(relative8, config.kinds);
6787
- result.language = detectLanguage(relative8);
6788
- const layerRule = findRuleMatch(config.layers, relative8);
6789
- if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
6790
- const kindRule = findRuleMatch(config.kinds, relative8);
6791
- if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
6792
7443
  if (fs14__namespace.existsSync(absolute) && fs14__namespace.statSync(absolute).isFile()) {
6793
7444
  const buffer = fs14__namespace.readFileSync(absolute);
6794
7445
  const decoded = decodeText(buffer);
@@ -6806,6 +7457,13 @@ function explainPath(config, target) {
6806
7457
  result.secretCount = findings.length;
6807
7458
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
6808
7459
  }
7460
+ result.layer = classifyLayer(relative8, config.layers);
7461
+ result.kind = classifyKind(relative8, config.kinds);
7462
+ result.language = detectLanguage(relative8);
7463
+ const layerRule = findRuleMatch(config.layers, relative8);
7464
+ if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
7465
+ const kindRule = findRuleMatch(config.kinds, relative8);
7466
+ if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
6809
7467
  const manifest = readManifest2(config);
6810
7468
  const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative8) : void 0;
6811
7469
  result.part = entry?.part ?? null;
@@ -6943,7 +7601,7 @@ function describePayloadDiff(before, after, sourceFilesIdentical) {
6943
7601
  }
6944
7602
  if (fingerprintDiffers && (sourceFilesIdentical || configurationDiffers)) {
6945
7603
  reasons.push(
6946
- `content fingerprint ${shortDigest(before.fingerprint)} \u2192 ${shortDigest(after.fingerprint)}` + (sourceFilesIdentical ? " (same source files, packed differently)" : "")
7604
+ `content fingerprint ${shortDigest(before.fingerprint)} \u2192 ${shortDigest(after.fingerprint)}` + (sourceFilesIdentical ? " (same source files, packed or configured differently)" : "")
6947
7605
  );
6948
7606
  }
6949
7607
  if (partsDiffer) {
@@ -7215,7 +7873,8 @@ function renderConfig(answers) {
7215
7873
  // matched value is never included \u2014 only the path, the line and the rule.
7216
7874
  sarif: ${answers.sarif},
7217
7875
  // Snapshot only the files that differ from a git ref (for example "main"),
7218
- // plus untracked ones. null and false both mean "snapshot everything".
7876
+ // plus untracked ones. null means "snapshot everything"; any other value must
7877
+ // be a git ref string, and anything else is a configuration error.
7219
7878
  changedSince: null,
7220
7879
  // Snapshot only what is staged in the index: the pre-commit counterpart.
7221
7880
  staged: false,
@@ -7331,6 +7990,24 @@ function displayWidth(line) {
7331
7990
  return width;
7332
7991
  }
7333
7992
  var GUTTER_PATTERN = /^[ \t]*(?:[❯◆◻◼▏✖][ \t]+)*/;
7993
+ function sliceByDisplayWidth(text2, maxCells) {
7994
+ let cells = 0;
7995
+ let lastSpace = -1;
7996
+ let index = 0;
7997
+ for (const character of text2) {
7998
+ const width = isWideCodePoint(character.codePointAt(0) ?? 0) ? 2 : 1;
7999
+ if (cells + width > maxCells) break;
8000
+ if (character === " ") lastSpace = index;
8001
+ cells += width;
8002
+ index += character.length;
8003
+ }
8004
+ if (index >= text2.length) return { head: text2, tail: "" };
8005
+ if (lastSpace > 0) {
8006
+ return { head: text2.slice(0, lastSpace), tail: text2.slice(lastSpace + 1).trimStart() };
8007
+ }
8008
+ const safeIndex = index > 0 ? index : Array.from(text2)[0]?.length ?? 1;
8009
+ return { head: text2.slice(0, safeIndex), tail: text2.slice(safeIndex).trimStart() };
8010
+ }
7334
8011
  function wrapOneLine(line, limit) {
7335
8012
  if (displayWidth(line) <= limit) return [line];
7336
8013
  const gutter = GUTTER_PATTERN.exec(line)?.[0] ?? "";
@@ -7345,12 +8022,11 @@ function wrapOneLine(line, limit) {
7345
8022
  rows.push(prefix + rest);
7346
8023
  break;
7347
8024
  }
7348
- let cut = room;
7349
- const space = rest.slice(0, room).lastIndexOf(" ");
7350
- if (space > 0) cut = space;
7351
- const taken = rest.slice(0, cut).trimEnd();
7352
- rows.push(`${prefix}${taken.length > 0 ? taken : rest.slice(0, cut)}`);
7353
- rest = rest.slice(cut).trimStart();
8025
+ const { head, tail } = sliceByDisplayWidth(rest, room);
8026
+ rows.push(
8027
+ `${prefix}${head.length > 0 ? head : rest.slice(0, 1)}`
8028
+ );
8029
+ rest = tail;
7354
8030
  prefix = continuation;
7355
8031
  }
7356
8032
  return rows;
@@ -7421,7 +8097,7 @@ function keyReader(input) {
7421
8097
  next() {
7422
8098
  const queued = queue.shift();
7423
8099
  if (queued) return Promise.resolve(queued);
7424
- return new Promise((resolve5) => waiters.push(resolve5));
8100
+ return new Promise((resolve6) => waiters.push(resolve6));
7425
8101
  },
7426
8102
  close() {
7427
8103
  input.off("keypress", onKey);
@@ -7638,17 +8314,25 @@ var CONFIG_CANDIDATES = [
7638
8314
  ".snapshotrc.json",
7639
8315
  ".snapshotrc"
7640
8316
  ];
7641
- function chooseConfigFileName(cwd) {
7642
- if (!supportsTypeScriptImports()) return "snapshot.config.mjs";
7643
- const pkgPath = path16__namespace.join(cwd, "package.json");
7644
- if (!fs14__namespace.existsSync(pkgPath)) return "snapshot.config.mjs";
8317
+ function parsePackageJson(raw) {
8318
+ const parsed = JSON.parse(stripJsonComments(raw));
8319
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
8320
+ throw new Error("package.json is not a JSON object");
8321
+ }
8322
+ return parsed;
8323
+ }
8324
+ function readPackageJson(cwd) {
7645
8325
  try {
7646
- const parsed = JSON.parse(fs14__namespace.readFileSync(pkgPath, "utf8"));
7647
- return parsed.type === "module" ? "snapshot.config.ts" : "snapshot.config.mjs";
8326
+ return parsePackageJson(fs14__namespace.readFileSync(path16__namespace.join(cwd, "package.json"), "utf8"));
7648
8327
  } catch {
7649
- return "snapshot.config.mjs";
8328
+ return null;
7650
8329
  }
7651
8330
  }
8331
+ function chooseConfigFileName(cwd) {
8332
+ if (!supportsTypeScriptImports()) return "snapshot.config.mjs";
8333
+ const parsed = readPackageJson(cwd);
8334
+ return parsed?.type === "module" ? "snapshot.config.ts" : "snapshot.config.mjs";
8335
+ }
7652
8336
  var SIZE_CHOICES = [
7653
8337
  { value: "60k", label: "Small", hint: "60 KB \xB7 ~15k tokens \xB7 tight context windows" },
7654
8338
  { value: "120k", label: "Medium", hint: "120 KB \xB7 ~30k tokens \xB7 recommended" },
@@ -7656,12 +8340,9 @@ var SIZE_CHOICES = [
7656
8340
  { value: "custom", label: "Custom\u2026", hint: "type a size like 150k or 1.5mb" }
7657
8341
  ];
7658
8342
  function packageJsonHasConfig(cwd) {
7659
- try {
7660
- const parsed = JSON.parse(fs14__namespace.readFileSync(path16__namespace.join(cwd, "package.json"), "utf8"));
7661
- return typeof parsed.snapshot === "object" && parsed.snapshot !== null && !Array.isArray(parsed.snapshot);
7662
- } catch {
7663
- return false;
7664
- }
8343
+ const parsed = readPackageJson(cwd);
8344
+ if (parsed === null) return false;
8345
+ return typeof parsed.snapshot === "object" && parsed.snapshot !== null && !Array.isArray(parsed.snapshot);
7665
8346
  }
7666
8347
  function artifactAnswers(options) {
7667
8348
  const artifacts = { ...DEFAULT_ANSWERS.artifacts };
@@ -7702,12 +8383,7 @@ function writeFileOrExplain(target, content) {
7702
8383
  function canWriteModuleConfig(name, cwd) {
7703
8384
  if (name.endsWith(".mjs") || name.endsWith(".ts")) return true;
7704
8385
  if (!name.endsWith(".js")) return false;
7705
- try {
7706
- const parsed = JSON.parse(fs14__namespace.readFileSync(path16__namespace.join(cwd, "package.json"), "utf8"));
7707
- return parsed.type === "module";
7708
- } catch {
7709
- return false;
7710
- }
8386
+ return readPackageJson(cwd)?.type === "module";
7711
8387
  }
7712
8388
  function configFormatLabel(name) {
7713
8389
  if (name.endsWith(".js")) return 'CommonJS `.js` (package.json has no "type": "module")';
@@ -7735,7 +8411,8 @@ function serializePackageJson(raw, value) {
7735
8411
  const crlf = raw.includes("\r\n");
7736
8412
  const body = JSON.stringify(value, null, spacing);
7737
8413
  const text2 = crlf ? body.replace(/\n/g, "\r\n") : body;
7738
- return `${text2}${raw.endsWith("\n") ? crlf ? "\r\n" : "\n" : ""}`;
8414
+ const bom = raw.startsWith("\uFEFF") ? "\uFEFF" : "";
8415
+ return `${bom}${text2}${raw.endsWith("\n") ? crlf ? "\r\n" : "\n" : ""}`;
7739
8416
  }
7740
8417
  function updatePackageJson(cwd, notes) {
7741
8418
  const packagePath = path16__namespace.join(cwd, "package.json");
@@ -7751,7 +8428,7 @@ function updatePackageJson(cwd, notes) {
7751
8428
  let parsed;
7752
8429
  try {
7753
8430
  raw = fs14__namespace.readFileSync(packagePath, "utf8");
7754
- parsed = JSON.parse(raw);
8431
+ parsed = parsePackageJson(raw);
7755
8432
  } catch {
7756
8433
  notes.push("Could not parse package.json; npm scripts and the devDependency were not added.");
7757
8434
  return unchanged;
@@ -8282,7 +8959,100 @@ function workerEntry(directory, isCjs) {
8282
8959
 
8283
8960
  // src/index.ts
8284
8961
  var SCHEMA_VERSION = "3.0.0";
8285
- var SUMMARY_MAX_SOURCE_BYTES = 2 * 1024 * 1024;
8962
+ var SUMMARY_MAX_SOURCE_BYTES2 = SUMMARY_MAX_SOURCE_BYTES;
8963
+ var FILE_DERIVATIONS = /* @__PURE__ */ new Map();
8964
+ var FILE_DERIVATION_LIMIT_BYTES = 64 * 1024 * 1024;
8965
+ var fileDerivationBytes = 0;
8966
+ function takeDerivation(path17, hash, settings) {
8967
+ const cached = FILE_DERIVATIONS.get(path17);
8968
+ if (cached === void 0 || cached.hash !== hash || cached.settings !== settings) return void 0;
8969
+ return cached;
8970
+ }
8971
+ function rememberDerivation(path17, hash, settings, derivation) {
8972
+ const bodyBytes = derivation.finalContent === derivation.redacted ? derivation.redacted.length : derivation.redacted.length + derivation.finalContent.length;
8973
+ const bytes = bodyBytes * 2 + 512;
8974
+ if (bytes > FILE_DERIVATION_LIMIT_BYTES / 4) return;
8975
+ while (fileDerivationBytes + bytes > FILE_DERIVATION_LIMIT_BYTES) {
8976
+ const oldest = FILE_DERIVATIONS.keys().next();
8977
+ if (oldest.done === true) break;
8978
+ const evicted = FILE_DERIVATIONS.get(oldest.value);
8979
+ FILE_DERIVATIONS.delete(oldest.value);
8980
+ if (evicted !== void 0) fileDerivationBytes -= evicted.bytes;
8981
+ }
8982
+ FILE_DERIVATIONS.set(path17, { ...derivation, hash, settings, bytes });
8983
+ fileDerivationBytes += bytes;
8984
+ }
8985
+ function derivationSettings(config) {
8986
+ const rules = config.secretRules.map(
8987
+ (rule) => `${rule.rule}\0${rule.pattern.source}\0${rule.pattern.flags}\0${rule.valueGroup ?? ""}`
8988
+ ).join("");
8989
+ return `${GENERATOR_VERSION}${configDigest(config)}${sha256Hex2(rules)}`;
8990
+ }
8991
+ function deriveFile(relativePath, rawContent, sizeBytes, config) {
8992
+ const lineCount = countLines(rawContent);
8993
+ const { redacted, findings } = scanAndRedactSecrets(rawContent, config.secretRules, relativePath);
8994
+ const isLarge = sizeBytes > config.largeFileBytes;
8995
+ let finalContent = redacted;
8996
+ let isPreviewTruncated = false;
8997
+ let includedLines = lineCount;
8998
+ let inclusionMode = "full";
8999
+ if (config.skeleton === true && isSkeletonizable(relativePath)) {
9000
+ const skeleton = skeletonizeTypeScript(redacted, relativePath);
9001
+ if (skeleton.collapsed > 0) {
9002
+ finalContent = skeleton.text;
9003
+ inclusionMode = "signatures";
9004
+ includedLines = countLines(skeleton.text);
9005
+ }
9006
+ }
9007
+ if (isLarge && inclusionMode !== "signatures") {
9008
+ const preview = truncatePreview(redacted, config.previewHeadLines, config.previewTailLines);
9009
+ finalContent = preview.content;
9010
+ isPreviewTruncated = preview.isTruncated;
9011
+ includedLines = preview.includedLines;
9012
+ inclusionMode = isPreviewTruncated ? "preview" : "full";
9013
+ }
9014
+ let summary;
9015
+ let summaryQuality;
9016
+ let summarySkip = null;
9017
+ let summaryWarning = null;
9018
+ let dependentImports = null;
9019
+ if (Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES2) {
9020
+ summarySkip = "oversize";
9021
+ dependentImports = [];
9022
+ } else if (isPreviewTruncated && hasStructuralSummary(relativePath)) {
9023
+ summarySkip = "preview";
9024
+ dependentImports = importsOfText(relativePath, rawContent);
9025
+ } else {
9026
+ try {
9027
+ const outcome = summarizeFile(relativePath, rawContent);
9028
+ summary = outcome?.summary ? maskSummaryStrings(outcome.summary, config.secretRules) : void 0;
9029
+ summaryQuality = outcome?.quality;
9030
+ if (isSourceSummary(summary) && summary.parseErrors) {
9031
+ summaryWarning = `Parse errors in ${maskPathText(relativePath, config.secretRules)} (${summary.parseErrors}); its summary is incomplete.`;
9032
+ }
9033
+ } catch (err) {
9034
+ summaryWarning = `Summary skipped for ${maskPathText(relativePath, config.secretRules)}: ${err.message}`.replace(
9035
+ /\s+/g,
9036
+ " "
9037
+ );
9038
+ }
9039
+ }
9040
+ return {
9041
+ redacted,
9042
+ findings,
9043
+ lineCount,
9044
+ finalContent,
9045
+ inclusionMode,
9046
+ isPreviewTruncated,
9047
+ includedLines,
9048
+ isLarge,
9049
+ summary,
9050
+ summaryQuality,
9051
+ summarySkip,
9052
+ summaryWarning,
9053
+ dependentImports
9054
+ };
9055
+ }
8286
9056
  function sha256Hex2(input) {
8287
9057
  return crypto2__namespace.createHash("sha256").update(input).digest("hex");
8288
9058
  }
@@ -8471,6 +9241,7 @@ function isProcessAlive(pid) {
8471
9241
  var OWNERSHIP_MARKER = ".codebase-snapshot";
8472
9242
  var SUPPORTED_MARKER_SCHEMAS = /* @__PURE__ */ new Set([SCHEMA_VERSION]);
8473
9243
  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;
9244
+ var SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/;
8474
9245
  function listEntries(dir) {
8475
9246
  const entries = [];
8476
9247
  const walk = (absolute, prefix) => {
@@ -8489,7 +9260,32 @@ function listEntries(dir) {
8489
9260
  walk(dir, "");
8490
9261
  return entries.sort();
8491
9262
  }
9263
+ function markerInventory(dir) {
9264
+ const entries = listEntries(dir);
9265
+ const files = [];
9266
+ for (const entry of entries) {
9267
+ if (entry === OWNERSHIP_MARKER) continue;
9268
+ if (IGNORABLE_ENTRIES.has(entry.slice(entry.lastIndexOf("/") + 1))) continue;
9269
+ const full = path16__namespace.join(dir, ...entry.split("/"));
9270
+ let stats;
9271
+ try {
9272
+ stats = fs14__namespace.lstatSync(full);
9273
+ } catch {
9274
+ continue;
9275
+ }
9276
+ if (!stats.isFile()) continue;
9277
+ let digest;
9278
+ try {
9279
+ digest = sha256Hex2(fs14__namespace.readFileSync(full));
9280
+ } catch {
9281
+ continue;
9282
+ }
9283
+ files.push({ path: entry, bytes: stats.size, sha256: digest });
9284
+ }
9285
+ return { entries, files };
9286
+ }
8492
9287
  function markerPayload(dir, state, id, createdAt) {
9288
+ const { entries, files } = markerInventory(dir);
8493
9289
  const marker2 = {
8494
9290
  generator: GENERATOR_NAME,
8495
9291
  version: GENERATOR_VERSION,
@@ -8498,7 +9294,8 @@ function markerPayload(dir, state, id, createdAt) {
8498
9294
  state,
8499
9295
  id,
8500
9296
  pid: process.pid,
8501
- entries: listEntries(dir)
9297
+ entries,
9298
+ files
8502
9299
  };
8503
9300
  const manifestPath = path16__namespace.join(dir, "manifest.json");
8504
9301
  if (fs14__namespace.existsSync(manifestPath)) {
@@ -8558,6 +9355,33 @@ function readOwnershipMarker(dir) {
8558
9355
  if (candidate.state !== "staging" && candidate.state !== "complete") {
8559
9356
  return { marker: null, problem: "its .codebase-snapshot marker records no run state" };
8560
9357
  }
9358
+ const rawFiles = candidate.files;
9359
+ let files;
9360
+ if (rawFiles !== void 0) {
9361
+ if (!Array.isArray(rawFiles)) {
9362
+ return {
9363
+ marker: null,
9364
+ problem: "its .codebase-snapshot marker's file inventory is not an array"
9365
+ };
9366
+ }
9367
+ files = [];
9368
+ for (const item of rawFiles) {
9369
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
9370
+ return {
9371
+ marker: null,
9372
+ problem: "its .codebase-snapshot marker's file inventory holds an entry that is not an object"
9373
+ };
9374
+ }
9375
+ const record = item;
9376
+ 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)) {
9377
+ return {
9378
+ marker: null,
9379
+ problem: "its .codebase-snapshot marker's file inventory holds an entry this build cannot read"
9380
+ };
9381
+ }
9382
+ files.push({ path: record.path, bytes: record.bytes, sha256: record.sha256 });
9383
+ }
9384
+ }
8561
9385
  return {
8562
9386
  marker: {
8563
9387
  generator: GENERATOR_NAME,
@@ -8568,7 +9392,8 @@ function readOwnershipMarker(dir) {
8568
9392
  id: candidate.id,
8569
9393
  pid: typeof candidate.pid === "number" ? candidate.pid : void 0,
8570
9394
  manifestSha256: typeof candidate.manifestSha256 === "string" ? candidate.manifestSha256 : void 0,
8571
- entries: Array.isArray(candidate.entries) && candidate.entries.every((entry) => typeof entry === "string") ? candidate.entries : void 0
9395
+ entries: Array.isArray(candidate.entries) && candidate.entries.every((entry) => typeof entry === "string") ? candidate.entries : void 0,
9396
+ files
8572
9397
  },
8573
9398
  problem: null
8574
9399
  };
@@ -8583,6 +9408,59 @@ function describeManifestProblem(value) {
8583
9408
  if (!Array.isArray(candidate.files)) return "has no files array";
8584
9409
  return null;
8585
9410
  }
9411
+ function verifyMarkerInventory(dir, entries, files) {
9412
+ const diskEntries = new Set(entries);
9413
+ const recorded = /* @__PURE__ */ new Map();
9414
+ for (const record of files) {
9415
+ if (recorded.has(record.path)) {
9416
+ return `its .codebase-snapshot inventory records ${record.path} twice`;
9417
+ }
9418
+ if (!diskEntries.has(record.path)) {
9419
+ return `its .codebase-snapshot inventory records ${record.path}, which is missing from the directory`;
9420
+ }
9421
+ recorded.set(record.path, record);
9422
+ }
9423
+ for (const entry of entries) {
9424
+ if (entry === OWNERSHIP_MARKER) continue;
9425
+ if (IGNORABLE_ENTRIES.has(entry.slice(entry.lastIndexOf("/") + 1))) continue;
9426
+ const full = path16__namespace.join(dir, ...entry.split("/"));
9427
+ let stats;
9428
+ try {
9429
+ stats = fs14__namespace.lstatSync(full);
9430
+ } catch {
9431
+ return `its .codebase-snapshot inventory lists ${entry}, which cannot be read`;
9432
+ }
9433
+ if (stats.isDirectory()) {
9434
+ if (recorded.has(entry)) {
9435
+ return `its .codebase-snapshot inventory records the directory ${entry} as a file`;
9436
+ }
9437
+ continue;
9438
+ }
9439
+ if (!stats.isFile()) {
9440
+ if (recorded.has(entry)) {
9441
+ return `its .codebase-snapshot inventory records ${entry} as a regular file, but it is not one`;
9442
+ }
9443
+ continue;
9444
+ }
9445
+ const record = recorded.get(entry);
9446
+ if (record === void 0) {
9447
+ return `its .codebase-snapshot inventory does not record the file ${entry}`;
9448
+ }
9449
+ if (record.bytes !== stats.size) {
9450
+ return `its .codebase-snapshot inventory records ${entry} as ${record.bytes} B, but it is ${stats.size} B`;
9451
+ }
9452
+ let digest;
9453
+ try {
9454
+ digest = sha256Hex2(fs14__namespace.readFileSync(full));
9455
+ } catch {
9456
+ return `its .codebase-snapshot inventory cannot verify ${entry}: the file could not be read`;
9457
+ }
9458
+ if (digest !== record.sha256) {
9459
+ return `its .codebase-snapshot inventory's digest for ${entry} does not match the file`;
9460
+ }
9461
+ }
9462
+ return null;
9463
+ }
8586
9464
  function assessSnapshotDirectory(dir) {
8587
9465
  const { marker: marker2, problem } = readOwnershipMarker(dir);
8588
9466
  if (!marker2) return { owned: false, problem, foreignEntries: [], marker: null };
@@ -8595,7 +9473,8 @@ function assessSnapshotDirectory(dir) {
8595
9473
  };
8596
9474
  }
8597
9475
  const manifestPath = path16__namespace.join(dir, "manifest.json");
8598
- if (fs14__namespace.existsSync(manifestPath)) {
9476
+ const hasManifest = fs14__namespace.existsSync(manifestPath);
9477
+ if (hasManifest) {
8599
9478
  let raw;
8600
9479
  try {
8601
9480
  raw = fs14__namespace.readFileSync(manifestPath, "utf8");
@@ -8651,6 +9530,14 @@ function assessSnapshotDirectory(dir) {
8651
9530
  marker: marker2
8652
9531
  };
8653
9532
  }
9533
+ if (marker2.files === void 0 && !hasManifest) {
9534
+ return {
9535
+ owned: false,
9536
+ problem: "its .codebase-snapshot marker records neither per-file digests nor a manifest digest, so it cannot prove this generator wrote the directory",
9537
+ foreignEntries: [],
9538
+ marker: marker2
9539
+ };
9540
+ }
8654
9541
  const recorded = new Set(marker2.entries ?? []);
8655
9542
  if (recorded.size === 0) {
8656
9543
  return {
@@ -8660,13 +9547,18 @@ function assessSnapshotDirectory(dir) {
8660
9547
  marker: marker2
8661
9548
  };
8662
9549
  }
8663
- const foreignEntries = listEntries(dir).filter(
9550
+ const entries = listEntries(dir);
9551
+ const foreignEntries = entries.filter(
8664
9552
  (entry) => !recorded.has(entry) && !IGNORABLE_ENTRIES.has(entry)
8665
9553
  );
9554
+ if (foreignEntries.length > 0) {
9555
+ return { owned: false, problem: null, foreignEntries, marker: marker2 };
9556
+ }
9557
+ const inventoryProblem = marker2.files === void 0 ? null : verifyMarkerInventory(dir, entries, marker2.files);
8666
9558
  return {
8667
- owned: foreignEntries.length === 0,
8668
- problem: null,
8669
- foreignEntries,
9559
+ owned: inventoryProblem === null,
9560
+ problem: inventoryProblem,
9561
+ foreignEntries: [],
8670
9562
  marker: marker2
8671
9563
  };
8672
9564
  }
@@ -8826,10 +9718,7 @@ function acquireRunLock(stagingRoot) {
8826
9718
  };
8827
9719
  } catch (err) {
8828
9720
  if (err.code !== "EEXIST") throw err;
8829
- if (attempt === 0 && lockOwnerIsGone(lockPath)) {
8830
- fs14__namespace.rmSync(lockPath, { force: true });
8831
- continue;
8832
- }
9721
+ if (attempt === 0 && reclaimStaleLock(lockPath)) continue;
8833
9722
  throw new Error(
8834
9723
  `Another generate run is already using the staging directory ${stagingRoot}. Wait for it to finish, or delete ${lockPath} if no other run is active.`
8835
9724
  );
@@ -8838,14 +9727,25 @@ function acquireRunLock(stagingRoot) {
8838
9727
  throw new Error(`Could not acquire the generate lock for ${stagingRoot}.`);
8839
9728
  }
8840
9729
  function lockKeyFor(stagingRoot) {
8841
- let key = stagingRoot;
8842
- try {
8843
- key = fs14__namespace.realpathSync(stagingRoot);
8844
- } catch {
8845
- }
9730
+ let key = canonicalLockTarget(stagingRoot);
8846
9731
  if (process.platform === "win32" || process.platform === "darwin") key = key.toLowerCase();
8847
9732
  return sha256Hex2(key).slice(0, 16);
8848
9733
  }
9734
+ function canonicalLockTarget(targetPath) {
9735
+ const resolved = path16__namespace.resolve(targetPath);
9736
+ let existing = resolved;
9737
+ const tail = [];
9738
+ for (; ; ) {
9739
+ try {
9740
+ return path16__namespace.join(fs14__namespace.realpathSync(existing), ...tail);
9741
+ } catch {
9742
+ const parent = path16__namespace.dirname(existing);
9743
+ if (parent === existing) return resolved;
9744
+ tail.unshift(path16__namespace.basename(existing));
9745
+ existing = parent;
9746
+ }
9747
+ }
9748
+ }
8849
9749
  function lockPathFor(stagingRoot) {
8850
9750
  return path16__namespace.join(os__namespace.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
8851
9751
  }
@@ -8870,6 +9770,24 @@ function lockOwnerIsGone(lockPath) {
8870
9770
  return err.code === "ESRCH";
8871
9771
  }
8872
9772
  }
9773
+ function reclaimStaleLock(lockPath) {
9774
+ let before;
9775
+ try {
9776
+ before = fs14__namespace.statSync(lockPath);
9777
+ } catch {
9778
+ return true;
9779
+ }
9780
+ if (!lockOwnerIsGone(lockPath)) return false;
9781
+ try {
9782
+ const current = fs14__namespace.statSync(lockPath);
9783
+ const sameFile = current.ino === before.ino && current.birthtimeMs === before.birthtimeMs && current.mtimeMs === before.mtimeMs;
9784
+ if (!sameFile) return false;
9785
+ fs14__namespace.rmSync(lockPath, { force: true });
9786
+ return true;
9787
+ } catch {
9788
+ return false;
9789
+ }
9790
+ }
8873
9791
  function lockFileIsAncient(lockPath) {
8874
9792
  try {
8875
9793
  return Date.now() - fs14__namespace.statSync(lockPath).mtimeMs > STALE_RUN_MS;
@@ -8927,7 +9845,6 @@ function swapOnce(stagingDir, outDir) {
8927
9845
  throw copyErr;
8928
9846
  }
8929
9847
  }
8930
- if (hadPrevious) fs14__namespace.rmSync(backupDir, { recursive: true, force: true });
8931
9848
  } catch (err) {
8932
9849
  if (hadPrevious && fs14__namespace.existsSync(backupDir)) {
8933
9850
  if (fs14__namespace.existsSync(outDir)) fs14__namespace.rmSync(outDir, { recursive: true, force: true });
@@ -8935,6 +9852,16 @@ function swapOnce(stagingDir, outDir) {
8935
9852
  }
8936
9853
  throw err;
8937
9854
  }
9855
+ if (hadPrevious) {
9856
+ try {
9857
+ fs14__namespace.rmSync(backupDir, { recursive: true, force: true });
9858
+ } catch (err) {
9859
+ process.stderr.write(
9860
+ `\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.
9861
+ `
9862
+ );
9863
+ }
9864
+ }
8938
9865
  }
8939
9866
  function sleepSync(milliseconds) {
8940
9867
  const buffer = new Int32Array(new SharedArrayBuffer(4));
@@ -8957,22 +9884,18 @@ function artifactWarnings(artifacts, sarif) {
8957
9884
  }
8958
9885
  return messages;
8959
9886
  }
9887
+ function installHookStdoutRedirect() {
9888
+ return installStdoutRouter();
9889
+ }
8960
9890
  function runAfterGenerate(config, manifest) {
8961
9891
  const hook = config.hooks.afterGenerate;
8962
9892
  if (!hook) return null;
8963
- const stdoutWrite = process.stdout.write.bind(process.stdout);
8964
- const stderrWrite = process.stderr.write.bind(process.stderr);
8965
- const hookScope = new async_hooks.AsyncLocalStorage();
8966
- const patchedWrite = ((...args) => hookScope.getStore() === true ? stderrWrite(...args) : stdoutWrite(...args));
8967
- const restoreStdout = () => {
8968
- if (process.stdout.write === patchedWrite) process.stdout.write = stdoutWrite;
8969
- };
9893
+ const releaseRedirect = installHookStdoutRedirect();
8970
9894
  let returned;
8971
9895
  try {
8972
- process.stdout.write = patchedWrite;
8973
- returned = hookScope.run(true, () => hook(manifest));
9896
+ returned = hookStdoutScope.run(true, () => hook(manifest));
8974
9897
  } catch (err) {
8975
- restoreStdout();
9898
+ releaseRedirect();
8976
9899
  const message = maskPathText(err.message, config.secretRules);
8977
9900
  manifest.warnings.push(`hooks.afterGenerate failed: ${message}`);
8978
9901
  manifest.totals.warningCount = manifest.warnings.length;
@@ -8980,10 +9903,10 @@ function runAfterGenerate(config, manifest) {
8980
9903
  }
8981
9904
  const thenable = returned;
8982
9905
  if (!thenable || typeof thenable.then !== "function") {
8983
- restoreStdout();
9906
+ releaseRedirect();
8984
9907
  return null;
8985
9908
  }
8986
- return Promise.resolve(returned).finally(restoreStdout);
9909
+ return Promise.resolve(returned).finally(releaseRedirect);
8987
9910
  }
8988
9911
  function partitionByBudget(files, config, fingerprint) {
8989
9912
  const budgetFor = (file) => config.budgets.byLayer[file.layer] ?? config.budgets.default;
@@ -8994,23 +9917,14 @@ function partitionByBudget(files, config, fingerprint) {
8994
9917
  if (bucket) bucket.push(file);
8995
9918
  else buckets.set(budget, [file]);
8996
9919
  }
8997
- if (buckets.size <= 1) {
8998
- const only = buckets.size === 1 ? Array.from(buckets.keys())[0] : config.maxPartBytes;
8999
- return partitionFiles(files, only, fingerprint);
9920
+ if (buckets.size === 0) return [];
9921
+ if (buckets.size === 1) {
9922
+ return partitionFiles(files, Array.from(buckets.keys())[0], fingerprint);
9000
9923
  }
9001
- const parts = [];
9002
- for (const budget of Array.from(buckets.keys()).sort((a, b) => a - b)) {
9003
- parts.push(...partitionFiles(buckets.get(budget) ?? [], budget, fingerprint));
9004
- }
9005
- const merged = renumberParts(parts, fingerprint);
9006
- const byPath = new Map(files.map((file) => [file.relativePath, file]));
9007
- for (const part of merged) {
9008
- for (const included of part.metadata.includedFiles) {
9009
- const file = byPath.get(included.relativePath);
9010
- if (file) file.part = part.filename;
9011
- }
9012
- }
9013
- return merged;
9924
+ return partitionFilesForBuckets(
9925
+ Array.from(buckets.entries()).sort(([left], [right]) => left - right).map(([budgetBytes, bucketFiles]) => ({ files: bucketFiles, budgetBytes })),
9926
+ fingerprint
9927
+ );
9014
9928
  }
9015
9929
  function generateSnapshot(configInput, options) {
9016
9930
  assertUsableConfigInput(configInput);
@@ -9042,6 +9956,7 @@ function generateSnapshot(configInput, options) {
9042
9956
  return false;
9043
9957
  }) : collection.files;
9044
9958
  const files = [];
9959
+ const derivationKey = derivationSettings(config);
9045
9960
  const monolithBodies = /* @__PURE__ */ new Map();
9046
9961
  const skipped = maskSkipRecords([...collection.skipped], config.secretRules);
9047
9962
  const secretFindings = [];
@@ -9054,6 +9969,7 @@ function generateSnapshot(configInput, options) {
9054
9969
  const fileWarnings = [];
9055
9970
  const oversizeSummaryPaths = [];
9056
9971
  const previewSummaryPaths = [];
9972
+ const skippedSummaryImports = /* @__PURE__ */ new Map();
9057
9973
  const layerCounts = {};
9058
9974
  const kindCounts = {};
9059
9975
  let totalLines = 0;
@@ -9118,8 +10034,6 @@ function generateSnapshot(configInput, options) {
9118
10034
  }
9119
10035
  const hashSha256 = sha256Hex2(buffer);
9120
10036
  const rawContent = decoded.text;
9121
- const lineCount = countLines(rawContent);
9122
- totalLines += lineCount;
9123
10037
  totalSizeBytes += stats.size;
9124
10038
  if (decoded.encoding !== "utf-8") {
9125
10039
  encodingNotes.push({
@@ -9133,66 +10047,25 @@ function generateSnapshot(configInput, options) {
9133
10047
  const language = detectLanguage(relativePath);
9134
10048
  bump(layerCounts, layer2);
9135
10049
  bump(kindCounts, kind);
9136
- const { redacted, findings } = scanAndRedactSecrets(
9137
- rawContent,
9138
- config.secretRules,
9139
- relativePath
9140
- );
9141
- secretFindings.push(...findings);
9142
- const isLarge = stats.size > config.largeFileBytes;
9143
- if (isLarge) largeFileCount += 1;
9144
- let finalContent = redacted;
9145
- let isPreviewTruncated = false;
9146
- let includedLines = lineCount;
9147
- let inclusionMode = "full";
9148
- if (config.skeleton === true && isSkeletonizable(relativePath)) {
9149
- const skeleton = skeletonizeTypeScript(redacted, relativePath);
9150
- if (skeleton.collapsed > 0) {
9151
- finalContent = skeleton.text;
9152
- inclusionMode = "signatures";
9153
- includedLines = countLines(skeleton.text);
9154
- }
9155
- }
9156
- if (isLarge && inclusionMode !== "signatures") {
9157
- const preview = truncatePreview(
9158
- redacted,
9159
- config.previewHeadLines,
9160
- config.previewTailLines
9161
- );
9162
- finalContent = preview.content;
9163
- isPreviewTruncated = preview.isTruncated;
9164
- includedLines = preview.includedLines;
9165
- inclusionMode = isPreviewTruncated ? "preview" : "full";
9166
- }
9167
- if (config.includeMonolith && (isPreviewTruncated || inclusionMode === "signatures")) {
9168
- monolithBodies.set(relativePath, redacted);
9169
- }
9170
- let summary;
9171
- let summaryQuality;
9172
- if (Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES) {
9173
- oversizeSummaryPaths.push(relativePath);
9174
- } else if (isPreviewTruncated && hasStructuralSummary(relativePath)) {
9175
- previewSummaryPaths.push(relativePath);
9176
- } else {
9177
- try {
9178
- const outcome = summarizeFile(relativePath, rawContent);
9179
- summary = outcome?.summary ? maskSummaryStrings(outcome.summary, config.secretRules) : void 0;
9180
- summaryQuality = outcome?.quality;
9181
- if (isSourceSummary(summary) && summary.parseErrors) {
9182
- fileWarnings.push({
9183
- path: relativePath,
9184
- message: `Parse errors in ${maskPathText(relativePath, config.secretRules)} (${summary.parseErrors}); its summary is incomplete.`
9185
- });
9186
- }
9187
- } catch (err) {
9188
- fileWarnings.push({
9189
- path: relativePath,
9190
- message: `Summary skipped for ${maskPathText(relativePath, config.secretRules)}: ${err.message}`.replace(
9191
- /\s+/g,
9192
- " "
9193
- )
9194
- });
9195
- }
10050
+ const derivation = takeDerivation(absolutePath, hashSha256, derivationKey) ?? (() => {
10051
+ const fresh = deriveFile(relativePath, rawContent, stats.size, config);
10052
+ rememberDerivation(absolutePath, hashSha256, derivationKey, fresh);
10053
+ return fresh;
10054
+ })();
10055
+ const { lineCount } = derivation;
10056
+ totalLines += lineCount;
10057
+ secretFindings.push(...derivation.findings);
10058
+ if (derivation.isLarge) largeFileCount += 1;
10059
+ if (derivation.summarySkip === "oversize") oversizeSummaryPaths.push(relativePath);
10060
+ else if (derivation.summarySkip === "preview") previewSummaryPaths.push(relativePath);
10061
+ if (derivation.dependentImports !== null) {
10062
+ skippedSummaryImports.set(relativePath, derivation.dependentImports);
10063
+ }
10064
+ if (derivation.summaryWarning !== null) {
10065
+ fileWarnings.push({ path: relativePath, message: derivation.summaryWarning });
10066
+ }
10067
+ if (config.includeMonolith && (derivation.isPreviewTruncated || derivation.inclusionMode === "signatures")) {
10068
+ monolithBodies.set(relativePath, derivation.redacted);
9196
10069
  }
9197
10070
  files.push({
9198
10071
  relativePath,
@@ -9203,24 +10076,25 @@ function generateSnapshot(configInput, options) {
9203
10076
  layer: layer2,
9204
10077
  kind,
9205
10078
  language,
9206
- inclusionMode,
9207
- isLarge,
9208
- isPreviewTruncated,
10079
+ inclusionMode: derivation.inclusionMode,
10080
+ isLarge: derivation.isLarge,
10081
+ isPreviewTruncated: derivation.isPreviewTruncated,
9209
10082
  originalLines: lineCount,
9210
- includedLines,
9211
- includedBytes: Buffer.byteLength(finalContent, "utf8"),
9212
- summary,
9213
- summaryQuality,
10083
+ includedLines: derivation.includedLines,
10084
+ includedBytes: Buffer.byteLength(derivation.finalContent, "utf8"),
10085
+ summary: derivation.summary,
10086
+ summaryQuality: derivation.summaryQuality,
9214
10087
  ...decoded.encoding === "utf-8" ? {} : { encoding: decoded.encoding },
9215
- content: finalContent
10088
+ content: derivation.finalContent
9216
10089
  });
9217
10090
  }
9218
10091
  if (changedScope !== null && changedPaths !== null && config.withDependents === true) {
9219
10092
  const keep = new Set(changedPaths);
9220
10093
  const resolver = buildImportResolver(files);
9221
10094
  for (const file of files) {
9222
- if (!isSourceSummary(file.summary)) continue;
9223
- if (importsChangedFile(file.relativePath, file.summary.imports, changedPaths, resolver)) {
10095
+ const fileImports = isSourceSummary(file.summary) ? file.summary.imports : skippedSummaryImports.get(file.relativePath) ?? [];
10096
+ if (fileImports.length === 0) continue;
10097
+ if (importsChangedFile(file.relativePath, fileImports, changedPaths, resolver)) {
9224
10098
  keep.add(file.relativePath);
9225
10099
  }
9226
10100
  }
@@ -9251,6 +10125,9 @@ function generateSnapshot(configInput, options) {
9251
10125
  for (const path17 of [...monolithBodies.keys()]) {
9252
10126
  if (!keep.has(path17)) monolithBodies.delete(path17);
9253
10127
  }
10128
+ for (const path17 of [...skippedSummaryImports.keys()]) {
10129
+ if (!keep.has(path17)) skippedSummaryImports.delete(path17);
10130
+ }
9254
10131
  }
9255
10132
  if (changedScope !== null) {
9256
10133
  for (const relativePath of unchangedPaths) {
@@ -9286,7 +10163,7 @@ function generateSnapshot(configInput, options) {
9286
10163
  const shown = oversizeSummaryPaths.slice(0, ENCODING_PATHS_SHOWN).map((entry) => maskPathText(entry, config.secretRules));
9287
10164
  const hidden = oversizeSummaryPaths.length - ENCODING_PATHS_SHOWN;
9288
10165
  warnings.push(
9289
- `${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.`
10166
+ `${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.`
9290
10167
  );
9291
10168
  }
9292
10169
  for (const [encoding, bucket] of encodingBuckets) {
@@ -9305,16 +10182,21 @@ function generateSnapshot(configInput, options) {
9305
10182
  }
9306
10183
  }
9307
10184
  const fingerprint = sha256Hex2(
9308
- files.map(
9309
- (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
9310
- ).join("\n")
10185
+ [
10186
+ ...files.map(
10187
+ (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
10188
+ ),
10189
+ `settings:${configDigest(config)}`
10190
+ ].join("\n")
9311
10191
  );
9312
10192
  const fullContents = /* @__PURE__ */ new Map();
9313
- for (const file of files) {
9314
- fullContents.set(
9315
- file.relativePath,
9316
- monolithBodies.get(file.relativePath) ?? file.content ?? ""
9317
- );
10193
+ if (config.includeMonolith) {
10194
+ for (const file of files) {
10195
+ fullContents.set(
10196
+ file.relativePath,
10197
+ monolithBodies.get(file.relativePath) ?? file.content ?? ""
10198
+ );
10199
+ }
9318
10200
  }
9319
10201
  const parts = partitionByBudget(files, config, fingerprint);
9320
10202
  const truncatedPreviewCount = files.filter((file) => file.isPreviewTruncated).length;
@@ -9573,9 +10455,9 @@ function generateSnapshot(configInput, options) {
9573
10455
  }
9574
10456
  writeOwnershipMarker(outDir, markerPayload(outDir, "complete", snapshotId, createdAt));
9575
10457
  };
9576
- shipHookState();
10458
+ if (config.hooks.afterGenerate) shipHookState();
9577
10459
  if (pendingHook) {
9578
- pendingHook.then(
10460
+ const tracked = pendingHook.then(
9579
10461
  () => {
9580
10462
  try {
9581
10463
  shipHookState();
@@ -9594,8 +10476,10 @@ function generateSnapshot(configInput, options) {
9594
10476
  } catch {
9595
10477
  }
9596
10478
  }
9597
- );
9598
- pendingHooks.set(outDir, pendingHook);
10479
+ ).finally(() => {
10480
+ if (pendingHooks.get(outDir) === tracked) pendingHooks.delete(outDir);
10481
+ });
10482
+ pendingHooks.set(outDir, tracked);
9599
10483
  }
9600
10484
  return manifest;
9601
10485
  } catch (err) {
@@ -9613,12 +10497,12 @@ function generateSnapshot(configInput, options) {
9613
10497
  }
9614
10498
  var pendingHooks = /* @__PURE__ */ new Map();
9615
10499
  async function generateSnapshotAsync(configInput, options) {
9616
- const manifest = generateSnapshot(configInput, options);
10500
+ assertUsableConfigInput(configInput);
9617
10501
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput ?? null);
10502
+ const manifest = generateSnapshot(config, options);
9618
10503
  const { outDir } = resolveSafeOutputDirs(config);
9619
10504
  const pending = pendingHooks.get(outDir);
9620
10505
  if (pending !== void 0) {
9621
- pendingHooks.delete(outDir);
9622
10506
  await pending.catch(() => void 0);
9623
10507
  }
9624
10508
  return manifest;