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/cli.cjs CHANGED
@@ -11,6 +11,7 @@ var ts = require('typescript');
11
11
  var readline = require('readline');
12
12
  var async_hooks = require('async_hooks');
13
13
  var os = require('os');
14
+ var http = require('http');
14
15
  var https = require('https');
15
16
  var worker_threads = require('worker_threads');
16
17
 
@@ -42,6 +43,7 @@ var crypto3__namespace = /*#__PURE__*/_interopNamespace(crypto3);
42
43
  var ts__default = /*#__PURE__*/_interopDefault(ts);
43
44
  var readline__namespace = /*#__PURE__*/_interopNamespace(readline);
44
45
  var os__namespace = /*#__PURE__*/_interopNamespace(os);
46
+ var http__namespace = /*#__PURE__*/_interopNamespace(http);
45
47
  var https__namespace = /*#__PURE__*/_interopNamespace(https);
46
48
 
47
49
  // src/cli.ts
@@ -207,6 +209,14 @@ function scanWorkspacePackages(cwd, patterns) {
207
209
  }
208
210
  return { files, dependencies };
209
211
  }
212
+ var SNAPSHOT_MARKER = ".codebase-snapshot";
213
+ function isToolOwnedDirectory(dir) {
214
+ try {
215
+ return fs14__namespace.statSync(dir).isDirectory() && fs14__namespace.existsSync(path16__namespace.join(dir, SNAPSHOT_MARKER));
216
+ } catch {
217
+ return false;
218
+ }
219
+ }
210
220
  function countMarkdownFiles(cwd) {
211
221
  let count = 0;
212
222
  let directoriesSeen = 0;
@@ -228,7 +238,9 @@ function countMarkdownFiles(cwd) {
228
238
  }
229
239
  if (!entry.isDirectory() || current.depth >= 2) continue;
230
240
  if (entry.name.startsWith(".") || SKIPPED_WALK_DIRS.has(entry.name)) continue;
231
- queue.push({ dir: path16__namespace.join(current.dir, entry.name), depth: current.depth + 1 });
241
+ const child = path16__namespace.join(current.dir, entry.name);
242
+ if (isToolOwnedDirectory(child)) continue;
243
+ queue.push({ dir: child, depth: current.depth + 1 });
232
244
  }
233
245
  }
234
246
  return count;
@@ -1097,18 +1109,24 @@ function detectPreset(cwd, forced) {
1097
1109
  }
1098
1110
 
1099
1111
  // src/security/patterns.ts
1100
- 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)";
1101
- var WEAK_CREDENTIAL_NAME = "(?:pass|id[_-]?token|credentials?)";
1112
+ 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)";
1113
+ var WEAK_CREDENTIAL_NAME = "(?:pass|credentials?)";
1102
1114
  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)";
1103
1115
  var UNQUOTED_MIN_LENGTH = 2;
1104
1116
  var PROSE_CONTINUATION = String.raw`(?!\s+[a-z])`;
1105
- 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;
1106
- 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;
1117
+ var UNQUOTED_VALUE_CHARS = String.raw`A-Za-z0-9_+=/%:~$!@#^*?-`;
1118
+ var UNQUOTED_VALUE_END = String.raw`[A-Za-z0-9_+=/%:.~$!@#^*?-]`;
1119
+ var UNQUOTED_VALUE_START = String.raw`[$!@#%^&*~+]`;
1120
+ var UNQUOTED_LITERAL = String.raw`(` + // one capture, whichever branch matched: valueGroup is 1
1121
+ 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;
1122
+ 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;
1107
1123
  var ASSIGN = String.raw`(?<![=!<>])[:=](?!=)`;
1108
1124
  var NOT_AFTER_QUOTE = String.raw`(?<!["'])`;
1109
1125
  var NOT_A_NAMESPACED_IDENTIFIER = String.raw`(?![a-z][a-z0-9]*(?:\.[a-z][a-z0-9-]*)+/)`;
1126
+ var QUOTED_CREDENTIAL_KEY = `["'](?!id[-_]token["'])[A-Za-z0-9_$-]{0,64}${STRONG_CREDENTIAL_NAME}["']`;
1110
1127
  var QUOTED_VALUE = String.raw`((?:[^"'\\\n]|\\\\["'](?=[A-Za-z0-9_])|\\.){1,512})`;
1111
1128
  var UNQUOTED_STRONG_NAME = `(?<!id[-_])${STRONG_CREDENTIAL_NAME}`;
1129
+ var CREDENTIAL_KEY_TAIL = new RegExp(`(?:${STRONG_CREDENTIAL_NAME})$`, "i");
1112
1130
  var DEFAULT_SECRET_PATTERNS = [
1113
1131
  {
1114
1132
  rule: "private-key-header",
@@ -1175,13 +1193,28 @@ var DEFAULT_SECRET_PATTERNS = [
1175
1193
  pattern: /xox[baprsdc]-[0-9A-Za-z-]{10,250}/
1176
1194
  },
1177
1195
  {
1178
- // Prefix-only vendors. Each prefix below is documented, globally unique and
1179
- // cannot collide with an ordinary identifier, which is what makes a bare
1180
- // prefix rule cheap and safe: `glpat-` (GitLab), `hvs.`/`s.` (Vault service
1181
- // and batch tokens), `whsec_` (Stripe webhook secret), `dckr_pat_` (Docker
1182
- // Hub), `hf_` (HuggingFace), `ya29.` (Google OAuth access token).
1196
+ // Known vendor token shapes: prefix-unique tokens, plus the few fixed layouts whose format is
1197
+ // documented and cannot collide with an ordinary identifier.
1198
+ //
1199
+ // Each prefix below is globally unique, which is what makes a bare prefix rule cheap and
1200
+ // safe: `glpat-` (GitLab), `hvs.`/`s.` (Vault service and batch tokens), `whsec_`
1201
+ // (Stripe webhook secret), `dckr_pat_` (Docker Hub), `hf_` (HuggingFace), `ya29.`
1202
+ // (Google OAuth access token), `shpat_`/`shpca_`/`shppa_`/`shpss_` (Shopify admin and
1203
+ // storefront tokens).
1204
+ //
1205
+ // The fixed shapes have no prefix to anchor on and were each emitted in clear:
1206
+ // - Telegram bot token: `<8-10 digit bot id>:<35-character secret>`.
1207
+ // - Discord bot token: `<base64 user id>.<6-8 char hmac>.<25-45 char signature>`; demanding
1208
+ // all three segments keeps ordinary dotted identifiers out.
1209
+ // - Azure DevOps personal access token: exactly 52 alphanumerics that always mix case and
1210
+ // digits, so a hash, a UUID or a plain identifier — all single-case or a different length —
1211
+ // does not match.
1212
+ //
1213
+ // The rule name still says "prefix" because that is how the catalogue began; it is the
1214
+ // vendor-token rule, and growing a new named rule per vendor would make the documented
1215
+ // pattern count drift on every release.
1183
1216
  rule: "known-vendor-token-prefix",
1184
- 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})/
1217
+ 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])/
1185
1218
  },
1186
1219
  {
1187
1220
  rule: "slack-webhook-url",
@@ -1236,39 +1269,52 @@ var DEFAULT_SECRET_PATTERNS = [
1236
1269
  // (including one invented tomorrow) is covered, provided the `//` is followed
1237
1270
  // immediately by the userinfo: `// see the docs` and a bare reminder comment
1238
1271
  // never match, because a space or the comment wording breaks the shape.
1272
+ //
1273
+ // Three shapes joined it, all the same fact — a URL carries the credential in plain sight —
1274
+ // and each cost a leak while it was elsewhere:
1275
+ // - The user part may be **empty**: Redis, SMTP, AMQP and FTP URLs routinely omit the username
1276
+ // (`redis://:password@host`), and a `{1,128}` prefix made every one of those invisible.
1277
+ // - `curl -u user:password` sends the same userinfo without a scheme; the lookbehind
1278
+ // consumes the flag so the match is the credential alone.
1279
+ // - An Azure SAS link authenticates with `?sig=`; the signature *is* the credential.
1239
1280
  rule: "uri-credentials",
1240
- pattern: /\/\/[^\s:/@"'`;()<>,]{1,128}:[^\s:/@"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/
1281
+ pattern: /\/\/[^\s:/@"'`;()<>,]{0,128}:[^\s:/@"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}|(?<=(?:^|[\s;|&(])--?u(?:ser)?[ \t=]{1,8})["']?[^\s"']{1,300}:[^\s"']{0,256}["']?|(?<=[?&])sig=[A-Za-z0-9%._=~-]{20,300}(?![A-Za-z0-9%._=~-])/
1241
1282
  },
1242
1283
  {
1243
1284
  // The host tail stops at quotes, `;`, `)`, `<`, `>` and `,`: an unbounded
1244
1285
  // `[^\s/]` used to swallow the closing quote and the statement separator of
1245
1286
  // the string the URL was written in.
1287
+ // The user part may be empty here too: `redis://:password@host` and `amqp://:password@host`
1288
+ // are how those services are configured when the account is the server's default.
1246
1289
  rule: "database-uri-credentials",
1247
- 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}/
1290
+ 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}/
1248
1291
  },
1249
1292
  {
1293
+ // An empty user part is valid userinfo (`smtp://:password@host`: the account is the server's
1294
+ // default), and it used to be the one shape every scheme-listed rule refused.
1250
1295
  rule: "basic-auth-url",
1251
- pattern: /(?:https?|ftp|sftp|ssh|git|smtp|smtps|ldap|ldaps):\/\/[^\s:@/"'`;()<>,]{1,128}:[^\s@/"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/i
1296
+ pattern: /(?:https?|ftp|sftp|ssh|git|smtp|smtps|ldap|ldaps):\/\/[^\s:@/"'`;()<>,]{0,128}:[^\s@/"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/i
1252
1297
  },
1253
1298
  {
1254
1299
  // Quoted credentials in any common key spelling. The value may be as short
1255
1300
  // as one character: `password: "hunter2"` is a credential whatever its
1256
1301
  // entropy, and a length floor was exactly how it survived into `parts`.
1257
1302
  //
1258
- // The key is either bare (`dbPassword:`) or wholly quoted (`"dbPassword":`).
1303
+ // The key is bare (`dbPassword:`), wholly quoted (`"password":`), or quoted with a
1304
+ // camelCase prefix (`"dbPassword":`) — the last one is {@link QUOTED_CREDENTIAL_KEY}.
1259
1305
  // There is deliberately no optional quote *before* the separator: that let a
1260
1306
  // previous string's closing quote stand in for the key's, so
1261
1307
  // ``${pass ? " PASS" : " FAIL"}`` had `" FAIL"` masked as if `PASS` were
1262
1308
  // the key name.
1263
1309
  rule: "credential-assignment",
1264
1310
  pattern: new RegExp(
1265
- `(?:["']${STRONG_CREDENTIAL_NAME}["']|${NOT_AFTER_QUOTE}${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_NAMESPACED_IDENTIFIER}(["'\`])${QUOTED_VALUE}\\1`,
1311
+ `(?:${QUOTED_CREDENTIAL_KEY}|${NOT_AFTER_QUOTE}(?<!id[-_])${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_NAMESPACED_IDENTIFIER}(["'\`])${QUOTED_VALUE}\\1`,
1266
1312
  "i"
1267
1313
  ),
1268
1314
  valueGroup: 2
1269
1315
  },
1270
1316
  {
1271
- // `pass`, `id-token` and `credentials` are ambiguous on their own, so they
1317
+ // `pass` and `credentials` are ambiguous on their own, so they
1272
1318
  // are accepted only against a quoted value long enough to be a credential.
1273
1319
  rule: "credential-assignment-weak",
1274
1320
  pattern: new RegExp(
@@ -1281,9 +1327,40 @@ var DEFAULT_SECRET_PATTERNS = [
1281
1327
  // The unquoted twin for YAML, docker-compose and `.env`: those formats never
1282
1328
  // quote their values, so the rules above cannot see them. `valueGroup` keeps
1283
1329
  // `POSTGRES_PASSWORD:` in the output.
1330
+ //
1331
+ // This is the one unquoted rule without `NOT_AFTER_QUOTE`, and the lookbehind is a
1332
+ // string-literal guard rather than a precision rule: a credential assignment *inside* a
1333
+ // literal — `const dsn = "password=hunter2;host=db"`, `curl -d "password=hunter2"` — was
1334
+ // rejected before it could be considered, and a DSN is a credential in a string. What made the
1335
+ // lookbehind redundant is the shape of `UNQUOTED_LITERAL`: a value has to start with a word
1336
+ // character, so `["awsSecret:", "apiKey:"]` — the list of key names the lookbehind was added
1337
+ // for — cannot match here anyway. `redact.ts` still refuses a match whose separator is inside
1338
+ // the literal, which is the case that list actually is.
1339
+ //
1340
+ // The name may also be a *quoted* key: YAML allows `"dbPassword": hunter2`, and JSON cannot
1341
+ // spell a key any other way, so the same {@link QUOTED_CREDENTIAL_KEY} fragment is used here.
1342
+ // Without it a quoted key whose value was not quoted emitted the value in clear.
1343
+ //
1344
+ // A colon-form assignment in a data file masks the whole remainder of the value to
1345
+ // end-of-line, whatever punctuation it holds. A strong credential name is the evidence that
1346
+ // the thing after it is a value, and the character classes above cannot cover every symbol a
1347
+ // password may contain — `password: pa&ss` used to stop at the `&`. This branch is a
1348
+ // lookbehind, so the match is the value alone, and `redact.ts` only applies it to a data or
1349
+ // shell file: in source code the same shape is an expression and stays untouched, and an `URL`
1350
+ // query string keeps its `&` separators because they are not a colon form.
1351
+ //
1352
+ // The `KEY=value` twin does the same for the `=` form, which INI, .properties and shell files
1353
+ // use: with a credential key the whole value is masked whatever symbols it contains
1354
+ // (`password=pa&ss`, `token=a<b`, `client_secret=x|y`). The value is bounded by whitespace
1355
+ // (end of line, or the space before a `# comment`), not by a symbol class — `envpass!@#$%^&*()` used
1356
+ // to stop before the parenthesis and leave the tail in clear. The lookbehind matches the value
1357
+ // alone and `redact.ts` decides, from the file and from the key, whether the line is an
1358
+ // assignment (it must be a data/shell file, the key must end in a credential name, and a URL
1359
+ // query parameter or `$VARIABLE` reference is not an assignment).
1284
1360
  rule: "credential-assignment-unquoted",
1285
1361
  pattern: new RegExp(
1286
- `${NOT_AFTER_QUOTE}${UNQUOTED_STRONG_NAME}\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_LITERAL_VALUE}${UNQUOTED_LITERAL}`,
1362
+ `(?:${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
1363
+ #]{1,300}`,
1287
1364
  "i"
1288
1365
  ),
1289
1366
  valueGroup: 1
@@ -1306,8 +1383,14 @@ var DEFAULT_SECRET_PATTERNS = [
1306
1383
  // needs no `valueGroup`. A lone `Bearer`/`Basic`, and a word after it that
1307
1384
  // cannot be a credential (`Bearer authentication`), stay readable: the value
1308
1385
  // must contain a digit, be at least 32 chars, or carry base64 `=` padding.
1386
+ //
1387
+ // A fourth shape was leaking: `Basic dXNlcjpwYXNz` is the base64 of `user:pass` — 12
1388
+ // characters, no digit, no padding — and the three tests above all said "not a
1389
+ // credential", so it reached the parts in clear. Mixed case is the discriminator: a base64
1390
+ // rendering of textual userinfo mixes cases, while the prose the earlier rules were
1391
+ // protecting (`Bearer authentication`) is a lowercase word.
1309
1392
  rule: "authorization-header",
1310
- 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_.+/=-])/
1393
+ pattern: /(?<=(?:Bearer|Basic)\s{1,8})(?:[A-Za-z0-9_.+/-]{0,31}[0-9][A-Za-z0-9_.+/-]{0,1024}|[A-Za-z0-9_.+/-]{32,1024}|[A-Za-z0-9_.+/-]{8,1024}={1,2}|(?=[A-Za-z0-9_.+/-]{0,1023}[A-Z])(?=[A-Za-z0-9_.+/-]{0,1023}[a-z])[A-Za-z0-9_.+/-]{12,1024})(?![A-Za-z0-9_.+/=-])/
1311
1394
  },
1312
1395
  {
1313
1396
  // Broader names than before (`apiKey`, `clientSecret`, `privateKey` were
@@ -1318,6 +1401,27 @@ var DEFAULT_SECRET_PATTERNS = [
1318
1401
  pattern: /(?<!["'])(?:api[_-]?key|secret[_-]?key|auth[_-]?token|client[_-]?secret|access[_-]?token|refresh[_-]?token|private[_-]?key|password|passwd|pwd)["']?\s*(?<![=!<>])[:=](?!=)\s*["']([^"'\s]{8,256})["']/i,
1319
1402
  valueGroup: 1
1320
1403
  },
1404
+ {
1405
+ // `${VAR:-fallback}` — a default value in a shell script, a `.env`, docker-compose or a
1406
+ // GitHub Actions workflow.
1407
+ //
1408
+ // This shape defeated every rule above it, and each refusal was individually reasonable:
1409
+ // the quoted rules need a quote after the separator, and the unquoted ones need the value to
1410
+ // begin with a word character — a fallback begins with `$`. So
1411
+ // `POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-MyProdPassword123!}` was emitted whole, `.env` files
1412
+ // and compose files included, which is where that idiom is the norm.
1413
+ //
1414
+ // The **fallback** is what gets masked, not the whole expansion: the variable name is the
1415
+ // readable context, exactly as `POSTGRES_PASSWORD:` is kept by the rule above. A single
1416
+ // interpolation with no operator (`${DB_PASSWORD}`) still does not match — there is nothing
1417
+ // between the braces to mask, and `isTemplateInterpolation` keeps such a value readable.
1418
+ rule: "interpolation-fallback-secret",
1419
+ pattern: new RegExp(
1420
+ `(?:["']${STRONG_CREDENTIAL_NAME}["']|${NOT_AFTER_QUOTE}${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}["'\`]?\\$\\{[A-Za-z_][A-Za-z0-9_]*:?[-=?+]([^}"'\`\\r\\n]{2,512})\\}["'\`]?`,
1421
+ "i"
1422
+ ),
1423
+ valueGroup: 1
1424
+ },
1321
1425
  {
1322
1426
  // Covers `.env` / shell assignment syntax, which never quotes its values and
1323
1427
  // was therefore invisible to the rule above. Anchored to the line start and
@@ -1345,8 +1449,8 @@ var DEFAULT_SECRET_PATTERNS = [
1345
1449
  valueGroup: 1
1346
1450
  }
1347
1451
  ];
1348
- var PEM_BLOCK_PATTERN = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----/g;
1349
- var PEM_UNTERMINATED_PATTERN = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----(?:\r?\n[A-Za-z0-9+/=]{4,}[ A-Za-z0-9+/=]*)+/g;
1452
+ var PEM_BLOCK_PATTERN = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----(?:(?!-----BEGIN)[\s\S])*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----/g;
1453
+ 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;
1350
1454
 
1351
1455
  // src/security/redact.ts
1352
1456
  var REDACTION_MARKER = "[REDACTED: potential secret-like value omitted from snapshot]";
@@ -1440,6 +1544,20 @@ function toGlobal(rule) {
1440
1544
  return new RegExp(rule.pattern.source, [...flags].join(""));
1441
1545
  }
1442
1546
  var LINE_BREAK = /(\r\n|\n|\r)/;
1547
+ var LINE_TERMINATOR = /\r\n|\n|\r/g;
1548
+ var COMPILED_RULES = /* @__PURE__ */ new WeakMap();
1549
+ function compiledRuleFor(rule) {
1550
+ let compiled = COMPILED_RULES.get(rule);
1551
+ if (compiled === void 0) {
1552
+ compiled = {
1553
+ rule: rule.rule,
1554
+ pattern: toGlobal(rule),
1555
+ ...rule.valueGroup === void 0 ? {} : { valueGroup: rule.valueGroup }
1556
+ };
1557
+ COMPILED_RULES.set(rule, compiled);
1558
+ }
1559
+ return compiled;
1560
+ }
1443
1561
  function scanAndRedactSecrets(content, rules, filePath) {
1444
1562
  const findings = [];
1445
1563
  let redacted = content;
@@ -1451,18 +1569,15 @@ function scanAndRedactSecrets(content, rules, filePath) {
1451
1569
  blockPattern.lastIndex += 1;
1452
1570
  continue;
1453
1571
  }
1454
- const line = redacted.slice(0, match.index).split("\n").length;
1455
- const newlines = (match[0].match(/\n/g) ?? []).length;
1572
+ const before = redacted.slice(0, match.index);
1573
+ const line = (before.match(LINE_TERMINATOR) ?? []).length + 1;
1574
+ const newlines = (match[0].match(LINE_TERMINATOR) ?? []).length;
1456
1575
  findings.push({ rules: ["private-key-block"], line, path: filePath });
1457
- redacted = redacted.slice(0, match.index) + PEM_REDACTION_MARKER + "\n".repeat(newlines) + redacted.slice(match.index + match[0].length);
1576
+ redacted = before + PEM_REDACTION_MARKER + "\n".repeat(newlines) + redacted.slice(match.index + match[0].length);
1458
1577
  blockPattern.lastIndex = match.index + PEM_REDACTION_MARKER.length + newlines;
1459
1578
  }
1460
1579
  }
1461
- const compiled = rules.map((rule) => ({
1462
- rule: rule.rule,
1463
- pattern: toGlobal(rule),
1464
- ...rule.valueGroup === void 0 ? {} : { valueGroup: rule.valueGroup }
1465
- }));
1580
+ const compiled = rules.map(compiledRuleFor);
1466
1581
  const segments = redacted.split(LINE_BREAK);
1467
1582
  let lineNumber = 1;
1468
1583
  for (let index = 0; index < segments.length; index += 2) {
@@ -1480,11 +1595,39 @@ function scanAndRedactSecrets(content, rules, filePath) {
1480
1595
  }
1481
1596
  const group = valueGroup === void 0 ? void 0 : match.indices?.[valueGroup];
1482
1597
  if (group && isSelfNamingConstant(line, group[0], group[1])) continue;
1483
- if (valueGroup !== void 0 && startsInsideStringLiteral(line, match.index)) continue;
1484
- if (group && isUnquotedValue(line, group[0]) && isDeclaredBinding(line, match.index)) {
1598
+ if (valueGroup !== void 0 && startsInsideStringLiteral(line, match.index, group?.[0])) {
1599
+ continue;
1600
+ }
1601
+ if (group && isUnquotedValue(line, group[0]) && isDeclaredBinding(line, match.index, filePath)) {
1485
1602
  continue;
1486
1603
  }
1487
1604
  if (group && isTemplateInterpolation(line, group[0], group[1])) continue;
1605
+ if (group && isUnquotedValue(line, group[0]) && TRUNCATING_VALUE_CHARS.test(line[group[1]] ?? "")) {
1606
+ continue;
1607
+ }
1608
+ if (valueGroup !== void 0 && group === void 0) {
1609
+ if (!isAssignmentFile(filePath)) continue;
1610
+ const assignment = assignmentAround(line, match.index);
1611
+ if (assignment.form === "=" && (assignment.reference || assignment.key === null || !CREDENTIAL_KEY_TAIL.test(assignment.key))) {
1612
+ continue;
1613
+ }
1614
+ }
1615
+ if (group && isUnquotedValue(line, group[0]) && OPENER_LED_VALUE.test(line.slice(group[0], group[1])) && !isAssignmentFile(filePath)) {
1616
+ continue;
1617
+ }
1618
+ if (group && isUnquotedValue(line, group[0])) {
1619
+ const assignment = assignmentAround(line, group[0]);
1620
+ const wholeValue = isAssignmentFile(filePath) && assignment.form !== null && !assignment.reference && !assignment.urlValue;
1621
+ if (wholeValue) {
1622
+ spans.push({
1623
+ start: group[0],
1624
+ end: Math.max(group[1], tokenEnd(line, group[0])),
1625
+ rule
1626
+ });
1627
+ matchedRules.add(rule);
1628
+ continue;
1629
+ }
1630
+ }
1488
1631
  spans.push(
1489
1632
  group ? { start: group[0], end: group[1], rule } : { start: match.index, end: match.index + match[0].length, rule }
1490
1633
  );
@@ -1502,6 +1645,8 @@ function scanAndRedactSecrets(content, rules, filePath) {
1502
1645
  }
1503
1646
  var TOKEN_CHARS_LEFT = /[A-Za-z0-9_+/-]/;
1504
1647
  var TOKEN_CHARS_RIGHT = /[A-Za-z0-9_+/=-]/;
1648
+ var TRUNCATING_VALUE_CHARS = /[<>|\\]/;
1649
+ var OPENER_LED_VALUE = /^[(\\[{]/;
1505
1650
  function expandOverToken(line, start, end) {
1506
1651
  let left = start;
1507
1652
  let right = end;
@@ -1514,14 +1659,20 @@ function expandOverToken(line, start, end) {
1514
1659
  while (right < line.length && TOKEN_CHARS_RIGHT.test(line[right])) right += 1;
1515
1660
  return { start: left, end: right };
1516
1661
  }
1517
- function startsInsideStringLiteral(line, matchIndex) {
1662
+ function startsInsideStringLiteral(line, matchIndex, valueStart) {
1518
1663
  let runStart = matchIndex;
1519
1664
  while (runStart > 0 && /[A-Za-z0-9_-]/.test(line[runStart - 1])) runStart -= 1;
1520
1665
  const before = runStart > 0 ? line[runStart - 1] : "";
1521
- return before === '"' || before === "'" || before === "`";
1666
+ if (before !== '"' && before !== "'" && before !== "`") return false;
1667
+ if (valueStart === void 0) return true;
1668
+ return /["'`]/.test(line.slice(matchIndex, valueStart));
1522
1669
  }
1523
1670
  function isTemplateInterpolation(line, start, end) {
1524
- return line[start] === "$" && line[start + 1] === "{" && line[end - 1] === "}";
1671
+ if (line[start] !== "$" || line[start + 1] !== "{" || line[end - 1] !== "}") {
1672
+ return false;
1673
+ }
1674
+ const inner = line.slice(start + 2, end - 1).trim();
1675
+ return /^[A-Za-z_$][A-Za-z0-9_$.()[\]]*$/.test(inner);
1525
1676
  }
1526
1677
  function isSelfNamingConstant(line, start, end) {
1527
1678
  const value = line.slice(start, end);
@@ -1542,13 +1693,48 @@ function isSelfNamingConstant(line, start, end) {
1542
1693
  }
1543
1694
  return line.endsWith(value, index);
1544
1695
  }
1696
+ function assignmentAround(line, valueStart) {
1697
+ let index = valueStart;
1698
+ while (index > 0 && (line[index - 1] === " " || line[index - 1] === " ")) index -= 1;
1699
+ const separator = index > 0 ? line[index - 1] : "";
1700
+ if (separator !== ":" && separator !== "=") {
1701
+ return { form: null, key: null, reference: false, rhsStart: -1, urlValue: false };
1702
+ }
1703
+ const separatorIndex = index - 1;
1704
+ index = separatorIndex;
1705
+ while (index > 0 && (line[index - 1] === " " || line[index - 1] === " ")) index -= 1;
1706
+ const keyEnd = index;
1707
+ while (index > 0 && /[A-Za-z0-9_$.-]/.test(line[index - 1])) index -= 1;
1708
+ const key = line.slice(index, keyEnd).replace(/^-+/, "");
1709
+ const before = index > 0 ? line[index - 1] : "";
1710
+ const reference = before === "?" || before === "&" || before === "$" || before === '"' || before === "'" || before === "`";
1711
+ let rhsStart = separatorIndex + 1;
1712
+ while (rhsStart < line.length && (line[rhsStart] === " " || line[rhsStart] === " ")) rhsStart += 1;
1713
+ const urlValue = /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(line.slice(rhsStart, tokenEnd(line, rhsStart)));
1714
+ return { form: separator === ":" ? ":" : "=", key, reference, rhsStart, urlValue };
1715
+ }
1716
+ function tokenEnd(line, start) {
1717
+ let end = start;
1718
+ while (end < line.length && !/\s/.test(line[end])) end += 1;
1719
+ return end;
1720
+ }
1545
1721
  function isUnquotedValue(line, start) {
1546
1722
  const before = start > 0 ? line[start - 1] : "";
1547
1723
  return before !== '"' && before !== "'" && before !== "`";
1548
1724
  }
1549
- var DECLARATION_KEYWORDS = /\b(?:const|let|var|readonly|public|private|protected|static|declare|export|using)\s+$/;
1725
+ var DECLARATION_KEYWORDS = /\b(?:const|let|var|readonly|public|private|protected|static|using)\s+$/;
1726
+ var ASSIGNMENT_FILE = /\.(?:sh|bash|zsh|ksh|fish|env|ya?ml|toml|ini|conf|cfg|properties|tf|tfvars|service)$/i;
1727
+ var ASSIGNMENT_BASENAME = /^(?:\.env(?:\.[^/]*)?|\.envrc|\.profile|\.bashrc|\.zshrc|\.bash_profile)$/i;
1728
+ function isAssignmentFile(filePath) {
1729
+ if (filePath === void 0) return false;
1730
+ const normalised = filePath.replace(/\\/g, "/");
1731
+ if (ASSIGNMENT_FILE.test(normalised)) return true;
1732
+ const base = normalised.slice(normalised.lastIndexOf("/") + 1);
1733
+ return ASSIGNMENT_BASENAME.test(base);
1734
+ }
1550
1735
  var DECLARATION_WINDOW = 40;
1551
- function isDeclaredBinding(line, matchIndex) {
1736
+ function isDeclaredBinding(line, matchIndex, filePath) {
1737
+ if (isAssignmentFile(filePath)) return false;
1552
1738
  let runStart = matchIndex;
1553
1739
  while (runStart > 0 && /[A-Za-z0-9_$]/.test(line[runStart - 1])) runStart -= 1;
1554
1740
  const from = Math.max(0, runStart - DECLARATION_WINDOW);
@@ -1590,6 +1776,15 @@ function readLinkTarget(linkPath, fallback) {
1590
1776
  return fallback;
1591
1777
  }
1592
1778
  }
1779
+ function brokenLinkRecord(linkPath, relativePath, rootReal) {
1780
+ const rawTarget = readLinkTarget(linkPath, linkPath);
1781
+ const resolvedFallback = path16__namespace.resolve(path16__namespace.dirname(linkPath), rawTarget);
1782
+ return isInside(rootReal, resolvedFallback) ? { path: relativePath, reason: "read-error", detail: "broken symlink" } : {
1783
+ path: relativePath,
1784
+ reason: "outside-root",
1785
+ detail: `link target resolves outside the scanned root (target: ${rawTarget}); not followed`
1786
+ };
1787
+ }
1593
1788
  function isInside(root, candidate) {
1594
1789
  const relative12 = path16__namespace.relative(root, candidate);
1595
1790
  return relative12 === "" || !relative12.startsWith(`..${path16__namespace.sep}`) && relative12 !== ".." && !path16__namespace.isAbsolute(relative12);
@@ -1679,6 +1874,13 @@ function isSensitivePath(relativePath) {
1679
1874
  return matchesSensitiveList(posixPath, base);
1680
1875
  }
1681
1876
  var GLOBAL_PATTERNS = /* @__PURE__ */ new WeakMap();
1877
+ var GLOB_REGEX_CACHE = /* @__PURE__ */ new Map();
1878
+ var GITIGNORE_REGEX_CACHE = /* @__PURE__ */ new Map();
1879
+ var REGEX_CACHE_LIMIT = 4096;
1880
+ function rememberCompiled(cache, key, value) {
1881
+ if (cache.size >= REGEX_CACHE_LIMIT) cache.clear();
1882
+ cache.set(key, value);
1883
+ }
1682
1884
  function globalPattern(pattern) {
1683
1885
  let compiled = GLOBAL_PATTERNS.get(pattern);
1684
1886
  if (compiled === void 0) {
@@ -1689,8 +1891,8 @@ function globalPattern(pattern) {
1689
1891
  }
1690
1892
  var DEFAULT_PATH_RULES = [...DEFAULT_SECRET_PATTERNS];
1691
1893
  function pathScanRules(extraRules) {
1692
- if (extraRules === void 0 || extraRules.length === 0) return DEFAULT_PATH_RULES;
1693
- return [...DEFAULT_SECRET_PATTERNS, ...extraRules];
1894
+ if (extraRules === void 0) return DEFAULT_PATH_RULES;
1895
+ return extraRules;
1694
1896
  }
1695
1897
  function findSecretInPath(relativePath, extraRules) {
1696
1898
  const posixPath = relativePath.replace(/\\/g, "/");
@@ -1739,11 +1941,22 @@ function maskSkipPaths(records, extraRules) {
1739
1941
  });
1740
1942
  }
1741
1943
  function globToRegExp(glob) {
1944
+ const cached = GLOB_REGEX_CACHE.get(glob);
1945
+ if (cached !== void 0) return cached;
1742
1946
  const normalized = glob.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
1743
1947
  const anchored = normalized.startsWith("/");
1744
1948
  const body = anchored ? normalized.slice(1) : normalized;
1745
1949
  const prefix = anchored || body.includes("/") ? "^" : "(?:^|.*/)";
1746
- return new RegExp(`${prefix}${globBodyToRegExp(body, true)}(?:/.*)?$`);
1950
+ let compiled;
1951
+ try {
1952
+ compiled = new RegExp(`${prefix}${globBodyToRegExp(body, true)}(?:/.*)?$`);
1953
+ } catch (error) {
1954
+ throw new Error(
1955
+ `"${glob}" is not a valid glob: ${error.message}. A character class must be ascending, as in "[a-z]".`
1956
+ );
1957
+ }
1958
+ rememberCompiled(GLOB_REGEX_CACHE, glob, compiled);
1959
+ return compiled;
1747
1960
  }
1748
1961
  function globBodyToRegExp(body, allowBraces) {
1749
1962
  let out = "";
@@ -1855,6 +2068,14 @@ function escapeRegExpChar(character) {
1855
2068
  return /[\\^$.*+?()[\]{}|/]/.test(character) ? `\\${character}` : character;
1856
2069
  }
1857
2070
  function matchGitignorePattern(target, pattern) {
2071
+ let compiled = GITIGNORE_REGEX_CACHE.get(pattern);
2072
+ if (compiled === void 0) {
2073
+ compiled = compileGitignorePattern(pattern);
2074
+ rememberCompiled(GITIGNORE_REGEX_CACHE, pattern, compiled);
2075
+ }
2076
+ return compiled.test(target);
2077
+ }
2078
+ function compileGitignorePattern(pattern) {
1858
2079
  const anchored = pattern.startsWith("/");
1859
2080
  const body = anchored ? pattern.slice(1) : pattern;
1860
2081
  let source = "";
@@ -1903,7 +2124,11 @@ function matchGitignorePattern(target, pattern) {
1903
2124
  source += escapeRegExpChar(character);
1904
2125
  }
1905
2126
  const prefix = anchored || body.includes("/") ? "^" : "(?:^|.*/)";
1906
- return new RegExp(`${prefix}${source}(?:/.*)?$`).test(target);
2127
+ try {
2128
+ return new RegExp(`${prefix}${source}(?:/.*)?$`);
2129
+ } catch {
2130
+ return /$^/;
2131
+ }
1907
2132
  }
1908
2133
  function matchesGitignoreRule(rule, scoped, isDirectory) {
1909
2134
  if (!rule.dirOnly) return matchGitignorePattern(scoped, rule.pattern);
@@ -1933,14 +2158,31 @@ function gitignoreVerdict(layers, relativePath, isDirectory) {
1933
2158
  }
1934
2159
  return verdict;
1935
2160
  }
1936
- function defaultIgnoreReason(relativePath) {
2161
+ var DEFAULT_TOOL_DIR_NAMES = ["snapshot"];
2162
+ function toolDirNamesFor(toolOwnedPaths) {
2163
+ const names = new Set(DEFAULT_TOOL_DIR_NAMES);
2164
+ for (const entry of toolOwnedPaths) {
2165
+ const base = entry.replace(/\\/g, "/").replace(/\/+$/, "").split("/").pop();
2166
+ if (base !== void 0 && base.length > 0) names.add(base);
2167
+ }
2168
+ return [...names];
2169
+ }
2170
+ function isToolLeftoverName(name, dirNames) {
2171
+ for (const dirName of dirNames) {
2172
+ if (name.startsWith(`${dirName}.backup-`) || name.startsWith(`${dirName}.partial-`)) {
2173
+ return true;
2174
+ }
2175
+ }
2176
+ return false;
2177
+ }
2178
+ function defaultIgnoreReason(relativePath, toolDirNames = DEFAULT_TOOL_DIR_NAMES) {
1937
2179
  const posixPath = relativePath.replace(/\\/g, "/");
1938
2180
  const parts = posixPath.split("/");
1939
2181
  for (let i = 0; i < parts.length - 1; i++) {
1940
2182
  if (DEFAULT_IGNORED_DIRS.includes(parts[i])) {
1941
2183
  return `built-in ignore: directory "${parts[i]}"`;
1942
2184
  }
1943
- if (parts[i].startsWith("snapshot.backup-")) {
2185
+ if (isToolLeftoverName(parts[i], toolDirNames)) {
1944
2186
  return `built-in ignore: leftover snapshot backup "${parts[i]}"`;
1945
2187
  }
1946
2188
  }
@@ -1948,6 +2190,9 @@ function defaultIgnoreReason(relativePath) {
1948
2190
  if (DEFAULT_IGNORED_FILES.includes(base)) {
1949
2191
  return `built-in ignore: filename "${base}"`;
1950
2192
  }
2193
+ if (isToolLeftoverName(base, toolDirNames)) {
2194
+ return `built-in ignore: leftover snapshot backup "${base}"`;
2195
+ }
1951
2196
  return null;
1952
2197
  }
1953
2198
  function listIgnoredPaths(cwd) {
@@ -2016,41 +2261,72 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
2016
2261
  }
2017
2262
  const reported = /* @__PURE__ */ new Set();
2018
2263
  const kept = [];
2264
+ const report = (linkedPath, record) => {
2265
+ if (reported.has(linkedPath)) return;
2266
+ reported.add(linkedPath);
2267
+ skipped.push(record);
2268
+ };
2019
2269
  for (const candidate of candidates) {
2020
2270
  const parts = candidate.split("/");
2021
- let linkedDir = null;
2271
+ let linkedPath = null;
2022
2272
  for (let depth = 1; depth <= parts.length; depth += 1) {
2023
2273
  const prefix = parts.slice(0, depth).join("/");
2024
2274
  if (isLink(path16__namespace.join(cwd, prefix))) {
2025
- linkedDir = prefix;
2275
+ linkedPath = prefix;
2026
2276
  break;
2027
2277
  }
2028
2278
  }
2029
- if (linkedDir === null) {
2279
+ if (linkedPath === null) {
2030
2280
  kept.push(candidate);
2031
2281
  continue;
2032
2282
  }
2033
- if (reported.has(linkedDir)) continue;
2034
- reported.add(linkedDir);
2035
- const absolute = path16__namespace.join(cwd, linkedDir);
2036
- let targetReal = absolute;
2283
+ const absolute = path16__namespace.join(cwd, linkedPath);
2284
+ const rawTarget = readLinkTarget(absolute, absolute);
2285
+ let targetReal = null;
2037
2286
  try {
2038
2287
  targetReal = fs14__namespace.realpathSync(absolute);
2039
2288
  } catch {
2289
+ targetReal = null;
2040
2290
  }
2041
- const target = readLinkTarget(absolute, targetReal);
2042
- const what = linkedDir === candidate ? "symbolic link" : "directory link";
2043
- skipped.push(
2044
- isInside(rootReal, targetReal) ? {
2045
- path: linkedDir,
2046
- reason: "symlink",
2047
- detail: `${what} not followed (target: ${target})`
2048
- } : {
2049
- path: linkedDir,
2291
+ if (targetReal === null) {
2292
+ report(linkedPath, brokenLinkRecord(absolute, linkedPath, rootReal));
2293
+ continue;
2294
+ }
2295
+ if (!isInside(rootReal, targetReal)) {
2296
+ report(linkedPath, {
2297
+ path: linkedPath,
2050
2298
  reason: "outside-root",
2051
- detail: `link target resolves outside the scanned root (target: ${target}); not followed`
2052
- }
2053
- );
2299
+ detail: `link target resolves outside the scanned root (target: ${rawTarget}); not followed`
2300
+ });
2301
+ continue;
2302
+ }
2303
+ let stats = null;
2304
+ try {
2305
+ stats = fs14__namespace.statSync(absolute);
2306
+ } catch {
2307
+ stats = null;
2308
+ }
2309
+ if (stats === null) {
2310
+ report(linkedPath, { path: linkedPath, reason: "read-error", detail: "unreadable symlink" });
2311
+ continue;
2312
+ }
2313
+ if (linkedPath !== candidate || stats.isDirectory()) {
2314
+ report(linkedPath, {
2315
+ path: linkedPath,
2316
+ reason: "symlink",
2317
+ detail: `directory link not followed (target: ${rawTarget})`
2318
+ });
2319
+ continue;
2320
+ }
2321
+ if (!stats.isFile()) {
2322
+ report(linkedPath, {
2323
+ path: linkedPath,
2324
+ reason: "symlink",
2325
+ detail: `link to neither a file nor a directory (target: ${rawTarget})`
2326
+ });
2327
+ continue;
2328
+ }
2329
+ kept.push(candidate);
2054
2330
  }
2055
2331
  return kept;
2056
2332
  }
@@ -2097,6 +2373,7 @@ function collectFiles(cwd, options = {}) {
2097
2373
  (options.toolOwnedPaths ?? []).map((entry) => entry.replace(/\\/g, "/"))
2098
2374
  );
2099
2375
  const isToolOwned = makeToolOwnedDecider(cwd, [...toolOwnedPaths]);
2376
+ const toolDirNames = toolDirNamesFor(toolOwnedPaths);
2100
2377
  let candidates;
2101
2378
  const skipped = [];
2102
2379
  const discovery = options.discovery ?? "auto";
@@ -2125,7 +2402,7 @@ function collectFiles(cwd, options = {}) {
2125
2402
  }
2126
2403
  const files = candidates.filter((file) => {
2127
2404
  if (isToolOwned(file)) return false;
2128
- const ignored = defaultIgnoreReason(file);
2405
+ const ignored = defaultIgnoreReason(file, toolDirNames);
2129
2406
  if (ignored) {
2130
2407
  skipped.push({ path: file, reason: "default-ignore", detail: ignored });
2131
2408
  return false;
@@ -2180,6 +2457,7 @@ function rootRealFor(root) {
2180
2457
  function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PURE__ */ new Set(), parentGitignoreLayers = []) {
2181
2458
  const results = { files: [], skipped: [] };
2182
2459
  const stack = [];
2460
+ const toolDirNames = toolDirNamesFor(reservedPaths);
2183
2461
  const relativeToBase = (target) => path16__namespace.relative(baseDir, target).replace(/\\/g, "/") || ".";
2184
2462
  const enter = (current, layers) => {
2185
2463
  if (visited.has(current)) return false;
@@ -2224,11 +2502,11 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
2224
2502
  });
2225
2503
  continue;
2226
2504
  }
2227
- if (DEFAULT_IGNORED_FILES.includes(entry.name) || entry.name.startsWith("snapshot.backup-")) {
2505
+ if (DEFAULT_IGNORED_FILES.includes(entry.name) || isToolLeftoverName(entry.name, toolDirNames)) {
2228
2506
  results.skipped.push({
2229
2507
  path: relPath,
2230
2508
  reason: "default-ignore",
2231
- detail: "built-in ignore: filename"
2509
+ detail: isToolLeftoverName(entry.name, toolDirNames) ? `built-in ignore: leftover snapshot backup "${entry.name}" (not descended)` : "built-in ignore: filename"
2232
2510
  });
2233
2511
  continue;
2234
2512
  }
@@ -2249,7 +2527,7 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
2249
2527
  try {
2250
2528
  targetReal = fs14__namespace.realpathSync(fullPath);
2251
2529
  } catch {
2252
- results.skipped.push({ path: relPath, reason: "read-error", detail: "broken symlink" });
2530
+ results.skipped.push(brokenLinkRecord(fullPath, relPath, rootReal));
2253
2531
  continue;
2254
2532
  }
2255
2533
  let stats;
@@ -2337,8 +2615,9 @@ function findConfigFile(cwd) {
2337
2615
  const pkgJsonPath = path16__namespace.join(cwd, "package.json");
2338
2616
  if (!fs14__namespace.existsSync(pkgJsonPath)) return null;
2339
2617
  try {
2340
- const parsed = JSON.parse(fs14__namespace.readFileSync(pkgJsonPath, "utf8"));
2341
- return parsed.snapshot === void 0 ? null : pkgJsonPath;
2618
+ const parsed = JSON.parse(stripJsonComments(fs14__namespace.readFileSync(pkgJsonPath, "utf8")));
2619
+ const snapshot = parsed?.snapshot;
2620
+ return typeof snapshot === "object" && snapshot !== null && !Array.isArray(snapshot) ? pkgJsonPath : null;
2342
2621
  } catch {
2343
2622
  return null;
2344
2623
  }
@@ -2388,15 +2667,19 @@ function normalizeBudgets(budgets, maxPartBytes) {
2388
2667
  }
2389
2668
  function normalizeResolvedConfig(config) {
2390
2669
  const discovery = isDiscoveryMode(config.discovery) ? config.discovery : "auto";
2670
+ const monolithWanted = config.includeMonolith === true || config.artifacts?.monolith === true;
2671
+ const artifacts = resolveArtifacts(
2672
+ config.artifacts,
2673
+ void 0,
2674
+ monolithWanted,
2675
+ monolithWanted
2676
+ );
2391
2677
  return markResolvedConfig({
2392
2678
  ...config,
2393
2679
  discovery,
2680
+ includeMonolith: artifacts.monolith,
2394
2681
  secretRules: compileSecretRules(config.secretRules),
2395
- artifacts: resolveArtifacts(
2396
- config.artifacts,
2397
- void 0,
2398
- config.includeMonolith === true
2399
- ),
2682
+ artifacts,
2400
2683
  include: resolveInclude(config.include),
2401
2684
  preset: typeof config.preset === "string" ? config.preset : "generic",
2402
2685
  presetExclude: [
@@ -2605,6 +2888,16 @@ async function importConfigModule(fullPath) {
2605
2888
  url$1.searchParams.set("codebaseSnapshotLoad", String(moduleConfigLoadToken));
2606
2889
  return await import(url$1.href);
2607
2890
  }
2891
+ function attachConfigDir(config, filePath) {
2892
+ if (typeof config === "object" && config !== null) {
2893
+ Object.defineProperty(config, CONFIG_DIR_SYMBOL, {
2894
+ value: path16__namespace.dirname(filePath),
2895
+ enumerable: false,
2896
+ configurable: true
2897
+ });
2898
+ }
2899
+ return config;
2900
+ }
2608
2901
  async function loadConfigFileDetailed(cwd) {
2609
2902
  const warnings = [];
2610
2903
  const errors = [];
@@ -2620,7 +2913,7 @@ async function loadConfigFileDetailed(cwd) {
2620
2913
  );
2621
2914
  }
2622
2915
  assertKnownConfigKeys(config, fullPath);
2623
- return { config, file: fullPath, warnings, errors };
2916
+ return { config: attachConfigDir(config, fullPath), file: fullPath, warnings, errors };
2624
2917
  } catch (err) {
2625
2918
  const raw = err.message;
2626
2919
  const message = raw.includes(fullPath) ? raw : `${fullPath}: ${raw}`;
@@ -2639,7 +2932,7 @@ async function loadConfigFileDetailed(cwd) {
2639
2932
  const imported = await importConfigModule(fullPath);
2640
2933
  const hasDefault = Object.prototype.hasOwnProperty.call(imported, "default");
2641
2934
  const config = readConfigExport(hasDefault ? imported.default : imported, fullPath);
2642
- return { config, file: fullPath, warnings, errors };
2935
+ return { config: attachConfigDir(config, fullPath), file: fullPath, warnings, errors };
2643
2936
  } catch (err) {
2644
2937
  const message = `Could not load ${fullPath}: ${err.message}`;
2645
2938
  warnings.push(message);
@@ -2657,7 +2950,12 @@ async function loadConfigFileDetailed(cwd) {
2657
2950
  snapshotKey,
2658
2951
  `${pkgJsonPath} (the "snapshot" key)`
2659
2952
  );
2660
- return { config: snapshotKey, file: pkgJsonPath, warnings, errors };
2953
+ return {
2954
+ config: attachConfigDir(snapshotKey, pkgJsonPath),
2955
+ file: pkgJsonPath,
2956
+ warnings,
2957
+ errors
2958
+ };
2661
2959
  }
2662
2960
  if (snapshotKey !== void 0) {
2663
2961
  const kind = Array.isArray(snapshotKey) ? "array" : typeof snapshotKey;
@@ -2696,7 +2994,7 @@ var DEFAULT_ARTIFACTS = {
2696
2994
  function isArtifactName(value) {
2697
2995
  return ARTIFACT_NAMES.includes(value);
2698
2996
  }
2699
- function resolveArtifacts(requested, skipped, includeMonolith, monolithOverride) {
2997
+ function resolveArtifacts(requested, skipped, includeMonolith, monolithOverride, only) {
2700
2998
  const artifacts = {
2701
2999
  ...DEFAULT_ARTIFACTS,
2702
3000
  // `includeMonolith` predates this selection and stays the switch for it.
@@ -2721,6 +3019,21 @@ function resolveArtifacts(requested, skipped, includeMonolith, monolithOverride)
2721
3019
  if (monolithOverride !== void 0) {
2722
3020
  artifacts.monolith = monolithOverride;
2723
3021
  }
3022
+ if (only !== void 0 && only.length > 0) {
3023
+ const keep = /* @__PURE__ */ new Set();
3024
+ for (const name of only) {
3025
+ if (!isArtifactName(name)) {
3026
+ throw new Error(
3027
+ `Unknown artifact "${name}". Expected one of: ${ARTIFACT_NAMES.join(", ")}.`
3028
+ );
3029
+ }
3030
+ keep.add(name);
3031
+ }
3032
+ for (const name of ARTIFACT_NAMES) {
3033
+ artifacts[name] = keep.has(name);
3034
+ }
3035
+ return artifacts;
3036
+ }
2724
3037
  for (const name of skipped ?? []) {
2725
3038
  if (!isArtifactName(name)) {
2726
3039
  throw new Error(
@@ -3021,7 +3334,8 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
3021
3334
  userConfig?.artifacts,
3022
3335
  cliOptions?.skipArtifacts,
3023
3336
  includeMonolith,
3024
- cliMonolith
3337
+ cliMonolith,
3338
+ cliOptions?.onlyArtifacts
3025
3339
  );
3026
3340
  const explicitMaxPartBytes = cliOptions?.maxPartBytes ?? userConfig?.maxPartBytes;
3027
3341
  const maxPartBytes = boundedBytes(
@@ -3195,7 +3509,18 @@ function configDigest(config) {
3195
3509
  excludePatterns: config.excludePatterns,
3196
3510
  preset: config.preset,
3197
3511
  layersMode: config.layersMode,
3198
- budgets: config.budgets,
3512
+ // `budgets.byLayer` is a plain object, and `JSON.stringify` preserves insertion order — so
3513
+ // `{ docs, api }` and `{ api, docs }` hashed differently despite being the same settings, and
3514
+ // `validate` reported configuration drift for a snapshot nobody had changed. The keys are
3515
+ // canonicalised here; nothing else about the object is order-dependent.
3516
+ budgets: {
3517
+ default: config.budgets.default,
3518
+ byLayer: Object.fromEntries(
3519
+ Object.entries(config.budgets.byLayer).sort(
3520
+ ([left], [right]) => left < right ? -1 : left > right ? 1 : 0
3521
+ )
3522
+ )
3523
+ },
3199
3524
  // The matcher is what makes a layer a layer. Hashing only the names meant that
3200
3525
  // moving `{ name: "api", match: "src/api/**" }` to `"src/v2/**"` produced the same
3201
3526
  // digest, so `validate` reported "valid and up to date" for a snapshot whose files
@@ -3297,6 +3622,10 @@ var SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
3297
3622
  ".mjs",
3298
3623
  ".cjs"
3299
3624
  ]);
3625
+ var PYTHON_EXTENSIONS = /* @__PURE__ */ new Set([".py", ".pyi"]);
3626
+ var RUBY_EXTENSIONS = /* @__PURE__ */ new Set([".rb", ".rake", ".gemspec"]);
3627
+ var C_EXTENSIONS = /* @__PURE__ */ new Set([".c", ".h", ".cc", ".cpp", ".cxx", ".hpp", ".hxx", ".m", ".mm"]);
3628
+ var PYTHON_SUFFIXES = [".py", ".pyi", "/__init__.py", "/__init__.pyi"];
3300
3629
  function buildImportResolver(files) {
3301
3630
  const byPath = /* @__PURE__ */ new Map();
3302
3631
  const byPathFolded = /* @__PURE__ */ new Map();
@@ -3323,11 +3652,45 @@ function buildImportResolver(files) {
3323
3652
  return { byPath, byPathFolded, byStem, byStemFolded };
3324
3653
  }
3325
3654
  function resolveSpecifier(fromFile, specifier, resolver) {
3655
+ const extension = path16__namespace.posix.extname(fromFile).toLowerCase();
3656
+ const exact = (key) => resolver.byPath.get(key) ?? resolver.byPathFolded.get(key.toLowerCase()) ?? null;
3657
+ const firstOf = (candidates) => {
3658
+ for (const candidate of candidates) {
3659
+ const hit = exact(candidate);
3660
+ if (hit) return hit;
3661
+ }
3662
+ return null;
3663
+ };
3664
+ if (PYTHON_EXTENSIONS.has(extension) && specifier.startsWith(".")) {
3665
+ const dots = /^\.+/.exec(specifier)?.[0].length ?? 0;
3666
+ const rest = specifier.slice(dots).replace(/\./g, "/");
3667
+ let base = path16__namespace.posix.dirname(fromFile);
3668
+ for (let up = 1; up < dots; up += 1) base = path16__namespace.posix.dirname(base);
3669
+ const joined2 = rest ? path16__namespace.posix.normalize(path16__namespace.posix.join(base, rest)) : base;
3670
+ return firstOf([joined2, ...PYTHON_SUFFIXES.map((suffix) => `${joined2}${suffix}`)]);
3671
+ }
3672
+ if (RUBY_EXTENSIONS.has(extension) && specifier.startsWith("./")) {
3673
+ const joined2 = path16__namespace.posix.normalize(
3674
+ path16__namespace.posix.join(path16__namespace.posix.dirname(fromFile), specifier)
3675
+ );
3676
+ return firstOf([`${joined2}.rb`, joined2]);
3677
+ }
3678
+ if (C_EXTENSIONS.has(extension) && specifier.startsWith("./")) {
3679
+ const joined2 = path16__namespace.posix.normalize(
3680
+ path16__namespace.posix.join(path16__namespace.posix.dirname(fromFile), specifier)
3681
+ );
3682
+ return exact(joined2);
3683
+ }
3684
+ if (extension === ".dart" && !specifier.includes(":")) {
3685
+ const joined2 = path16__namespace.posix.normalize(
3686
+ path16__namespace.posix.join(path16__namespace.posix.dirname(fromFile), specifier)
3687
+ );
3688
+ return firstOf([joined2, `${joined2}.dart`]);
3689
+ }
3326
3690
  if (!RELATIVE_SPECIFIER.test(specifier)) return null;
3327
3691
  const joined = path16__namespace.posix.normalize(
3328
3692
  path16__namespace.posix.join(path16__namespace.posix.dirname(fromFile), specifier)
3329
3693
  );
3330
- const exact = (key) => resolver.byPath.get(key) ?? resolver.byPathFolded.get(key.toLowerCase()) ?? null;
3331
3694
  const direct = exact(joined);
3332
3695
  if (direct) return direct;
3333
3696
  for (const suffix of IMPORT_CANDIDATE_SUFFIXES) {
@@ -3453,13 +3816,23 @@ function summarizeTypeScriptSource(relativePath, content) {
3453
3816
  if (ts__default.default.isImportDeclaration(node) && ts__default.default.isStringLiteral(node.moduleSpecifier)) {
3454
3817
  summary.imports.push(node.moduleSpecifier.text);
3455
3818
  }
3819
+ if (ts__default.default.isImportEqualsDeclaration(node) && ts__default.default.isExternalModuleReference(node.moduleReference) && node.moduleReference.expression !== void 0 && ts__default.default.isStringLiteral(node.moduleReference.expression)) {
3820
+ summary.imports.push(node.moduleReference.expression.text);
3821
+ }
3822
+ if (ts__default.default.isCallExpression(node) && node.arguments.length >= 1) {
3823
+ const firstArgument = node.arguments[0];
3824
+ if (firstArgument !== void 0 && ts__default.default.isStringLiteral(firstArgument)) {
3825
+ const isDynamicImport = node.expression.kind === ts__default.default.SyntaxKind.ImportKeyword;
3826
+ const isRequire = ts__default.default.isIdentifier(node.expression) && node.expression.text === "require";
3827
+ if (isDynamicImport || isRequire) summary.imports.push(firstArgument.text);
3828
+ }
3829
+ }
3456
3830
  if (ts__default.default.isExportDeclaration(node)) {
3457
3831
  if (node.moduleSpecifier && ts__default.default.isStringLiteral(node.moduleSpecifier)) {
3458
3832
  summary.imports.push(node.moduleSpecifier.text);
3833
+ summary.reExports.push(node.moduleSpecifier.text);
3459
3834
  if (node.exportClause && ts__default.default.isNamespaceExport(node.exportClause)) {
3460
3835
  summary.exports.push(node.exportClause.name.text);
3461
- } else if (!node.exportClause) {
3462
- summary.reExports.push(node.moduleSpecifier.text);
3463
3836
  }
3464
3837
  }
3465
3838
  if (node.exportClause && ts__default.default.isNamedExports(node.exportClause)) {
@@ -3604,7 +3977,7 @@ function isCapitalizedName(name) {
3604
3977
  }
3605
3978
 
3606
3979
  // src/ast/profiles/cfamily.ts
3607
- var INCLUDE = /^#\s*include\s*[<"]([^>"]+)[>"]/;
3980
+ var INCLUDE = /^#\s*include\s*([<"])([^>"]+)[>"]/;
3608
3981
  var DEFINE = /^#\s*define\s+([A-Za-z_]\w*)/;
3609
3982
  var USING = /^using\s+(?:namespace\s+)?([\w:]+)\s*;/;
3610
3983
  var TYPE_DECL = /^(?:typedef\s+)?(?:struct|union|class|enum)\s+([A-Za-z_]\w*)/;
@@ -3623,7 +3996,7 @@ var cfamilyProfile = {
3623
3996
  }
3624
3997
  const included = INCLUDE.exec(trimmed);
3625
3998
  if (included) {
3626
- summary.imports.push(included[1]);
3999
+ summary.imports.push(included[1] === '"' ? `./${included[2]}` : included[2]);
3627
4000
  return;
3628
4001
  }
3629
4002
  const used = USING.exec(trimmed);
@@ -4027,7 +4400,15 @@ var pythonProfile = {
4027
4400
  }
4028
4401
  const from = FROM_IMPORT.exec(trimmed);
4029
4402
  if (from) {
4030
- summary.imports.push(from[1]);
4403
+ const module = from[1];
4404
+ if (/^\.+$/.test(module)) {
4405
+ for (const name of from[2].split(",")) {
4406
+ const imported2 = name.replace(/[()]/g, "").trim().split(/\s+as\s+/)[0].trim();
4407
+ if (/^[A-Za-z_]\w*$/.test(imported2)) summary.imports.push(`${module}${imported2}`);
4408
+ }
4409
+ } else {
4410
+ summary.imports.push(module);
4411
+ }
4031
4412
  routePending = false;
4032
4413
  return;
4033
4414
  }
@@ -4076,7 +4457,8 @@ var pythonProfile = {
4076
4457
  };
4077
4458
 
4078
4459
  // src/ast/profiles/ruby.ts
4079
- var REQUIRE = /^require(?:_relative)?\s+["']([^"']+)["']/;
4460
+ var REQUIRE_RELATIVE = /^require_relative\s+["']([^"']+)["']/;
4461
+ var REQUIRE = /^require\s+["']([^"']+)["']/;
4080
4462
  var CLASS_OR_MODULE = /^(?:class|module)\s+([A-Z][\w:]*)/;
4081
4463
  var METHOD2 = /^def\s+(?:self\.)?([A-Za-z_]\w*[?!=]?)/;
4082
4464
  var rubyProfile = {
@@ -4087,6 +4469,11 @@ var rubyProfile = {
4087
4469
  eachLine(content, (line) => {
4088
4470
  const trimmed = line.trim();
4089
4471
  if (!trimmed || trimmed.startsWith("#")) return;
4472
+ const relative12 = REQUIRE_RELATIVE.exec(trimmed);
4473
+ if (relative12) {
4474
+ summary.imports.push(`./${relative12[1]}`);
4475
+ return;
4476
+ }
4090
4477
  const required = REQUIRE.exec(trimmed);
4091
4478
  if (required) {
4092
4479
  summary.imports.push(required[1]);
@@ -4177,7 +4564,8 @@ var rustProfile = {
4177
4564
  };
4178
4565
 
4179
4566
  // src/ast/profiles/sfc.ts
4180
- var SCRIPT_BLOCK = /<script[^>]*>([\s\S]*?)<\/script>/gi;
4567
+ var SCRIPT_BLOCK = /<script([^>]*)>([\s\S]*?)<\/script>/gi;
4568
+ var JSX_LANG = /\blang\s*=\s*["']?[tj]sx\b/i;
4181
4569
  var ASTRO_FRONTMATTER = /^\uFEFF?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?=\r?\n|$)/;
4182
4570
  function componentName(path22) {
4183
4571
  const base = path22.split("/").pop() ?? path22;
@@ -4188,13 +4576,15 @@ var sfcProfile = {
4188
4576
  extensions: [".vue", ".svelte", ".astro"],
4189
4577
  summarize(path22, content) {
4190
4578
  let script = "";
4579
+ let usesJsx = path22.toLowerCase().endsWith(".astro");
4191
4580
  if (path22.toLowerCase().endsWith(".astro")) {
4192
4581
  const frontmatter = ASTRO_FRONTMATTER.exec(content);
4193
4582
  if (frontmatter) script += `${frontmatter[1]}
4194
4583
  `;
4195
4584
  }
4196
4585
  for (const match of content.matchAll(SCRIPT_BLOCK)) {
4197
- script += `${match[1]}
4586
+ if (JSX_LANG.test(match[1] ?? "")) usesJsx = true;
4587
+ script += `${match[2]}
4198
4588
  `;
4199
4589
  }
4200
4590
  const name = componentName(path22);
@@ -4206,7 +4596,7 @@ var sfcProfile = {
4206
4596
  }
4207
4597
  return { summary: finalizeSummary(summary2), quality: "heuristic" };
4208
4598
  }
4209
- const summary = summarizeTypeScriptSource(`${name}.ts`, script);
4599
+ const summary = summarizeTypeScriptSource(`${name}.${usesJsx ? "tsx" : "ts"}`, script);
4210
4600
  summary.reactComponents.push(name);
4211
4601
  summary.exports.push(name);
4212
4602
  return { summary: finalizeSummary(summary), quality: "ast" };
@@ -4640,18 +5030,22 @@ function isBinaryFile(absolutePath) {
4640
5030
  }
4641
5031
 
4642
5032
  // src/ast/imports.ts
5033
+ var SUMMARY_MAX_SOURCE_BYTES = 2 * 1024 * 1024;
4643
5034
  var TS_SOURCE_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
4644
5035
  var isTsSource = (relativePath) => {
4645
5036
  const lower = relativePath.toLowerCase();
4646
5037
  return TS_SOURCE_EXTENSIONS.some((extension) => lower.endsWith(extension));
4647
5038
  };
4648
5039
  function importsOfText(relativePath, text2) {
5040
+ if (Buffer.byteLength(text2, "utf8") > SUMMARY_MAX_SOURCE_BYTES) return [];
4649
5041
  if (isTsSource(relativePath)) return summarizeTypeScriptSource(relativePath, text2).imports;
4650
5042
  return summarizeWithProfile(relativePath, text2)?.summary.imports ?? [];
4651
5043
  }
4652
5044
  function importsOfFile(relativePath, absolutePath) {
4653
5045
  let buffer;
4654
5046
  try {
5047
+ const stats = fs14__namespace.statSync(absolutePath);
5048
+ if (!stats.isFile() || stats.size > SUMMARY_MAX_SOURCE_BYTES) return [];
4655
5049
  buffer = fs14__namespace.readFileSync(absolutePath);
4656
5050
  } catch {
4657
5051
  return [];
@@ -4727,16 +5121,14 @@ function emptyDrift() {
4727
5121
  function sha256Hex(buffer) {
4728
5122
  return crypto3__namespace.createHash("sha256").update(buffer).digest("hex");
4729
5123
  }
4730
- var VERIFY_SNIFF_MAX_BYTES = 8 * 1024 * 1024;
4731
5124
  function wouldNowBeIncluded(cwd, relativePath) {
4732
5125
  const absolutePath = path16__namespace.join(cwd, relativePath);
4733
5126
  try {
4734
5127
  const stats = fs14__namespace.statSync(absolutePath);
4735
5128
  if (!stats.isFile()) return false;
4736
- if (stats.size <= VERIFY_SNIFF_MAX_BYTES) {
4737
- return !decodeText(fs14__namespace.readFileSync(absolutePath)).binary;
4738
- }
4739
- return !isBinaryFile(absolutePath);
5129
+ if (isBinaryExtension(absolutePath)) return false;
5130
+ if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) return false;
5131
+ return !decodeText(fs14__namespace.readFileSync(absolutePath)).binary;
4740
5132
  } catch {
4741
5133
  return false;
4742
5134
  }
@@ -4782,9 +5174,13 @@ function describeManifestShapeProblem(value) {
4782
5174
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
4783
5175
  return 'a "parts" entry is not an object';
4784
5176
  }
4785
- if (typeof entry.filename !== "string") {
5177
+ const filename = entry.filename;
5178
+ if (typeof filename !== "string" || filename.trim() === "") {
4786
5179
  return 'a "parts" entry has no "filename"';
4787
5180
  }
5181
+ if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path16__namespace.isAbsolute(filename)) {
5182
+ return 'a "parts" entry "filename" must be a bare filename inside parts/';
5183
+ }
4788
5184
  }
4789
5185
  if (!candidate.layers || typeof candidate.layers !== "object" || Array.isArray(candidate.layers)) {
4790
5186
  return 'missing "layers" object';
@@ -4895,7 +5291,7 @@ function validateSnapshot(configInput) {
4895
5291
  });
4896
5292
  for (const diskFile of collection.files) {
4897
5293
  const snapshotHash = manifestFileMap.get(diskFile);
4898
- if (!snapshotHash) {
5294
+ if (snapshotHash === void 0) {
4899
5295
  const skipReason = skippedReasonOnDisk(diskFile);
4900
5296
  if (skipReason === "unchanged") {
4901
5297
  if (unchangedScope !== null) {
@@ -4909,6 +5305,11 @@ function validateSnapshot(configInput) {
4909
5305
  drift.missingInSnapshot.push(diskFile);
4910
5306
  continue;
4911
5307
  }
5308
+ if (unchangedScope !== null && !unchangedScope.has(diskFile) && !becameDependent(diskFile)) {
5309
+ drift.configMismatches.push(
5310
+ `scope: ${maskedPath(diskFile, config.secretRules)} is in the snapshot but is no longer in the changed-files scope`
5311
+ );
5312
+ }
4912
5313
  let diskHash;
4913
5314
  try {
4914
5315
  diskHash = sha256Hex(fs14__namespace.readFileSync(path16__namespace.join(config.cwd, diskFile)));
@@ -5049,6 +5450,41 @@ function validateSnapshot(configInput) {
5049
5450
  `includeSensitiveFiles: manifest ${recorded.includeSensitiveFiles} vs current ${config.includeSensitiveFiles}`
5050
5451
  );
5051
5452
  }
5453
+ if ((recorded.maxPartTokens ?? void 0) !== (config.maxPartTokens ?? void 0)) {
5454
+ drift.configMismatches.push(
5455
+ `maxPartTokens: manifest ${String(recorded.maxPartTokens ?? "unset")} vs current ${String(config.maxPartTokens ?? "unset")}`
5456
+ );
5457
+ }
5458
+ if ((recorded.maxMonolithBytes ?? null) !== (config.maxMonolithBytes ?? null)) {
5459
+ drift.configMismatches.push(
5460
+ `maxMonolithBytes: manifest ${String(recorded.maxMonolithBytes ?? null)} vs current ${String(config.maxMonolithBytes ?? null)}`
5461
+ );
5462
+ }
5463
+ if (Boolean(recorded.skeleton) !== Boolean(config.skeleton)) {
5464
+ drift.configMismatches.push(
5465
+ `skeleton: manifest ${Boolean(recorded.skeleton)} vs current ${Boolean(config.skeleton)}`
5466
+ );
5467
+ }
5468
+ if (Boolean(recorded.sarif) !== Boolean(config.sarif)) {
5469
+ drift.configMismatches.push(
5470
+ `sarif: manifest ${Boolean(recorded.sarif)} vs current ${Boolean(config.sarif)}`
5471
+ );
5472
+ }
5473
+ if ((recorded.changedSince ?? void 0) !== (config.changedSince ?? void 0)) {
5474
+ drift.configMismatches.push(
5475
+ `changedSince: manifest ${String(recorded.changedSince ?? "unset")} vs current ${String(config.changedSince ?? "unset")}`
5476
+ );
5477
+ }
5478
+ if (Boolean(recorded.staged) !== Boolean(config.staged)) {
5479
+ drift.configMismatches.push(
5480
+ `staged: manifest ${Boolean(recorded.staged)} vs current ${Boolean(config.staged)}`
5481
+ );
5482
+ }
5483
+ if (Boolean(recorded.withDependents) !== Boolean(config.withDependents)) {
5484
+ drift.configMismatches.push(
5485
+ `withDependents: manifest ${Boolean(recorded.withDependents)} vs current ${Boolean(config.withDependents)}`
5486
+ );
5487
+ }
5052
5488
  const effectiveDiscovery = config.discovery ?? "auto";
5053
5489
  const recordedDiscovery = recorded.discovery;
5054
5490
  if (recordedDiscovery !== void 0 && recordedDiscovery !== effectiveDiscovery) {
@@ -5365,7 +5801,7 @@ function describePayloadDiff(before, after, sourceFilesIdentical) {
5365
5801
  }
5366
5802
  if (fingerprintDiffers && (sourceFilesIdentical || configurationDiffers)) {
5367
5803
  reasons.push(
5368
- `content fingerprint ${shortDigest(before.fingerprint)} \u2192 ${shortDigest(after.fingerprint)}` + (sourceFilesIdentical ? " (same source files, packed differently)" : "")
5804
+ `content fingerprint ${shortDigest(before.fingerprint)} \u2192 ${shortDigest(after.fingerprint)}` + (sourceFilesIdentical ? " (same source files, packed or configured differently)" : "")
5369
5805
  );
5370
5806
  }
5371
5807
  if (partsDiffer) {
@@ -5523,9 +5959,21 @@ function renderDiffText(diff) {
5523
5959
  }
5524
5960
 
5525
5961
  // src/partitioner/preview.ts
5962
+ var LINE_ENDINGS = /\r\n|\r/g;
5963
+ var normaliseLineEndings = (content) => content.replace(LINE_ENDINGS, "\n");
5526
5964
  function countLines(content) {
5527
5965
  if (content.length === 0) return 0;
5528
- return content.split("\n").length - (content.endsWith("\n") ? 1 : 0);
5966
+ let breaks = 0;
5967
+ for (let index = 0; index < content.length; index += 1) {
5968
+ const code = content.charCodeAt(index);
5969
+ if (code === 10) {
5970
+ breaks += 1;
5971
+ continue;
5972
+ }
5973
+ if (code === 13 && content.charCodeAt(index + 1) !== 10) breaks += 1;
5974
+ }
5975
+ const last = content.charCodeAt(content.length - 1);
5976
+ return last === 10 || last === 13 ? breaks : breaks + 1;
5529
5977
  }
5530
5978
  function truncateToBytes(content, maxBytes) {
5531
5979
  if (maxBytes <= 0) return { content: "", isTruncated: content.length > 0 };
@@ -5536,17 +5984,18 @@ function truncateToBytes(content, maxBytes) {
5536
5984
  return { content: slice, isTruncated: true };
5537
5985
  }
5538
5986
  function truncatePreview(content, headLines, tailLines) {
5539
- const lines = content.split("\n");
5540
- const total = countLines(content);
5987
+ const normalised = normaliseLineEndings(content);
5988
+ const lines = normalised.split("\n");
5989
+ const total = countLines(normalised);
5541
5990
  if (total <= headLines + tailLines) {
5542
5991
  return {
5543
- content,
5992
+ content: normalised,
5544
5993
  isTruncated: false,
5545
5994
  originalLines: total,
5546
5995
  includedLines: total
5547
5996
  };
5548
5997
  }
5549
- const window = content.endsWith("\n") ? lines.slice(0, -1) : lines;
5998
+ const window = normalised.endsWith("\n") ? lines.slice(0, -1) : lines;
5550
5999
  const head = window.slice(0, headLines);
5551
6000
  const tail = tailLines > 0 ? window.slice(window.length - tailLines) : [];
5552
6001
  const omitted = total - head.length - tail.length;
@@ -5666,10 +6115,13 @@ function describeMatcher(matcher) {
5666
6115
  return String(matcher);
5667
6116
  }
5668
6117
  function normalizeTarget(cwd, target) {
5669
- const absolute = path16__namespace.resolve(cwd, target);
5670
- const relative12 = path16__namespace.relative(cwd, absolute);
5671
- if (relative12.startsWith("..") || path16__namespace.isAbsolute(relative12)) return target;
5672
- return relative12.split(path16__namespace.sep).join("/");
6118
+ const resolvedCwd = path16__namespace.resolve(cwd);
6119
+ const absolute = path16__namespace.resolve(resolvedCwd, target);
6120
+ const relative12 = path16__namespace.relative(resolvedCwd, absolute);
6121
+ if (relative12 === "" || relative12 === ".." || relative12.startsWith(`..${path16__namespace.sep}`) || path16__namespace.isAbsolute(relative12)) {
6122
+ return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
6123
+ }
6124
+ return { relative: relative12.split(path16__namespace.sep).join("/"), outsideRoot: false };
5673
6125
  }
5674
6126
  function findRuleMatch(rules, relativePath) {
5675
6127
  return rules.find(
@@ -5696,9 +6148,19 @@ function readManifest2(config) {
5696
6148
  }
5697
6149
  }
5698
6150
  function explainPath(config, target) {
5699
- const relative12 = normalizeTarget(config.cwd, target);
5700
- const absolute = path16__namespace.join(config.cwd, relative12);
6151
+ const normalized = normalizeTarget(config.cwd, target);
6152
+ const relative12 = normalized.relative;
5701
6153
  const maskedPath2 = findSecretInPath(relative12, config.secretRules)?.masked ?? relative12;
6154
+ if (normalized.outsideRoot) {
6155
+ return {
6156
+ path: maskedPath2,
6157
+ exists: false,
6158
+ included: false,
6159
+ reason: "outside-root",
6160
+ detail: "path resolves outside the configured repository root and was not inspected"
6161
+ };
6162
+ }
6163
+ const absolute = path16__namespace.join(config.cwd, relative12);
5702
6164
  const result = {
5703
6165
  path: maskedPath2,
5704
6166
  exists: fs14__namespace.existsSync(absolute),
@@ -5772,6 +6234,12 @@ function explainPath(config, target) {
5772
6234
  return result;
5773
6235
  }
5774
6236
  }
6237
+ if (isBinaryExtension(absolute)) {
6238
+ result.included = false;
6239
+ result.reason = "binary";
6240
+ result.detail = "binary extension; generate skips it without reading and records `binary` in manifest.skipped[]";
6241
+ return result;
6242
+ }
5775
6243
  let sizeOnDisk = null;
5776
6244
  try {
5777
6245
  sizeOnDisk = fs14__namespace.statSync(absolute).size;
@@ -5784,13 +6252,6 @@ function explainPath(config, target) {
5784
6252
  result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
5785
6253
  return result;
5786
6254
  }
5787
- result.layer = classifyLayer(relative12, config.layers);
5788
- result.kind = classifyKind(relative12, config.kinds);
5789
- result.language = detectLanguage(relative12);
5790
- const layerRule = findRuleMatch(config.layers, relative12);
5791
- if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
5792
- const kindRule = findRuleMatch(config.kinds, relative12);
5793
- if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
5794
6255
  if (fs14__namespace.existsSync(absolute) && fs14__namespace.statSync(absolute).isFile()) {
5795
6256
  const buffer = fs14__namespace.readFileSync(absolute);
5796
6257
  const decoded = decodeText(buffer);
@@ -5808,6 +6269,13 @@ function explainPath(config, target) {
5808
6269
  result.secretCount = findings.length;
5809
6270
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
5810
6271
  }
6272
+ result.layer = classifyLayer(relative12, config.layers);
6273
+ result.kind = classifyKind(relative12, config.kinds);
6274
+ result.language = detectLanguage(relative12);
6275
+ const layerRule = findRuleMatch(config.layers, relative12);
6276
+ if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
6277
+ const kindRule = findRuleMatch(config.kinds, relative12);
6278
+ if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
5811
6279
  const manifest = readManifest2(config);
5812
6280
  const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative12) : void 0;
5813
6281
  result.part = entry?.part ?? null;
@@ -5848,45 +6316,217 @@ function renderExplainText(result) {
5848
6316
  );
5849
6317
  return lines.join("\n");
5850
6318
  }
5851
- function appendGitignoreEntries(cwd, entries) {
5852
- const wanted = [...new Set(entries)].filter((entry) => entry.trim().length > 0);
5853
- if (wanted.length === 0) return { added: [], note: null };
5854
- const ignorePath = path16__namespace.join(cwd, ".gitignore");
5855
- const manual = `Add ${wanted.map((entry) => `"${entry}"`).join(" and ")} to your .gitignore yourself.`;
5856
- let existing = "";
5857
- try {
5858
- if (fs14__namespace.existsSync(ignorePath)) {
5859
- if (fs14__namespace.statSync(ignorePath).isDirectory()) {
5860
- return { added: [], note: `${ignorePath} is a directory, so it was not updated. ${manual}` };
6319
+
6320
+ // src/ast/structured.ts
6321
+ function stripJsonComments2(content) {
6322
+ const text2 = content.replace(/^\uFEFF/, "");
6323
+ const withoutComments = stripComments(text2);
6324
+ return stripTrailingCommas2(withoutComments);
6325
+ }
6326
+ function stripComments(text2) {
6327
+ let out = "";
6328
+ let inString = false;
6329
+ let escaped = false;
6330
+ for (let index = 0; index < text2.length; index += 1) {
6331
+ const char = text2[index];
6332
+ if (inString) {
6333
+ out += char;
6334
+ if (escaped) escaped = false;
6335
+ else if (char === "\\") escaped = true;
6336
+ else if (char === '"') inString = false;
6337
+ continue;
6338
+ }
6339
+ if (char === '"') {
6340
+ inString = true;
6341
+ out += char;
6342
+ continue;
6343
+ }
6344
+ if (char === "/" && text2[index + 1] === "/") {
6345
+ while (index < text2.length && text2[index] !== "\n" && text2[index] !== "\r") index += 1;
6346
+ index -= 1;
6347
+ continue;
6348
+ }
6349
+ if (char === "/" && text2[index + 1] === "*") {
6350
+ index += 2;
6351
+ while (index < text2.length && !(text2[index] === "*" && text2[index + 1] === "/")) {
6352
+ if (text2[index] === "\n" || text2[index] === "\r") out += text2[index];
6353
+ index += 1;
5861
6354
  }
5862
- existing = fs14__namespace.readFileSync(ignorePath, "utf8");
6355
+ index += 1;
6356
+ continue;
5863
6357
  }
5864
- } catch (err) {
5865
- return {
5866
- added: [],
5867
- note: `${ignorePath} could not be read (${err.message}). ${manual}`
5868
- };
5869
- }
5870
- const present = new Set(existing.split(/\r?\n/).map((line) => line.trim()));
5871
- const added = wanted.filter((entry) => !present.has(entry));
5872
- if (added.length === 0) return { added: [], note: null };
5873
- const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : "\n";
5874
- try {
5875
- fs14__namespace.writeFileSync(ignorePath, `${existing}${prefix}${added.join("\n")}
5876
- `, "utf8");
5877
- } catch (err) {
5878
- return { added: [], note: `${err.message}. ${manual}` };
6358
+ out += char;
5879
6359
  }
5880
- return { added, note: null };
5881
- }
5882
- function gitignorePath(cwd, filePath) {
5883
- return path16__namespace.relative(cwd, filePath).split(path16__namespace.sep).join("/");
6360
+ return out;
5884
6361
  }
5885
-
5886
- // src/version.ts
5887
- var GENERATOR_NAME = "codebase-snapshot";
5888
- var GENERATOR_VERSION = "0.9.12";
5889
- var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
6362
+ function stripTrailingCommas2(text2) {
6363
+ let out = "";
6364
+ let inString = false;
6365
+ let escaped = false;
6366
+ for (let index = 0; index < text2.length; index += 1) {
6367
+ const char = text2[index];
6368
+ if (inString) {
6369
+ out += char;
6370
+ if (escaped) escaped = false;
6371
+ else if (char === "\\") escaped = true;
6372
+ else if (char === '"') inString = false;
6373
+ continue;
6374
+ }
6375
+ if (char === '"') {
6376
+ inString = true;
6377
+ out += char;
6378
+ continue;
6379
+ }
6380
+ if (char === ",") {
6381
+ let next = index + 1;
6382
+ while (next < text2.length && /\s/.test(text2[next])) next += 1;
6383
+ if (text2[next] === "}" || text2[next] === "]") continue;
6384
+ }
6385
+ out += char;
6386
+ }
6387
+ return out;
6388
+ }
6389
+ function summarizeJson(content) {
6390
+ try {
6391
+ const parsed = JSON.parse(stripJsonComments2(content));
6392
+ if (Array.isArray(parsed)) {
6393
+ const sample = parsed[0];
6394
+ const sampleKeys = sample && typeof sample === "object" && !Array.isArray(sample) ? Object.keys(sample).slice(0, 10).sort() : [];
6395
+ return {
6396
+ shape: "array",
6397
+ itemCount: parsed.length,
6398
+ keys: [],
6399
+ sampleKeys
6400
+ };
6401
+ }
6402
+ if (parsed && typeof parsed === "object") {
6403
+ const keys = Object.keys(parsed).sort();
6404
+ return {
6405
+ shape: "object",
6406
+ itemCount: keys.length,
6407
+ keys: keys.slice(0, 30),
6408
+ sampleKeys: []
6409
+ };
6410
+ }
6411
+ return {
6412
+ shape: typeof parsed,
6413
+ itemCount: null,
6414
+ keys: [],
6415
+ sampleKeys: []
6416
+ };
6417
+ } catch {
6418
+ return {
6419
+ shape: "invalid-json",
6420
+ itemCount: null,
6421
+ keys: [],
6422
+ sampleKeys: []
6423
+ };
6424
+ }
6425
+ }
6426
+ function frontMatterEnd(lines) {
6427
+ if (lines.length < 3 || lines[0].trim() !== "---") return 0;
6428
+ for (let index = 1; index < lines.length; index += 1) {
6429
+ const line = lines[index];
6430
+ const candidate = line.trim();
6431
+ if (candidate === "---" || candidate === "...") {
6432
+ return index > 1 ? index : 0;
6433
+ }
6434
+ if (candidate === "") continue;
6435
+ if (/^#(\s|$)/.test(candidate)) continue;
6436
+ if (/^(`{3,}|~{3,})/.test(candidate)) return 0;
6437
+ if (/^#{1,6}\s+\S/.test(candidate)) return 0;
6438
+ const isYamlMapping = /^[A-Za-z0-9_.-]+\s*:(\s|$)/.test(candidate);
6439
+ const isListItem = /^-(?:(\s|$))/.test(candidate);
6440
+ const isIndented = /^[ \t]/.test(line);
6441
+ if (!isYamlMapping && !isListItem && !isIndented) return 0;
6442
+ }
6443
+ return 0;
6444
+ }
6445
+ function summarizeMarkdown(content) {
6446
+ const headings = [];
6447
+ const frontmatterKeys = [];
6448
+ const lines = content.replace(/^\uFEFF/, "").split(/\r\n|\n|\r/);
6449
+ let inFrontmatter = false;
6450
+ let fence = null;
6451
+ const frontMatterEndLine = frontMatterEnd(lines);
6452
+ for (let index = 0; index < lines.length; index++) {
6453
+ const line = lines[index];
6454
+ if (index === 0 && frontMatterEndLine > 0) {
6455
+ inFrontmatter = true;
6456
+ continue;
6457
+ }
6458
+ if (inFrontmatter) {
6459
+ const trimmedFrontmatter = line.trim();
6460
+ if (trimmedFrontmatter === "---" || trimmedFrontmatter === "...") {
6461
+ inFrontmatter = false;
6462
+ continue;
6463
+ }
6464
+ const match = /^([A-Za-z0-9_.-]+)\s*:/.exec(line);
6465
+ if (match) frontmatterKeys.push(match[1]);
6466
+ continue;
6467
+ }
6468
+ const trimmed = line.trim();
6469
+ const fenceMatch = /^(`{3,}|~{3,})(.*)$/.exec(trimmed);
6470
+ if (fenceMatch) {
6471
+ const run = fenceMatch[1];
6472
+ const rest = fenceMatch[2].trim();
6473
+ if (fence === null) {
6474
+ fence = { marker: run[0], length: run.length };
6475
+ } else if (run[0] === fence.marker && run.length >= fence.length && rest === "") {
6476
+ fence = null;
6477
+ }
6478
+ continue;
6479
+ }
6480
+ if (fence !== null) continue;
6481
+ const headingMatch = /^(#{1,6})\s+(.+)$/.exec(trimmed);
6482
+ if (headingMatch) {
6483
+ headings.push(`${headingMatch[1]} ${headingMatch[2].trim()}`);
6484
+ }
6485
+ }
6486
+ return {
6487
+ headings: headings.slice(0, 40),
6488
+ frontmatterKeys: Array.from(new Set(frontmatterKeys)).sort()
6489
+ };
6490
+ }
6491
+ function appendGitignoreEntries(cwd, entries) {
6492
+ const wanted = [...new Set(entries)].filter((entry) => entry.trim().length > 0);
6493
+ if (wanted.length === 0) return { added: [], note: null };
6494
+ const ignorePath = path16__namespace.join(cwd, ".gitignore");
6495
+ const manual = `Add ${wanted.map((entry) => `"${entry}"`).join(" and ")} to your .gitignore yourself.`;
6496
+ let existing = "";
6497
+ try {
6498
+ if (fs14__namespace.existsSync(ignorePath)) {
6499
+ if (fs14__namespace.statSync(ignorePath).isDirectory()) {
6500
+ return { added: [], note: `${ignorePath} is a directory, so it was not updated. ${manual}` };
6501
+ }
6502
+ existing = fs14__namespace.readFileSync(ignorePath, "utf8");
6503
+ }
6504
+ } catch (err) {
6505
+ return {
6506
+ added: [],
6507
+ note: `${ignorePath} could not be read (${err.message}). ${manual}`
6508
+ };
6509
+ }
6510
+ const present = new Set(existing.split(/\r?\n/).map((line) => line.trim()));
6511
+ const added = wanted.filter((entry) => !present.has(entry));
6512
+ if (added.length === 0) return { added: [], note: null };
6513
+ const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : "\n";
6514
+ try {
6515
+ fs14__namespace.writeFileSync(ignorePath, `${existing}${prefix}${added.join("\n")}
6516
+ `, "utf8");
6517
+ } catch (err) {
6518
+ return { added: [], note: `${err.message}. ${manual}` };
6519
+ }
6520
+ return { added, note: null };
6521
+ }
6522
+ function gitignorePath(cwd, filePath) {
6523
+ return path16__namespace.relative(cwd, filePath).split(path16__namespace.sep).join("/");
6524
+ }
6525
+
6526
+ // src/version.ts
6527
+ var GENERATOR_NAME = "codebase-snapshot";
6528
+ var GENERATOR_VERSION = "0.9.15";
6529
+ var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
5890
6530
  function isOurGeneratorName(name) {
5891
6531
  if (typeof name !== "string") return false;
5892
6532
  return name === GENERATOR_NAME || LEGACY_GENERATOR_NAMES.includes(name);
@@ -5972,7 +6612,8 @@ function renderConfig(answers) {
5972
6612
  // matched value is never included \u2014 only the path, the line and the rule.
5973
6613
  sarif: ${answers.sarif},
5974
6614
  // Snapshot only the files that differ from a git ref (for example "main"),
5975
- // plus untracked ones. null and false both mean "snapshot everything".
6615
+ // plus untracked ones. null means "snapshot everything"; any other value must
6616
+ // be a git ref string, and anything else is a configuration error.
5976
6617
  changedSince: null,
5977
6618
  // Snapshot only what is staged in the index: the pre-commit counterpart.
5978
6619
  staged: false,
@@ -6088,6 +6729,24 @@ function displayWidth(line) {
6088
6729
  return width;
6089
6730
  }
6090
6731
  var GUTTER_PATTERN = /^[ \t]*(?:[❯◆◻◼▏✖][ \t]+)*/;
6732
+ function sliceByDisplayWidth(text2, maxCells) {
6733
+ let cells = 0;
6734
+ let lastSpace = -1;
6735
+ let index = 0;
6736
+ for (const character of text2) {
6737
+ const width = isWideCodePoint(character.codePointAt(0) ?? 0) ? 2 : 1;
6738
+ if (cells + width > maxCells) break;
6739
+ if (character === " ") lastSpace = index;
6740
+ cells += width;
6741
+ index += character.length;
6742
+ }
6743
+ if (index >= text2.length) return { head: text2, tail: "" };
6744
+ if (lastSpace > 0) {
6745
+ return { head: text2.slice(0, lastSpace), tail: text2.slice(lastSpace + 1).trimStart() };
6746
+ }
6747
+ const safeIndex = index > 0 ? index : Array.from(text2)[0]?.length ?? 1;
6748
+ return { head: text2.slice(0, safeIndex), tail: text2.slice(safeIndex).trimStart() };
6749
+ }
6091
6750
  function wrapOneLine(line, limit) {
6092
6751
  if (displayWidth(line) <= limit) return [line];
6093
6752
  const gutter = GUTTER_PATTERN.exec(line)?.[0] ?? "";
@@ -6102,12 +6761,11 @@ function wrapOneLine(line, limit) {
6102
6761
  rows.push(prefix + rest);
6103
6762
  break;
6104
6763
  }
6105
- let cut = room;
6106
- const space = rest.slice(0, room).lastIndexOf(" ");
6107
- if (space > 0) cut = space;
6108
- const taken = rest.slice(0, cut).trimEnd();
6109
- rows.push(`${prefix}${taken.length > 0 ? taken : rest.slice(0, cut)}`);
6110
- rest = rest.slice(cut).trimStart();
6764
+ const { head, tail } = sliceByDisplayWidth(rest, room);
6765
+ rows.push(
6766
+ `${prefix}${head.length > 0 ? head : rest.slice(0, 1)}`
6767
+ );
6768
+ rest = tail;
6111
6769
  prefix = continuation;
6112
6770
  }
6113
6771
  return rows;
@@ -6178,7 +6836,7 @@ function keyReader(input) {
6178
6836
  next() {
6179
6837
  const queued = queue.shift();
6180
6838
  if (queued) return Promise.resolve(queued);
6181
- return new Promise((resolve9) => waiters.push(resolve9));
6839
+ return new Promise((resolve10) => waiters.push(resolve10));
6182
6840
  },
6183
6841
  close() {
6184
6842
  input.off("keypress", onKey);
@@ -6395,17 +7053,25 @@ var CONFIG_CANDIDATES = [
6395
7053
  ".snapshotrc.json",
6396
7054
  ".snapshotrc"
6397
7055
  ];
6398
- function chooseConfigFileName(cwd) {
6399
- if (!supportsTypeScriptImports()) return "snapshot.config.mjs";
6400
- const pkgPath = path16__namespace.join(cwd, "package.json");
6401
- if (!fs14__namespace.existsSync(pkgPath)) return "snapshot.config.mjs";
7056
+ function parsePackageJson(raw) {
7057
+ const parsed = JSON.parse(stripJsonComments2(raw));
7058
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
7059
+ throw new Error("package.json is not a JSON object");
7060
+ }
7061
+ return parsed;
7062
+ }
7063
+ function readPackageJson(cwd) {
6402
7064
  try {
6403
- const parsed = JSON.parse(fs14__namespace.readFileSync(pkgPath, "utf8"));
6404
- return parsed.type === "module" ? "snapshot.config.ts" : "snapshot.config.mjs";
7065
+ return parsePackageJson(fs14__namespace.readFileSync(path16__namespace.join(cwd, "package.json"), "utf8"));
6405
7066
  } catch {
6406
- return "snapshot.config.mjs";
7067
+ return null;
6407
7068
  }
6408
7069
  }
7070
+ function chooseConfigFileName(cwd) {
7071
+ if (!supportsTypeScriptImports()) return "snapshot.config.mjs";
7072
+ const parsed = readPackageJson(cwd);
7073
+ return parsed?.type === "module" ? "snapshot.config.ts" : "snapshot.config.mjs";
7074
+ }
6409
7075
  var SIZE_CHOICES = [
6410
7076
  { value: "60k", label: "Small", hint: "60 KB \xB7 ~15k tokens \xB7 tight context windows" },
6411
7077
  { value: "120k", label: "Medium", hint: "120 KB \xB7 ~30k tokens \xB7 recommended" },
@@ -6413,12 +7079,9 @@ var SIZE_CHOICES = [
6413
7079
  { value: "custom", label: "Custom\u2026", hint: "type a size like 150k or 1.5mb" }
6414
7080
  ];
6415
7081
  function packageJsonHasConfig(cwd) {
6416
- try {
6417
- const parsed = JSON.parse(fs14__namespace.readFileSync(path16__namespace.join(cwd, "package.json"), "utf8"));
6418
- return typeof parsed.snapshot === "object" && parsed.snapshot !== null && !Array.isArray(parsed.snapshot);
6419
- } catch {
6420
- return false;
6421
- }
7082
+ const parsed = readPackageJson(cwd);
7083
+ if (parsed === null) return false;
7084
+ return typeof parsed.snapshot === "object" && parsed.snapshot !== null && !Array.isArray(parsed.snapshot);
6422
7085
  }
6423
7086
  function artifactAnswers(options) {
6424
7087
  const artifacts = { ...DEFAULT_ANSWERS.artifacts };
@@ -6459,12 +7122,7 @@ function writeFileOrExplain(target, content) {
6459
7122
  function canWriteModuleConfig(name, cwd) {
6460
7123
  if (name.endsWith(".mjs") || name.endsWith(".ts")) return true;
6461
7124
  if (!name.endsWith(".js")) return false;
6462
- try {
6463
- const parsed = JSON.parse(fs14__namespace.readFileSync(path16__namespace.join(cwd, "package.json"), "utf8"));
6464
- return parsed.type === "module";
6465
- } catch {
6466
- return false;
6467
- }
7125
+ return readPackageJson(cwd)?.type === "module";
6468
7126
  }
6469
7127
  function configFormatLabel(name) {
6470
7128
  if (name.endsWith(".js")) return 'CommonJS `.js` (package.json has no "type": "module")';
@@ -6492,7 +7150,8 @@ function serializePackageJson(raw, value) {
6492
7150
  const crlf = raw.includes("\r\n");
6493
7151
  const body = JSON.stringify(value, null, spacing);
6494
7152
  const text2 = crlf ? body.replace(/\n/g, "\r\n") : body;
6495
- return `${text2}${raw.endsWith("\n") ? crlf ? "\r\n" : "\n" : ""}`;
7153
+ const bom = raw.startsWith("\uFEFF") ? "\uFEFF" : "";
7154
+ return `${bom}${text2}${raw.endsWith("\n") ? crlf ? "\r\n" : "\n" : ""}`;
6496
7155
  }
6497
7156
  function updatePackageJson(cwd, notes) {
6498
7157
  const packagePath = path16__namespace.join(cwd, "package.json");
@@ -6508,7 +7167,7 @@ function updatePackageJson(cwd, notes) {
6508
7167
  let parsed;
6509
7168
  try {
6510
7169
  raw = fs14__namespace.readFileSync(packagePath, "utf8");
6511
- parsed = JSON.parse(raw);
7170
+ parsed = parsePackageJson(raw);
6512
7171
  } catch {
6513
7172
  notes.push("Could not parse package.json; npm scripts and the devDependency were not added.");
6514
7173
  return unchanged;
@@ -6923,174 +7582,99 @@ function hasPriorSnapshot(cwd, outDir) {
6923
7582
  if (parsed === null || typeof parsed !== "object") return false;
6924
7583
  return isOurGeneratorName(parsed.generator);
6925
7584
  }
6926
-
6927
- // src/ast/structured.ts
6928
- function stripJsonComments2(content) {
6929
- const text2 = content.replace(/^\uFEFF/, "");
6930
- let out = "";
6931
- let inString = false;
6932
- let inLineComment = false;
6933
- let inBlockComment = false;
6934
- for (let i = 0; i < text2.length; i++) {
6935
- const char = text2[i];
6936
- const next = text2[i + 1];
6937
- if (inLineComment) {
6938
- if (char === "\n") {
6939
- inLineComment = false;
6940
- out += char;
6941
- }
6942
- continue;
6943
- }
6944
- if (inBlockComment) {
6945
- if (char === "*" && next === "/") {
6946
- inBlockComment = false;
6947
- i += 1;
7585
+ var hookStdoutScope = new async_hooks.AsyncLocalStorage();
7586
+ var captureScope = new async_hooks.AsyncLocalStorage();
7587
+ var installs = 0;
7588
+ var underlying = null;
7589
+ var router = null;
7590
+ var asText = (chunk) => typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
7591
+ var callbackIn = (rest) => {
7592
+ for (const argument of rest) {
7593
+ if (typeof argument === "function") return argument;
7594
+ }
7595
+ return void 0;
7596
+ };
7597
+ function installStdoutRouter() {
7598
+ if (installs === 0) {
7599
+ underlying = process.stdout.write;
7600
+ const realStdout = underlying.bind(process.stdout);
7601
+ const realStderr = process.stderr.write.bind(process.stderr);
7602
+ router = ((...args) => {
7603
+ if (hookStdoutScope.getStore() === true) return realStderr(...args);
7604
+ const capture = captureScope.getStore();
7605
+ if (capture !== void 0) {
7606
+ capture.write(asText(args[0]));
7607
+ const callback = callbackIn(args.slice(1));
7608
+ if (callback) callback(null);
7609
+ return true;
6948
7610
  }
6949
- continue;
6950
- }
6951
- if (inString) {
6952
- out += char;
6953
- if (char === "\\") {
6954
- if (next !== void 0) {
6955
- out += next;
6956
- i += 1;
6957
- }
6958
- } else if (char === '"') {
6959
- inString = false;
7611
+ return realStdout(...args);
7612
+ });
7613
+ process.stdout.write = router;
7614
+ }
7615
+ installs += 1;
7616
+ let released = false;
7617
+ return () => {
7618
+ if (released) return;
7619
+ released = true;
7620
+ installs -= 1;
7621
+ if (installs === 0) {
7622
+ if (process.stdout.write === router && underlying !== null) {
7623
+ process.stdout.write = underlying;
6960
7624
  }
6961
- continue;
6962
- }
6963
- if (char === '"') {
6964
- inString = true;
6965
- out += char;
6966
- continue;
6967
- }
6968
- if (char === "/" && next === "/") {
6969
- inLineComment = true;
6970
- i += 1;
6971
- continue;
7625
+ underlying = null;
7626
+ router = null;
6972
7627
  }
6973
- if (char === "/" && next === "*") {
6974
- inBlockComment = true;
6975
- i += 1;
6976
- continue;
6977
- }
6978
- out += char;
6979
- }
6980
- return out;
7628
+ };
6981
7629
  }
6982
- function summarizeJson(content) {
7630
+ async function runWithStdoutCapture(fn) {
7631
+ let text2 = "";
7632
+ const release = installStdoutRouter();
6983
7633
  try {
6984
- const parsed = JSON.parse(stripJsonComments2(content));
6985
- if (Array.isArray(parsed)) {
6986
- const sample = parsed[0];
6987
- const sampleKeys = sample && typeof sample === "object" && !Array.isArray(sample) ? Object.keys(sample).slice(0, 10).sort() : [];
6988
- return {
6989
- shape: "array",
6990
- itemCount: parsed.length,
6991
- keys: [],
6992
- sampleKeys
6993
- };
6994
- }
6995
- if (parsed && typeof parsed === "object") {
6996
- const keys = Object.keys(parsed).sort();
6997
- return {
6998
- shape: "object",
6999
- itemCount: keys.length,
7000
- keys: keys.slice(0, 30),
7001
- sampleKeys: []
7002
- };
7003
- }
7004
- return {
7005
- shape: typeof parsed,
7006
- itemCount: null,
7007
- keys: [],
7008
- sampleKeys: []
7009
- };
7010
- } catch {
7011
- return {
7012
- shape: "invalid-json",
7013
- itemCount: null,
7014
- keys: [],
7015
- sampleKeys: []
7016
- };
7017
- }
7018
- }
7019
- function summarizeMarkdown(content) {
7020
- const headings = [];
7021
- const frontmatterKeys = [];
7022
- const lines = content.replace(/^\uFEFF/, "").split("\n");
7023
- let inFrontmatter = false;
7024
- let fence = null;
7025
- let closesFrontmatter = false;
7026
- for (let index = 1; index < lines.length; index++) {
7027
- if (lines[index].trim() === "---") {
7028
- closesFrontmatter = true;
7029
- break;
7030
- }
7031
- }
7032
- for (let index = 0; index < lines.length; index++) {
7033
- const line = lines[index];
7034
- if (index === 0 && line.trim() === "---" && closesFrontmatter) {
7035
- inFrontmatter = true;
7036
- continue;
7037
- }
7038
- if (inFrontmatter) {
7039
- if (line.trim() === "---") {
7040
- inFrontmatter = false;
7041
- continue;
7042
- }
7043
- const match = /^([a-zA-Z0-9_-]+):/.exec(line);
7044
- if (match) frontmatterKeys.push(match[1]);
7045
- continue;
7046
- }
7047
- const trimmed = line.trim();
7048
- const fenceMatch = /^(`{3,}|~{3,})(.*)$/.exec(trimmed);
7049
- if (fenceMatch) {
7050
- const run = fenceMatch[1];
7051
- const rest = fenceMatch[2].trim();
7052
- if (fence === null) {
7053
- fence = { marker: run[0], length: run.length };
7054
- } else if (run[0] === fence.marker && run.length >= fence.length && rest === "") {
7055
- fence = null;
7056
- }
7057
- continue;
7058
- }
7059
- if (fence !== null) continue;
7060
- const headingMatch = /^(#{1,6})\s+(.+)$/.exec(trimmed);
7061
- if (headingMatch) {
7062
- headings.push(`${headingMatch[1]} ${headingMatch[2].trim()}`);
7063
- }
7634
+ const value = await captureScope.run(
7635
+ { write: (chunk) => void (text2 += chunk) },
7636
+ fn
7637
+ );
7638
+ return { value, text: text2 };
7639
+ } finally {
7640
+ release();
7064
7641
  }
7065
- return {
7066
- headings: headings.slice(0, 40),
7067
- frontmatterKeys: Array.from(new Set(frontmatterKeys)).sort()
7068
- };
7069
7642
  }
7070
7643
  function hasCollapsibleBody(node) {
7071
7644
  if (!("body" in node)) return false;
7072
7645
  const body = node.body;
7073
7646
  return body !== void 0 && ts__default.default.isBlock(body);
7074
7647
  }
7075
- function isTsxFileName(fileName) {
7076
- return fileName.toLowerCase().endsWith(".tsx");
7648
+ function scriptKindFor(fileName) {
7649
+ const lower = fileName.toLowerCase();
7650
+ if (lower.endsWith(".tsx")) return ts__default.default.ScriptKind.TSX;
7651
+ if (lower.endsWith(".jsx")) return ts__default.default.ScriptKind.JSX;
7652
+ if (lower.endsWith(".js") || lower.endsWith(".mjs") || lower.endsWith(".cjs")) {
7653
+ return ts__default.default.ScriptKind.JS;
7654
+ }
7655
+ return ts__default.default.ScriptKind.TS;
7077
7656
  }
7078
7657
  function skeletonizeTypeScript(source, fileName = "file.ts") {
7079
- const scriptKind = isTsxFileName(fileName) ? ts__default.default.ScriptKind.TSX : ts__default.default.ScriptKind.TS;
7080
7658
  const sourceFile = ts__default.default.createSourceFile(
7081
7659
  fileName,
7082
7660
  source,
7083
7661
  ts__default.default.ScriptTarget.Latest,
7084
- true,
7085
- scriptKind
7662
+ // `setParentNodes: false`. Nothing here reads `.parent` — the one `getStart` call is given the
7663
+ // source file explicitly, which is the reason that argument exists. Asking for parent pointers
7664
+ // makes the parser run a second full pass over every node in the file to set them, on top of
7665
+ // the summary parse this same file already pays for.
7666
+ false,
7667
+ scriptKindFor(fileName)
7086
7668
  );
7087
7669
  const spans = [];
7088
7670
  const visit = (node) => {
7089
7671
  if ((ts__default.default.isFunctionDeclaration(node) || ts__default.default.isMethodDeclaration(node) || ts__default.default.isConstructorDeclaration(node) || ts__default.default.isGetAccessorDeclaration(node) || ts__default.default.isSetAccessorDeclaration(node) || ts__default.default.isFunctionExpression(node) || ts__default.default.isArrowFunction(node)) && hasCollapsibleBody(node)) {
7090
7672
  const body = node.body;
7091
- const start = body.getStart(sourceFile);
7092
- const end = body.getEnd();
7093
- if (end > start) spans.push({ start, end });
7673
+ if (body.statements.length > 0) {
7674
+ const start = body.getStart(sourceFile);
7675
+ const end = body.getEnd();
7676
+ if (end > start) spans.push({ start, end });
7677
+ }
7094
7678
  }
7095
7679
  ts__default.default.forEachChild(node, visit);
7096
7680
  };
@@ -7102,16 +7686,21 @@ function skeletonizeTypeScript(source, fileName = "file.ts") {
7102
7686
  if (last && span.start < last.end) continue;
7103
7687
  outermost.push(span);
7104
7688
  }
7105
- let text2 = source;
7106
- for (let index = outermost.length - 1; index >= 0; index -= 1) {
7107
- const span = outermost[index];
7108
- text2 = `${text2.slice(0, span.start)}{ /* ... */ }${text2.slice(span.end)}`;
7689
+ const chunks = [];
7690
+ let cursor = 0;
7691
+ for (const span of outermost) {
7692
+ chunks.push(source.slice(cursor, span.start), "{ /* ... */ }");
7693
+ cursor = span.end;
7109
7694
  }
7110
- return { text: text2, collapsed: outermost.length };
7695
+ chunks.push(source.slice(cursor));
7696
+ return { text: chunks.join(""), collapsed: outermost.length };
7111
7697
  }
7112
7698
  function isSkeletonizable(filePath) {
7113
7699
  const lower = filePath.toLowerCase();
7114
- return lower.endsWith(".ts") || lower.endsWith(".tsx") || lower.endsWith(".mts") || lower.endsWith(".cts");
7700
+ if (lower.endsWith(".d.ts") || lower.endsWith(".d.mts") || lower.endsWith(".d.cts")) {
7701
+ return false;
7702
+ }
7703
+ return lower.endsWith(".ts") || lower.endsWith(".tsx") || lower.endsWith(".mts") || lower.endsWith(".cts") || lower.endsWith(".js") || lower.endsWith(".jsx") || lower.endsWith(".mjs") || lower.endsWith(".cjs");
7115
7704
  }
7116
7705
 
7117
7706
  // src/generator/audit.ts
@@ -7379,23 +7968,55 @@ function truncateWithBudgetMarker(content, maxBytes, budget, originalLines) {
7379
7968
  };
7380
7969
  }
7381
7970
  function partitionFiles(files, maxPartBytes, contentFingerprint) {
7382
- if (files.length === 0) return [];
7383
- const budget = Math.max(MIN_SECTION_BUDGET_BYTES + HEADER_RESERVE_BYTES, maxPartBytes);
7384
- const sectionBudget = budget - HEADER_RESERVE_BYTES;
7385
- const prepared = files.map((file) => prepareSection(file, sectionBudget));
7386
- let groups = greedyGroups(prepared, budget);
7971
+ return partitionFilesForBuckets([{ files, budgetBytes: maxPartBytes }], contentFingerprint);
7972
+ }
7973
+ function partitionFilesForBuckets(buckets, contentFingerprint) {
7974
+ const groups = [];
7975
+ for (const bucket of buckets) {
7976
+ if (bucket.files.length === 0) continue;
7977
+ const budget = Math.max(
7978
+ MIN_SECTION_BUDGET_BYTES + HEADER_RESERVE_BYTES,
7979
+ bucket.budgetBytes
7980
+ );
7981
+ const sectionBudget = budget - HEADER_RESERVE_BYTES;
7982
+ const prepared = bucket.files.map((file) => prepareSection(file, sectionBudget, budget));
7983
+ for (const sections of greedyGroups(prepared, budget)) groups.push({ sections, budget });
7984
+ }
7985
+ if (groups.length === 0) return [];
7986
+ const measurements = /* @__PURE__ */ new Map();
7987
+ const widthOf = (total) => Math.max(3, String(total).length);
7988
+ const measure = (group, index, total) => {
7989
+ const cached = measurements.get(group);
7990
+ const width = widthOf(total);
7991
+ if (cached !== void 0 && cached.index === index && cached.width === width) {
7992
+ return cached.size;
7993
+ }
7994
+ const { content } = assembleGroup(group, index, total, contentFingerprint);
7995
+ const size2 = Buffer.byteLength(content, "utf8");
7996
+ measurements.set(group, { index, width, size: size2 });
7997
+ return size2;
7998
+ };
7387
7999
  for (let pass = 0; pass < MAX_SPLIT_PASSES; pass++) {
7388
- const rendered = renderGroups(groups, budget, contentFingerprint);
7389
- const oversized = rendered.findIndex((part) => part.metadata.byteSize > budget);
7390
- if (oversized === -1) return rendered;
8000
+ const total = groups.length;
8001
+ let oversized = -1;
8002
+ for (let index = 0; index < total; index += 1) {
8003
+ const group2 = groups[index];
8004
+ if (measure(group2, index, total) > group2.budget) {
8005
+ oversized = index;
8006
+ break;
8007
+ }
8008
+ }
8009
+ if (oversized === -1) return renderGroups(groups, contentFingerprint);
7391
8010
  const group = groups[oversized];
7392
- if (group.length > 1) {
7393
- const moved = group.pop();
7394
- groups.splice(oversized + 1, 0, [moved]);
8011
+ if (group.sections.length > 1) {
8012
+ const moved = group.sections.pop();
8013
+ groups.splice(oversized + 1, 0, { sections: [moved], budget: group.budget });
8014
+ measurements.delete(group);
7395
8015
  continue;
7396
8016
  }
7397
- const [section] = group;
7398
- const overflow = rendered[oversized].metadata.byteSize - budget;
8017
+ const [section] = group.sections;
8018
+ if (section === void 0) return renderGroups(groups, contentFingerprint);
8019
+ const overflow = measure(group, oversized, total) - group.budget;
7399
8020
  const currentContent = section.file.content ?? "";
7400
8021
  const shrinkTo = Math.max(
7401
8022
  0,
@@ -7404,26 +8025,33 @@ function partitionFiles(files, maxPartBytes, contentFingerprint) {
7404
8025
  const shrunk = truncateWithBudgetMarker(
7405
8026
  currentContent,
7406
8027
  shrinkTo,
7407
- budget,
8028
+ group.budget,
7408
8029
  section.file.originalLines
7409
8030
  );
7410
8031
  if (shrunk.isTruncated) {
7411
8032
  applyTruncatedContent(section.file, shrunk.content);
7412
8033
  section.text = renderFileSection(section.file);
7413
8034
  section.byteSize = Buffer.byteLength(section.text, "utf8");
8035
+ measurements.delete(group);
7414
8036
  continue;
7415
8037
  }
8038
+ const rendered = renderGroups(groups, contentFingerprint);
7416
8039
  const marker2 = TRUNCATION_MARKER;
7417
- assertBudgetHoldsMarker(budget);
8040
+ assertBudgetHoldsMarker(group.budget);
7418
8041
  const target = Math.max(
7419
8042
  0,
7420
- budget - Buffer.byteLength(marker2, "utf8") - TOKEN_LINE_SLACK
8043
+ group.budget - Buffer.byteLength(marker2, "utf8") - TOKEN_LINE_SLACK
7421
8044
  );
7422
8045
  const clipped = truncateToBytes(rendered[oversized].markdown, target);
7423
- rendered[oversized] = rehashPart(rendered[oversized], clipped.content + marker2);
8046
+ rendered[oversized] = rehashPart(
8047
+ rendered[oversized],
8048
+ clipped.content + marker2
8049
+ );
7424
8050
  return rendered;
7425
8051
  }
7426
- return enforceBudget(renderGroups(groups, budget, contentFingerprint), budget);
8052
+ return renderGroups(groups, contentFingerprint).flatMap(
8053
+ (part) => enforceBudget([part], part.metadata.budgetBytes)
8054
+ );
7427
8055
  }
7428
8056
  var TRUNCATION_MARKER = "\n... [part truncated: cannot fit budget] ...\n";
7429
8057
  function assertBudgetHoldsMarker(budget) {
@@ -7446,69 +8074,7 @@ function enforceBudget(parts, budget) {
7446
8074
  return rehashPart(part, clipped.content + TRUNCATION_MARKER);
7447
8075
  });
7448
8076
  }
7449
- function renumberParts(parts, contentFingerprint) {
7450
- const total = parts.length;
7451
- if (total === 0) return [];
7452
- const zeroPad = (index) => String(index).padStart(Math.max(3, String(total).length), "0");
7453
- const nameFor = (position) => `part-${zeroPad(position)}.md`;
7454
- const marker2 = "## Contents\n";
7455
- const renumbered = parts.map((part, index) => {
7456
- const markerIndex = part.markdown.indexOf(marker2);
7457
- const body = markerIndex === -1 ? "" : part.markdown.slice(markerIndex + marker2.length);
7458
- const included = part.metadata.includedFiles;
7459
- if (markerIndex === -1) {
7460
- throw new Error(`${part.filename} has no "## Contents" section to re-number.`);
7461
- }
7462
- const layerCounts = {};
7463
- const kindCounts = {};
7464
- for (const file of included) {
7465
- layerCounts[file.layer] = (layerCounts[file.layer] || 0) + 1;
7466
- kindCounts[file.kind] = (kindCounts[file.kind] || 0) + 1;
7467
- }
7468
- const pathLines = included.map((file) => displayPath(file.relativePath));
7469
- const listFence = fenceForText(pathLines.join("\n"), 3);
7470
- const header = [
7471
- `# Codebase Snapshot Part ${zeroPad(index + 1)} of ${zeroPad(total)}`,
7472
- "",
7473
- `- Previous: ${index === 0 ? "none" : nameFor(index)}`,
7474
- `- Next: ${index === total - 1 ? "none" : nameFor(index + 2)}`,
7475
- `- Files: ${included.length}`,
7476
- `- Content Fingerprint: ${contentFingerprint || "none"}`,
7477
- `- Layers: ${topEntries(layerCounts, 6) || "none"}`,
7478
- `- Kinds: ${topEntries(kindCounts, 8) || "none"}`,
7479
- "",
7480
- UNTRUSTED_CONTENT_NOTICE,
7481
- "",
7482
- "## Files",
7483
- "",
7484
- `${listFence}text`,
7485
- ...pathLines,
7486
- listFence,
7487
- "",
7488
- "## Contents",
7489
- ""
7490
- ].join("\n");
7491
- const assembled = (header + body).replace(/\r\n/g, "\n");
7492
- const estimatedTokens = estimateTokens(assembled);
7493
- const markdown = insertTokenLine(assembled, estimatedTokens);
7494
- const metadata = {
7495
- ...part.metadata,
7496
- index: index + 1,
7497
- filename: nameFor(index + 1),
7498
- byteSize: Buffer.byteLength(markdown, "utf8"),
7499
- estimatedTokens,
7500
- sha256: crypto3__namespace.createHash("sha256").update(markdown).digest("hex"),
7501
- lines: countLines(markdown),
7502
- fileCount: included.length,
7503
- layersCovered: Object.keys(layerCounts).sort()
7504
- };
7505
- return { filename: metadata.filename, markdown, metadata };
7506
- });
7507
- return renumbered.map(
7508
- (part) => enforceBudget([part], part.metadata.budgetBytes)[0] ?? part
7509
- );
7510
- }
7511
- var SECTION_TRUNCATION_NOTICE = "\n... [section truncated: metadata alone exceeds the part budget] ...\n";
8077
+ var SECTION_TRUNCATION_NOTICE = "... [section truncated: the fixed metadata and a code fence did not fit the part budget] ...";
7512
8078
  var METADATA_VALUE_MAX = 200;
7513
8079
  var DISPLAY_PATH_MAX = 300;
7514
8080
  function capValue(value, max) {
@@ -7521,7 +8087,7 @@ var displayPath = (value) => capValue(escapeControls(value), DISPLAY_PATH_MAX);
7521
8087
  function topEntries(counts, limit) {
7522
8088
  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(", ");
7523
8089
  }
7524
- function prepareSection(file, sectionBudget) {
8090
+ function prepareSection(file, sectionBudget, partBudget) {
7525
8091
  let text2 = renderFileSection(file);
7526
8092
  let byteSize = Buffer.byteLength(text2, "utf8");
7527
8093
  if (byteSize <= sectionBudget) return { file, text: text2, byteSize };
@@ -7533,7 +8099,7 @@ function prepareSection(file, sectionBudget) {
7533
8099
  const truncated = truncateWithBudgetMarker(
7534
8100
  content,
7535
8101
  allowed,
7536
- sectionBudget,
8102
+ partBudget,
7537
8103
  file.originalLines
7538
8104
  );
7539
8105
  if (!truncated.isTruncated) return;
@@ -7550,13 +8116,57 @@ function prepareSection(file, sectionBudget) {
7550
8116
  shrinkBody();
7551
8117
  }
7552
8118
  if (byteSize > sectionBudget) {
7553
- const target = sectionBudget - Buffer.byteLength(SECTION_TRUNCATION_NOTICE, "utf8");
7554
- const truncated = truncateToBytes(text2, Math.max(0, target));
7555
- text2 = truncated.content + SECTION_TRUNCATION_NOTICE;
8119
+ applyTruncatedContent(file, SECTION_TRUNCATION_NOTICE);
8120
+ file.summary = void 0;
8121
+ file.summaryOmitted = true;
8122
+ text2 = renderFileSection(file);
7556
8123
  byteSize = Buffer.byteLength(text2, "utf8");
8124
+ if (byteSize > sectionBudget) {
8125
+ text2 = truncateRenderedSection(text2, sectionBudget, fenceForContent(file.content ?? ""));
8126
+ byteSize = Buffer.byteLength(text2, "utf8");
8127
+ }
7557
8128
  }
7558
8129
  return { file, text: text2, byteSize };
7559
8130
  }
8131
+ function truncateRenderedSection(text2, sectionBudget, fence) {
8132
+ const closing = `
8133
+ ${SECTION_TRUNCATION_NOTICE}
8134
+ ${fence}
8135
+ `;
8136
+ const bodyRoom = sectionBudget - Buffer.byteLength(closing, "utf8");
8137
+ if (bodyRoom > 0) {
8138
+ const cut2 = truncateToBytes(text2, bodyRoom).content;
8139
+ const lastBreak2 = cut2.lastIndexOf("\n");
8140
+ const kept = lastBreak2 >= 0 ? cut2.slice(0, lastBreak2 + 1) : "";
8141
+ if (fenceIsOpen(kept, fence)) return `${kept}${closing}`;
8142
+ }
8143
+ const probe = text2.slice(0, 512);
8144
+ const emptyFence = fenceForText(probe.slice(0, Math.max(0, probe.lastIndexOf("\n") + 1)), 4);
8145
+ const block = `
8146
+ ${emptyFence}
8147
+ ${SECTION_TRUNCATION_NOTICE}
8148
+ ${emptyFence}
8149
+ `;
8150
+ const prefixRoom = sectionBudget - Buffer.byteLength(block, "utf8");
8151
+ const cut = prefixRoom > 0 ? truncateToBytes(text2, prefixRoom).content : "";
8152
+ const lastBreak = cut.lastIndexOf("\n");
8153
+ const prefix = lastBreak >= 0 ? cut.slice(0, lastBreak + 1) : "";
8154
+ return `${dropTrailingOpenFence(prefix, fence)}${block}`;
8155
+ }
8156
+ function dropTrailingOpenFence(text2, fence) {
8157
+ if (!fenceIsOpen(text2, fence)) return text2;
8158
+ const lines = text2.split("\n");
8159
+ const opening = lines.findIndex((line) => line.startsWith(fence));
8160
+ if (opening < 0) return text2;
8161
+ return lines.slice(0, opening).join("\n") + (opening > 0 ? "\n" : "");
8162
+ }
8163
+ function fenceIsOpen(text2, fence) {
8164
+ let open = false;
8165
+ for (const line of text2.split("\n")) {
8166
+ if (line.startsWith(fence)) open = !open;
8167
+ }
8168
+ return open;
8169
+ }
7560
8170
  function applyTruncatedContent(file, content) {
7561
8171
  file.content = content;
7562
8172
  file.isPreviewTruncated = true;
@@ -7604,52 +8214,64 @@ function greedyGroups(sections, budget) {
7604
8214
  if (current.length > 0) groups.push(current);
7605
8215
  return groups;
7606
8216
  }
7607
- function renderGroups(groups, budget, contentFingerprint) {
8217
+ function assembleGroup(group, index, total, contentFingerprint) {
8218
+ const width = Math.max(3, String(total).length);
8219
+ const zeroPad = (value) => String(value).padStart(width, "0");
8220
+ const filename = `part-${zeroPad(index + 1)}.md`;
8221
+ const prev = index === 0 ? "none" : `part-${zeroPad(index)}.md`;
8222
+ const next = index === total - 1 ? "none" : `part-${zeroPad(index + 2)}.md`;
8223
+ for (const section of group.sections) {
8224
+ section.file.part = filename;
8225
+ }
8226
+ const layerCounts = {};
8227
+ const kindCounts = {};
8228
+ for (const section of group.sections) {
8229
+ layerCounts[section.file.layer] = (layerCounts[section.file.layer] || 0) + 1;
8230
+ kindCounts[section.file.kind] = (kindCounts[section.file.kind] || 0) + 1;
8231
+ }
8232
+ const pathLines = group.sections.map((s) => displayPath(s.file.relativePath));
8233
+ const listFence = fenceForText(pathLines.join("\n"), 3);
8234
+ const header = [
8235
+ `# Codebase Snapshot Part ${zeroPad(index + 1)} of ${zeroPad(total)}`,
8236
+ "",
8237
+ `- Previous: ${prev}`,
8238
+ `- Next: ${next}`,
8239
+ `- Files: ${group.sections.length}`,
8240
+ `- Content Fingerprint: ${contentFingerprint || "none"}`,
8241
+ `- Layers: ${topEntries(layerCounts, 6) || "none"}`,
8242
+ `- Kinds: ${topEntries(kindCounts, 8) || "none"}`,
8243
+ "",
8244
+ UNTRUSTED_CONTENT_NOTICE,
8245
+ "",
8246
+ "## Files",
8247
+ "",
8248
+ `${listFence}text`,
8249
+ ...pathLines,
8250
+ listFence,
8251
+ "",
8252
+ "## Contents",
8253
+ ""
8254
+ ].join("\n");
8255
+ const assembled = (header + group.sections.map((s) => s.text).join("")).replace(
8256
+ /\r\n|\r/g,
8257
+ "\n"
8258
+ );
8259
+ const estimatedTokens = estimateTokens(assembled);
8260
+ return { filename, content: insertTokenLine(assembled, estimatedTokens), estimatedTokens };
8261
+ }
8262
+ function renderGroups(groups, contentFingerprint) {
7608
8263
  const total = groups.length;
7609
- const zeroPad = (index) => String(index).padStart(Math.max(3, String(total).length), "0");
7610
8264
  return groups.map((group, index) => {
7611
- const filename = `part-${zeroPad(index + 1)}.md`;
7612
- const prev = index === 0 ? "none" : `part-${zeroPad(index)}.md`;
7613
- const next = index === total - 1 ? "none" : `part-${zeroPad(index + 2)}.md`;
7614
- for (const section of group) {
7615
- section.file.part = filename;
7616
- }
7617
- const layersCovered = Array.from(new Set(group.map((s) => s.file.layer))).sort();
7618
- const layerCounts = {};
7619
- const kindCounts = {};
7620
- for (const section of group) {
7621
- layerCounts[section.file.layer] = (layerCounts[section.file.layer] || 0) + 1;
7622
- kindCounts[section.file.kind] = (kindCounts[section.file.kind] || 0) + 1;
7623
- }
7624
- const pathLines = group.map((s) => displayPath(s.file.relativePath));
7625
- const listFence = fenceForText(pathLines.join("\n"), 3);
7626
- const header = [
7627
- `# Codebase Snapshot Part ${zeroPad(index + 1)} of ${zeroPad(total)}`,
7628
- "",
7629
- `- Previous: ${prev}`,
7630
- `- Next: ${next}`,
7631
- `- Files: ${group.length}`,
7632
- `- Content Fingerprint: ${contentFingerprint || "none"}`,
7633
- `- Layers: ${topEntries(layerCounts, 6) || "none"}`,
7634
- `- Kinds: ${topEntries(kindCounts, 8) || "none"}`,
7635
- "",
7636
- UNTRUSTED_CONTENT_NOTICE,
7637
- "",
7638
- "## Files",
7639
- "",
7640
- `${listFence}text`,
7641
- ...pathLines,
7642
- listFence,
7643
- "",
7644
- "## Contents",
7645
- ""
7646
- ].join("\n");
7647
- const assembled = (header + group.map((s) => s.text).join("")).replace(/\r\n/g, "\n");
7648
- const estimatedTokens = estimateTokens(assembled);
7649
- const content = insertTokenLine(assembled, estimatedTokens);
8265
+ const { filename, content, estimatedTokens } = assembleGroup(
8266
+ group,
8267
+ index,
8268
+ total,
8269
+ contentFingerprint
8270
+ );
7650
8271
  const byteSize = Buffer.byteLength(content, "utf8");
7651
8272
  const sha256 = crypto3__namespace.createHash("sha256").update(content).digest("hex");
7652
- const includedFiles = group.map(({ file }) => ({
8273
+ const layersCovered = Array.from(new Set(group.sections.map((s) => s.file.layer))).sort();
8274
+ const includedFiles = group.sections.map(({ file }) => ({
7653
8275
  relativePath: file.relativePath,
7654
8276
  sourceBytes: file.sizeBytes,
7655
8277
  includedBytes: file.includedBytes,
@@ -7662,10 +8284,10 @@ function renderGroups(groups, budget, contentFingerprint) {
7662
8284
  filename,
7663
8285
  byteSize,
7664
8286
  estimatedTokens,
7665
- budgetBytes: budget,
8287
+ budgetBytes: group.budget,
7666
8288
  sha256,
7667
8289
  lines: countLines(content),
7668
- fileCount: group.length,
8290
+ fileCount: group.sections.length,
7669
8291
  layersCovered,
7670
8292
  includedFiles
7671
8293
  };
@@ -7673,7 +8295,7 @@ function renderGroups(groups, budget, contentFingerprint) {
7673
8295
  });
7674
8296
  }
7675
8297
  function emittedBody(content) {
7676
- const normalised = content.replace(/\r\n/g, "\n");
8298
+ const normalised = content.replace(/\r\n|\r/g, "\n");
7677
8299
  return normalised.endsWith("\n") ? normalised.slice(0, -1) : normalised;
7678
8300
  }
7679
8301
  function compactMetadata(file) {
@@ -7741,7 +8363,7 @@ function generateMonolithJson(manifest, filesWithContent) {
7741
8363
  }
7742
8364
  function generateMonolithMarkdown(manifest, filesWithContent) {
7743
8365
  const sections = filesWithContent.map((file) => {
7744
- const content = (file.content ?? "").replace(/\r\n/g, "\n");
8366
+ const content = (file.content ?? "").replace(/\r\n|\r/g, "\n");
7745
8367
  const fence = fenceForContent(content);
7746
8368
  return [
7747
8369
  `## File: ${escapeControls(file.relativePath)}`,
@@ -8001,22 +8623,28 @@ function updateCommand(kind) {
8001
8623
  if (kind === "local") return "npm install codebase-snapshot@latest";
8002
8624
  return "npm install -g codebase-snapshot";
8003
8625
  }
8004
- function versionParts(value) {
8005
- const core = value.trim().replace(/^v/i, "").split("-")[0];
8006
- return core.split(".").map((part) => {
8626
+ function parseSemver(value) {
8627
+ const cleaned = value.trim().replace(/^v/i, "").split("+")[0] ?? "";
8628
+ const dash = cleaned.indexOf("-");
8629
+ const corePart = dash === -1 ? cleaned : cleaned.slice(0, dash);
8630
+ const prerelease = dash === -1 ? null : cleaned.slice(dash + 1);
8631
+ const core = corePart.split(".").map((part) => {
8007
8632
  const parsed = Number(part);
8008
8633
  return Number.isFinite(parsed) ? parsed : 0;
8009
8634
  });
8635
+ return { core, prerelease };
8010
8636
  }
8011
8637
  function isNewer(candidate, current) {
8012
- const left = versionParts(candidate);
8013
- const right = versionParts(current);
8014
- const length = Math.max(left.length, right.length);
8638
+ const left = parseSemver(candidate);
8639
+ const right = parseSemver(current);
8640
+ if (left.prerelease !== null && right.prerelease === null) return false;
8641
+ const length = Math.max(left.core.length, right.core.length);
8015
8642
  for (let index = 0; index < length; index += 1) {
8016
- const a = left[index] ?? 0;
8017
- const b = right[index] ?? 0;
8643
+ const a = left.core[index] ?? 0;
8644
+ const b = right.core[index] ?? 0;
8018
8645
  if (a !== b) return a > b;
8019
8646
  }
8647
+ if (left.prerelease === null && right.prerelease !== null) return true;
8020
8648
  return false;
8021
8649
  }
8022
8650
  function cacheDirectory(env = process.env, platform = process.platform) {
@@ -8084,14 +8712,22 @@ function writeCache(file, entry) {
8084
8712
  }
8085
8713
  }
8086
8714
  function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOUT_MS) {
8087
- return new Promise((resolve9) => {
8715
+ return new Promise((resolve10) => {
8088
8716
  let settled = false;
8717
+ let request = null;
8089
8718
  const finish = (value) => {
8090
8719
  if (settled) return;
8091
8720
  settled = true;
8092
- resolve9(value);
8721
+ clearTimeout(deadline);
8722
+ resolve10(value);
8093
8723
  };
8094
- const request = https__namespace.get(
8724
+ const deadline = setTimeout(() => {
8725
+ request?.destroy();
8726
+ finish(null);
8727
+ }, timeoutMs);
8728
+ deadline.unref();
8729
+ const transport = url.startsWith("http:") ? http__namespace : https__namespace;
8730
+ request = transport.get(
8095
8731
  url,
8096
8732
  {
8097
8733
  headers: {
@@ -8110,7 +8746,7 @@ function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOU
8110
8746
  response.on("data", (chunk) => {
8111
8747
  body += chunk;
8112
8748
  if (body.length > 64 * 1024) {
8113
- request.destroy();
8749
+ request?.destroy();
8114
8750
  finish(null);
8115
8751
  }
8116
8752
  });
@@ -8125,10 +8761,6 @@ function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOU
8125
8761
  }
8126
8762
  );
8127
8763
  request.on("error", () => finish(null));
8128
- request.setTimeout(timeoutMs, () => {
8129
- request.destroy();
8130
- finish(null);
8131
- });
8132
8764
  });
8133
8765
  }
8134
8766
  async function checkForUpdate(options) {
@@ -8287,7 +8919,10 @@ const { parentPort, workerData } = require("node:worker_threads");
8287
8919
  parentPort.postMessage({ ok: false, message: loaded.errors.join("; ") });
8288
8920
  return;
8289
8921
  }
8290
- const config = mod.resolveConfig(loaded.config, workerData.cliOptions, workerData.cwd);
8922
+ // \`hooks: {}\` is a value, not an absence: the config is applied with the hook list emptied,
8923
+ // so the run is the documented MCP run rather than the CLI run with one setting removed.
8924
+ const base = loaded.config ? { ...loaded.config, hooks: {} } : null;
8925
+ const config = mod.resolveConfig(base, workerData.cliOptions, workerData.cwd);
8291
8926
  const manifest = mod.generateSnapshot(config);
8292
8927
  parentPort.postMessage({
8293
8928
  ok: true,
@@ -8310,14 +8945,15 @@ const { parentPort, workerData } = require("node:worker_threads");
8310
8945
  })();
8311
8946
  `;
8312
8947
  function generateInWorker(cwd, cliOptions) {
8313
- return new Promise((resolve9) => {
8948
+ return new Promise((resolve10) => {
8314
8949
  let settled = false;
8950
+ let worker = null;
8315
8951
  const finish = (result) => {
8316
8952
  if (settled) return;
8317
8953
  settled = true;
8318
- resolve9(result);
8954
+ if (worker !== null) void worker.terminate();
8955
+ resolve10(result);
8319
8956
  };
8320
- let worker;
8321
8957
  const isCjs = typeof __dirname !== "undefined";
8322
8958
  const directory = isCjs ? __dirname : path16__namespace.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href))));
8323
8959
  try {
@@ -8350,7 +8986,100 @@ function generateInWorker(cwd, cliOptions) {
8350
8986
 
8351
8987
  // src/index.ts
8352
8988
  var SCHEMA_VERSION = "3.0.0";
8353
- var SUMMARY_MAX_SOURCE_BYTES = 2 * 1024 * 1024;
8989
+ var SUMMARY_MAX_SOURCE_BYTES2 = SUMMARY_MAX_SOURCE_BYTES;
8990
+ var FILE_DERIVATIONS = /* @__PURE__ */ new Map();
8991
+ var FILE_DERIVATION_LIMIT_BYTES = 64 * 1024 * 1024;
8992
+ var fileDerivationBytes = 0;
8993
+ function takeDerivation(path22, hash, settings) {
8994
+ const cached = FILE_DERIVATIONS.get(path22);
8995
+ if (cached === void 0 || cached.hash !== hash || cached.settings !== settings) return void 0;
8996
+ return cached;
8997
+ }
8998
+ function rememberDerivation(path22, hash, settings, derivation) {
8999
+ const bodyBytes = derivation.finalContent === derivation.redacted ? derivation.redacted.length : derivation.redacted.length + derivation.finalContent.length;
9000
+ const bytes = bodyBytes * 2 + 512;
9001
+ if (bytes > FILE_DERIVATION_LIMIT_BYTES / 4) return;
9002
+ while (fileDerivationBytes + bytes > FILE_DERIVATION_LIMIT_BYTES) {
9003
+ const oldest = FILE_DERIVATIONS.keys().next();
9004
+ if (oldest.done === true) break;
9005
+ const evicted = FILE_DERIVATIONS.get(oldest.value);
9006
+ FILE_DERIVATIONS.delete(oldest.value);
9007
+ if (evicted !== void 0) fileDerivationBytes -= evicted.bytes;
9008
+ }
9009
+ FILE_DERIVATIONS.set(path22, { ...derivation, hash, settings, bytes });
9010
+ fileDerivationBytes += bytes;
9011
+ }
9012
+ function derivationSettings(config) {
9013
+ const rules = config.secretRules.map(
9014
+ (rule) => `${rule.rule}\0${rule.pattern.source}\0${rule.pattern.flags}\0${rule.valueGroup ?? ""}`
9015
+ ).join("");
9016
+ return `${GENERATOR_VERSION}${configDigest(config)}${sha256Hex2(rules)}`;
9017
+ }
9018
+ function deriveFile(relativePath, rawContent, sizeBytes, config) {
9019
+ const lineCount = countLines(rawContent);
9020
+ const { redacted, findings } = scanAndRedactSecrets(rawContent, config.secretRules, relativePath);
9021
+ const isLarge = sizeBytes > config.largeFileBytes;
9022
+ let finalContent = redacted;
9023
+ let isPreviewTruncated = false;
9024
+ let includedLines = lineCount;
9025
+ let inclusionMode = "full";
9026
+ if (config.skeleton === true && isSkeletonizable(relativePath)) {
9027
+ const skeleton = skeletonizeTypeScript(redacted, relativePath);
9028
+ if (skeleton.collapsed > 0) {
9029
+ finalContent = skeleton.text;
9030
+ inclusionMode = "signatures";
9031
+ includedLines = countLines(skeleton.text);
9032
+ }
9033
+ }
9034
+ if (isLarge && inclusionMode !== "signatures") {
9035
+ const preview = truncatePreview(redacted, config.previewHeadLines, config.previewTailLines);
9036
+ finalContent = preview.content;
9037
+ isPreviewTruncated = preview.isTruncated;
9038
+ includedLines = preview.includedLines;
9039
+ inclusionMode = isPreviewTruncated ? "preview" : "full";
9040
+ }
9041
+ let summary;
9042
+ let summaryQuality;
9043
+ let summarySkip = null;
9044
+ let summaryWarning = null;
9045
+ let dependentImports = null;
9046
+ if (Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES2) {
9047
+ summarySkip = "oversize";
9048
+ dependentImports = [];
9049
+ } else if (isPreviewTruncated && hasStructuralSummary(relativePath)) {
9050
+ summarySkip = "preview";
9051
+ dependentImports = importsOfText(relativePath, rawContent);
9052
+ } else {
9053
+ try {
9054
+ const outcome = summarizeFile(relativePath, rawContent);
9055
+ summary = outcome?.summary ? maskSummaryStrings(outcome.summary, config.secretRules) : void 0;
9056
+ summaryQuality = outcome?.quality;
9057
+ if (isSourceSummary(summary) && summary.parseErrors) {
9058
+ summaryWarning = `Parse errors in ${maskPathText(relativePath, config.secretRules)} (${summary.parseErrors}); its summary is incomplete.`;
9059
+ }
9060
+ } catch (err) {
9061
+ summaryWarning = `Summary skipped for ${maskPathText(relativePath, config.secretRules)}: ${err.message}`.replace(
9062
+ /\s+/g,
9063
+ " "
9064
+ );
9065
+ }
9066
+ }
9067
+ return {
9068
+ redacted,
9069
+ findings,
9070
+ lineCount,
9071
+ finalContent,
9072
+ inclusionMode,
9073
+ isPreviewTruncated,
9074
+ includedLines,
9075
+ isLarge,
9076
+ summary,
9077
+ summaryQuality,
9078
+ summarySkip,
9079
+ summaryWarning,
9080
+ dependentImports
9081
+ };
9082
+ }
8354
9083
  function sha256Hex2(input) {
8355
9084
  return crypto3__namespace.createHash("sha256").update(input).digest("hex");
8356
9085
  }
@@ -8539,6 +9268,7 @@ function isProcessAlive(pid) {
8539
9268
  var OWNERSHIP_MARKER = ".codebase-snapshot";
8540
9269
  var SUPPORTED_MARKER_SCHEMAS = /* @__PURE__ */ new Set([SCHEMA_VERSION]);
8541
9270
  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;
9271
+ var SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/;
8542
9272
  function listEntries(dir) {
8543
9273
  const entries = [];
8544
9274
  const walk = (absolute, prefix) => {
@@ -8557,7 +9287,32 @@ function listEntries(dir) {
8557
9287
  walk(dir, "");
8558
9288
  return entries.sort();
8559
9289
  }
9290
+ function markerInventory(dir) {
9291
+ const entries = listEntries(dir);
9292
+ const files = [];
9293
+ for (const entry of entries) {
9294
+ if (entry === OWNERSHIP_MARKER) continue;
9295
+ if (IGNORABLE_ENTRIES.has(entry.slice(entry.lastIndexOf("/") + 1))) continue;
9296
+ const full = path16__namespace.join(dir, ...entry.split("/"));
9297
+ let stats;
9298
+ try {
9299
+ stats = fs14__namespace.lstatSync(full);
9300
+ } catch {
9301
+ continue;
9302
+ }
9303
+ if (!stats.isFile()) continue;
9304
+ let digest;
9305
+ try {
9306
+ digest = sha256Hex2(fs14__namespace.readFileSync(full));
9307
+ } catch {
9308
+ continue;
9309
+ }
9310
+ files.push({ path: entry, bytes: stats.size, sha256: digest });
9311
+ }
9312
+ return { entries, files };
9313
+ }
8560
9314
  function markerPayload(dir, state, id, createdAt) {
9315
+ const { entries, files } = markerInventory(dir);
8561
9316
  const marker2 = {
8562
9317
  generator: GENERATOR_NAME,
8563
9318
  version: GENERATOR_VERSION,
@@ -8566,7 +9321,8 @@ function markerPayload(dir, state, id, createdAt) {
8566
9321
  state,
8567
9322
  id,
8568
9323
  pid: process.pid,
8569
- entries: listEntries(dir)
9324
+ entries,
9325
+ files
8570
9326
  };
8571
9327
  const manifestPath = path16__namespace.join(dir, "manifest.json");
8572
9328
  if (fs14__namespace.existsSync(manifestPath)) {
@@ -8626,6 +9382,33 @@ function readOwnershipMarker(dir) {
8626
9382
  if (candidate.state !== "staging" && candidate.state !== "complete") {
8627
9383
  return { marker: null, problem: "its .codebase-snapshot marker records no run state" };
8628
9384
  }
9385
+ const rawFiles = candidate.files;
9386
+ let files;
9387
+ if (rawFiles !== void 0) {
9388
+ if (!Array.isArray(rawFiles)) {
9389
+ return {
9390
+ marker: null,
9391
+ problem: "its .codebase-snapshot marker's file inventory is not an array"
9392
+ };
9393
+ }
9394
+ files = [];
9395
+ for (const item of rawFiles) {
9396
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
9397
+ return {
9398
+ marker: null,
9399
+ problem: "its .codebase-snapshot marker's file inventory holds an entry that is not an object"
9400
+ };
9401
+ }
9402
+ const record = item;
9403
+ 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)) {
9404
+ return {
9405
+ marker: null,
9406
+ problem: "its .codebase-snapshot marker's file inventory holds an entry this build cannot read"
9407
+ };
9408
+ }
9409
+ files.push({ path: record.path, bytes: record.bytes, sha256: record.sha256 });
9410
+ }
9411
+ }
8629
9412
  return {
8630
9413
  marker: {
8631
9414
  generator: GENERATOR_NAME,
@@ -8636,7 +9419,8 @@ function readOwnershipMarker(dir) {
8636
9419
  id: candidate.id,
8637
9420
  pid: typeof candidate.pid === "number" ? candidate.pid : void 0,
8638
9421
  manifestSha256: typeof candidate.manifestSha256 === "string" ? candidate.manifestSha256 : void 0,
8639
- entries: Array.isArray(candidate.entries) && candidate.entries.every((entry) => typeof entry === "string") ? candidate.entries : void 0
9422
+ entries: Array.isArray(candidate.entries) && candidate.entries.every((entry) => typeof entry === "string") ? candidate.entries : void 0,
9423
+ files
8640
9424
  },
8641
9425
  problem: null
8642
9426
  };
@@ -8651,6 +9435,59 @@ function describeManifestProblem(value) {
8651
9435
  if (!Array.isArray(candidate.files)) return "has no files array";
8652
9436
  return null;
8653
9437
  }
9438
+ function verifyMarkerInventory(dir, entries, files) {
9439
+ const diskEntries = new Set(entries);
9440
+ const recorded = /* @__PURE__ */ new Map();
9441
+ for (const record of files) {
9442
+ if (recorded.has(record.path)) {
9443
+ return `its .codebase-snapshot inventory records ${record.path} twice`;
9444
+ }
9445
+ if (!diskEntries.has(record.path)) {
9446
+ return `its .codebase-snapshot inventory records ${record.path}, which is missing from the directory`;
9447
+ }
9448
+ recorded.set(record.path, record);
9449
+ }
9450
+ for (const entry of entries) {
9451
+ if (entry === OWNERSHIP_MARKER) continue;
9452
+ if (IGNORABLE_ENTRIES.has(entry.slice(entry.lastIndexOf("/") + 1))) continue;
9453
+ const full = path16__namespace.join(dir, ...entry.split("/"));
9454
+ let stats;
9455
+ try {
9456
+ stats = fs14__namespace.lstatSync(full);
9457
+ } catch {
9458
+ return `its .codebase-snapshot inventory lists ${entry}, which cannot be read`;
9459
+ }
9460
+ if (stats.isDirectory()) {
9461
+ if (recorded.has(entry)) {
9462
+ return `its .codebase-snapshot inventory records the directory ${entry} as a file`;
9463
+ }
9464
+ continue;
9465
+ }
9466
+ if (!stats.isFile()) {
9467
+ if (recorded.has(entry)) {
9468
+ return `its .codebase-snapshot inventory records ${entry} as a regular file, but it is not one`;
9469
+ }
9470
+ continue;
9471
+ }
9472
+ const record = recorded.get(entry);
9473
+ if (record === void 0) {
9474
+ return `its .codebase-snapshot inventory does not record the file ${entry}`;
9475
+ }
9476
+ if (record.bytes !== stats.size) {
9477
+ return `its .codebase-snapshot inventory records ${entry} as ${record.bytes} B, but it is ${stats.size} B`;
9478
+ }
9479
+ let digest;
9480
+ try {
9481
+ digest = sha256Hex2(fs14__namespace.readFileSync(full));
9482
+ } catch {
9483
+ return `its .codebase-snapshot inventory cannot verify ${entry}: the file could not be read`;
9484
+ }
9485
+ if (digest !== record.sha256) {
9486
+ return `its .codebase-snapshot inventory's digest for ${entry} does not match the file`;
9487
+ }
9488
+ }
9489
+ return null;
9490
+ }
8654
9491
  function assessSnapshotDirectory(dir) {
8655
9492
  const { marker: marker2, problem } = readOwnershipMarker(dir);
8656
9493
  if (!marker2) return { owned: false, problem, foreignEntries: [], marker: null };
@@ -8663,7 +9500,8 @@ function assessSnapshotDirectory(dir) {
8663
9500
  };
8664
9501
  }
8665
9502
  const manifestPath = path16__namespace.join(dir, "manifest.json");
8666
- if (fs14__namespace.existsSync(manifestPath)) {
9503
+ const hasManifest = fs14__namespace.existsSync(manifestPath);
9504
+ if (hasManifest) {
8667
9505
  let raw;
8668
9506
  try {
8669
9507
  raw = fs14__namespace.readFileSync(manifestPath, "utf8");
@@ -8714,7 +9552,15 @@ function assessSnapshotDirectory(dir) {
8714
9552
  } else if (marker2.manifestSha256) {
8715
9553
  return {
8716
9554
  owned: false,
8717
- problem: "its manifest.json is missing although its marker records one",
9555
+ problem: "its manifest.json is missing although its marker records one",
9556
+ foreignEntries: [],
9557
+ marker: marker2
9558
+ };
9559
+ }
9560
+ if (marker2.files === void 0 && !hasManifest) {
9561
+ return {
9562
+ owned: false,
9563
+ problem: "its .codebase-snapshot marker records neither per-file digests nor a manifest digest, so it cannot prove this generator wrote the directory",
8718
9564
  foreignEntries: [],
8719
9565
  marker: marker2
8720
9566
  };
@@ -8728,13 +9574,18 @@ function assessSnapshotDirectory(dir) {
8728
9574
  marker: marker2
8729
9575
  };
8730
9576
  }
8731
- const foreignEntries = listEntries(dir).filter(
9577
+ const entries = listEntries(dir);
9578
+ const foreignEntries = entries.filter(
8732
9579
  (entry) => !recorded.has(entry) && !IGNORABLE_ENTRIES.has(entry)
8733
9580
  );
9581
+ if (foreignEntries.length > 0) {
9582
+ return { owned: false, problem: null, foreignEntries, marker: marker2 };
9583
+ }
9584
+ const inventoryProblem = marker2.files === void 0 ? null : verifyMarkerInventory(dir, entries, marker2.files);
8734
9585
  return {
8735
- owned: foreignEntries.length === 0,
8736
- problem: null,
8737
- foreignEntries,
9586
+ owned: inventoryProblem === null,
9587
+ problem: inventoryProblem,
9588
+ foreignEntries: [],
8738
9589
  marker: marker2
8739
9590
  };
8740
9591
  }
@@ -8894,10 +9745,7 @@ function acquireRunLock(stagingRoot) {
8894
9745
  };
8895
9746
  } catch (err) {
8896
9747
  if (err.code !== "EEXIST") throw err;
8897
- if (attempt === 0 && lockOwnerIsGone(lockPath)) {
8898
- fs14__namespace.rmSync(lockPath, { force: true });
8899
- continue;
8900
- }
9748
+ if (attempt === 0 && reclaimStaleLock(lockPath)) continue;
8901
9749
  throw new Error(
8902
9750
  `Another generate run is already using the staging directory ${stagingRoot}. Wait for it to finish, or delete ${lockPath} if no other run is active.`
8903
9751
  );
@@ -8906,14 +9754,25 @@ function acquireRunLock(stagingRoot) {
8906
9754
  throw new Error(`Could not acquire the generate lock for ${stagingRoot}.`);
8907
9755
  }
8908
9756
  function lockKeyFor(stagingRoot) {
8909
- let key = stagingRoot;
8910
- try {
8911
- key = fs14__namespace.realpathSync(stagingRoot);
8912
- } catch {
8913
- }
9757
+ let key = canonicalLockTarget(stagingRoot);
8914
9758
  if (process.platform === "win32" || process.platform === "darwin") key = key.toLowerCase();
8915
9759
  return sha256Hex2(key).slice(0, 16);
8916
9760
  }
9761
+ function canonicalLockTarget(targetPath2) {
9762
+ const resolved = path16__namespace.resolve(targetPath2);
9763
+ let existing = resolved;
9764
+ const tail = [];
9765
+ for (; ; ) {
9766
+ try {
9767
+ return path16__namespace.join(fs14__namespace.realpathSync(existing), ...tail);
9768
+ } catch {
9769
+ const parent = path16__namespace.dirname(existing);
9770
+ if (parent === existing) return resolved;
9771
+ tail.unshift(path16__namespace.basename(existing));
9772
+ existing = parent;
9773
+ }
9774
+ }
9775
+ }
8917
9776
  function lockPathFor(stagingRoot) {
8918
9777
  return path16__namespace.join(os__namespace.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
8919
9778
  }
@@ -8938,6 +9797,24 @@ function lockOwnerIsGone(lockPath) {
8938
9797
  return err.code === "ESRCH";
8939
9798
  }
8940
9799
  }
9800
+ function reclaimStaleLock(lockPath) {
9801
+ let before;
9802
+ try {
9803
+ before = fs14__namespace.statSync(lockPath);
9804
+ } catch {
9805
+ return true;
9806
+ }
9807
+ if (!lockOwnerIsGone(lockPath)) return false;
9808
+ try {
9809
+ const current = fs14__namespace.statSync(lockPath);
9810
+ const sameFile = current.ino === before.ino && current.birthtimeMs === before.birthtimeMs && current.mtimeMs === before.mtimeMs;
9811
+ if (!sameFile) return false;
9812
+ fs14__namespace.rmSync(lockPath, { force: true });
9813
+ return true;
9814
+ } catch {
9815
+ return false;
9816
+ }
9817
+ }
8941
9818
  function lockFileIsAncient(lockPath) {
8942
9819
  try {
8943
9820
  return Date.now() - fs14__namespace.statSync(lockPath).mtimeMs > STALE_RUN_MS;
@@ -8995,7 +9872,6 @@ function swapOnce(stagingDir, outDir) {
8995
9872
  throw copyErr;
8996
9873
  }
8997
9874
  }
8998
- if (hadPrevious) fs14__namespace.rmSync(backupDir, { recursive: true, force: true });
8999
9875
  } catch (err) {
9000
9876
  if (hadPrevious && fs14__namespace.existsSync(backupDir)) {
9001
9877
  if (fs14__namespace.existsSync(outDir)) fs14__namespace.rmSync(outDir, { recursive: true, force: true });
@@ -9003,6 +9879,16 @@ function swapOnce(stagingDir, outDir) {
9003
9879
  }
9004
9880
  throw err;
9005
9881
  }
9882
+ if (hadPrevious) {
9883
+ try {
9884
+ fs14__namespace.rmSync(backupDir, { recursive: true, force: true });
9885
+ } catch (err) {
9886
+ process.stderr.write(
9887
+ `\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.
9888
+ `
9889
+ );
9890
+ }
9891
+ }
9006
9892
  }
9007
9893
  function sleepSync(milliseconds) {
9008
9894
  const buffer = new Int32Array(new SharedArrayBuffer(4));
@@ -9025,22 +9911,18 @@ function artifactWarnings(artifacts, sarif) {
9025
9911
  }
9026
9912
  return messages;
9027
9913
  }
9914
+ function installHookStdoutRedirect() {
9915
+ return installStdoutRouter();
9916
+ }
9028
9917
  function runAfterGenerate(config, manifest) {
9029
9918
  const hook = config.hooks.afterGenerate;
9030
9919
  if (!hook) return null;
9031
- const stdoutWrite = process.stdout.write.bind(process.stdout);
9032
- const stderrWrite = process.stderr.write.bind(process.stderr);
9033
- const hookScope = new async_hooks.AsyncLocalStorage();
9034
- const patchedWrite = ((...args) => hookScope.getStore() === true ? stderrWrite(...args) : stdoutWrite(...args));
9035
- const restoreStdout = () => {
9036
- if (process.stdout.write === patchedWrite) process.stdout.write = stdoutWrite;
9037
- };
9920
+ const releaseRedirect = installHookStdoutRedirect();
9038
9921
  let returned;
9039
9922
  try {
9040
- process.stdout.write = patchedWrite;
9041
- returned = hookScope.run(true, () => hook(manifest));
9923
+ returned = hookStdoutScope.run(true, () => hook(manifest));
9042
9924
  } catch (err) {
9043
- restoreStdout();
9925
+ releaseRedirect();
9044
9926
  const message = maskPathText(err.message, config.secretRules);
9045
9927
  manifest.warnings.push(`hooks.afterGenerate failed: ${message}`);
9046
9928
  manifest.totals.warningCount = manifest.warnings.length;
@@ -9048,10 +9930,10 @@ function runAfterGenerate(config, manifest) {
9048
9930
  }
9049
9931
  const thenable = returned;
9050
9932
  if (!thenable || typeof thenable.then !== "function") {
9051
- restoreStdout();
9933
+ releaseRedirect();
9052
9934
  return null;
9053
9935
  }
9054
- return Promise.resolve(returned).finally(restoreStdout);
9936
+ return Promise.resolve(returned).finally(releaseRedirect);
9055
9937
  }
9056
9938
  function partitionByBudget(files, config, fingerprint) {
9057
9939
  const budgetFor = (file) => config.budgets.byLayer[file.layer] ?? config.budgets.default;
@@ -9062,23 +9944,14 @@ function partitionByBudget(files, config, fingerprint) {
9062
9944
  if (bucket) bucket.push(file);
9063
9945
  else buckets.set(budget, [file]);
9064
9946
  }
9065
- if (buckets.size <= 1) {
9066
- const only = buckets.size === 1 ? Array.from(buckets.keys())[0] : config.maxPartBytes;
9067
- return partitionFiles(files, only, fingerprint);
9068
- }
9069
- const parts = [];
9070
- for (const budget of Array.from(buckets.keys()).sort((a, b) => a - b)) {
9071
- parts.push(...partitionFiles(buckets.get(budget) ?? [], budget, fingerprint));
9072
- }
9073
- const merged = renumberParts(parts, fingerprint);
9074
- const byPath = new Map(files.map((file) => [file.relativePath, file]));
9075
- for (const part of merged) {
9076
- for (const included of part.metadata.includedFiles) {
9077
- const file = byPath.get(included.relativePath);
9078
- if (file) file.part = part.filename;
9079
- }
9947
+ if (buckets.size === 0) return [];
9948
+ if (buckets.size === 1) {
9949
+ return partitionFiles(files, Array.from(buckets.keys())[0], fingerprint);
9080
9950
  }
9081
- return merged;
9951
+ return partitionFilesForBuckets(
9952
+ Array.from(buckets.entries()).sort(([left], [right]) => left - right).map(([budgetBytes, bucketFiles]) => ({ files: bucketFiles, budgetBytes })),
9953
+ fingerprint
9954
+ );
9082
9955
  }
9083
9956
  function generateSnapshot(configInput, options) {
9084
9957
  assertUsableConfigInput(configInput);
@@ -9110,6 +9983,7 @@ function generateSnapshot(configInput, options) {
9110
9983
  return false;
9111
9984
  }) : collection.files;
9112
9985
  const files = [];
9986
+ const derivationKey = derivationSettings(config);
9113
9987
  const monolithBodies = /* @__PURE__ */ new Map();
9114
9988
  const skipped = maskSkipRecords([...collection.skipped], config.secretRules);
9115
9989
  const secretFindings = [];
@@ -9122,6 +9996,7 @@ function generateSnapshot(configInput, options) {
9122
9996
  const fileWarnings = [];
9123
9997
  const oversizeSummaryPaths = [];
9124
9998
  const previewSummaryPaths = [];
9999
+ const skippedSummaryImports = /* @__PURE__ */ new Map();
9125
10000
  const layerCounts = {};
9126
10001
  const kindCounts = {};
9127
10002
  let totalLines = 0;
@@ -9186,8 +10061,6 @@ function generateSnapshot(configInput, options) {
9186
10061
  }
9187
10062
  const hashSha256 = sha256Hex2(buffer);
9188
10063
  const rawContent = decoded.text;
9189
- const lineCount = countLines(rawContent);
9190
- totalLines += lineCount;
9191
10064
  totalSizeBytes += stats.size;
9192
10065
  if (decoded.encoding !== "utf-8") {
9193
10066
  encodingNotes.push({
@@ -9201,66 +10074,25 @@ function generateSnapshot(configInput, options) {
9201
10074
  const language = detectLanguage(relativePath);
9202
10075
  bump(layerCounts, layer2);
9203
10076
  bump(kindCounts, kind);
9204
- const { redacted, findings } = scanAndRedactSecrets(
9205
- rawContent,
9206
- config.secretRules,
9207
- relativePath
9208
- );
9209
- secretFindings.push(...findings);
9210
- const isLarge = stats.size > config.largeFileBytes;
9211
- if (isLarge) largeFileCount += 1;
9212
- let finalContent = redacted;
9213
- let isPreviewTruncated = false;
9214
- let includedLines = lineCount;
9215
- let inclusionMode = "full";
9216
- if (config.skeleton === true && isSkeletonizable(relativePath)) {
9217
- const skeleton = skeletonizeTypeScript(redacted, relativePath);
9218
- if (skeleton.collapsed > 0) {
9219
- finalContent = skeleton.text;
9220
- inclusionMode = "signatures";
9221
- includedLines = countLines(skeleton.text);
9222
- }
9223
- }
9224
- if (isLarge && inclusionMode !== "signatures") {
9225
- const preview = truncatePreview(
9226
- redacted,
9227
- config.previewHeadLines,
9228
- config.previewTailLines
9229
- );
9230
- finalContent = preview.content;
9231
- isPreviewTruncated = preview.isTruncated;
9232
- includedLines = preview.includedLines;
9233
- inclusionMode = isPreviewTruncated ? "preview" : "full";
9234
- }
9235
- if (config.includeMonolith && (isPreviewTruncated || inclusionMode === "signatures")) {
9236
- monolithBodies.set(relativePath, redacted);
9237
- }
9238
- let summary;
9239
- let summaryQuality;
9240
- if (Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES) {
9241
- oversizeSummaryPaths.push(relativePath);
9242
- } else if (isPreviewTruncated && hasStructuralSummary(relativePath)) {
9243
- previewSummaryPaths.push(relativePath);
9244
- } else {
9245
- try {
9246
- const outcome = summarizeFile(relativePath, rawContent);
9247
- summary = outcome?.summary ? maskSummaryStrings(outcome.summary, config.secretRules) : void 0;
9248
- summaryQuality = outcome?.quality;
9249
- if (isSourceSummary(summary) && summary.parseErrors) {
9250
- fileWarnings.push({
9251
- path: relativePath,
9252
- message: `Parse errors in ${maskPathText(relativePath, config.secretRules)} (${summary.parseErrors}); its summary is incomplete.`
9253
- });
9254
- }
9255
- } catch (err) {
9256
- fileWarnings.push({
9257
- path: relativePath,
9258
- message: `Summary skipped for ${maskPathText(relativePath, config.secretRules)}: ${err.message}`.replace(
9259
- /\s+/g,
9260
- " "
9261
- )
9262
- });
9263
- }
10077
+ const derivation = takeDerivation(absolutePath, hashSha256, derivationKey) ?? (() => {
10078
+ const fresh = deriveFile(relativePath, rawContent, stats.size, config);
10079
+ rememberDerivation(absolutePath, hashSha256, derivationKey, fresh);
10080
+ return fresh;
10081
+ })();
10082
+ const { lineCount } = derivation;
10083
+ totalLines += lineCount;
10084
+ secretFindings.push(...derivation.findings);
10085
+ if (derivation.isLarge) largeFileCount += 1;
10086
+ if (derivation.summarySkip === "oversize") oversizeSummaryPaths.push(relativePath);
10087
+ else if (derivation.summarySkip === "preview") previewSummaryPaths.push(relativePath);
10088
+ if (derivation.dependentImports !== null) {
10089
+ skippedSummaryImports.set(relativePath, derivation.dependentImports);
10090
+ }
10091
+ if (derivation.summaryWarning !== null) {
10092
+ fileWarnings.push({ path: relativePath, message: derivation.summaryWarning });
10093
+ }
10094
+ if (config.includeMonolith && (derivation.isPreviewTruncated || derivation.inclusionMode === "signatures")) {
10095
+ monolithBodies.set(relativePath, derivation.redacted);
9264
10096
  }
9265
10097
  files.push({
9266
10098
  relativePath,
@@ -9271,24 +10103,25 @@ function generateSnapshot(configInput, options) {
9271
10103
  layer: layer2,
9272
10104
  kind,
9273
10105
  language,
9274
- inclusionMode,
9275
- isLarge,
9276
- isPreviewTruncated,
10106
+ inclusionMode: derivation.inclusionMode,
10107
+ isLarge: derivation.isLarge,
10108
+ isPreviewTruncated: derivation.isPreviewTruncated,
9277
10109
  originalLines: lineCount,
9278
- includedLines,
9279
- includedBytes: Buffer.byteLength(finalContent, "utf8"),
9280
- summary,
9281
- summaryQuality,
10110
+ includedLines: derivation.includedLines,
10111
+ includedBytes: Buffer.byteLength(derivation.finalContent, "utf8"),
10112
+ summary: derivation.summary,
10113
+ summaryQuality: derivation.summaryQuality,
9282
10114
  ...decoded.encoding === "utf-8" ? {} : { encoding: decoded.encoding },
9283
- content: finalContent
10115
+ content: derivation.finalContent
9284
10116
  });
9285
10117
  }
9286
10118
  if (changedScope !== null && changedPaths !== null && config.withDependents === true) {
9287
10119
  const keep = new Set(changedPaths);
9288
10120
  const resolver = buildImportResolver(files);
9289
10121
  for (const file of files) {
9290
- if (!isSourceSummary(file.summary)) continue;
9291
- if (importsChangedFile(file.relativePath, file.summary.imports, changedPaths, resolver)) {
10122
+ const fileImports = isSourceSummary(file.summary) ? file.summary.imports : skippedSummaryImports.get(file.relativePath) ?? [];
10123
+ if (fileImports.length === 0) continue;
10124
+ if (importsChangedFile(file.relativePath, fileImports, changedPaths, resolver)) {
9292
10125
  keep.add(file.relativePath);
9293
10126
  }
9294
10127
  }
@@ -9319,6 +10152,9 @@ function generateSnapshot(configInput, options) {
9319
10152
  for (const path22 of [...monolithBodies.keys()]) {
9320
10153
  if (!keep.has(path22)) monolithBodies.delete(path22);
9321
10154
  }
10155
+ for (const path22 of [...skippedSummaryImports.keys()]) {
10156
+ if (!keep.has(path22)) skippedSummaryImports.delete(path22);
10157
+ }
9322
10158
  }
9323
10159
  if (changedScope !== null) {
9324
10160
  for (const relativePath of unchangedPaths) {
@@ -9354,7 +10190,7 @@ function generateSnapshot(configInput, options) {
9354
10190
  const shown = oversizeSummaryPaths.slice(0, ENCODING_PATHS_SHOWN).map((entry) => maskPathText(entry, config.secretRules));
9355
10191
  const hidden = oversizeSummaryPaths.length - ENCODING_PATHS_SHOWN;
9356
10192
  warnings.push(
9357
- `${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.`
10193
+ `${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.`
9358
10194
  );
9359
10195
  }
9360
10196
  for (const [encoding, bucket] of encodingBuckets) {
@@ -9373,16 +10209,21 @@ function generateSnapshot(configInput, options) {
9373
10209
  }
9374
10210
  }
9375
10211
  const fingerprint = sha256Hex2(
9376
- files.map(
9377
- (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
9378
- ).join("\n")
10212
+ [
10213
+ ...files.map(
10214
+ (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
10215
+ ),
10216
+ `settings:${configDigest(config)}`
10217
+ ].join("\n")
9379
10218
  );
9380
10219
  const fullContents = /* @__PURE__ */ new Map();
9381
- for (const file of files) {
9382
- fullContents.set(
9383
- file.relativePath,
9384
- monolithBodies.get(file.relativePath) ?? file.content ?? ""
9385
- );
10220
+ if (config.includeMonolith) {
10221
+ for (const file of files) {
10222
+ fullContents.set(
10223
+ file.relativePath,
10224
+ monolithBodies.get(file.relativePath) ?? file.content ?? ""
10225
+ );
10226
+ }
9386
10227
  }
9387
10228
  const parts = partitionByBudget(files, config, fingerprint);
9388
10229
  const truncatedPreviewCount = files.filter((file) => file.isPreviewTruncated).length;
@@ -9641,9 +10482,9 @@ function generateSnapshot(configInput, options) {
9641
10482
  }
9642
10483
  writeOwnershipMarker(outDir, markerPayload(outDir, "complete", snapshotId, createdAt));
9643
10484
  };
9644
- shipHookState();
10485
+ if (config.hooks.afterGenerate) shipHookState();
9645
10486
  if (pendingHook) {
9646
- pendingHook.then(
10487
+ const tracked = pendingHook.then(
9647
10488
  () => {
9648
10489
  try {
9649
10490
  shipHookState();
@@ -9662,8 +10503,10 @@ function generateSnapshot(configInput, options) {
9662
10503
  } catch {
9663
10504
  }
9664
10505
  }
9665
- );
9666
- pendingHooks.set(outDir, pendingHook);
10506
+ ).finally(() => {
10507
+ if (pendingHooks.get(outDir) === tracked) pendingHooks.delete(outDir);
10508
+ });
10509
+ pendingHooks.set(outDir, tracked);
9667
10510
  }
9668
10511
  return manifest;
9669
10512
  } catch (err) {
@@ -9685,7 +10528,17 @@ var pendingHooks = /* @__PURE__ */ new Map();
9685
10528
  var FILE_HEADING = "### FILE: ";
9686
10529
  var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
9687
10530
  var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
10531
+ var META_PREFIX = "- Meta: ";
10532
+ var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
10533
+ var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
9688
10534
  var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
10535
+ var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
10536
+ function readIncludedLines(fields) {
10537
+ const last = fields[fields.length - 1];
10538
+ if (last === void 0) return null;
10539
+ const counts = COMPACT_COUNTS.exec(last.trim());
10540
+ return counts === null ? null : Number(counts[1]);
10541
+ }
9689
10542
  function parsePartSections(partText) {
9690
10543
  const lines = partText.split("\n");
9691
10544
  const sections = [];
@@ -9703,20 +10556,17 @@ function parsePartSections(partText) {
9703
10556
  while (cursor < lines.length && !CONTENT_MARKERS.has(lines[cursor])) {
9704
10557
  const line = lines[cursor];
9705
10558
  if (line.startsWith(FILE_HEADING)) break;
9706
- if (line.startsWith("- Meta: ")) {
9707
- for (const field of line.slice("- Meta: ".length).split("|")) {
10559
+ if (line.startsWith(META_PREFIX)) {
10560
+ const fields = line.slice(META_PREFIX.length).split("|");
10561
+ for (const field of fields) {
9708
10562
  const value = field.trim();
9709
10563
  if (INCLUSION_MODES.has(value)) inclusion = value;
9710
10564
  }
9711
- const counts = /(-?\d+) of (-?\d+) lines|(\d+) lines/.exec(line);
9712
- if (counts) {
9713
- const emitted = counts[1] ?? counts[3];
9714
- includedLines = Number.isFinite(Number(emitted)) ? Number(emitted) : null;
9715
- }
9716
- } else if (line.startsWith("- Inclusion: ")) {
9717
- inclusion = line.slice("- Inclusion: ".length).trim();
9718
- } else if (line.startsWith("- Included Lines: ")) {
9719
- const value = Number(line.slice("- Included Lines: ".length).trim());
10565
+ includedLines = readIncludedLines(fields);
10566
+ } else if (line.startsWith(LEGACY_INCLUSION_PREFIX)) {
10567
+ inclusion = line.slice(LEGACY_INCLUSION_PREFIX.length).trim();
10568
+ } else if (line.startsWith(LEGACY_INCLUDED_LINES_PREFIX)) {
10569
+ const value = Number(line.slice(LEGACY_INCLUDED_LINES_PREFIX.length).trim());
9720
10570
  includedLines = Number.isFinite(value) ? value : null;
9721
10571
  }
9722
10572
  cursor += 1;
@@ -9793,6 +10643,18 @@ function isInside2(parent, child) {
9793
10643
  const foldedChild = foldForComparison(child);
9794
10644
  return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path16__namespace.sep}`);
9795
10645
  }
10646
+ function resolveThroughExistingAncestor(target) {
10647
+ let existing = target;
10648
+ const missing = [];
10649
+ while (!fs14__namespace.existsSync(existing)) {
10650
+ missing.unshift(path16__namespace.basename(existing));
10651
+ const parent = path16__namespace.dirname(existing);
10652
+ if (parent === existing) break;
10653
+ existing = parent;
10654
+ }
10655
+ const resolved = canonicalPath(existing);
10656
+ return missing.length === 0 ? resolved : path16__namespace.join(resolved, ...missing);
10657
+ }
9796
10658
  function resolveRoot(requested, context) {
9797
10659
  if (requested !== void 0 && (typeof requested !== "string" || requested.trim().length === 0)) {
9798
10660
  return { ok: false, message: '"root" must be a non-empty string when provided.' };
@@ -9815,10 +10677,10 @@ function resolveRoot(requested, context) {
9815
10677
  const shown = context.roots.join(", ");
9816
10678
  return {
9817
10679
  ok: false,
9818
- message: `"${wanted}" resolves outside the directories this server may read (${shown}). Restart it with --root <path> to add a repository.`
10680
+ message: `"${wanted}" resolves outside the directories this server may read (${shown}). The server reads the directory it was started for; restart it with --cwd <directory> to serve a different repository.`
9819
10681
  };
9820
10682
  }
9821
- async function openWorkspace(root, overrides = {}) {
10683
+ async function openWorkspace(root, overrides = {}, allowedRoots) {
9822
10684
  const loaded = await loadConfigFileDetailed(root);
9823
10685
  if (loaded.errors.length > 0) {
9824
10686
  return {
@@ -9837,12 +10699,45 @@ async function openWorkspace(root, overrides = {}) {
9837
10699
  }
9838
10700
  cliOptions.maxPartBytes = parsed;
9839
10701
  }
10702
+ if (overrides.maxPartTokens !== void 0) {
10703
+ const parsed = parseByteSize(overrides.maxPartTokens);
10704
+ if (parsed === void 0) {
10705
+ return {
10706
+ ok: false,
10707
+ message: '"maxPartTokens" must be a token count, for example 32000 or "32k".'
10708
+ };
10709
+ }
10710
+ cliOptions.maxPartTokens = parsed;
10711
+ }
9840
10712
  if (overrides.outDir !== void 0) {
9841
10713
  if (typeof overrides.outDir !== "string" || overrides.outDir.trim().length === 0) {
9842
10714
  return { ok: false, message: '"outDir" must be a non-empty string.' };
9843
10715
  }
9844
- cliOptions.outDir = overrides.outDir.trim();
10716
+ const requested = overrides.outDir.trim();
10717
+ const permitted = allowedRoots !== void 0 && allowedRoots.length > 0 ? allowedRoots : [root];
10718
+ const resolved = resolveThroughExistingAncestor(path16__namespace.resolve(root, requested));
10719
+ if (!permitted.some((allowed) => isInside2(canonicalPath(allowed), resolved))) {
10720
+ const shown = permitted.map((allowed) => canonicalPath(allowed)).join(", ");
10721
+ return {
10722
+ ok: false,
10723
+ message: `"outDir" must resolve inside the repository this server serves (${shown}). A tool argument may not place the snapshot outside it; pass a directory inside the root, or restart the server with --cwd pointing at the repository you want to write.`
10724
+ };
10725
+ }
10726
+ cliOptions.outDir = requested;
10727
+ }
10728
+ if (overrides.changedSince !== void 0) {
10729
+ if (typeof overrides.changedSince !== "string" || overrides.changedSince.trim().length === 0) {
10730
+ return {
10731
+ ok: false,
10732
+ message: '"changedSince" must be a git ref such as "main" or "HEAD~3".'
10733
+ };
10734
+ }
10735
+ cliOptions.changedSince = overrides.changedSince.trim();
9845
10736
  }
10737
+ if (overrides.skeleton === true) cliOptions.skeleton = true;
10738
+ if (overrides.sarif === true) cliOptions.sarif = true;
10739
+ if (overrides.staged === true) cliOptions.staged = true;
10740
+ if (overrides.withDependents === true) cliOptions.withDependents = true;
9846
10741
  try {
9847
10742
  const config = resolveConfig(loaded.config, cliOptions, root);
9848
10743
  return { ok: true, workspace: { root, config, configFile: loaded.file, cliOptions } };
@@ -9854,6 +10749,16 @@ var manifestCache = /* @__PURE__ */ new Map();
9854
10749
  function manifestPathFor(workspace) {
9855
10750
  return path16__namespace.resolve(workspace.root, workspace.config.outDir, "manifest.json");
9856
10751
  }
10752
+ function partPathFor(workspace, filename) {
10753
+ if (filename.length === 0 || filename.includes("\0")) return null;
10754
+ const partsDir = path16__namespace.resolve(workspace.root, workspace.config.outDir, "parts");
10755
+ const resolved = path16__namespace.resolve(partsDir, filename);
10756
+ const relative12 = path16__namespace.relative(partsDir, resolved);
10757
+ if (relative12.length === 0 || relative12.includes(path16__namespace.sep) || relative12.includes("/") || relative12.includes("\\") || path16__namespace.isAbsolute(relative12)) {
10758
+ return null;
10759
+ }
10760
+ return resolved;
10761
+ }
9857
10762
  function readManifest3(workspace) {
9858
10763
  const file = manifestPathFor(workspace);
9859
10764
  const shown = path16__namespace.relative(workspace.root, file).split(path16__namespace.sep).join("/") || file;
@@ -9921,9 +10826,47 @@ var ROOT_PROPERTY = {
9921
10826
  };
9922
10827
  var OUT_DIR_PROPERTY = {
9923
10828
  type: "string",
9924
- description: "Snapshot directory, relative to the root. Defaults to the project configuration's outDir."
10829
+ description: "Snapshot directory, relative to the root, and it must resolve inside the served repository. Defaults to the project configuration's outDir."
9925
10830
  };
9926
10831
  var outDirOverride = (args) => ({ outDir: args.outDir });
10832
+ var SCOPE_PROPERTIES = {
10833
+ maxPartTokens: {
10834
+ type: "string",
10835
+ description: 'Token ceiling per part, for example 32000 or "32k". Narrower than maxPartBytes; it converts at four bytes per token.'
10836
+ },
10837
+ skeleton: {
10838
+ type: "boolean",
10839
+ description: "Replace every function body with `{ /* ... */ }`, keeping signatures, imports and exports. Applies to TypeScript, JavaScript and JSX."
10840
+ },
10841
+ sarif: {
10842
+ type: "boolean",
10843
+ description: "Also write reports/audit.sarif beside reports/audit.md, for CI code scanning."
10844
+ },
10845
+ changedSince: {
10846
+ type: "string",
10847
+ description: 'Only files changed since this git ref, for example "main" or "HEAD~3".'
10848
+ },
10849
+ staged: {
10850
+ type: "boolean",
10851
+ description: "Only files staged in the git index."
10852
+ },
10853
+ withDependents: {
10854
+ type: "boolean",
10855
+ description: "With staged or changedSince, also include the files that import the changed ones (one hop)."
10856
+ }
10857
+ };
10858
+ function workspaceOverrides(args) {
10859
+ return {
10860
+ outDir: args.outDir,
10861
+ maxPartBytes: args.maxPartBytes,
10862
+ maxPartTokens: args.maxPartTokens,
10863
+ skeleton: args.skeleton,
10864
+ sarif: args.sarif,
10865
+ changedSince: args.changedSince,
10866
+ staged: args.staged,
10867
+ withDependents: args.withDependents
10868
+ };
10869
+ }
9927
10870
  function failure(message) {
9928
10871
  return { text: message, isError: true };
9929
10872
  }
@@ -9954,12 +10897,13 @@ function summarizeDrift(drift) {
9954
10897
  }
9955
10898
  function toRelativePath(root, value) {
9956
10899
  const cleaned = value.trim();
9957
- if (cleaned.length === 0) return null;
9958
- if (!path16__namespace.isAbsolute(cleaned)) {
9959
- return cleaned.replace(/\\/g, "/").replace(/^\.\//, "");
10900
+ if (cleaned.length === 0 || cleaned.includes("\0")) return null;
10901
+ const resolvedRoot = path16__namespace.resolve(root);
10902
+ const absolute = path16__namespace.resolve(resolvedRoot, cleaned);
10903
+ const relative12 = path16__namespace.relative(resolvedRoot, absolute);
10904
+ if (relative12 === "" || relative12 === ".." || relative12.startsWith(`..${path16__namespace.sep}`) || path16__namespace.isAbsolute(relative12)) {
10905
+ return null;
9960
10906
  }
9961
- const relative12 = path16__namespace.relative(root, cleaned);
9962
- if (relative12.startsWith("..") || path16__namespace.isAbsolute(relative12)) return null;
9963
10907
  return relative12.split(path16__namespace.sep).join("/");
9964
10908
  }
9965
10909
  function symbolsOf(entry) {
@@ -10001,7 +10945,7 @@ function symbolsOf(entry) {
10001
10945
  async function prepare(args, context, overrides = {}) {
10002
10946
  const rootOutcome = resolveRoot(args.root, context);
10003
10947
  if (!rootOutcome.ok) return { ok: false, outcome: failure(rootOutcome.message) };
10004
- const opened = await openWorkspace(rootOutcome.root, overrides);
10948
+ const opened = await openWorkspace(rootOutcome.root, overrides, context.roots);
10005
10949
  if (!opened.ok) return { ok: false, outcome: failure(opened.message) };
10006
10950
  return { ok: true, workspace: opened.workspace };
10007
10951
  }
@@ -10095,7 +11039,8 @@ var planTool = {
10095
11039
  maxPartBytes: {
10096
11040
  type: "string",
10097
11041
  description: 'Byte budget per part, for example 307200 or "300k". Defaults to the project configuration.'
10098
- }
11042
+ },
11043
+ ...SCOPE_PROPERTIES
10099
11044
  },
10100
11045
  additionalProperties: false
10101
11046
  },
@@ -10112,7 +11057,7 @@ var planTool = {
10112
11057
  },
10113
11058
  annotations: READ_ONLY,
10114
11059
  async handler(args, context) {
10115
- const prepared = await prepare(args, context, { maxPartBytes: args.maxPartBytes, outDir: args.outDir });
11060
+ const prepared = await prepare(args, context, workspaceOverrides(args));
10116
11061
  if (!prepared.ok) return prepared.outcome;
10117
11062
  const workspace = prepared.workspace;
10118
11063
  let manifest;
@@ -10170,7 +11115,8 @@ var generateTool = {
10170
11115
  maxPartBytes: {
10171
11116
  type: "string",
10172
11117
  description: 'Byte budget per part, for example 307200 or "300k". Defaults to the project configuration.'
10173
- }
11118
+ },
11119
+ ...SCOPE_PROPERTIES
10174
11120
  },
10175
11121
  additionalProperties: false
10176
11122
  },
@@ -10186,10 +11132,7 @@ var generateTool = {
10186
11132
  },
10187
11133
  annotations: WRITES,
10188
11134
  async handler(args, context) {
10189
- const prepared = await prepare(args, context, {
10190
- maxPartBytes: args.maxPartBytes,
10191
- outDir: args.outDir
10192
- });
11135
+ const prepared = await prepare(args, context, workspaceOverrides(args));
10193
11136
  if (!prepared.ok) return prepared.outcome;
10194
11137
  const workspace = prepared.workspace;
10195
11138
  const result = await generateInWorker(workspace.root, workspace.cliOptions);
@@ -10228,7 +11171,7 @@ var validateTool = {
10228
11171
  description: "Re-read the repository and report whether the snapshot on disk still matches it. Use it before trusting context that came from an earlier session, or after changing the config.",
10229
11172
  inputSchema: {
10230
11173
  type: "object",
10231
- properties: { root: ROOT_PROPERTY, outDir: OUT_DIR_PROPERTY },
11174
+ properties: { root: ROOT_PROPERTY, outDir: OUT_DIR_PROPERTY, ...SCOPE_PROPERTIES },
10232
11175
  additionalProperties: false
10233
11176
  },
10234
11177
  outputSchema: {
@@ -10240,7 +11183,7 @@ var validateTool = {
10240
11183
  },
10241
11184
  annotations: READ_ONLY,
10242
11185
  async handler(args, context) {
10243
- const prepared = await prepare(args, context, outDirOverride(args));
11186
+ const prepared = await prepare(args, context, workspaceOverrides(args));
10244
11187
  if (!prepared.ok) return prepared.outcome;
10245
11188
  const workspace = prepared.workspace;
10246
11189
  let result;
@@ -10585,7 +11528,12 @@ var readTool = {
10585
11528
  `${relativePath} is not in the snapshot. Call snapshot_locate to find the path, or snapshot_explain to learn why it was excluded.`
10586
11529
  );
10587
11530
  }
10588
- const partPath = path16__namespace.resolve(workspace.root, workspace.config.outDir, "parts", entry.part);
11531
+ const partPath = partPathFor(workspace, entry.part);
11532
+ if (partPath === null) {
11533
+ return failure(
11534
+ `${entry.part} is not a part of this snapshot: its name leaves ${workspace.config.outDir}/parts. Run snapshot_generate to rebuild it.`
11535
+ );
11536
+ }
10589
11537
  let partText;
10590
11538
  try {
10591
11539
  partText = fs14__namespace.readFileSync(partPath, "utf8");
@@ -10665,7 +11613,8 @@ var explainTool = {
10665
11613
  description: "Path relative to the repository root. Directories are explained as a whole."
10666
11614
  },
10667
11615
  root: ROOT_PROPERTY,
10668
- outDir: OUT_DIR_PROPERTY
11616
+ outDir: OUT_DIR_PROPERTY,
11617
+ ...SCOPE_PROPERTIES
10669
11618
  },
10670
11619
  required: ["path"],
10671
11620
  additionalProperties: false
@@ -10680,7 +11629,7 @@ var explainTool = {
10680
11629
  },
10681
11630
  annotations: READ_ONLY,
10682
11631
  async handler(args, context) {
10683
- const prepared = await prepare(args, context, outDirOverride(args));
11632
+ const prepared = await prepare(args, context, workspaceOverrides(args));
10684
11633
  if (!prepared.ok) return prepared.outcome;
10685
11634
  const workspace = prepared.workspace;
10686
11635
  if (typeof args.path !== "string") return failure('"path" must be a string.');
@@ -10793,6 +11742,16 @@ var ERROR_CODES = {
10793
11742
  methodNotFound: -32601,
10794
11743
  invalidParams: -32602,
10795
11744
  internalError: -32603,
11745
+ /**
11746
+ * A resource whose complete text is larger than one read may return.
11747
+ *
11748
+ * `-32000` is JSON-RPC's range for implementation-defined server errors, which is what this is:
11749
+ * there is no standard code for "the document is too large", and answering with -32602 would tell
11750
+ * a client its request was malformed when it was not. The message names the size, the limit and
11751
+ * the tool to use instead, because a resource read that cannot return the whole resource must not
11752
+ * invent a partial one.
11753
+ */
11754
+ resourceTooLarge: -32e3,
10796
11755
  unsupportedProtocolVersion: -32022
10797
11756
  };
10798
11757
  var METHOD3 = {
@@ -10901,16 +11860,14 @@ var COMMAND_OPTION_SCOPE = {
10901
11860
  "version"
10902
11861
  ],
10903
11862
  validate: VALIDATE_OPTIONS,
11863
+ // `report` reads `manifest.json` and prints what is there; a generation setting would change
11864
+ // nothing. The seven generation flags used to be listed here and were accepted as silent no-ops
11865
+ // — the exact "flag that parses but changes nothing" this table exists to prevent — while
11866
+ // `--discovery` was already rejected. Both the parser and `describe`'s `appliesTo` read this
11867
+ // list, so removing them narrows the two together.
10904
11868
  report: [
10905
11869
  "cwd",
10906
11870
  "out-dir",
10907
- "max-part-bytes",
10908
- "large-file-bytes",
10909
- "max-monolith-bytes",
10910
- "include-monolith",
10911
- "include-sensitive-files",
10912
- "skip-artifacts",
10913
- "only-artifacts",
10914
11871
  "no-config",
10915
11872
  "no-update-check",
10916
11873
  "format",
@@ -11381,7 +12338,7 @@ function buildAgentContract() {
11381
12338
  type: "string",
11382
12339
  default: "generate",
11383
12340
  appliesTo: optionAppliesTo("mode"),
11384
- summary: "Select the command when no command word is given. Values: generate, validate, check, report, init, setup, explain, diff, describe, skill. A command word and --mode must name the same command; a contradiction is a usage error (exit 2)."
12341
+ summary: "Select the command when no command word is given. Values: generate, validate, check, report, init, setup, explain, diff, describe, skill, mcp. A command word and --mode must name the same command; a contradiction is a usage error (exit 2)."
11385
12342
  },
11386
12343
  {
11387
12344
  flag: "--cwd",
@@ -11518,7 +12475,7 @@ function buildAgentContract() {
11518
12475
  { key: "preset", type: "string", default: "detected", summary: "Force a preset. Unknown names are an error." },
11519
12476
  { key: "maxPartBytes", type: "number | string", default: 307200, summary: "Per-part byte budget." },
11520
12477
  { key: "maxPartTokens", type: "number | string | null", default: null, summary: "Per-part token ceiling; narrows maxPartBytes. Minimum 1024." },
11521
- { key: "skeleton", type: "boolean", default: false, summary: "Collapse function bodies to `{ /* ... */ }` in TypeScript files." },
12478
+ { key: "skeleton", type: "boolean", default: false, summary: "Collapse function bodies to `{ /* ... */ }` in TS, JS, TSX and JSX files." },
11522
12479
  { key: "sarif", type: "boolean", default: false, summary: "Also write reports/audit.sarif." },
11523
12480
  { key: "changedSince", type: "string | null", default: null, summary: "Snapshot only files that differ from this git ref." },
11524
12481
  { key: "staged", type: "boolean", default: false, summary: "Snapshot only files staged in the index." },
@@ -11942,25 +12899,205 @@ function classifyRequest(method, params, session) {
11942
12899
  data: unsupportedVersionData(inspection.meta.version)
11943
12900
  };
11944
12901
  }
11945
- return { kind: "era", era: "modern", version: inspection.meta.version };
11946
- }
11947
- if (inspection.kind === "incomplete") {
11948
- return {
11949
- kind: "error",
11950
- code: ERROR_CODES.invalidParams,
11951
- message: `The request _meta is missing the required key "${inspection.missing}".`
11952
- };
11953
- }
11954
- if (method === METHOD3.discover) {
11955
- return { kind: "era", era: "modern", version: MODERN_PROTOCOL_VERSIONS[0] };
11956
- }
11957
- return { kind: "era", era: "legacy", version: null };
11958
- }
11959
- function negotiateLegacyVersion(requested) {
11960
- if (typeof requested === "string" && isLegacyVersion(requested)) {
11961
- return { version: requested, matched: true };
11962
- }
11963
- return { version: DEFAULT_LEGACY_PROTOCOL_VERSION, matched: false };
12902
+ return { kind: "era", era: "modern", version: inspection.meta.version };
12903
+ }
12904
+ if (inspection.kind === "incomplete") {
12905
+ return {
12906
+ kind: "error",
12907
+ code: ERROR_CODES.invalidParams,
12908
+ message: `The request _meta is missing the required key "${inspection.missing}".`
12909
+ };
12910
+ }
12911
+ if (method === METHOD3.discover) {
12912
+ return { kind: "era", era: "modern", version: MODERN_PROTOCOL_VERSIONS[0] };
12913
+ }
12914
+ return { kind: "era", era: "legacy", version: null };
12915
+ }
12916
+ function negotiateLegacyVersion(requested) {
12917
+ if (typeof requested === "string" && isLegacyVersion(requested)) {
12918
+ return { version: requested, matched: true };
12919
+ }
12920
+ return { version: DEFAULT_LEGACY_PROTOCOL_VERSION, matched: false };
12921
+ }
12922
+ var MAX_RESOURCE_BYTES = 512 * 1024;
12923
+ var ResourceTooLargeError = class extends Error {
12924
+ constructor(uri, bytes, limit, message) {
12925
+ super(message);
12926
+ this.uri = uri;
12927
+ this.bytes = bytes;
12928
+ this.limit = limit;
12929
+ this.name = "ResourceTooLargeError";
12930
+ }
12931
+ uri;
12932
+ bytes;
12933
+ limit;
12934
+ };
12935
+ function refuseTooLarge(uri, bytes, advice) {
12936
+ throw new ResourceTooLargeError(
12937
+ uri,
12938
+ bytes,
12939
+ MAX_RESOURCE_BYTES,
12940
+ `${uri} is ${formatBytes2(bytes)}, above the ${formatBytes2(MAX_RESOURCE_BYTES)} single-read limit, so it was not returned. ${advice}`
12941
+ );
12942
+ }
12943
+ function ensureSingleRead(uri, text2, advice) {
12944
+ const bytes = Buffer.byteLength(text2, "utf8");
12945
+ if (bytes > MAX_RESOURCE_BYTES) refuseTooLarge(uri, bytes, advice);
12946
+ return text2;
12947
+ }
12948
+ var MANIFEST_ADVICE = "Cutting a JSON document at the limit leaves invalid JSON, so this resource is never truncated. Use the snapshot_locate, snapshot_read and snapshot_status tools instead \u2014 they read the manifest directly \u2014 or read manifest.json from the snapshot directory.";
12949
+ var PART_ADVICE = "A part cut at the limit is a fragment of a file, not the file. Use snapshot_locate to find the file inside this part that you need, then snapshot_read for a bounded window of it.";
12950
+ var REPORT_ADVICE = "A report cut at the limit would look complete and would not be. Read it from the snapshot directory instead: the file on disk is complete.";
12951
+ var PART_URI = /^snapshot:\/\/parts\/(\d+)$/;
12952
+ var REPORT_URIS = /* @__PURE__ */ new Map([
12953
+ ["snapshot://reports/audit", { file: "audit.md", title: "Secret audit and risk findings" }],
12954
+ ["snapshot://reports/tree", { file: "project-tree.md", title: "Project tree" }],
12955
+ ["snapshot://reports/navigation", { file: "navigation.md", title: "Navigation index" }]
12956
+ ]);
12957
+ function formatBytes2(bytes) {
12958
+ if (bytes < 1024) return `${bytes} B`;
12959
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;
12960
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
12961
+ }
12962
+ async function workspaceFor(context) {
12963
+ const root = resolveRoot(void 0, context);
12964
+ if (!root.ok) return { error: root.message };
12965
+ const opened = await openWorkspace(root.root);
12966
+ if (!opened.ok) return { error: opened.message };
12967
+ return opened.workspace;
12968
+ }
12969
+ function readFileIfPresent(file) {
12970
+ try {
12971
+ return fs14__namespace.readFileSync(file, "utf8");
12972
+ } catch {
12973
+ return null;
12974
+ }
12975
+ }
12976
+ function buildResourceProvider() {
12977
+ return {
12978
+ async list(context) {
12979
+ const resources = [
12980
+ {
12981
+ uri: "snapshot://manifest",
12982
+ name: "manifest",
12983
+ title: "Snapshot manifest",
12984
+ description: "Every file in the snapshot with its layer, kind, language, part and hash, plus the reason each excluded file was excluded. A manifest larger than 512 kB is refused with its size instead of truncated: cut JSON does not parse. Use snapshot_locate, snapshot_read and snapshot_status for a large repository.",
12985
+ mimeType: "application/json"
12986
+ },
12987
+ {
12988
+ uri: "snapshot://contract",
12989
+ name: "contract",
12990
+ title: "Tool contract",
12991
+ description: "The machine-readable description of the codebase-snapshot command line.",
12992
+ mimeType: "application/json"
12993
+ },
12994
+ {
12995
+ uri: "snapshot://skill",
12996
+ name: "skill",
12997
+ title: "Agent skill",
12998
+ description: "Usage guidance for an agent working with this tool.",
12999
+ mimeType: "text/markdown"
13000
+ }
13001
+ ];
13002
+ for (const [uri, report] of REPORT_URIS) {
13003
+ resources.push({
13004
+ uri,
13005
+ name: report.file.replace(/\.md$/, ""),
13006
+ title: report.title,
13007
+ description: `${report.title} from the most recent snapshot. A report larger than 512 kB is refused rather than truncated; read the file from the snapshot directory.`,
13008
+ mimeType: "text/markdown"
13009
+ });
13010
+ }
13011
+ const workspace = await workspaceFor(context);
13012
+ if ("error" in workspace) return resources;
13013
+ const read = readManifest3(workspace);
13014
+ if (!read.ok) return resources;
13015
+ for (const part of read.manifest.parts) {
13016
+ const readable = part.byteSize <= MAX_RESOURCE_BYTES;
13017
+ resources.push({
13018
+ uri: `snapshot://parts/${part.index}`,
13019
+ name: `part-${String(part.index).padStart(3, "0")}`,
13020
+ title: `Part ${part.index} (${part.fileCount} files, ${formatBytes2(part.byteSize)})`,
13021
+ description: `Part ${part.index} of ${read.manifest.parts.length}: ${part.fileCount} file(s), ${part.lines} line(s), ${formatBytes2(part.byteSize)}.` + (readable ? "" : ` Above the ${formatBytes2(MAX_RESOURCE_BYTES)} single-read limit, so this resource is refused rather than truncated; use snapshot_locate and snapshot_read.`),
13022
+ mimeType: "text/markdown"
13023
+ });
13024
+ }
13025
+ return resources;
13026
+ },
13027
+ templates() {
13028
+ return [
13029
+ {
13030
+ uriTemplate: "snapshot://parts/{index}",
13031
+ name: "part",
13032
+ title: "Snapshot part",
13033
+ description: "One budgeted part of the snapshot, by its 1-based index.",
13034
+ mimeType: "text/markdown"
13035
+ }
13036
+ ];
13037
+ },
13038
+ async read(uri, context) {
13039
+ if (uri === "snapshot://contract") {
13040
+ const contract = buildAgentContract();
13041
+ return {
13042
+ uri,
13043
+ mimeType: "application/json",
13044
+ text: ensureSingleRead(
13045
+ uri,
13046
+ JSON.stringify(contract, null, 2),
13047
+ "Run 'codebase-snapshot describe --format json' for the complete contract."
13048
+ )
13049
+ };
13050
+ }
13051
+ if (uri === "snapshot://skill") {
13052
+ return {
13053
+ uri,
13054
+ mimeType: "text/markdown",
13055
+ text: ensureSingleRead(
13056
+ uri,
13057
+ renderSkill(),
13058
+ "Print it with 'codebase-snapshot skill'."
13059
+ )
13060
+ };
13061
+ }
13062
+ const workspace = await workspaceFor(context);
13063
+ if ("error" in workspace) return null;
13064
+ const report = REPORT_URIS.get(uri);
13065
+ if (report) {
13066
+ const text2 = readFileIfPresent(
13067
+ path16__namespace.resolve(workspace.root, workspace.config.outDir, "reports", report.file)
13068
+ );
13069
+ if (text2 === null) return null;
13070
+ return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, REPORT_ADVICE) };
13071
+ }
13072
+ if (uri === "snapshot://manifest") {
13073
+ const read = readManifest3(workspace);
13074
+ if (!read.ok) return null;
13075
+ const text2 = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
13076
+ return { uri, mimeType: "application/json", text: ensureSingleRead(uri, text2, MANIFEST_ADVICE) };
13077
+ }
13078
+ const partMatch = PART_URI.exec(uri);
13079
+ if (partMatch) {
13080
+ const read = readManifest3(workspace);
13081
+ if (!read.ok) return null;
13082
+ const index = Number(partMatch[1]);
13083
+ const part = read.manifest.parts.find((candidate) => candidate.index === index);
13084
+ if (!part) return null;
13085
+ const partPath = partPathFor(workspace, part.filename);
13086
+ if (partPath === null) return null;
13087
+ let partBytes;
13088
+ try {
13089
+ partBytes = fs14__namespace.statSync(partPath).size;
13090
+ } catch {
13091
+ return null;
13092
+ }
13093
+ if (partBytes > MAX_RESOURCE_BYTES) refuseTooLarge(uri, partBytes, PART_ADVICE);
13094
+ const text2 = readFileIfPresent(partPath);
13095
+ if (text2 === null) return null;
13096
+ return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, PART_ADVICE) };
13097
+ }
13098
+ return null;
13099
+ }
13100
+ };
11964
13101
  }
11965
13102
 
11966
13103
  // src/mcp/schema.ts
@@ -12189,7 +13326,22 @@ function createMcpServer(options) {
12189
13326
  if (typeof uri !== "string") {
12190
13327
  return errorResponse(id, ERROR_CODES.invalidParams, 'resources/read requires a "uri" string.');
12191
13328
  }
12192
- const contents = await options.resources.read(uri, options.context);
13329
+ let contents;
13330
+ try {
13331
+ contents = await options.resources.read(uri, options.context);
13332
+ } catch (error) {
13333
+ if (error instanceof ResourceTooLargeError) {
13334
+ options.context.log(
13335
+ `mcp: refused ${error.uri} (${error.bytes} bytes, limit ${error.limit}); returning it would truncate it`
13336
+ );
13337
+ return errorResponse(id, ERROR_CODES.resourceTooLarge, error.message, {
13338
+ uri: error.uri,
13339
+ bytes: error.bytes,
13340
+ limit: error.limit
13341
+ });
13342
+ }
13343
+ throw error;
13344
+ }
12193
13345
  if (!contents) {
12194
13346
  return errorResponse(id, ERROR_CODES.invalidParams, `Unknown resource "${uri}".`);
12195
13347
  }
@@ -12270,7 +13422,11 @@ function createMcpServer(options) {
12270
13422
  }
12271
13423
  async function dispatch(message) {
12272
13424
  if (!isJsonObject(message)) {
12273
- return errorResponse(null, ERROR_CODES.parseError, "Message is not a JSON object.");
13425
+ return errorResponse(
13426
+ null,
13427
+ ERROR_CODES.invalidRequest,
13428
+ Array.isArray(message) ? "Batch requests are not supported: send one JSON-RPC message per line." : "Message is not a JSON object."
13429
+ );
12274
13430
  }
12275
13431
  const isRequest = Object.prototype.hasOwnProperty.call(message, "id");
12276
13432
  const method = message.method;
@@ -12322,146 +13478,6 @@ function createMcpServer(options) {
12322
13478
  }
12323
13479
  };
12324
13480
  }
12325
- var MAX_RESOURCE_BYTES = 512 * 1024;
12326
- var PART_URI = /^snapshot:\/\/parts\/(\d+)$/;
12327
- var REPORT_URIS = /* @__PURE__ */ new Map([
12328
- ["snapshot://reports/audit", { file: "audit.md", title: "Secret audit and risk findings" }],
12329
- ["snapshot://reports/tree", { file: "project-tree.md", title: "Project tree" }],
12330
- ["snapshot://reports/navigation", { file: "navigation.md", title: "Navigation index" }]
12331
- ]);
12332
- function formatBytes2(bytes) {
12333
- if (bytes < 1024) return `${bytes} B`;
12334
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;
12335
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
12336
- }
12337
- function truncationMarker(originalBytes) {
12338
- return `
12339
-
12340
- [truncated: ${formatBytes2(originalBytes)} total. Use the snapshot_read tool for a line window.]
12341
- `;
12342
- }
12343
- function capUtf8(text2, limit) {
12344
- const size2 = Buffer.byteLength(text2, "utf8");
12345
- if (size2 <= limit) return { text: text2, truncated: false };
12346
- const cut = Buffer.from(text2, "utf8").subarray(0, limit).toString("utf8").replace(/\uFFFD+$/, "");
12347
- return { text: `${cut}${truncationMarker(size2)}`, truncated: true };
12348
- }
12349
- async function workspaceFor(context) {
12350
- const root = resolveRoot(void 0, context);
12351
- if (!root.ok) return { error: root.message };
12352
- const opened = await openWorkspace(root.root);
12353
- if (!opened.ok) return { error: opened.message };
12354
- return opened.workspace;
12355
- }
12356
- function readFileIfPresent(file) {
12357
- try {
12358
- return fs14__namespace.readFileSync(file, "utf8");
12359
- } catch {
12360
- return null;
12361
- }
12362
- }
12363
- function buildResourceProvider() {
12364
- return {
12365
- async list(context) {
12366
- const resources = [
12367
- {
12368
- uri: "snapshot://manifest",
12369
- name: "manifest",
12370
- title: "Snapshot manifest",
12371
- description: "Every file in the snapshot with its layer, kind, language, part and hash, plus the reason each excluded file was excluded.",
12372
- mimeType: "application/json"
12373
- },
12374
- {
12375
- uri: "snapshot://contract",
12376
- name: "contract",
12377
- title: "Tool contract",
12378
- description: "The machine-readable description of the codebase-snapshot command line.",
12379
- mimeType: "application/json"
12380
- },
12381
- {
12382
- uri: "snapshot://skill",
12383
- name: "skill",
12384
- title: "Agent skill",
12385
- description: "Usage guidance for an agent working with this tool.",
12386
- mimeType: "text/markdown"
12387
- }
12388
- ];
12389
- for (const [uri, report] of REPORT_URIS) {
12390
- resources.push({
12391
- uri,
12392
- name: report.file.replace(/\.md$/, ""),
12393
- title: report.title,
12394
- description: `${report.title} from the most recent snapshot.`,
12395
- mimeType: "text/markdown"
12396
- });
12397
- }
12398
- const workspace = await workspaceFor(context);
12399
- if ("error" in workspace) return resources;
12400
- const read = readManifest3(workspace);
12401
- if (!read.ok) return resources;
12402
- for (const part of read.manifest.parts) {
12403
- resources.push({
12404
- uri: `snapshot://parts/${part.index}`,
12405
- name: `part-${String(part.index).padStart(3, "0")}`,
12406
- title: `Part ${part.index} (${part.fileCount} files, ${formatBytes2(part.byteSize)})`,
12407
- description: `Part ${part.index} of ${read.manifest.parts.length}: ${part.fileCount} file(s), ${part.lines} line(s), ${formatBytes2(part.byteSize)}.`,
12408
- mimeType: "text/markdown"
12409
- });
12410
- }
12411
- return resources;
12412
- },
12413
- templates() {
12414
- return [
12415
- {
12416
- uriTemplate: "snapshot://parts/{index}",
12417
- name: "part",
12418
- title: "Snapshot part",
12419
- description: "One budgeted part of the snapshot, by its 1-based index.",
12420
- mimeType: "text/markdown"
12421
- }
12422
- ];
12423
- },
12424
- async read(uri, context) {
12425
- if (uri === "snapshot://contract") {
12426
- const contract = buildAgentContract();
12427
- return { uri, mimeType: "application/json", text: JSON.stringify(contract, null, 2) };
12428
- }
12429
- if (uri === "snapshot://skill") {
12430
- return { uri, mimeType: "text/markdown", text: renderSkill() };
12431
- }
12432
- const workspace = await workspaceFor(context);
12433
- if ("error" in workspace) return null;
12434
- const report = REPORT_URIS.get(uri);
12435
- if (report) {
12436
- const text2 = readFileIfPresent(
12437
- path16__namespace.resolve(workspace.root, workspace.config.outDir, "reports", report.file)
12438
- );
12439
- if (text2 === null) return null;
12440
- return { uri, mimeType: "text/markdown", text: capUtf8(text2, MAX_RESOURCE_BYTES).text };
12441
- }
12442
- if (uri === "snapshot://manifest") {
12443
- const read = readManifest3(workspace);
12444
- if (!read.ok) return null;
12445
- const text2 = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
12446
- return { uri, mimeType: "application/json", text: capUtf8(text2, MAX_RESOURCE_BYTES).text };
12447
- }
12448
- const partMatch = PART_URI.exec(uri);
12449
- if (partMatch) {
12450
- const read = readManifest3(workspace);
12451
- if (!read.ok) return null;
12452
- const index = Number(partMatch[1]);
12453
- const part = read.manifest.parts.find((candidate) => candidate.index === index);
12454
- if (!part) return null;
12455
- const text2 = readFileIfPresent(
12456
- path16__namespace.resolve(workspace.root, workspace.config.outDir, "parts", part.filename)
12457
- );
12458
- if (text2 === null) return null;
12459
- return { uri, mimeType: "text/markdown", text: capUtf8(text2, MAX_RESOURCE_BYTES).text };
12460
- }
12461
- return null;
12462
- }
12463
- };
12464
- }
12465
13481
 
12466
13482
  // src/mcp/instructions.ts
12467
13483
  var SERVER_INSTRUCTIONS = [
@@ -12486,11 +13502,11 @@ var MAX_LINE_BYTES = 32 * 1024 * 1024;
12486
13502
  function createWriter(output) {
12487
13503
  return {
12488
13504
  write(value) {
12489
- return new Promise((resolve9, reject) => {
13505
+ return new Promise((resolve10, reject) => {
12490
13506
  output.write(`${JSON.stringify(value)}
12491
13507
  `, (error) => {
12492
13508
  if (error) reject(error);
12493
- else resolve9();
13509
+ else resolve10();
12494
13510
  });
12495
13511
  });
12496
13512
  }
@@ -12498,6 +13514,7 @@ function createWriter(output) {
12498
13514
  }
12499
13515
  function createLineReader(input, options) {
12500
13516
  let buffer = "";
13517
+ let bufferBytes = 0;
12501
13518
  let discarding = false;
12502
13519
  let discardedBytes = 0;
12503
13520
  const deliver = (line) => {
@@ -12510,6 +13527,13 @@ function createLineReader(input, options) {
12510
13527
  if (trimmed.trim().length === 0) return;
12511
13528
  options.onLine(trimmed);
12512
13529
  };
13530
+ const discardBuffered = () => {
13531
+ discarding = true;
13532
+ discardedBytes += bufferBytes;
13533
+ buffer = "";
13534
+ bufferBytes = 0;
13535
+ options.onOverflow?.(discardedBytes);
13536
+ };
12513
13537
  const drain = () => {
12514
13538
  let index = buffer.indexOf("\n");
12515
13539
  while (index >= 0) {
@@ -12517,42 +13541,57 @@ function createLineReader(input, options) {
12517
13541
  buffer = buffer.slice(index + 1);
12518
13542
  if (discarding) {
12519
13543
  deliver(line);
12520
- } else if (line.length > MAX_LINE_BYTES) {
12521
- options.onOverflow?.(line.length);
12522
13544
  } else {
12523
- deliver(line);
13545
+ const lineBytes = Buffer.byteLength(line, "utf8");
13546
+ if (lineBytes > MAX_LINE_BYTES) options.onOverflow?.(lineBytes);
13547
+ else deliver(line);
12524
13548
  }
12525
13549
  index = buffer.indexOf("\n");
12526
13550
  }
13551
+ bufferBytes = Buffer.byteLength(buffer, "utf8");
13552
+ if (!discarding && bufferBytes > MAX_LINE_BYTES) discardBuffered();
12527
13553
  };
12528
13554
  const onData = (chunk) => {
13555
+ const chunkBytes = Buffer.byteLength(chunk, "utf8");
12529
13556
  if (discarding) {
12530
13557
  const index = chunk.indexOf("\n");
12531
13558
  if (index < 0) {
12532
- discardedBytes += chunk.length;
13559
+ discardedBytes += chunkBytes;
12533
13560
  return;
12534
13561
  }
12535
13562
  buffer = chunk.slice(index + 1);
13563
+ bufferBytes = Buffer.byteLength(buffer, "utf8");
12536
13564
  deliver("");
12537
13565
  drain();
12538
13566
  return;
12539
13567
  }
12540
- buffer += chunk;
12541
- drain();
12542
- if (buffer.length > MAX_LINE_BYTES) {
13568
+ if (chunk.indexOf("\n") < 0 && bufferBytes + chunkBytes > MAX_LINE_BYTES) {
12543
13569
  discarding = true;
12544
- discardedBytes = buffer.length;
13570
+ discardedBytes = bufferBytes + chunkBytes;
12545
13571
  buffer = "";
13572
+ bufferBytes = 0;
12546
13573
  options.onOverflow?.(discardedBytes);
12547
13574
  return;
12548
13575
  }
13576
+ buffer += chunk;
13577
+ drain();
12549
13578
  };
12550
13579
  const onEnd = () => {
12551
- if (buffer.length > 0) {
12552
- const rest = buffer;
12553
- buffer = "";
12554
- deliver(rest);
13580
+ const rest = buffer;
13581
+ const restBytes = bufferBytes || Buffer.byteLength(rest, "utf8");
13582
+ buffer = "";
13583
+ bufferBytes = 0;
13584
+ if (rest.length === 0) return;
13585
+ if (discarding) {
13586
+ discarding = false;
13587
+ discardedBytes = 0;
13588
+ return;
13589
+ }
13590
+ if (restBytes > MAX_LINE_BYTES) {
13591
+ options.onOverflow?.(restBytes);
13592
+ return;
12555
13593
  }
13594
+ deliver(rest);
12556
13595
  };
12557
13596
  input.setEncoding("utf8");
12558
13597
  input.on("data", onData);
@@ -12603,8 +13642,8 @@ async function runStdioServer(options) {
12603
13642
  let inFlight = 0;
12604
13643
  let inputEnded = false;
12605
13644
  let resolveDone = () => void 0;
12606
- const finished = new Promise((resolve9) => {
12607
- resolveDone = resolve9;
13645
+ const finished = new Promise((resolve10) => {
13646
+ resolveDone = resolve10;
12608
13647
  });
12609
13648
  const finishIfIdle = () => {
12610
13649
  if (inputEnded && inFlight === 0) resolveDone(0);
@@ -12909,7 +13948,24 @@ function parseCliArgs(argv) {
12909
13948
  let args = [];
12910
13949
  const explicitMode = values.mode ? String(values.mode) : void 0;
12911
13950
  const firstPositional = positionals[0];
12912
- if (firstPositional !== void 0) {
13951
+ const modeCommand = explicitMode === void 0 ? void 0 : COMMAND_ALIASES.get(explicitMode);
13952
+ if (explicitMode !== void 0 && modeCommand === void 0) {
13953
+ throw new UsageError(
13954
+ `Unknown --mode "${explicitMode}". Expected one of: ${Array.from(COMMAND_ALIASES.keys()).join(", ")}.`
13955
+ );
13956
+ }
13957
+ if (modeCommand !== void 0) {
13958
+ command = modeCommand;
13959
+ if (firstPositional !== void 0) {
13960
+ const named = COMMAND_ALIASES.get(firstPositional);
13961
+ if (named !== void 0 && named !== modeCommand) {
13962
+ throw new UsageError(
13963
+ `--mode ${explicitMode} contradicts the command "${firstPositional}". Pass one or the other.`
13964
+ );
13965
+ }
13966
+ args = named !== void 0 ? positionals.slice(1) : positionals;
13967
+ }
13968
+ } else if (firstPositional !== void 0) {
12913
13969
  const resolved = COMMAND_ALIASES.get(firstPositional);
12914
13970
  if (!resolved) {
12915
13971
  throw new UsageError(
@@ -12918,27 +13974,6 @@ function parseCliArgs(argv) {
12918
13974
  }
12919
13975
  command = resolved;
12920
13976
  args = positionals.slice(1);
12921
- } else if (explicitMode !== void 0) {
12922
- const resolved = COMMAND_ALIASES.get(explicitMode);
12923
- if (!resolved) {
12924
- throw new UsageError(
12925
- `Unknown --mode "${explicitMode}". Expected one of: ${Array.from(COMMAND_ALIASES.keys()).join(", ")}.`
12926
- );
12927
- }
12928
- command = resolved;
12929
- }
12930
- if (explicitMode !== void 0) {
12931
- const resolvedMode = COMMAND_ALIASES.get(explicitMode);
12932
- if (!resolvedMode) {
12933
- throw new UsageError(
12934
- `Unknown --mode "${explicitMode}". Expected one of: ${Array.from(COMMAND_ALIASES.keys()).join(", ")}.`
12935
- );
12936
- }
12937
- if (firstPositional !== void 0 && resolvedMode !== command) {
12938
- throw new UsageError(
12939
- `--mode ${explicitMode} contradicts the command "${firstPositional}". Pass one or the other.`
12940
- );
12941
- }
12942
13977
  }
12943
13978
  const expectedArgs = COMMAND_ARITY[command];
12944
13979
  if (args.length !== expectedArgs) {
@@ -13128,7 +14163,9 @@ function nextStepHint(cwd, scriptsAddedNow) {
13128
14163
  let hasScript = scriptsAddedNow;
13129
14164
  if (!hasScript) {
13130
14165
  try {
13131
- const parsed = JSON.parse(fs14__namespace.readFileSync(path16__namespace.join(cwd, "package.json"), "utf8"));
14166
+ const parsed = JSON.parse(
14167
+ stripJsonComments2(fs14__namespace.readFileSync(path16__namespace.join(cwd, "package.json"), "utf8"))
14168
+ );
13132
14169
  hasScript = typeof parsed.scripts?.snapshot === "string";
13133
14170
  } catch {
13134
14171
  hasScript = false;
@@ -13229,19 +14266,19 @@ function installDependencies(cwd) {
13229
14266
  }
13230
14267
  return { manager: manager.name, command, ok: true, detail: seconds };
13231
14268
  }
13232
- async function captureStdout(fn) {
13233
- const original = process.stdout.write.bind(process.stdout);
13234
- let text2 = "";
13235
- process.stdout.write = ((chunk) => {
13236
- text2 += typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
13237
- return true;
13238
- });
13239
- try {
13240
- const code = await fn();
13241
- return { code, text: text2 };
13242
- } finally {
13243
- process.stdout.write = original;
14269
+ async function setupHookOutDir(invocation, init) {
14270
+ if (!init.reused || invocation.outDir !== void 0) return init.outDir;
14271
+ const loaded = await loadConfigFileDetailed(invocation.cwd);
14272
+ if (loaded.errors.length > 0) {
14273
+ throw new Error(
14274
+ `The config file could not be read: ${loaded.errors.join("; ")}. Fix it, or delete it to use the defaults.`
14275
+ );
13244
14276
  }
14277
+ return resolveConfig(loaded.config, {}, invocation.cwd).outDir;
14278
+ }
14279
+ async function captureStdout(fn) {
14280
+ const { value, text: text2 } = await runWithStdoutCapture(fn);
14281
+ return { code: value, text: text2 };
13245
14282
  }
13246
14283
  async function runSetupCommand(invocation, options = {}) {
13247
14284
  try {
@@ -13272,7 +14309,13 @@ async function runSetupCommand(invocation, options = {}) {
13272
14309
  reuseConfig: true,
13273
14310
  dryRun: invocation.dryRun
13274
14311
  });
13275
- const hook = invocation.installHook === true ? installPreCommitHook(invocation.cwd, init.outDir) : null;
14312
+ const keptConfigPath = init.reused ? findConfigFile(invocation.cwd) ?? init.configPath : init.configPath;
14313
+ const appliedPreset = init.reused ? null : init.preset;
14314
+ if (init.reused && invocation.preset !== void 0) {
14315
+ init.notes.push(
14316
+ `--preset ${invocation.preset} was not applied: the existing config is kept. Edit its preset setting, or run \`init --force\` to write a new one.`
14317
+ );
14318
+ }
13276
14319
  if (invocation.dryRun) {
13277
14320
  const manager = invocation.noInstall ? null : detectPackageManager(invocation.cwd).name;
13278
14321
  if (invocation.format === "json") {
@@ -13280,9 +14323,9 @@ async function runSetupCommand(invocation, options = {}) {
13280
14323
  `${JSON.stringify(
13281
14324
  {
13282
14325
  dryRun: true,
13283
- configPath: init.configPath,
14326
+ configPath: keptConfigPath,
13284
14327
  configReused: init.reused,
13285
- preset: init.preset,
14328
+ preset: appliedPreset,
13286
14329
  install: manager,
13287
14330
  configText: init.configText
13288
14331
  },
@@ -13295,7 +14338,7 @@ async function runSetupCommand(invocation, options = {}) {
13295
14338
  }
13296
14339
  info("\n\u{1F9EA} Dry run \u2014 setup would:");
13297
14340
  info(
13298
- ` 1. ${init.reused ? `keep ${path16__namespace.basename(init.configPath)}` : `write ${path16__namespace.basename(init.configPath)} (preset: ${init.preset})`}`
14341
+ ` 1. ${init.reused ? `keep ${path16__namespace.basename(keptConfigPath)}` : `write ${path16__namespace.basename(keptConfigPath)} (preset: ${appliedPreset})`}`
13299
14342
  );
13300
14343
  info(" 2. add the npm scripts, the devDependency and the .gitignore entries");
13301
14344
  if (manager !== null) info(` 3. install with ${manager}`);
@@ -13304,12 +14347,13 @@ async function runSetupCommand(invocation, options = {}) {
13304
14347
  info(init.configText);
13305
14348
  return 0;
13306
14349
  }
14350
+ const hook = invocation.installHook === true ? installPreCommitHook(invocation.cwd, await setupHookOutDir(invocation, init)) : null;
13307
14351
  if (invocation.format !== "json") {
13308
14352
  if (!interactive) info(`\u{1F680} Setup for: ${invocation.cwd}`);
13309
14353
  if (init.reused) {
13310
- info(`\u267B Keeping ${path16__namespace.basename(init.configPath)} (${presetSummary(init)})`);
14354
+ info(`\u267B Keeping ${path16__namespace.basename(keptConfigPath)}`);
13311
14355
  } else {
13312
- info(`\u2705 Created ${path16__namespace.basename(init.configPath)} (${presetSummary(init)})`);
14356
+ info(`\u2705 Created ${path16__namespace.basename(keptConfigPath)} (${presetSummary(init)})`);
13313
14357
  }
13314
14358
  if (init.scripts.length > 0) info(` Added npm scripts: ${init.scripts.join(", ")}`);
13315
14359
  if (init.dependency.added && init.dependency.range !== null) {
@@ -13319,6 +14363,9 @@ async function runSetupCommand(invocation, options = {}) {
13319
14363
  info(` Added to .gitignore: ${init.gitignoreEntries.join(", ")}`);
13320
14364
  }
13321
14365
  if (hook) for (const note of hook.notes) info(` ${note}`);
14366
+ if (init.reused && invocation.preset !== void 0) {
14367
+ info(` \u26A0 --preset ${invocation.preset} was not applied: the existing config is kept.`);
14368
+ }
13322
14369
  }
13323
14370
  let install = null;
13324
14371
  if (invocation.noInstall) {
@@ -13336,7 +14383,9 @@ async function runSetupCommand(invocation, options = {}) {
13336
14383
  if (invocation.includeSensitiveFiles === true) generateArgs.push("--include-sensitive-files");
13337
14384
  const budget = invocation.maxPartBytesRaw ?? invocation.maxPartBytes;
13338
14385
  if (budget !== void 0) generateArgs.push("--max-part-bytes", String(budget));
13339
- if ((invocation.skipArtifacts ?? []).length > 0) {
14386
+ if ((invocation.onlyArtifacts ?? []).length > 0) {
14387
+ generateArgs.push("--only-artifacts", (invocation.onlyArtifacts ?? []).join(","));
14388
+ } else if ((invocation.skipArtifacts ?? []).length > 0) {
13340
14389
  generateArgs.push("--skip-artifacts", (invocation.skipArtifacts ?? []).join(","));
13341
14390
  }
13342
14391
  if (invocation.includeMonolith === true) generateArgs.push("--include-monolith");
@@ -13356,31 +14405,33 @@ async function runSetupCommand(invocation, options = {}) {
13356
14405
  if (invocation.watch) generateArgs.push("--watch");
13357
14406
  if (invocation.format === "json") {
13358
14407
  const generated = await captureStdout(() => main(generateArgs));
13359
- let manifest = null;
14408
+ let parsed = null;
13360
14409
  try {
13361
- manifest = JSON.parse(generated.text);
14410
+ parsed = JSON.parse(generated.text);
13362
14411
  } catch {
13363
- manifest = null;
14412
+ parsed = null;
14413
+ }
14414
+ const setup = {
14415
+ configPath: keptConfigPath,
14416
+ configReused: init.reused,
14417
+ preset: appliedPreset,
14418
+ scripts: init.scripts,
14419
+ dependency: init.dependency,
14420
+ gitignoreEntries: init.gitignoreEntries,
14421
+ install,
14422
+ notes: init.notes,
14423
+ hook
14424
+ };
14425
+ if (generated.code !== 0) {
14426
+ const inner = parsed && typeof parsed.error === "object" && parsed.error !== null ? parsed.error : { message: "Snapshot generation failed during setup.", exitCode: generated.code };
14427
+ process.stdout.write(
14428
+ `${JSON.stringify({ error: inner, setup, manifest: null }, null, 2)}
14429
+ `
14430
+ );
14431
+ return generated.code;
13364
14432
  }
13365
14433
  process.stdout.write(
13366
- `${JSON.stringify(
13367
- {
13368
- setup: {
13369
- configPath: init.configPath,
13370
- configReused: init.reused,
13371
- preset: init.preset,
13372
- scripts: init.scripts,
13373
- dependency: init.dependency,
13374
- gitignoreEntries: init.gitignoreEntries,
13375
- install,
13376
- notes: init.notes,
13377
- hook
13378
- },
13379
- manifest
13380
- },
13381
- null,
13382
- 2
13383
- )}
14434
+ `${JSON.stringify({ setup, manifest: parsed }, null, 2)}
13384
14435
  `
13385
14436
  );
13386
14437
  return generated.code;
@@ -13496,7 +14547,19 @@ function requestsJsonFormat(argv) {
13496
14547
  }
13497
14548
  return format === "json";
13498
14549
  }
14550
+ var closedStdoutGuarded = false;
14551
+ function guardClosedStdout() {
14552
+ if (closedStdoutGuarded) return;
14553
+ closedStdoutGuarded = true;
14554
+ process.stdout.on("error", (error) => {
14555
+ if (error.code === "EPIPE" || error.code === "ECONNRESET") {
14556
+ process.exit(0);
14557
+ }
14558
+ throw error;
14559
+ });
14560
+ }
13499
14561
  async function main(argv = process.argv.slice(2)) {
14562
+ guardClosedStdout();
13500
14563
  const pending = process.stdout.isTTY === true && shouldCheck(argv, process.env) ? checkForUpdate({ current: GENERATOR_VERSION, cacheFile: cacheFilePath() }) : null;
13501
14564
  const code = await runCommand(argv);
13502
14565
  if (pending) {
@@ -13552,51 +14615,49 @@ ${USAGE}
13552
14615
  const skipConfig = invocation.noConfig || invocation.command === "diff";
13553
14616
  const loaded = skipConfig ? { config: null, warnings: [], errors: [], file: null } : await loadConfigFileDetailed(invocation.cwd);
13554
14617
  if (invocation.noConfig) info("\u2699 --no-config: using built-in defaults, config file ignored");
13555
- for (const warning of loaded.warnings) warn(`\u26A0 Config: ${warning}`);
13556
14618
  if (loaded.errors.length > 0) {
13557
- warn("\u274C The config file could not be read. Fix it, or delete it to use the defaults.");
13558
- return 1;
14619
+ return fail(
14620
+ invocation.format,
14621
+ `The config file could not be read: ${loaded.errors.join("; ")}. Fix it, or delete it to use the defaults.`
14622
+ );
13559
14623
  }
14624
+ for (const warning of loaded.warnings) warn(`\u26A0 Config: ${warning}`);
13560
14625
  if (loaded.file) info(`\u2699 Using config ${path16__namespace.relative(process.cwd(), loaded.file) || loaded.file}`);
13561
- const resolved = resolveConfig(
13562
- loaded.config,
13563
- {
13564
- mode: invocation.command,
13565
- format: invocation.format,
13566
- dryRun: invocation.dryRun,
13567
- cwd: invocation.cwd,
13568
- outDir: invocation.outDir,
13569
- includeMonolith: invocation.includeMonolith,
13570
- includeSensitiveFiles: invocation.includeSensitiveFiles,
13571
- maxPartBytes: invocation.maxPartBytes,
13572
- maxPartTokens: invocation.maxPartTokens,
13573
- largeFileBytes: invocation.largeFileBytes,
13574
- maxMonolithBytes: invocation.maxMonolithBytes,
13575
- skipArtifacts: invocation.skipArtifacts,
13576
- discovery: invocation.discovery,
13577
- changedSince: invocation.changedSince,
13578
- staged: invocation.staged,
13579
- withDependents: invocation.withDependents,
13580
- skeleton: invocation.skeleton,
13581
- sarif: invocation.sarif
13582
- },
13583
- invocation.cwd
13584
- );
14626
+ let resolved;
14627
+ try {
14628
+ resolved = resolveConfig(
14629
+ loaded.config,
14630
+ {
14631
+ mode: invocation.command,
14632
+ format: invocation.format,
14633
+ dryRun: invocation.dryRun,
14634
+ cwd: invocation.cwd,
14635
+ outDir: invocation.outDir,
14636
+ includeMonolith: invocation.includeMonolith,
14637
+ includeSensitiveFiles: invocation.includeSensitiveFiles,
14638
+ maxPartBytes: invocation.maxPartBytes,
14639
+ maxPartTokens: invocation.maxPartTokens,
14640
+ largeFileBytes: invocation.largeFileBytes,
14641
+ maxMonolithBytes: invocation.maxMonolithBytes,
14642
+ skipArtifacts: invocation.skipArtifacts,
14643
+ // `--only-artifacts` is forwarded as itself, not only as the derived suppression list:
14644
+ // suppression cannot switch an artifact *on*, so a config that had turned one of the
14645
+ // requested artifacts off left the run with nothing to write.
14646
+ onlyArtifacts: invocation.onlyArtifacts,
14647
+ discovery: invocation.discovery,
14648
+ changedSince: invocation.changedSince,
14649
+ staged: invocation.staged,
14650
+ withDependents: invocation.withDependents,
14651
+ skeleton: invocation.skeleton,
14652
+ sarif: invocation.sarif
14653
+ },
14654
+ invocation.cwd
14655
+ );
14656
+ } catch (err) {
14657
+ return fail(invocation.format, err.message);
14658
+ }
13585
14659
  if (invocation.command === "validate") {
13586
14660
  const result = validateSnapshot(resolved);
13587
- if (result.valid) {
13588
- const manifestPath = path16__namespace.resolve(resolved.cwd, resolved.outDir, "manifest.json");
13589
- let manifest;
13590
- try {
13591
- manifest = JSON.parse(fs14__namespace.readFileSync(manifestPath, "utf8"));
13592
- } catch {
13593
- manifest = void 0;
13594
- }
13595
- const shapeError = manifest === void 0 ? null : describeManifestShapeProblem(manifest);
13596
- if (shapeError) {
13597
- return fail(invocation.format, `${manifestPath} is not a snapshot manifest: ${shapeError}`);
13598
- }
13599
- }
13600
14661
  emit(invocation.format, result, () => renderValidateText(result));
13601
14662
  return result.valid ? 0 : 1;
13602
14663
  }
@@ -13791,10 +14852,13 @@ function isGeneratedWatchPath(candidate, paths) {
13791
14852
  const outDir = comparablePath(path16__namespace.resolve(paths.cwd, paths.outDir));
13792
14853
  const tmpDir = comparablePath(path16__namespace.resolve(paths.cwd, paths.tmpDir));
13793
14854
  if (isSameOrInside(outDir, absolute) || isSameOrInside(tmpDir, absolute)) return true;
13794
- const parent = path16__namespace.dirname(absolute);
13795
- if (parent === path16__namespace.dirname(outDir) && path16__namespace.basename(absolute).startsWith(`${path16__namespace.basename(outDir)}.backup-`)) {
13796
- return true;
13797
- }
14855
+ const offsets = [path16__namespace.basename(outDir), path16__namespace.basename(tmpDir)].filter((name) => name.length > 0);
14856
+ const leftover = absolute.split(/[\\/]+/).some(
14857
+ (segment) => offsets.some(
14858
+ (name) => segment.startsWith(`${name}.backup-`) || segment.startsWith(`${name}.partial-`)
14859
+ )
14860
+ );
14861
+ if (leftover) return true;
13798
14862
  return absolute.split(/[\\/]+/).some((segment) => VCS_SEGMENTS.has(segment));
13799
14863
  }
13800
14864
  function decideWatchEvent(state, event, paths) {
@@ -13869,6 +14933,7 @@ async function runWatchLoop(invocation, resolved, options) {
13869
14933
  largeFileBytes: invocation.largeFileBytes,
13870
14934
  maxMonolithBytes: invocation.maxMonolithBytes,
13871
14935
  skipArtifacts: invocation.skipArtifacts,
14936
+ onlyArtifacts: invocation.onlyArtifacts,
13872
14937
  discovery: invocation.discovery,
13873
14938
  changedSince: invocation.changedSince,
13874
14939
  staged: invocation.staged,
@@ -13925,12 +14990,12 @@ async function runWatchLoop(invocation, resolved, options) {
13925
14990
  info(`\u26A0 Watch error: ${err.message}`);
13926
14991
  info(" The watcher may have missed changes. Restart with Ctrl+C if they stop arriving.");
13927
14992
  });
13928
- await new Promise((resolve9) => {
14993
+ await new Promise((resolve10) => {
13929
14994
  const stop = () => {
13930
14995
  stopped = true;
13931
14996
  if (timer) clearTimeout(timer);
13932
14997
  watcher.close();
13933
- resolve9();
14998
+ resolve10();
13934
14999
  };
13935
15000
  process.once("SIGINT", stop);
13936
15001
  process.once("SIGTERM", stop);