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/bin.js CHANGED
@@ -180,6 +180,14 @@ function scanWorkspacePackages(cwd, patterns) {
180
180
  }
181
181
  return { files, dependencies };
182
182
  }
183
+ var SNAPSHOT_MARKER = ".codebase-snapshot";
184
+ function isToolOwnedDirectory(dir) {
185
+ try {
186
+ return fs.statSync(dir).isDirectory() && fs.existsSync(path.join(dir, SNAPSHOT_MARKER));
187
+ } catch {
188
+ return false;
189
+ }
190
+ }
183
191
  function countMarkdownFiles(cwd) {
184
192
  let count = 0;
185
193
  let directoriesSeen = 0;
@@ -201,7 +209,9 @@ function countMarkdownFiles(cwd) {
201
209
  }
202
210
  if (!entry.isDirectory() || current.depth >= 2) continue;
203
211
  if (entry.name.startsWith(".") || SKIPPED_WALK_DIRS.has(entry.name)) continue;
204
- queue.push({ dir: path.join(current.dir, entry.name), depth: current.depth + 1 });
212
+ const child = path.join(current.dir, entry.name);
213
+ if (isToolOwnedDirectory(child)) continue;
214
+ queue.push({ dir: child, depth: current.depth + 1 });
205
215
  }
206
216
  }
207
217
  return count;
@@ -1070,18 +1080,24 @@ function detectPreset(cwd, forced) {
1070
1080
  }
1071
1081
 
1072
1082
  // src/security/patterns.ts
1073
- 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)";
1074
- var WEAK_CREDENTIAL_NAME = "(?:pass|id[_-]?token|credentials?)";
1083
+ 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)";
1084
+ var WEAK_CREDENTIAL_NAME = "(?:pass|credentials?)";
1075
1085
  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)";
1076
1086
  var UNQUOTED_MIN_LENGTH = 2;
1077
1087
  var PROSE_CONTINUATION = String.raw`(?!\s+[a-z])`;
1078
- 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;
1079
- 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;
1088
+ var UNQUOTED_VALUE_CHARS = String.raw`A-Za-z0-9_+=/%:~$!@#^*?-`;
1089
+ var UNQUOTED_VALUE_END = String.raw`[A-Za-z0-9_+=/%:.~$!@#^*?-]`;
1090
+ var UNQUOTED_VALUE_START = String.raw`[$!@#%^&*~+]`;
1091
+ var UNQUOTED_LITERAL = String.raw`(` + // one capture, whichever branch matched: valueGroup is 1
1092
+ 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;
1093
+ 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;
1080
1094
  var ASSIGN = String.raw`(?<![=!<>])[:=](?!=)`;
1081
1095
  var NOT_AFTER_QUOTE = String.raw`(?<!["'])`;
1082
1096
  var NOT_A_NAMESPACED_IDENTIFIER = String.raw`(?![a-z][a-z0-9]*(?:\.[a-z][a-z0-9-]*)+/)`;
1097
+ var QUOTED_CREDENTIAL_KEY = `["'](?!id[-_]token["'])[A-Za-z0-9_$-]{0,64}${STRONG_CREDENTIAL_NAME}["']`;
1083
1098
  var QUOTED_VALUE = String.raw`((?:[^"'\\\n]|\\\\["'](?=[A-Za-z0-9_])|\\.){1,512})`;
1084
1099
  var UNQUOTED_STRONG_NAME = `(?<!id[-_])${STRONG_CREDENTIAL_NAME}`;
1100
+ var CREDENTIAL_KEY_TAIL = new RegExp(`(?:${STRONG_CREDENTIAL_NAME})$`, "i");
1085
1101
  var DEFAULT_SECRET_PATTERNS = [
1086
1102
  {
1087
1103
  rule: "private-key-header",
@@ -1148,13 +1164,28 @@ var DEFAULT_SECRET_PATTERNS = [
1148
1164
  pattern: /xox[baprsdc]-[0-9A-Za-z-]{10,250}/
1149
1165
  },
1150
1166
  {
1151
- // Prefix-only vendors. Each prefix below is documented, globally unique and
1152
- // cannot collide with an ordinary identifier, which is what makes a bare
1153
- // prefix rule cheap and safe: `glpat-` (GitLab), `hvs.`/`s.` (Vault service
1154
- // and batch tokens), `whsec_` (Stripe webhook secret), `dckr_pat_` (Docker
1155
- // Hub), `hf_` (HuggingFace), `ya29.` (Google OAuth access token).
1167
+ // Known vendor token shapes: prefix-unique tokens, plus the few fixed layouts whose format is
1168
+ // documented and cannot collide with an ordinary identifier.
1169
+ //
1170
+ // Each prefix below is globally unique, which is what makes a bare prefix rule cheap and
1171
+ // safe: `glpat-` (GitLab), `hvs.`/`s.` (Vault service and batch tokens), `whsec_`
1172
+ // (Stripe webhook secret), `dckr_pat_` (Docker Hub), `hf_` (HuggingFace), `ya29.`
1173
+ // (Google OAuth access token), `shpat_`/`shpca_`/`shppa_`/`shpss_` (Shopify admin and
1174
+ // storefront tokens).
1175
+ //
1176
+ // The fixed shapes have no prefix to anchor on and were each emitted in clear:
1177
+ // - Telegram bot token: `<8-10 digit bot id>:<35-character secret>`.
1178
+ // - Discord bot token: `<base64 user id>.<6-8 char hmac>.<25-45 char signature>`; demanding
1179
+ // all three segments keeps ordinary dotted identifiers out.
1180
+ // - Azure DevOps personal access token: exactly 52 alphanumerics that always mix case and
1181
+ // digits, so a hash, a UUID or a plain identifier — all single-case or a different length —
1182
+ // does not match.
1183
+ //
1184
+ // The rule name still says "prefix" because that is how the catalogue began; it is the
1185
+ // vendor-token rule, and growing a new named rule per vendor would make the documented
1186
+ // pattern count drift on every release.
1156
1187
  rule: "known-vendor-token-prefix",
1157
- 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})/
1188
+ 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])/
1158
1189
  },
1159
1190
  {
1160
1191
  rule: "slack-webhook-url",
@@ -1209,39 +1240,52 @@ var DEFAULT_SECRET_PATTERNS = [
1209
1240
  // (including one invented tomorrow) is covered, provided the `//` is followed
1210
1241
  // immediately by the userinfo: `// see the docs` and a bare reminder comment
1211
1242
  // never match, because a space or the comment wording breaks the shape.
1243
+ //
1244
+ // Three shapes joined it, all the same fact — a URL carries the credential in plain sight —
1245
+ // and each cost a leak while it was elsewhere:
1246
+ // - The user part may be **empty**: Redis, SMTP, AMQP and FTP URLs routinely omit the username
1247
+ // (`redis://:password@host`), and a `{1,128}` prefix made every one of those invisible.
1248
+ // - `curl -u user:password` sends the same userinfo without a scheme; the lookbehind
1249
+ // consumes the flag so the match is the credential alone.
1250
+ // - An Azure SAS link authenticates with `?sig=`; the signature *is* the credential.
1212
1251
  rule: "uri-credentials",
1213
- pattern: /\/\/[^\s:/@"'`;()<>,]{1,128}:[^\s:/@"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/
1252
+ pattern: /\/\/[^\s:/@"'`;()<>,]{0,128}:[^\s:/@"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}|(?<=(?:^|[\s;|&(])--?u(?:ser)?[ \t=]{1,8})["']?[^\s"']{1,300}:[^\s"']{0,256}["']?|(?<=[?&])sig=[A-Za-z0-9%._=~-]{20,300}(?![A-Za-z0-9%._=~-])/
1214
1253
  },
1215
1254
  {
1216
1255
  // The host tail stops at quotes, `;`, `)`, `<`, `>` and `,`: an unbounded
1217
1256
  // `[^\s/]` used to swallow the closing quote and the statement separator of
1218
1257
  // the string the URL was written in.
1258
+ // The user part may be empty here too: `redis://:password@host` and `amqp://:password@host`
1259
+ // are how those services are configured when the account is the server's default.
1219
1260
  rule: "database-uri-credentials",
1220
- 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}/
1261
+ 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}/
1221
1262
  },
1222
1263
  {
1264
+ // An empty user part is valid userinfo (`smtp://:password@host`: the account is the server's
1265
+ // default), and it used to be the one shape every scheme-listed rule refused.
1223
1266
  rule: "basic-auth-url",
1224
- pattern: /(?:https?|ftp|sftp|ssh|git|smtp|smtps|ldap|ldaps):\/\/[^\s:@/"'`;()<>,]{1,128}:[^\s@/"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/i
1267
+ pattern: /(?:https?|ftp|sftp|ssh|git|smtp|smtps|ldap|ldaps):\/\/[^\s:@/"'`;()<>,]{0,128}:[^\s@/"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/i
1225
1268
  },
1226
1269
  {
1227
1270
  // Quoted credentials in any common key spelling. The value may be as short
1228
1271
  // as one character: `password: "hunter2"` is a credential whatever its
1229
1272
  // entropy, and a length floor was exactly how it survived into `parts`.
1230
1273
  //
1231
- // The key is either bare (`dbPassword:`) or wholly quoted (`"dbPassword":`).
1274
+ // The key is bare (`dbPassword:`), wholly quoted (`"password":`), or quoted with a
1275
+ // camelCase prefix (`"dbPassword":`) — the last one is {@link QUOTED_CREDENTIAL_KEY}.
1232
1276
  // There is deliberately no optional quote *before* the separator: that let a
1233
1277
  // previous string's closing quote stand in for the key's, so
1234
1278
  // ``${pass ? " PASS" : " FAIL"}`` had `" FAIL"` masked as if `PASS` were
1235
1279
  // the key name.
1236
1280
  rule: "credential-assignment",
1237
1281
  pattern: new RegExp(
1238
- `(?:["']${STRONG_CREDENTIAL_NAME}["']|${NOT_AFTER_QUOTE}${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_NAMESPACED_IDENTIFIER}(["'\`])${QUOTED_VALUE}\\1`,
1282
+ `(?:${QUOTED_CREDENTIAL_KEY}|${NOT_AFTER_QUOTE}(?<!id[-_])${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_NAMESPACED_IDENTIFIER}(["'\`])${QUOTED_VALUE}\\1`,
1239
1283
  "i"
1240
1284
  ),
1241
1285
  valueGroup: 2
1242
1286
  },
1243
1287
  {
1244
- // `pass`, `id-token` and `credentials` are ambiguous on their own, so they
1288
+ // `pass` and `credentials` are ambiguous on their own, so they
1245
1289
  // are accepted only against a quoted value long enough to be a credential.
1246
1290
  rule: "credential-assignment-weak",
1247
1291
  pattern: new RegExp(
@@ -1254,9 +1298,40 @@ var DEFAULT_SECRET_PATTERNS = [
1254
1298
  // The unquoted twin for YAML, docker-compose and `.env`: those formats never
1255
1299
  // quote their values, so the rules above cannot see them. `valueGroup` keeps
1256
1300
  // `POSTGRES_PASSWORD:` in the output.
1301
+ //
1302
+ // This is the one unquoted rule without `NOT_AFTER_QUOTE`, and the lookbehind is a
1303
+ // string-literal guard rather than a precision rule: a credential assignment *inside* a
1304
+ // literal — `const dsn = "password=hunter2;host=db"`, `curl -d "password=hunter2"` — was
1305
+ // rejected before it could be considered, and a DSN is a credential in a string. What made the
1306
+ // lookbehind redundant is the shape of `UNQUOTED_LITERAL`: a value has to start with a word
1307
+ // character, so `["awsSecret:", "apiKey:"]` — the list of key names the lookbehind was added
1308
+ // for — cannot match here anyway. `redact.ts` still refuses a match whose separator is inside
1309
+ // the literal, which is the case that list actually is.
1310
+ //
1311
+ // The name may also be a *quoted* key: YAML allows `"dbPassword": hunter2`, and JSON cannot
1312
+ // spell a key any other way, so the same {@link QUOTED_CREDENTIAL_KEY} fragment is used here.
1313
+ // Without it a quoted key whose value was not quoted emitted the value in clear.
1314
+ //
1315
+ // A colon-form assignment in a data file masks the whole remainder of the value to
1316
+ // end-of-line, whatever punctuation it holds. A strong credential name is the evidence that
1317
+ // the thing after it is a value, and the character classes above cannot cover every symbol a
1318
+ // password may contain — `password: pa&ss` used to stop at the `&`. This branch is a
1319
+ // lookbehind, so the match is the value alone, and `redact.ts` only applies it to a data or
1320
+ // shell file: in source code the same shape is an expression and stays untouched, and an `URL`
1321
+ // query string keeps its `&` separators because they are not a colon form.
1322
+ //
1323
+ // The `KEY=value` twin does the same for the `=` form, which INI, .properties and shell files
1324
+ // use: with a credential key the whole value is masked whatever symbols it contains
1325
+ // (`password=pa&ss`, `token=a<b`, `client_secret=x|y`). The value is bounded by whitespace
1326
+ // (end of line, or the space before a `# comment`), not by a symbol class — `envpass!@#$%^&*()` used
1327
+ // to stop before the parenthesis and leave the tail in clear. The lookbehind matches the value
1328
+ // alone and `redact.ts` decides, from the file and from the key, whether the line is an
1329
+ // assignment (it must be a data/shell file, the key must end in a credential name, and a URL
1330
+ // query parameter or `$VARIABLE` reference is not an assignment).
1257
1331
  rule: "credential-assignment-unquoted",
1258
1332
  pattern: new RegExp(
1259
- `${NOT_AFTER_QUOTE}${UNQUOTED_STRONG_NAME}\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_LITERAL_VALUE}${UNQUOTED_LITERAL}`,
1333
+ `(?:${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
1334
+ #]{1,300}`,
1260
1335
  "i"
1261
1336
  ),
1262
1337
  valueGroup: 1
@@ -1279,8 +1354,14 @@ var DEFAULT_SECRET_PATTERNS = [
1279
1354
  // needs no `valueGroup`. A lone `Bearer`/`Basic`, and a word after it that
1280
1355
  // cannot be a credential (`Bearer authentication`), stay readable: the value
1281
1356
  // must contain a digit, be at least 32 chars, or carry base64 `=` padding.
1357
+ //
1358
+ // A fourth shape was leaking: `Basic dXNlcjpwYXNz` is the base64 of `user:pass` — 12
1359
+ // characters, no digit, no padding — and the three tests above all said "not a
1360
+ // credential", so it reached the parts in clear. Mixed case is the discriminator: a base64
1361
+ // rendering of textual userinfo mixes cases, while the prose the earlier rules were
1362
+ // protecting (`Bearer authentication`) is a lowercase word.
1282
1363
  rule: "authorization-header",
1283
- 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_.+/=-])/
1364
+ pattern: /(?<=(?:Bearer|Basic)\s{1,8})(?:[A-Za-z0-9_.+/-]{0,31}[0-9][A-Za-z0-9_.+/-]{0,1024}|[A-Za-z0-9_.+/-]{32,1024}|[A-Za-z0-9_.+/-]{8,1024}={1,2}|(?=[A-Za-z0-9_.+/-]{0,1023}[A-Z])(?=[A-Za-z0-9_.+/-]{0,1023}[a-z])[A-Za-z0-9_.+/-]{12,1024})(?![A-Za-z0-9_.+/=-])/
1284
1365
  },
1285
1366
  {
1286
1367
  // Broader names than before (`apiKey`, `clientSecret`, `privateKey` were
@@ -1291,6 +1372,27 @@ var DEFAULT_SECRET_PATTERNS = [
1291
1372
  pattern: /(?<!["'])(?:api[_-]?key|secret[_-]?key|auth[_-]?token|client[_-]?secret|access[_-]?token|refresh[_-]?token|private[_-]?key|password|passwd|pwd)["']?\s*(?<![=!<>])[:=](?!=)\s*["']([^"'\s]{8,256})["']/i,
1292
1373
  valueGroup: 1
1293
1374
  },
1375
+ {
1376
+ // `${VAR:-fallback}` — a default value in a shell script, a `.env`, docker-compose or a
1377
+ // GitHub Actions workflow.
1378
+ //
1379
+ // This shape defeated every rule above it, and each refusal was individually reasonable:
1380
+ // the quoted rules need a quote after the separator, and the unquoted ones need the value to
1381
+ // begin with a word character — a fallback begins with `$`. So
1382
+ // `POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-MyProdPassword123!}` was emitted whole, `.env` files
1383
+ // and compose files included, which is where that idiom is the norm.
1384
+ //
1385
+ // The **fallback** is what gets masked, not the whole expansion: the variable name is the
1386
+ // readable context, exactly as `POSTGRES_PASSWORD:` is kept by the rule above. A single
1387
+ // interpolation with no operator (`${DB_PASSWORD}`) still does not match — there is nothing
1388
+ // between the braces to mask, and `isTemplateInterpolation` keeps such a value readable.
1389
+ rule: "interpolation-fallback-secret",
1390
+ pattern: new RegExp(
1391
+ `(?:["']${STRONG_CREDENTIAL_NAME}["']|${NOT_AFTER_QUOTE}${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}["'\`]?\\$\\{[A-Za-z_][A-Za-z0-9_]*:?[-=?+]([^}"'\`\\r\\n]{2,512})\\}["'\`]?`,
1392
+ "i"
1393
+ ),
1394
+ valueGroup: 1
1395
+ },
1294
1396
  {
1295
1397
  // Covers `.env` / shell assignment syntax, which never quotes its values and
1296
1398
  // was therefore invisible to the rule above. Anchored to the line start and
@@ -1318,8 +1420,8 @@ var DEFAULT_SECRET_PATTERNS = [
1318
1420
  valueGroup: 1
1319
1421
  }
1320
1422
  ];
1321
- var PEM_BLOCK_PATTERN = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----/g;
1322
- var PEM_UNTERMINATED_PATTERN = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----(?:\r?\n[A-Za-z0-9+/=]{4,}[ A-Za-z0-9+/=]*)+/g;
1423
+ var PEM_BLOCK_PATTERN = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----(?:(?!-----BEGIN)[\s\S])*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----/g;
1424
+ 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;
1323
1425
 
1324
1426
  // src/security/redact.ts
1325
1427
  var REDACTION_MARKER = "[REDACTED: potential secret-like value omitted from snapshot]";
@@ -1413,6 +1515,20 @@ function toGlobal(rule) {
1413
1515
  return new RegExp(rule.pattern.source, [...flags].join(""));
1414
1516
  }
1415
1517
  var LINE_BREAK = /(\r\n|\n|\r)/;
1518
+ var LINE_TERMINATOR = /\r\n|\n|\r/g;
1519
+ var COMPILED_RULES = /* @__PURE__ */ new WeakMap();
1520
+ function compiledRuleFor(rule) {
1521
+ let compiled = COMPILED_RULES.get(rule);
1522
+ if (compiled === void 0) {
1523
+ compiled = {
1524
+ rule: rule.rule,
1525
+ pattern: toGlobal(rule),
1526
+ ...rule.valueGroup === void 0 ? {} : { valueGroup: rule.valueGroup }
1527
+ };
1528
+ COMPILED_RULES.set(rule, compiled);
1529
+ }
1530
+ return compiled;
1531
+ }
1416
1532
  function scanAndRedactSecrets(content, rules, filePath) {
1417
1533
  const findings = [];
1418
1534
  let redacted = content;
@@ -1424,18 +1540,15 @@ function scanAndRedactSecrets(content, rules, filePath) {
1424
1540
  blockPattern.lastIndex += 1;
1425
1541
  continue;
1426
1542
  }
1427
- const line = redacted.slice(0, match.index).split("\n").length;
1428
- const newlines = (match[0].match(/\n/g) ?? []).length;
1543
+ const before = redacted.slice(0, match.index);
1544
+ const line = (before.match(LINE_TERMINATOR) ?? []).length + 1;
1545
+ const newlines = (match[0].match(LINE_TERMINATOR) ?? []).length;
1429
1546
  findings.push({ rules: ["private-key-block"], line, path: filePath });
1430
- redacted = redacted.slice(0, match.index) + PEM_REDACTION_MARKER + "\n".repeat(newlines) + redacted.slice(match.index + match[0].length);
1547
+ redacted = before + PEM_REDACTION_MARKER + "\n".repeat(newlines) + redacted.slice(match.index + match[0].length);
1431
1548
  blockPattern.lastIndex = match.index + PEM_REDACTION_MARKER.length + newlines;
1432
1549
  }
1433
1550
  }
1434
- const compiled = rules.map((rule) => ({
1435
- rule: rule.rule,
1436
- pattern: toGlobal(rule),
1437
- ...rule.valueGroup === void 0 ? {} : { valueGroup: rule.valueGroup }
1438
- }));
1551
+ const compiled = rules.map(compiledRuleFor);
1439
1552
  const segments = redacted.split(LINE_BREAK);
1440
1553
  let lineNumber = 1;
1441
1554
  for (let index = 0; index < segments.length; index += 2) {
@@ -1453,11 +1566,39 @@ function scanAndRedactSecrets(content, rules, filePath) {
1453
1566
  }
1454
1567
  const group = valueGroup === void 0 ? void 0 : match.indices?.[valueGroup];
1455
1568
  if (group && isSelfNamingConstant(line, group[0], group[1])) continue;
1456
- if (valueGroup !== void 0 && startsInsideStringLiteral(line, match.index)) continue;
1457
- if (group && isUnquotedValue(line, group[0]) && isDeclaredBinding(line, match.index)) {
1569
+ if (valueGroup !== void 0 && startsInsideStringLiteral(line, match.index, group?.[0])) {
1570
+ continue;
1571
+ }
1572
+ if (group && isUnquotedValue(line, group[0]) && isDeclaredBinding(line, match.index, filePath)) {
1458
1573
  continue;
1459
1574
  }
1460
1575
  if (group && isTemplateInterpolation(line, group[0], group[1])) continue;
1576
+ if (group && isUnquotedValue(line, group[0]) && TRUNCATING_VALUE_CHARS.test(line[group[1]] ?? "")) {
1577
+ continue;
1578
+ }
1579
+ if (valueGroup !== void 0 && group === void 0) {
1580
+ if (!isAssignmentFile(filePath)) continue;
1581
+ const assignment = assignmentAround(line, match.index);
1582
+ if (assignment.form === "=" && (assignment.reference || assignment.key === null || !CREDENTIAL_KEY_TAIL.test(assignment.key))) {
1583
+ continue;
1584
+ }
1585
+ }
1586
+ if (group && isUnquotedValue(line, group[0]) && OPENER_LED_VALUE.test(line.slice(group[0], group[1])) && !isAssignmentFile(filePath)) {
1587
+ continue;
1588
+ }
1589
+ if (group && isUnquotedValue(line, group[0])) {
1590
+ const assignment = assignmentAround(line, group[0]);
1591
+ const wholeValue = isAssignmentFile(filePath) && assignment.form !== null && !assignment.reference && !assignment.urlValue;
1592
+ if (wholeValue) {
1593
+ spans.push({
1594
+ start: group[0],
1595
+ end: Math.max(group[1], tokenEnd(line, group[0])),
1596
+ rule
1597
+ });
1598
+ matchedRules.add(rule);
1599
+ continue;
1600
+ }
1601
+ }
1461
1602
  spans.push(
1462
1603
  group ? { start: group[0], end: group[1], rule } : { start: match.index, end: match.index + match[0].length, rule }
1463
1604
  );
@@ -1475,6 +1616,8 @@ function scanAndRedactSecrets(content, rules, filePath) {
1475
1616
  }
1476
1617
  var TOKEN_CHARS_LEFT = /[A-Za-z0-9_+/-]/;
1477
1618
  var TOKEN_CHARS_RIGHT = /[A-Za-z0-9_+/=-]/;
1619
+ var TRUNCATING_VALUE_CHARS = /[<>|\\]/;
1620
+ var OPENER_LED_VALUE = /^[(\\[{]/;
1478
1621
  function expandOverToken(line, start, end) {
1479
1622
  let left = start;
1480
1623
  let right = end;
@@ -1487,14 +1630,20 @@ function expandOverToken(line, start, end) {
1487
1630
  while (right < line.length && TOKEN_CHARS_RIGHT.test(line[right])) right += 1;
1488
1631
  return { start: left, end: right };
1489
1632
  }
1490
- function startsInsideStringLiteral(line, matchIndex) {
1633
+ function startsInsideStringLiteral(line, matchIndex, valueStart) {
1491
1634
  let runStart = matchIndex;
1492
1635
  while (runStart > 0 && /[A-Za-z0-9_-]/.test(line[runStart - 1])) runStart -= 1;
1493
1636
  const before = runStart > 0 ? line[runStart - 1] : "";
1494
- return before === '"' || before === "'" || before === "`";
1637
+ if (before !== '"' && before !== "'" && before !== "`") return false;
1638
+ if (valueStart === void 0) return true;
1639
+ return /["'`]/.test(line.slice(matchIndex, valueStart));
1495
1640
  }
1496
1641
  function isTemplateInterpolation(line, start, end) {
1497
- return line[start] === "$" && line[start + 1] === "{" && line[end - 1] === "}";
1642
+ if (line[start] !== "$" || line[start + 1] !== "{" || line[end - 1] !== "}") {
1643
+ return false;
1644
+ }
1645
+ const inner = line.slice(start + 2, end - 1).trim();
1646
+ return /^[A-Za-z_$][A-Za-z0-9_$.()[\]]*$/.test(inner);
1498
1647
  }
1499
1648
  function isSelfNamingConstant(line, start, end) {
1500
1649
  const value = line.slice(start, end);
@@ -1515,13 +1664,48 @@ function isSelfNamingConstant(line, start, end) {
1515
1664
  }
1516
1665
  return line.endsWith(value, index);
1517
1666
  }
1667
+ function assignmentAround(line, valueStart) {
1668
+ let index = valueStart;
1669
+ while (index > 0 && (line[index - 1] === " " || line[index - 1] === " ")) index -= 1;
1670
+ const separator = index > 0 ? line[index - 1] : "";
1671
+ if (separator !== ":" && separator !== "=") {
1672
+ return { form: null, key: null, reference: false, rhsStart: -1, urlValue: false };
1673
+ }
1674
+ const separatorIndex = index - 1;
1675
+ index = separatorIndex;
1676
+ while (index > 0 && (line[index - 1] === " " || line[index - 1] === " ")) index -= 1;
1677
+ const keyEnd = index;
1678
+ while (index > 0 && /[A-Za-z0-9_$.-]/.test(line[index - 1])) index -= 1;
1679
+ const key = line.slice(index, keyEnd).replace(/^-+/, "");
1680
+ const before = index > 0 ? line[index - 1] : "";
1681
+ const reference = before === "?" || before === "&" || before === "$" || before === '"' || before === "'" || before === "`";
1682
+ let rhsStart = separatorIndex + 1;
1683
+ while (rhsStart < line.length && (line[rhsStart] === " " || line[rhsStart] === " ")) rhsStart += 1;
1684
+ const urlValue = /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(line.slice(rhsStart, tokenEnd(line, rhsStart)));
1685
+ return { form: separator === ":" ? ":" : "=", key, reference, rhsStart, urlValue };
1686
+ }
1687
+ function tokenEnd(line, start) {
1688
+ let end = start;
1689
+ while (end < line.length && !/\s/.test(line[end])) end += 1;
1690
+ return end;
1691
+ }
1518
1692
  function isUnquotedValue(line, start) {
1519
1693
  const before = start > 0 ? line[start - 1] : "";
1520
1694
  return before !== '"' && before !== "'" && before !== "`";
1521
1695
  }
1522
- var DECLARATION_KEYWORDS = /\b(?:const|let|var|readonly|public|private|protected|static|declare|export|using)\s+$/;
1696
+ var DECLARATION_KEYWORDS = /\b(?:const|let|var|readonly|public|private|protected|static|using)\s+$/;
1697
+ var ASSIGNMENT_FILE = /\.(?:sh|bash|zsh|ksh|fish|env|ya?ml|toml|ini|conf|cfg|properties|tf|tfvars|service)$/i;
1698
+ var ASSIGNMENT_BASENAME = /^(?:\.env(?:\.[^/]*)?|\.envrc|\.profile|\.bashrc|\.zshrc|\.bash_profile)$/i;
1699
+ function isAssignmentFile(filePath) {
1700
+ if (filePath === void 0) return false;
1701
+ const normalised = filePath.replace(/\\/g, "/");
1702
+ if (ASSIGNMENT_FILE.test(normalised)) return true;
1703
+ const base = normalised.slice(normalised.lastIndexOf("/") + 1);
1704
+ return ASSIGNMENT_BASENAME.test(base);
1705
+ }
1523
1706
  var DECLARATION_WINDOW = 40;
1524
- function isDeclaredBinding(line, matchIndex) {
1707
+ function isDeclaredBinding(line, matchIndex, filePath) {
1708
+ if (isAssignmentFile(filePath)) return false;
1525
1709
  let runStart = matchIndex;
1526
1710
  while (runStart > 0 && /[A-Za-z0-9_$]/.test(line[runStart - 1])) runStart -= 1;
1527
1711
  const from = Math.max(0, runStart - DECLARATION_WINDOW);
@@ -1563,6 +1747,15 @@ function readLinkTarget(linkPath, fallback) {
1563
1747
  return fallback;
1564
1748
  }
1565
1749
  }
1750
+ function brokenLinkRecord(linkPath, relativePath, rootReal) {
1751
+ const rawTarget = readLinkTarget(linkPath, linkPath);
1752
+ const resolvedFallback = path2.resolve(path2.dirname(linkPath), rawTarget);
1753
+ return isInside(rootReal, resolvedFallback) ? { path: relativePath, reason: "read-error", detail: "broken symlink" } : {
1754
+ path: relativePath,
1755
+ reason: "outside-root",
1756
+ detail: `link target resolves outside the scanned root (target: ${rawTarget}); not followed`
1757
+ };
1758
+ }
1566
1759
  function isInside(root, candidate) {
1567
1760
  const relative12 = path2.relative(root, candidate);
1568
1761
  return relative12 === "" || !relative12.startsWith(`..${path2.sep}`) && relative12 !== ".." && !path2.isAbsolute(relative12);
@@ -1652,6 +1845,13 @@ function isSensitivePath(relativePath) {
1652
1845
  return matchesSensitiveList(posixPath, base);
1653
1846
  }
1654
1847
  var GLOBAL_PATTERNS = /* @__PURE__ */ new WeakMap();
1848
+ var GLOB_REGEX_CACHE = /* @__PURE__ */ new Map();
1849
+ var GITIGNORE_REGEX_CACHE = /* @__PURE__ */ new Map();
1850
+ var REGEX_CACHE_LIMIT = 4096;
1851
+ function rememberCompiled(cache, key, value) {
1852
+ if (cache.size >= REGEX_CACHE_LIMIT) cache.clear();
1853
+ cache.set(key, value);
1854
+ }
1655
1855
  function globalPattern(pattern) {
1656
1856
  let compiled = GLOBAL_PATTERNS.get(pattern);
1657
1857
  if (compiled === void 0) {
@@ -1662,8 +1862,8 @@ function globalPattern(pattern) {
1662
1862
  }
1663
1863
  var DEFAULT_PATH_RULES = [...DEFAULT_SECRET_PATTERNS];
1664
1864
  function pathScanRules(extraRules) {
1665
- if (extraRules === void 0 || extraRules.length === 0) return DEFAULT_PATH_RULES;
1666
- return [...DEFAULT_SECRET_PATTERNS, ...extraRules];
1865
+ if (extraRules === void 0) return DEFAULT_PATH_RULES;
1866
+ return extraRules;
1667
1867
  }
1668
1868
  function findSecretInPath(relativePath, extraRules) {
1669
1869
  const posixPath = relativePath.replace(/\\/g, "/");
@@ -1712,11 +1912,22 @@ function maskSkipPaths(records, extraRules) {
1712
1912
  });
1713
1913
  }
1714
1914
  function globToRegExp(glob) {
1915
+ const cached = GLOB_REGEX_CACHE.get(glob);
1916
+ if (cached !== void 0) return cached;
1715
1917
  const normalized = glob.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
1716
1918
  const anchored = normalized.startsWith("/");
1717
1919
  const body = anchored ? normalized.slice(1) : normalized;
1718
1920
  const prefix = anchored || body.includes("/") ? "^" : "(?:^|.*/)";
1719
- return new RegExp(`${prefix}${globBodyToRegExp(body, true)}(?:/.*)?$`);
1921
+ let compiled;
1922
+ try {
1923
+ compiled = new RegExp(`${prefix}${globBodyToRegExp(body, true)}(?:/.*)?$`);
1924
+ } catch (error) {
1925
+ throw new Error(
1926
+ `"${glob}" is not a valid glob: ${error.message}. A character class must be ascending, as in "[a-z]".`
1927
+ );
1928
+ }
1929
+ rememberCompiled(GLOB_REGEX_CACHE, glob, compiled);
1930
+ return compiled;
1720
1931
  }
1721
1932
  function globBodyToRegExp(body, allowBraces) {
1722
1933
  let out = "";
@@ -1828,6 +2039,14 @@ function escapeRegExpChar(character) {
1828
2039
  return /[\\^$.*+?()[\]{}|/]/.test(character) ? `\\${character}` : character;
1829
2040
  }
1830
2041
  function matchGitignorePattern(target, pattern) {
2042
+ let compiled = GITIGNORE_REGEX_CACHE.get(pattern);
2043
+ if (compiled === void 0) {
2044
+ compiled = compileGitignorePattern(pattern);
2045
+ rememberCompiled(GITIGNORE_REGEX_CACHE, pattern, compiled);
2046
+ }
2047
+ return compiled.test(target);
2048
+ }
2049
+ function compileGitignorePattern(pattern) {
1831
2050
  const anchored = pattern.startsWith("/");
1832
2051
  const body = anchored ? pattern.slice(1) : pattern;
1833
2052
  let source = "";
@@ -1876,7 +2095,11 @@ function matchGitignorePattern(target, pattern) {
1876
2095
  source += escapeRegExpChar(character);
1877
2096
  }
1878
2097
  const prefix = anchored || body.includes("/") ? "^" : "(?:^|.*/)";
1879
- return new RegExp(`${prefix}${source}(?:/.*)?$`).test(target);
2098
+ try {
2099
+ return new RegExp(`${prefix}${source}(?:/.*)?$`);
2100
+ } catch {
2101
+ return /$^/;
2102
+ }
1880
2103
  }
1881
2104
  function matchesGitignoreRule(rule, scoped, isDirectory) {
1882
2105
  if (!rule.dirOnly) return matchGitignorePattern(scoped, rule.pattern);
@@ -1906,14 +2129,31 @@ function gitignoreVerdict(layers, relativePath, isDirectory) {
1906
2129
  }
1907
2130
  return verdict;
1908
2131
  }
1909
- function defaultIgnoreReason(relativePath) {
2132
+ var DEFAULT_TOOL_DIR_NAMES = ["snapshot"];
2133
+ function toolDirNamesFor(toolOwnedPaths) {
2134
+ const names = new Set(DEFAULT_TOOL_DIR_NAMES);
2135
+ for (const entry of toolOwnedPaths) {
2136
+ const base = entry.replace(/\\/g, "/").replace(/\/+$/, "").split("/").pop();
2137
+ if (base !== void 0 && base.length > 0) names.add(base);
2138
+ }
2139
+ return [...names];
2140
+ }
2141
+ function isToolLeftoverName(name, dirNames) {
2142
+ for (const dirName of dirNames) {
2143
+ if (name.startsWith(`${dirName}.backup-`) || name.startsWith(`${dirName}.partial-`)) {
2144
+ return true;
2145
+ }
2146
+ }
2147
+ return false;
2148
+ }
2149
+ function defaultIgnoreReason(relativePath, toolDirNames = DEFAULT_TOOL_DIR_NAMES) {
1910
2150
  const posixPath = relativePath.replace(/\\/g, "/");
1911
2151
  const parts = posixPath.split("/");
1912
2152
  for (let i = 0; i < parts.length - 1; i++) {
1913
2153
  if (DEFAULT_IGNORED_DIRS.includes(parts[i])) {
1914
2154
  return `built-in ignore: directory "${parts[i]}"`;
1915
2155
  }
1916
- if (parts[i].startsWith("snapshot.backup-")) {
2156
+ if (isToolLeftoverName(parts[i], toolDirNames)) {
1917
2157
  return `built-in ignore: leftover snapshot backup "${parts[i]}"`;
1918
2158
  }
1919
2159
  }
@@ -1921,6 +2161,9 @@ function defaultIgnoreReason(relativePath) {
1921
2161
  if (DEFAULT_IGNORED_FILES.includes(base)) {
1922
2162
  return `built-in ignore: filename "${base}"`;
1923
2163
  }
2164
+ if (isToolLeftoverName(base, toolDirNames)) {
2165
+ return `built-in ignore: leftover snapshot backup "${base}"`;
2166
+ }
1924
2167
  return null;
1925
2168
  }
1926
2169
  function listIgnoredPaths(cwd) {
@@ -1989,41 +2232,72 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
1989
2232
  }
1990
2233
  const reported = /* @__PURE__ */ new Set();
1991
2234
  const kept = [];
2235
+ const report = (linkedPath, record) => {
2236
+ if (reported.has(linkedPath)) return;
2237
+ reported.add(linkedPath);
2238
+ skipped.push(record);
2239
+ };
1992
2240
  for (const candidate of candidates) {
1993
2241
  const parts = candidate.split("/");
1994
- let linkedDir = null;
2242
+ let linkedPath = null;
1995
2243
  for (let depth = 1; depth <= parts.length; depth += 1) {
1996
2244
  const prefix = parts.slice(0, depth).join("/");
1997
2245
  if (isLink(path2.join(cwd, prefix))) {
1998
- linkedDir = prefix;
2246
+ linkedPath = prefix;
1999
2247
  break;
2000
2248
  }
2001
2249
  }
2002
- if (linkedDir === null) {
2250
+ if (linkedPath === null) {
2003
2251
  kept.push(candidate);
2004
2252
  continue;
2005
2253
  }
2006
- if (reported.has(linkedDir)) continue;
2007
- reported.add(linkedDir);
2008
- const absolute = path2.join(cwd, linkedDir);
2009
- let targetReal = absolute;
2254
+ const absolute = path2.join(cwd, linkedPath);
2255
+ const rawTarget = readLinkTarget(absolute, absolute);
2256
+ let targetReal = null;
2010
2257
  try {
2011
2258
  targetReal = fs2.realpathSync(absolute);
2012
2259
  } catch {
2260
+ targetReal = null;
2013
2261
  }
2014
- const target = readLinkTarget(absolute, targetReal);
2015
- const what = linkedDir === candidate ? "symbolic link" : "directory link";
2016
- skipped.push(
2017
- isInside(rootReal, targetReal) ? {
2018
- path: linkedDir,
2019
- reason: "symlink",
2020
- detail: `${what} not followed (target: ${target})`
2021
- } : {
2022
- path: linkedDir,
2262
+ if (targetReal === null) {
2263
+ report(linkedPath, brokenLinkRecord(absolute, linkedPath, rootReal));
2264
+ continue;
2265
+ }
2266
+ if (!isInside(rootReal, targetReal)) {
2267
+ report(linkedPath, {
2268
+ path: linkedPath,
2023
2269
  reason: "outside-root",
2024
- detail: `link target resolves outside the scanned root (target: ${target}); not followed`
2025
- }
2026
- );
2270
+ detail: `link target resolves outside the scanned root (target: ${rawTarget}); not followed`
2271
+ });
2272
+ continue;
2273
+ }
2274
+ let stats = null;
2275
+ try {
2276
+ stats = fs2.statSync(absolute);
2277
+ } catch {
2278
+ stats = null;
2279
+ }
2280
+ if (stats === null) {
2281
+ report(linkedPath, { path: linkedPath, reason: "read-error", detail: "unreadable symlink" });
2282
+ continue;
2283
+ }
2284
+ if (linkedPath !== candidate || stats.isDirectory()) {
2285
+ report(linkedPath, {
2286
+ path: linkedPath,
2287
+ reason: "symlink",
2288
+ detail: `directory link not followed (target: ${rawTarget})`
2289
+ });
2290
+ continue;
2291
+ }
2292
+ if (!stats.isFile()) {
2293
+ report(linkedPath, {
2294
+ path: linkedPath,
2295
+ reason: "symlink",
2296
+ detail: `link to neither a file nor a directory (target: ${rawTarget})`
2297
+ });
2298
+ continue;
2299
+ }
2300
+ kept.push(candidate);
2027
2301
  }
2028
2302
  return kept;
2029
2303
  }
@@ -2070,6 +2344,7 @@ function collectFiles(cwd, options = {}) {
2070
2344
  (options.toolOwnedPaths ?? []).map((entry) => entry.replace(/\\/g, "/"))
2071
2345
  );
2072
2346
  const isToolOwned = makeToolOwnedDecider(cwd, [...toolOwnedPaths]);
2347
+ const toolDirNames = toolDirNamesFor(toolOwnedPaths);
2073
2348
  let candidates;
2074
2349
  const skipped = [];
2075
2350
  const discovery = options.discovery ?? "auto";
@@ -2098,7 +2373,7 @@ function collectFiles(cwd, options = {}) {
2098
2373
  }
2099
2374
  const files = candidates.filter((file) => {
2100
2375
  if (isToolOwned(file)) return false;
2101
- const ignored = defaultIgnoreReason(file);
2376
+ const ignored = defaultIgnoreReason(file, toolDirNames);
2102
2377
  if (ignored) {
2103
2378
  skipped.push({ path: file, reason: "default-ignore", detail: ignored });
2104
2379
  return false;
@@ -2153,6 +2428,7 @@ function rootRealFor(root) {
2153
2428
  function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PURE__ */ new Set(), parentGitignoreLayers = []) {
2154
2429
  const results = { files: [], skipped: [] };
2155
2430
  const stack = [];
2431
+ const toolDirNames = toolDirNamesFor(reservedPaths);
2156
2432
  const relativeToBase = (target) => path2.relative(baseDir, target).replace(/\\/g, "/") || ".";
2157
2433
  const enter = (current, layers) => {
2158
2434
  if (visited.has(current)) return false;
@@ -2197,11 +2473,11 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
2197
2473
  });
2198
2474
  continue;
2199
2475
  }
2200
- if (DEFAULT_IGNORED_FILES.includes(entry.name) || entry.name.startsWith("snapshot.backup-")) {
2476
+ if (DEFAULT_IGNORED_FILES.includes(entry.name) || isToolLeftoverName(entry.name, toolDirNames)) {
2201
2477
  results.skipped.push({
2202
2478
  path: relPath,
2203
2479
  reason: "default-ignore",
2204
- detail: "built-in ignore: filename"
2480
+ detail: isToolLeftoverName(entry.name, toolDirNames) ? `built-in ignore: leftover snapshot backup "${entry.name}" (not descended)` : "built-in ignore: filename"
2205
2481
  });
2206
2482
  continue;
2207
2483
  }
@@ -2222,7 +2498,7 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
2222
2498
  try {
2223
2499
  targetReal = fs2.realpathSync(fullPath);
2224
2500
  } catch {
2225
- results.skipped.push({ path: relPath, reason: "read-error", detail: "broken symlink" });
2501
+ results.skipped.push(brokenLinkRecord(fullPath, relPath, rootReal));
2226
2502
  continue;
2227
2503
  }
2228
2504
  let stats;
@@ -2322,8 +2598,9 @@ function findConfigFile(cwd) {
2322
2598
  const pkgJsonPath = path3.join(cwd, "package.json");
2323
2599
  if (!fs3.existsSync(pkgJsonPath)) return null;
2324
2600
  try {
2325
- const parsed = JSON.parse(fs3.readFileSync(pkgJsonPath, "utf8"));
2326
- return parsed.snapshot === void 0 ? null : pkgJsonPath;
2601
+ const parsed = JSON.parse(stripJsonComments(fs3.readFileSync(pkgJsonPath, "utf8")));
2602
+ const snapshot = parsed?.snapshot;
2603
+ return typeof snapshot === "object" && snapshot !== null && !Array.isArray(snapshot) ? pkgJsonPath : null;
2327
2604
  } catch {
2328
2605
  return null;
2329
2606
  }
@@ -2373,15 +2650,19 @@ function normalizeBudgets(budgets, maxPartBytes) {
2373
2650
  }
2374
2651
  function normalizeResolvedConfig(config) {
2375
2652
  const discovery = isDiscoveryMode(config.discovery) ? config.discovery : "auto";
2653
+ const monolithWanted = config.includeMonolith === true || config.artifacts?.monolith === true;
2654
+ const artifacts = resolveArtifacts(
2655
+ config.artifacts,
2656
+ void 0,
2657
+ monolithWanted,
2658
+ monolithWanted
2659
+ );
2376
2660
  return markResolvedConfig({
2377
2661
  ...config,
2378
2662
  discovery,
2663
+ includeMonolith: artifacts.monolith,
2379
2664
  secretRules: compileSecretRules(config.secretRules),
2380
- artifacts: resolveArtifacts(
2381
- config.artifacts,
2382
- void 0,
2383
- config.includeMonolith === true
2384
- ),
2665
+ artifacts,
2385
2666
  include: resolveInclude(config.include),
2386
2667
  preset: typeof config.preset === "string" ? config.preset : "generic",
2387
2668
  presetExclude: [
@@ -2590,6 +2871,16 @@ async function importConfigModule(fullPath) {
2590
2871
  url.searchParams.set("codebaseSnapshotLoad", String(moduleConfigLoadToken));
2591
2872
  return await import(url.href);
2592
2873
  }
2874
+ function attachConfigDir(config, filePath) {
2875
+ if (typeof config === "object" && config !== null) {
2876
+ Object.defineProperty(config, CONFIG_DIR_SYMBOL, {
2877
+ value: path3.dirname(filePath),
2878
+ enumerable: false,
2879
+ configurable: true
2880
+ });
2881
+ }
2882
+ return config;
2883
+ }
2593
2884
  async function loadConfigFileDetailed(cwd) {
2594
2885
  const warnings = [];
2595
2886
  const errors = [];
@@ -2605,7 +2896,7 @@ async function loadConfigFileDetailed(cwd) {
2605
2896
  );
2606
2897
  }
2607
2898
  assertKnownConfigKeys(config, fullPath);
2608
- return { config, file: fullPath, warnings, errors };
2899
+ return { config: attachConfigDir(config, fullPath), file: fullPath, warnings, errors };
2609
2900
  } catch (err) {
2610
2901
  const raw = err.message;
2611
2902
  const message = raw.includes(fullPath) ? raw : `${fullPath}: ${raw}`;
@@ -2624,7 +2915,7 @@ async function loadConfigFileDetailed(cwd) {
2624
2915
  const imported = await importConfigModule(fullPath);
2625
2916
  const hasDefault = Object.prototype.hasOwnProperty.call(imported, "default");
2626
2917
  const config = readConfigExport(hasDefault ? imported.default : imported, fullPath);
2627
- return { config, file: fullPath, warnings, errors };
2918
+ return { config: attachConfigDir(config, fullPath), file: fullPath, warnings, errors };
2628
2919
  } catch (err) {
2629
2920
  const message = `Could not load ${fullPath}: ${err.message}`;
2630
2921
  warnings.push(message);
@@ -2642,7 +2933,12 @@ async function loadConfigFileDetailed(cwd) {
2642
2933
  snapshotKey,
2643
2934
  `${pkgJsonPath} (the "snapshot" key)`
2644
2935
  );
2645
- return { config: snapshotKey, file: pkgJsonPath, warnings, errors };
2936
+ return {
2937
+ config: attachConfigDir(snapshotKey, pkgJsonPath),
2938
+ file: pkgJsonPath,
2939
+ warnings,
2940
+ errors
2941
+ };
2646
2942
  }
2647
2943
  if (snapshotKey !== void 0) {
2648
2944
  const kind = Array.isArray(snapshotKey) ? "array" : typeof snapshotKey;
@@ -2681,7 +2977,7 @@ var DEFAULT_ARTIFACTS = {
2681
2977
  function isArtifactName(value) {
2682
2978
  return ARTIFACT_NAMES.includes(value);
2683
2979
  }
2684
- function resolveArtifacts(requested, skipped, includeMonolith, monolithOverride) {
2980
+ function resolveArtifacts(requested, skipped, includeMonolith, monolithOverride, only) {
2685
2981
  const artifacts = {
2686
2982
  ...DEFAULT_ARTIFACTS,
2687
2983
  // `includeMonolith` predates this selection and stays the switch for it.
@@ -2706,6 +3002,21 @@ function resolveArtifacts(requested, skipped, includeMonolith, monolithOverride)
2706
3002
  if (monolithOverride !== void 0) {
2707
3003
  artifacts.monolith = monolithOverride;
2708
3004
  }
3005
+ if (only !== void 0 && only.length > 0) {
3006
+ const keep = /* @__PURE__ */ new Set();
3007
+ for (const name of only) {
3008
+ if (!isArtifactName(name)) {
3009
+ throw new Error(
3010
+ `Unknown artifact "${name}". Expected one of: ${ARTIFACT_NAMES.join(", ")}.`
3011
+ );
3012
+ }
3013
+ keep.add(name);
3014
+ }
3015
+ for (const name of ARTIFACT_NAMES) {
3016
+ artifacts[name] = keep.has(name);
3017
+ }
3018
+ return artifacts;
3019
+ }
2709
3020
  for (const name of skipped ?? []) {
2710
3021
  if (!isArtifactName(name)) {
2711
3022
  throw new Error(
@@ -3006,7 +3317,8 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
3006
3317
  userConfig?.artifacts,
3007
3318
  cliOptions?.skipArtifacts,
3008
3319
  includeMonolith,
3009
- cliMonolith
3320
+ cliMonolith,
3321
+ cliOptions?.onlyArtifacts
3010
3322
  );
3011
3323
  const explicitMaxPartBytes = cliOptions?.maxPartBytes ?? userConfig?.maxPartBytes;
3012
3324
  const maxPartBytes = boundedBytes(
@@ -3180,7 +3492,18 @@ function configDigest(config) {
3180
3492
  excludePatterns: config.excludePatterns,
3181
3493
  preset: config.preset,
3182
3494
  layersMode: config.layersMode,
3183
- budgets: config.budgets,
3495
+ // `budgets.byLayer` is a plain object, and `JSON.stringify` preserves insertion order — so
3496
+ // `{ docs, api }` and `{ api, docs }` hashed differently despite being the same settings, and
3497
+ // `validate` reported configuration drift for a snapshot nobody had changed. The keys are
3498
+ // canonicalised here; nothing else about the object is order-dependent.
3499
+ budgets: {
3500
+ default: config.budgets.default,
3501
+ byLayer: Object.fromEntries(
3502
+ Object.entries(config.budgets.byLayer).sort(
3503
+ ([left], [right]) => left < right ? -1 : left > right ? 1 : 0
3504
+ )
3505
+ )
3506
+ },
3184
3507
  // The matcher is what makes a layer a layer. Hashing only the names meant that
3185
3508
  // moving `{ name: "api", match: "src/api/**" }` to `"src/v2/**"` produced the same
3186
3509
  // digest, so `validate` reported "valid and up to date" for a snapshot whose files
@@ -3288,6 +3611,10 @@ var SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
3288
3611
  ".mjs",
3289
3612
  ".cjs"
3290
3613
  ]);
3614
+ var PYTHON_EXTENSIONS = /* @__PURE__ */ new Set([".py", ".pyi"]);
3615
+ var RUBY_EXTENSIONS = /* @__PURE__ */ new Set([".rb", ".rake", ".gemspec"]);
3616
+ var C_EXTENSIONS = /* @__PURE__ */ new Set([".c", ".h", ".cc", ".cpp", ".cxx", ".hpp", ".hxx", ".m", ".mm"]);
3617
+ var PYTHON_SUFFIXES = [".py", ".pyi", "/__init__.py", "/__init__.pyi"];
3291
3618
  function buildImportResolver(files) {
3292
3619
  const byPath = /* @__PURE__ */ new Map();
3293
3620
  const byPathFolded = /* @__PURE__ */ new Map();
@@ -3314,11 +3641,45 @@ function buildImportResolver(files) {
3314
3641
  return { byPath, byPathFolded, byStem, byStemFolded };
3315
3642
  }
3316
3643
  function resolveSpecifier(fromFile, specifier, resolver) {
3644
+ const extension = path4.posix.extname(fromFile).toLowerCase();
3645
+ const exact = (key) => resolver.byPath.get(key) ?? resolver.byPathFolded.get(key.toLowerCase()) ?? null;
3646
+ const firstOf = (candidates) => {
3647
+ for (const candidate of candidates) {
3648
+ const hit = exact(candidate);
3649
+ if (hit) return hit;
3650
+ }
3651
+ return null;
3652
+ };
3653
+ if (PYTHON_EXTENSIONS.has(extension) && specifier.startsWith(".")) {
3654
+ const dots = /^\.+/.exec(specifier)?.[0].length ?? 0;
3655
+ const rest = specifier.slice(dots).replace(/\./g, "/");
3656
+ let base = path4.posix.dirname(fromFile);
3657
+ for (let up = 1; up < dots; up += 1) base = path4.posix.dirname(base);
3658
+ const joined2 = rest ? path4.posix.normalize(path4.posix.join(base, rest)) : base;
3659
+ return firstOf([joined2, ...PYTHON_SUFFIXES.map((suffix) => `${joined2}${suffix}`)]);
3660
+ }
3661
+ if (RUBY_EXTENSIONS.has(extension) && specifier.startsWith("./")) {
3662
+ const joined2 = path4.posix.normalize(
3663
+ path4.posix.join(path4.posix.dirname(fromFile), specifier)
3664
+ );
3665
+ return firstOf([`${joined2}.rb`, joined2]);
3666
+ }
3667
+ if (C_EXTENSIONS.has(extension) && specifier.startsWith("./")) {
3668
+ const joined2 = path4.posix.normalize(
3669
+ path4.posix.join(path4.posix.dirname(fromFile), specifier)
3670
+ );
3671
+ return exact(joined2);
3672
+ }
3673
+ if (extension === ".dart" && !specifier.includes(":")) {
3674
+ const joined2 = path4.posix.normalize(
3675
+ path4.posix.join(path4.posix.dirname(fromFile), specifier)
3676
+ );
3677
+ return firstOf([joined2, `${joined2}.dart`]);
3678
+ }
3317
3679
  if (!RELATIVE_SPECIFIER.test(specifier)) return null;
3318
3680
  const joined = path4.posix.normalize(
3319
3681
  path4.posix.join(path4.posix.dirname(fromFile), specifier)
3320
3682
  );
3321
- const exact = (key) => resolver.byPath.get(key) ?? resolver.byPathFolded.get(key.toLowerCase()) ?? null;
3322
3683
  const direct = exact(joined);
3323
3684
  if (direct) return direct;
3324
3685
  for (const suffix of IMPORT_CANDIDATE_SUFFIXES) {
@@ -3450,13 +3811,23 @@ function summarizeTypeScriptSource(relativePath, content) {
3450
3811
  if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
3451
3812
  summary.imports.push(node.moduleSpecifier.text);
3452
3813
  }
3814
+ if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference) && node.moduleReference.expression !== void 0 && ts.isStringLiteral(node.moduleReference.expression)) {
3815
+ summary.imports.push(node.moduleReference.expression.text);
3816
+ }
3817
+ if (ts.isCallExpression(node) && node.arguments.length >= 1) {
3818
+ const firstArgument = node.arguments[0];
3819
+ if (firstArgument !== void 0 && ts.isStringLiteral(firstArgument)) {
3820
+ const isDynamicImport = node.expression.kind === ts.SyntaxKind.ImportKeyword;
3821
+ const isRequire = ts.isIdentifier(node.expression) && node.expression.text === "require";
3822
+ if (isDynamicImport || isRequire) summary.imports.push(firstArgument.text);
3823
+ }
3824
+ }
3453
3825
  if (ts.isExportDeclaration(node)) {
3454
3826
  if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {
3455
3827
  summary.imports.push(node.moduleSpecifier.text);
3828
+ summary.reExports.push(node.moduleSpecifier.text);
3456
3829
  if (node.exportClause && ts.isNamespaceExport(node.exportClause)) {
3457
3830
  summary.exports.push(node.exportClause.name.text);
3458
- } else if (!node.exportClause) {
3459
- summary.reExports.push(node.moduleSpecifier.text);
3460
3831
  }
3461
3832
  }
3462
3833
  if (node.exportClause && ts.isNamedExports(node.exportClause)) {
@@ -3601,7 +3972,7 @@ function isCapitalizedName(name) {
3601
3972
  }
3602
3973
 
3603
3974
  // src/ast/profiles/cfamily.ts
3604
- var INCLUDE = /^#\s*include\s*[<"]([^>"]+)[>"]/;
3975
+ var INCLUDE = /^#\s*include\s*([<"])([^>"]+)[>"]/;
3605
3976
  var DEFINE = /^#\s*define\s+([A-Za-z_]\w*)/;
3606
3977
  var USING = /^using\s+(?:namespace\s+)?([\w:]+)\s*;/;
3607
3978
  var TYPE_DECL = /^(?:typedef\s+)?(?:struct|union|class|enum)\s+([A-Za-z_]\w*)/;
@@ -3620,7 +3991,7 @@ var cfamilyProfile = {
3620
3991
  }
3621
3992
  const included = INCLUDE.exec(trimmed);
3622
3993
  if (included) {
3623
- summary.imports.push(included[1]);
3994
+ summary.imports.push(included[1] === '"' ? `./${included[2]}` : included[2]);
3624
3995
  return;
3625
3996
  }
3626
3997
  const used = USING.exec(trimmed);
@@ -4024,7 +4395,15 @@ var pythonProfile = {
4024
4395
  }
4025
4396
  const from = FROM_IMPORT.exec(trimmed);
4026
4397
  if (from) {
4027
- summary.imports.push(from[1]);
4398
+ const module = from[1];
4399
+ if (/^\.+$/.test(module)) {
4400
+ for (const name of from[2].split(",")) {
4401
+ const imported2 = name.replace(/[()]/g, "").trim().split(/\s+as\s+/)[0].trim();
4402
+ if (/^[A-Za-z_]\w*$/.test(imported2)) summary.imports.push(`${module}${imported2}`);
4403
+ }
4404
+ } else {
4405
+ summary.imports.push(module);
4406
+ }
4028
4407
  routePending = false;
4029
4408
  return;
4030
4409
  }
@@ -4073,7 +4452,8 @@ var pythonProfile = {
4073
4452
  };
4074
4453
 
4075
4454
  // src/ast/profiles/ruby.ts
4076
- var REQUIRE = /^require(?:_relative)?\s+["']([^"']+)["']/;
4455
+ var REQUIRE_RELATIVE = /^require_relative\s+["']([^"']+)["']/;
4456
+ var REQUIRE = /^require\s+["']([^"']+)["']/;
4077
4457
  var CLASS_OR_MODULE = /^(?:class|module)\s+([A-Z][\w:]*)/;
4078
4458
  var METHOD2 = /^def\s+(?:self\.)?([A-Za-z_]\w*[?!=]?)/;
4079
4459
  var rubyProfile = {
@@ -4084,6 +4464,11 @@ var rubyProfile = {
4084
4464
  eachLine(content, (line) => {
4085
4465
  const trimmed = line.trim();
4086
4466
  if (!trimmed || trimmed.startsWith("#")) return;
4467
+ const relative12 = REQUIRE_RELATIVE.exec(trimmed);
4468
+ if (relative12) {
4469
+ summary.imports.push(`./${relative12[1]}`);
4470
+ return;
4471
+ }
4087
4472
  const required = REQUIRE.exec(trimmed);
4088
4473
  if (required) {
4089
4474
  summary.imports.push(required[1]);
@@ -4174,7 +4559,8 @@ var rustProfile = {
4174
4559
  };
4175
4560
 
4176
4561
  // src/ast/profiles/sfc.ts
4177
- var SCRIPT_BLOCK = /<script[^>]*>([\s\S]*?)<\/script>/gi;
4562
+ var SCRIPT_BLOCK = /<script([^>]*)>([\s\S]*?)<\/script>/gi;
4563
+ var JSX_LANG = /\blang\s*=\s*["']?[tj]sx\b/i;
4178
4564
  var ASTRO_FRONTMATTER = /^\uFEFF?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?=\r?\n|$)/;
4179
4565
  function componentName(path22) {
4180
4566
  const base = path22.split("/").pop() ?? path22;
@@ -4185,13 +4571,15 @@ var sfcProfile = {
4185
4571
  extensions: [".vue", ".svelte", ".astro"],
4186
4572
  summarize(path22, content) {
4187
4573
  let script = "";
4574
+ let usesJsx = path22.toLowerCase().endsWith(".astro");
4188
4575
  if (path22.toLowerCase().endsWith(".astro")) {
4189
4576
  const frontmatter = ASTRO_FRONTMATTER.exec(content);
4190
4577
  if (frontmatter) script += `${frontmatter[1]}
4191
4578
  `;
4192
4579
  }
4193
4580
  for (const match of content.matchAll(SCRIPT_BLOCK)) {
4194
- script += `${match[1]}
4581
+ if (JSX_LANG.test(match[1] ?? "")) usesJsx = true;
4582
+ script += `${match[2]}
4195
4583
  `;
4196
4584
  }
4197
4585
  const name = componentName(path22);
@@ -4203,7 +4591,7 @@ var sfcProfile = {
4203
4591
  }
4204
4592
  return { summary: finalizeSummary(summary2), quality: "heuristic" };
4205
4593
  }
4206
- const summary = summarizeTypeScriptSource(`${name}.ts`, script);
4594
+ const summary = summarizeTypeScriptSource(`${name}.${usesJsx ? "tsx" : "ts"}`, script);
4207
4595
  summary.reactComponents.push(name);
4208
4596
  summary.exports.push(name);
4209
4597
  return { summary: finalizeSummary(summary), quality: "ast" };
@@ -4641,18 +5029,22 @@ function isBinaryFile(absolutePath) {
4641
5029
  }
4642
5030
 
4643
5031
  // src/ast/imports.ts
5032
+ var SUMMARY_MAX_SOURCE_BYTES = 2 * 1024 * 1024;
4644
5033
  var TS_SOURCE_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
4645
5034
  var isTsSource = (relativePath) => {
4646
5035
  const lower = relativePath.toLowerCase();
4647
5036
  return TS_SOURCE_EXTENSIONS.some((extension) => lower.endsWith(extension));
4648
5037
  };
4649
5038
  function importsOfText(relativePath, text2) {
5039
+ if (Buffer.byteLength(text2, "utf8") > SUMMARY_MAX_SOURCE_BYTES) return [];
4650
5040
  if (isTsSource(relativePath)) return summarizeTypeScriptSource(relativePath, text2).imports;
4651
5041
  return summarizeWithProfile(relativePath, text2)?.summary.imports ?? [];
4652
5042
  }
4653
5043
  function importsOfFile(relativePath, absolutePath) {
4654
5044
  let buffer;
4655
5045
  try {
5046
+ const stats = fs5.statSync(absolutePath);
5047
+ if (!stats.isFile() || stats.size > SUMMARY_MAX_SOURCE_BYTES) return [];
4656
5048
  buffer = fs5.readFileSync(absolutePath);
4657
5049
  } catch {
4658
5050
  return [];
@@ -4728,16 +5120,14 @@ function emptyDrift() {
4728
5120
  function sha256Hex(buffer) {
4729
5121
  return crypto.createHash("sha256").update(buffer).digest("hex");
4730
5122
  }
4731
- var VERIFY_SNIFF_MAX_BYTES = 8 * 1024 * 1024;
4732
5123
  function wouldNowBeIncluded(cwd, relativePath) {
4733
5124
  const absolutePath = path6.join(cwd, relativePath);
4734
5125
  try {
4735
5126
  const stats = fs6.statSync(absolutePath);
4736
5127
  if (!stats.isFile()) return false;
4737
- if (stats.size <= VERIFY_SNIFF_MAX_BYTES) {
4738
- return !decodeText(fs6.readFileSync(absolutePath)).binary;
4739
- }
4740
- return !isBinaryFile(absolutePath);
5128
+ if (isBinaryExtension(absolutePath)) return false;
5129
+ if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) return false;
5130
+ return !decodeText(fs6.readFileSync(absolutePath)).binary;
4741
5131
  } catch {
4742
5132
  return false;
4743
5133
  }
@@ -4783,9 +5173,13 @@ function describeManifestShapeProblem(value) {
4783
5173
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
4784
5174
  return 'a "parts" entry is not an object';
4785
5175
  }
4786
- if (typeof entry.filename !== "string") {
5176
+ const filename = entry.filename;
5177
+ if (typeof filename !== "string" || filename.trim() === "") {
4787
5178
  return 'a "parts" entry has no "filename"';
4788
5179
  }
5180
+ if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path6.isAbsolute(filename)) {
5181
+ return 'a "parts" entry "filename" must be a bare filename inside parts/';
5182
+ }
4789
5183
  }
4790
5184
  if (!candidate.layers || typeof candidate.layers !== "object" || Array.isArray(candidate.layers)) {
4791
5185
  return 'missing "layers" object';
@@ -4896,7 +5290,7 @@ function validateSnapshot(configInput) {
4896
5290
  });
4897
5291
  for (const diskFile of collection.files) {
4898
5292
  const snapshotHash = manifestFileMap.get(diskFile);
4899
- if (!snapshotHash) {
5293
+ if (snapshotHash === void 0) {
4900
5294
  const skipReason = skippedReasonOnDisk(diskFile);
4901
5295
  if (skipReason === "unchanged") {
4902
5296
  if (unchangedScope !== null) {
@@ -4910,6 +5304,11 @@ function validateSnapshot(configInput) {
4910
5304
  drift.missingInSnapshot.push(diskFile);
4911
5305
  continue;
4912
5306
  }
5307
+ if (unchangedScope !== null && !unchangedScope.has(diskFile) && !becameDependent(diskFile)) {
5308
+ drift.configMismatches.push(
5309
+ `scope: ${maskedPath(diskFile, config.secretRules)} is in the snapshot but is no longer in the changed-files scope`
5310
+ );
5311
+ }
4913
5312
  let diskHash;
4914
5313
  try {
4915
5314
  diskHash = sha256Hex(fs6.readFileSync(path6.join(config.cwd, diskFile)));
@@ -5050,6 +5449,41 @@ function validateSnapshot(configInput) {
5050
5449
  `includeSensitiveFiles: manifest ${recorded.includeSensitiveFiles} vs current ${config.includeSensitiveFiles}`
5051
5450
  );
5052
5451
  }
5452
+ if ((recorded.maxPartTokens ?? void 0) !== (config.maxPartTokens ?? void 0)) {
5453
+ drift.configMismatches.push(
5454
+ `maxPartTokens: manifest ${String(recorded.maxPartTokens ?? "unset")} vs current ${String(config.maxPartTokens ?? "unset")}`
5455
+ );
5456
+ }
5457
+ if ((recorded.maxMonolithBytes ?? null) !== (config.maxMonolithBytes ?? null)) {
5458
+ drift.configMismatches.push(
5459
+ `maxMonolithBytes: manifest ${String(recorded.maxMonolithBytes ?? null)} vs current ${String(config.maxMonolithBytes ?? null)}`
5460
+ );
5461
+ }
5462
+ if (Boolean(recorded.skeleton) !== Boolean(config.skeleton)) {
5463
+ drift.configMismatches.push(
5464
+ `skeleton: manifest ${Boolean(recorded.skeleton)} vs current ${Boolean(config.skeleton)}`
5465
+ );
5466
+ }
5467
+ if (Boolean(recorded.sarif) !== Boolean(config.sarif)) {
5468
+ drift.configMismatches.push(
5469
+ `sarif: manifest ${Boolean(recorded.sarif)} vs current ${Boolean(config.sarif)}`
5470
+ );
5471
+ }
5472
+ if ((recorded.changedSince ?? void 0) !== (config.changedSince ?? void 0)) {
5473
+ drift.configMismatches.push(
5474
+ `changedSince: manifest ${String(recorded.changedSince ?? "unset")} vs current ${String(config.changedSince ?? "unset")}`
5475
+ );
5476
+ }
5477
+ if (Boolean(recorded.staged) !== Boolean(config.staged)) {
5478
+ drift.configMismatches.push(
5479
+ `staged: manifest ${Boolean(recorded.staged)} vs current ${Boolean(config.staged)}`
5480
+ );
5481
+ }
5482
+ if (Boolean(recorded.withDependents) !== Boolean(config.withDependents)) {
5483
+ drift.configMismatches.push(
5484
+ `withDependents: manifest ${Boolean(recorded.withDependents)} vs current ${Boolean(config.withDependents)}`
5485
+ );
5486
+ }
5053
5487
  const effectiveDiscovery = config.discovery ?? "auto";
5054
5488
  const recordedDiscovery = recorded.discovery;
5055
5489
  if (recordedDiscovery !== void 0 && recordedDiscovery !== effectiveDiscovery) {
@@ -5366,7 +5800,7 @@ function describePayloadDiff(before, after, sourceFilesIdentical) {
5366
5800
  }
5367
5801
  if (fingerprintDiffers && (sourceFilesIdentical || configurationDiffers)) {
5368
5802
  reasons.push(
5369
- `content fingerprint ${shortDigest(before.fingerprint)} \u2192 ${shortDigest(after.fingerprint)}` + (sourceFilesIdentical ? " (same source files, packed differently)" : "")
5803
+ `content fingerprint ${shortDigest(before.fingerprint)} \u2192 ${shortDigest(after.fingerprint)}` + (sourceFilesIdentical ? " (same source files, packed or configured differently)" : "")
5370
5804
  );
5371
5805
  }
5372
5806
  if (partsDiffer) {
@@ -5528,9 +5962,21 @@ import * as fs8 from "fs";
5528
5962
  import * as path9 from "path";
5529
5963
 
5530
5964
  // src/partitioner/preview.ts
5965
+ var LINE_ENDINGS = /\r\n|\r/g;
5966
+ var normaliseLineEndings = (content) => content.replace(LINE_ENDINGS, "\n");
5531
5967
  function countLines(content) {
5532
5968
  if (content.length === 0) return 0;
5533
- return content.split("\n").length - (content.endsWith("\n") ? 1 : 0);
5969
+ let breaks = 0;
5970
+ for (let index = 0; index < content.length; index += 1) {
5971
+ const code = content.charCodeAt(index);
5972
+ if (code === 10) {
5973
+ breaks += 1;
5974
+ continue;
5975
+ }
5976
+ if (code === 13 && content.charCodeAt(index + 1) !== 10) breaks += 1;
5977
+ }
5978
+ const last = content.charCodeAt(content.length - 1);
5979
+ return last === 10 || last === 13 ? breaks : breaks + 1;
5534
5980
  }
5535
5981
  function truncateToBytes(content, maxBytes) {
5536
5982
  if (maxBytes <= 0) return { content: "", isTruncated: content.length > 0 };
@@ -5541,17 +5987,18 @@ function truncateToBytes(content, maxBytes) {
5541
5987
  return { content: slice, isTruncated: true };
5542
5988
  }
5543
5989
  function truncatePreview(content, headLines, tailLines) {
5544
- const lines = content.split("\n");
5545
- const total = countLines(content);
5990
+ const normalised = normaliseLineEndings(content);
5991
+ const lines = normalised.split("\n");
5992
+ const total = countLines(normalised);
5546
5993
  if (total <= headLines + tailLines) {
5547
5994
  return {
5548
- content,
5995
+ content: normalised,
5549
5996
  isTruncated: false,
5550
5997
  originalLines: total,
5551
5998
  includedLines: total
5552
5999
  };
5553
6000
  }
5554
- const window = content.endsWith("\n") ? lines.slice(0, -1) : lines;
6001
+ const window = normalised.endsWith("\n") ? lines.slice(0, -1) : lines;
5555
6002
  const head = window.slice(0, headLines);
5556
6003
  const tail = tailLines > 0 ? window.slice(window.length - tailLines) : [];
5557
6004
  const omitted = total - head.length - tail.length;
@@ -5674,10 +6121,13 @@ function describeMatcher(matcher) {
5674
6121
  return String(matcher);
5675
6122
  }
5676
6123
  function normalizeTarget(cwd, target) {
5677
- const absolute = path9.resolve(cwd, target);
5678
- const relative12 = path9.relative(cwd, absolute);
5679
- if (relative12.startsWith("..") || path9.isAbsolute(relative12)) return target;
5680
- return relative12.split(path9.sep).join("/");
6124
+ const resolvedCwd = path9.resolve(cwd);
6125
+ const absolute = path9.resolve(resolvedCwd, target);
6126
+ const relative12 = path9.relative(resolvedCwd, absolute);
6127
+ if (relative12 === "" || relative12 === ".." || relative12.startsWith(`..${path9.sep}`) || path9.isAbsolute(relative12)) {
6128
+ return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
6129
+ }
6130
+ return { relative: relative12.split(path9.sep).join("/"), outsideRoot: false };
5681
6131
  }
5682
6132
  function findRuleMatch(rules, relativePath) {
5683
6133
  return rules.find(
@@ -5704,9 +6154,19 @@ function readManifest2(config) {
5704
6154
  }
5705
6155
  }
5706
6156
  function explainPath(config, target) {
5707
- const relative12 = normalizeTarget(config.cwd, target);
5708
- const absolute = path9.join(config.cwd, relative12);
6157
+ const normalized = normalizeTarget(config.cwd, target);
6158
+ const relative12 = normalized.relative;
5709
6159
  const maskedPath2 = findSecretInPath(relative12, config.secretRules)?.masked ?? relative12;
6160
+ if (normalized.outsideRoot) {
6161
+ return {
6162
+ path: maskedPath2,
6163
+ exists: false,
6164
+ included: false,
6165
+ reason: "outside-root",
6166
+ detail: "path resolves outside the configured repository root and was not inspected"
6167
+ };
6168
+ }
6169
+ const absolute = path9.join(config.cwd, relative12);
5710
6170
  const result = {
5711
6171
  path: maskedPath2,
5712
6172
  exists: fs8.existsSync(absolute),
@@ -5780,6 +6240,12 @@ function explainPath(config, target) {
5780
6240
  return result;
5781
6241
  }
5782
6242
  }
6243
+ if (isBinaryExtension(absolute)) {
6244
+ result.included = false;
6245
+ result.reason = "binary";
6246
+ result.detail = "binary extension; generate skips it without reading and records `binary` in manifest.skipped[]";
6247
+ return result;
6248
+ }
5783
6249
  let sizeOnDisk = null;
5784
6250
  try {
5785
6251
  sizeOnDisk = fs8.statSync(absolute).size;
@@ -5792,13 +6258,6 @@ function explainPath(config, target) {
5792
6258
  result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
5793
6259
  return result;
5794
6260
  }
5795
- result.layer = classifyLayer(relative12, config.layers);
5796
- result.kind = classifyKind(relative12, config.kinds);
5797
- result.language = detectLanguage(relative12);
5798
- const layerRule = findRuleMatch(config.layers, relative12);
5799
- if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
5800
- const kindRule = findRuleMatch(config.kinds, relative12);
5801
- if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
5802
6261
  if (fs8.existsSync(absolute) && fs8.statSync(absolute).isFile()) {
5803
6262
  const buffer = fs8.readFileSync(absolute);
5804
6263
  const decoded = decodeText(buffer);
@@ -5816,6 +6275,13 @@ function explainPath(config, target) {
5816
6275
  result.secretCount = findings.length;
5817
6276
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
5818
6277
  }
6278
+ result.layer = classifyLayer(relative12, config.layers);
6279
+ result.kind = classifyKind(relative12, config.kinds);
6280
+ result.language = detectLanguage(relative12);
6281
+ const layerRule = findRuleMatch(config.layers, relative12);
6282
+ if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
6283
+ const kindRule = findRuleMatch(config.kinds, relative12);
6284
+ if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
5819
6285
  const manifest = readManifest2(config);
5820
6286
  const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative12) : void 0;
5821
6287
  result.part = entry?.part ?? null;
@@ -5861,49 +6327,221 @@ function renderExplainText(result) {
5861
6327
  import * as fs10 from "fs";
5862
6328
  import * as path11 from "path";
5863
6329
 
5864
- // src/gitignore.ts
5865
- import * as fs9 from "fs";
5866
- import * as path10 from "path";
5867
- function appendGitignoreEntries(cwd, entries) {
5868
- const wanted = [...new Set(entries)].filter((entry) => entry.trim().length > 0);
5869
- if (wanted.length === 0) return { added: [], note: null };
5870
- const ignorePath = path10.join(cwd, ".gitignore");
5871
- const manual = `Add ${wanted.map((entry) => `"${entry}"`).join(" and ")} to your .gitignore yourself.`;
5872
- let existing = "";
5873
- try {
5874
- if (fs9.existsSync(ignorePath)) {
5875
- if (fs9.statSync(ignorePath).isDirectory()) {
5876
- return { added: [], note: `${ignorePath} is a directory, so it was not updated. ${manual}` };
6330
+ // src/ast/structured.ts
6331
+ function stripJsonComments2(content) {
6332
+ const text2 = content.replace(/^\uFEFF/, "");
6333
+ const withoutComments = stripComments(text2);
6334
+ return stripTrailingCommas2(withoutComments);
6335
+ }
6336
+ function stripComments(text2) {
6337
+ let out = "";
6338
+ let inString = false;
6339
+ let escaped = false;
6340
+ for (let index = 0; index < text2.length; index += 1) {
6341
+ const char = text2[index];
6342
+ if (inString) {
6343
+ out += char;
6344
+ if (escaped) escaped = false;
6345
+ else if (char === "\\") escaped = true;
6346
+ else if (char === '"') inString = false;
6347
+ continue;
6348
+ }
6349
+ if (char === '"') {
6350
+ inString = true;
6351
+ out += char;
6352
+ continue;
6353
+ }
6354
+ if (char === "/" && text2[index + 1] === "/") {
6355
+ while (index < text2.length && text2[index] !== "\n" && text2[index] !== "\r") index += 1;
6356
+ index -= 1;
6357
+ continue;
6358
+ }
6359
+ if (char === "/" && text2[index + 1] === "*") {
6360
+ index += 2;
6361
+ while (index < text2.length && !(text2[index] === "*" && text2[index + 1] === "/")) {
6362
+ if (text2[index] === "\n" || text2[index] === "\r") out += text2[index];
6363
+ index += 1;
5877
6364
  }
5878
- existing = fs9.readFileSync(ignorePath, "utf8");
6365
+ index += 1;
6366
+ continue;
5879
6367
  }
5880
- } catch (err) {
5881
- return {
5882
- added: [],
5883
- note: `${ignorePath} could not be read (${err.message}). ${manual}`
5884
- };
5885
- }
5886
- const present = new Set(existing.split(/\r?\n/).map((line) => line.trim()));
5887
- const added = wanted.filter((entry) => !present.has(entry));
5888
- if (added.length === 0) return { added: [], note: null };
5889
- const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : "\n";
5890
- try {
5891
- fs9.writeFileSync(ignorePath, `${existing}${prefix}${added.join("\n")}
5892
- `, "utf8");
5893
- } catch (err) {
5894
- return { added: [], note: `${err.message}. ${manual}` };
6368
+ out += char;
5895
6369
  }
5896
- return { added, note: null };
5897
- }
5898
- function gitignorePath(cwd, filePath) {
5899
- return path10.relative(cwd, filePath).split(path10.sep).join("/");
6370
+ return out;
5900
6371
  }
5901
-
5902
- // src/version.ts
5903
- var GENERATOR_NAME = "codebase-snapshot";
5904
- var GENERATOR_VERSION = "0.9.12";
5905
- var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
5906
- function isOurGeneratorName(name) {
6372
+ function stripTrailingCommas2(text2) {
6373
+ let out = "";
6374
+ let inString = false;
6375
+ let escaped = false;
6376
+ for (let index = 0; index < text2.length; index += 1) {
6377
+ const char = text2[index];
6378
+ if (inString) {
6379
+ out += char;
6380
+ if (escaped) escaped = false;
6381
+ else if (char === "\\") escaped = true;
6382
+ else if (char === '"') inString = false;
6383
+ continue;
6384
+ }
6385
+ if (char === '"') {
6386
+ inString = true;
6387
+ out += char;
6388
+ continue;
6389
+ }
6390
+ if (char === ",") {
6391
+ let next = index + 1;
6392
+ while (next < text2.length && /\s/.test(text2[next])) next += 1;
6393
+ if (text2[next] === "}" || text2[next] === "]") continue;
6394
+ }
6395
+ out += char;
6396
+ }
6397
+ return out;
6398
+ }
6399
+ function summarizeJson(content) {
6400
+ try {
6401
+ const parsed = JSON.parse(stripJsonComments2(content));
6402
+ if (Array.isArray(parsed)) {
6403
+ const sample = parsed[0];
6404
+ const sampleKeys = sample && typeof sample === "object" && !Array.isArray(sample) ? Object.keys(sample).slice(0, 10).sort() : [];
6405
+ return {
6406
+ shape: "array",
6407
+ itemCount: parsed.length,
6408
+ keys: [],
6409
+ sampleKeys
6410
+ };
6411
+ }
6412
+ if (parsed && typeof parsed === "object") {
6413
+ const keys = Object.keys(parsed).sort();
6414
+ return {
6415
+ shape: "object",
6416
+ itemCount: keys.length,
6417
+ keys: keys.slice(0, 30),
6418
+ sampleKeys: []
6419
+ };
6420
+ }
6421
+ return {
6422
+ shape: typeof parsed,
6423
+ itemCount: null,
6424
+ keys: [],
6425
+ sampleKeys: []
6426
+ };
6427
+ } catch {
6428
+ return {
6429
+ shape: "invalid-json",
6430
+ itemCount: null,
6431
+ keys: [],
6432
+ sampleKeys: []
6433
+ };
6434
+ }
6435
+ }
6436
+ function frontMatterEnd(lines) {
6437
+ if (lines.length < 3 || lines[0].trim() !== "---") return 0;
6438
+ for (let index = 1; index < lines.length; index += 1) {
6439
+ const line = lines[index];
6440
+ const candidate = line.trim();
6441
+ if (candidate === "---" || candidate === "...") {
6442
+ return index > 1 ? index : 0;
6443
+ }
6444
+ if (candidate === "") continue;
6445
+ if (/^#(\s|$)/.test(candidate)) continue;
6446
+ if (/^(`{3,}|~{3,})/.test(candidate)) return 0;
6447
+ if (/^#{1,6}\s+\S/.test(candidate)) return 0;
6448
+ const isYamlMapping = /^[A-Za-z0-9_.-]+\s*:(\s|$)/.test(candidate);
6449
+ const isListItem = /^-(?:(\s|$))/.test(candidate);
6450
+ const isIndented = /^[ \t]/.test(line);
6451
+ if (!isYamlMapping && !isListItem && !isIndented) return 0;
6452
+ }
6453
+ return 0;
6454
+ }
6455
+ function summarizeMarkdown(content) {
6456
+ const headings = [];
6457
+ const frontmatterKeys = [];
6458
+ const lines = content.replace(/^\uFEFF/, "").split(/\r\n|\n|\r/);
6459
+ let inFrontmatter = false;
6460
+ let fence = null;
6461
+ const frontMatterEndLine = frontMatterEnd(lines);
6462
+ for (let index = 0; index < lines.length; index++) {
6463
+ const line = lines[index];
6464
+ if (index === 0 && frontMatterEndLine > 0) {
6465
+ inFrontmatter = true;
6466
+ continue;
6467
+ }
6468
+ if (inFrontmatter) {
6469
+ const trimmedFrontmatter = line.trim();
6470
+ if (trimmedFrontmatter === "---" || trimmedFrontmatter === "...") {
6471
+ inFrontmatter = false;
6472
+ continue;
6473
+ }
6474
+ const match = /^([A-Za-z0-9_.-]+)\s*:/.exec(line);
6475
+ if (match) frontmatterKeys.push(match[1]);
6476
+ continue;
6477
+ }
6478
+ const trimmed = line.trim();
6479
+ const fenceMatch = /^(`{3,}|~{3,})(.*)$/.exec(trimmed);
6480
+ if (fenceMatch) {
6481
+ const run = fenceMatch[1];
6482
+ const rest = fenceMatch[2].trim();
6483
+ if (fence === null) {
6484
+ fence = { marker: run[0], length: run.length };
6485
+ } else if (run[0] === fence.marker && run.length >= fence.length && rest === "") {
6486
+ fence = null;
6487
+ }
6488
+ continue;
6489
+ }
6490
+ if (fence !== null) continue;
6491
+ const headingMatch = /^(#{1,6})\s+(.+)$/.exec(trimmed);
6492
+ if (headingMatch) {
6493
+ headings.push(`${headingMatch[1]} ${headingMatch[2].trim()}`);
6494
+ }
6495
+ }
6496
+ return {
6497
+ headings: headings.slice(0, 40),
6498
+ frontmatterKeys: Array.from(new Set(frontmatterKeys)).sort()
6499
+ };
6500
+ }
6501
+
6502
+ // src/gitignore.ts
6503
+ import * as fs9 from "fs";
6504
+ import * as path10 from "path";
6505
+ function appendGitignoreEntries(cwd, entries) {
6506
+ const wanted = [...new Set(entries)].filter((entry) => entry.trim().length > 0);
6507
+ if (wanted.length === 0) return { added: [], note: null };
6508
+ const ignorePath = path10.join(cwd, ".gitignore");
6509
+ const manual = `Add ${wanted.map((entry) => `"${entry}"`).join(" and ")} to your .gitignore yourself.`;
6510
+ let existing = "";
6511
+ try {
6512
+ if (fs9.existsSync(ignorePath)) {
6513
+ if (fs9.statSync(ignorePath).isDirectory()) {
6514
+ return { added: [], note: `${ignorePath} is a directory, so it was not updated. ${manual}` };
6515
+ }
6516
+ existing = fs9.readFileSync(ignorePath, "utf8");
6517
+ }
6518
+ } catch (err) {
6519
+ return {
6520
+ added: [],
6521
+ note: `${ignorePath} could not be read (${err.message}). ${manual}`
6522
+ };
6523
+ }
6524
+ const present = new Set(existing.split(/\r?\n/).map((line) => line.trim()));
6525
+ const added = wanted.filter((entry) => !present.has(entry));
6526
+ if (added.length === 0) return { added: [], note: null };
6527
+ const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : "\n";
6528
+ try {
6529
+ fs9.writeFileSync(ignorePath, `${existing}${prefix}${added.join("\n")}
6530
+ `, "utf8");
6531
+ } catch (err) {
6532
+ return { added: [], note: `${err.message}. ${manual}` };
6533
+ }
6534
+ return { added, note: null };
6535
+ }
6536
+ function gitignorePath(cwd, filePath) {
6537
+ return path10.relative(cwd, filePath).split(path10.sep).join("/");
6538
+ }
6539
+
6540
+ // src/version.ts
6541
+ var GENERATOR_NAME = "codebase-snapshot";
6542
+ var GENERATOR_VERSION = "0.9.15";
6543
+ var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
6544
+ function isOurGeneratorName(name) {
5907
6545
  if (typeof name !== "string") return false;
5908
6546
  return name === GENERATOR_NAME || LEGACY_GENERATOR_NAMES.includes(name);
5909
6547
  }
@@ -5992,7 +6630,8 @@ function renderConfig(answers) {
5992
6630
  // matched value is never included \u2014 only the path, the line and the rule.
5993
6631
  sarif: ${answers.sarif},
5994
6632
  // Snapshot only the files that differ from a git ref (for example "main"),
5995
- // plus untracked ones. null and false both mean "snapshot everything".
6633
+ // plus untracked ones. null means "snapshot everything"; any other value must
6634
+ // be a git ref string, and anything else is a configuration error.
5996
6635
  changedSince: null,
5997
6636
  // Snapshot only what is staged in the index: the pre-commit counterpart.
5998
6637
  staged: false,
@@ -6111,6 +6750,24 @@ function displayWidth(line) {
6111
6750
  return width;
6112
6751
  }
6113
6752
  var GUTTER_PATTERN = /^[ \t]*(?:[❯◆◻◼▏✖][ \t]+)*/;
6753
+ function sliceByDisplayWidth(text2, maxCells) {
6754
+ let cells = 0;
6755
+ let lastSpace = -1;
6756
+ let index = 0;
6757
+ for (const character of text2) {
6758
+ const width = isWideCodePoint(character.codePointAt(0) ?? 0) ? 2 : 1;
6759
+ if (cells + width > maxCells) break;
6760
+ if (character === " ") lastSpace = index;
6761
+ cells += width;
6762
+ index += character.length;
6763
+ }
6764
+ if (index >= text2.length) return { head: text2, tail: "" };
6765
+ if (lastSpace > 0) {
6766
+ return { head: text2.slice(0, lastSpace), tail: text2.slice(lastSpace + 1).trimStart() };
6767
+ }
6768
+ const safeIndex = index > 0 ? index : Array.from(text2)[0]?.length ?? 1;
6769
+ return { head: text2.slice(0, safeIndex), tail: text2.slice(safeIndex).trimStart() };
6770
+ }
6114
6771
  function wrapOneLine(line, limit) {
6115
6772
  if (displayWidth(line) <= limit) return [line];
6116
6773
  const gutter = GUTTER_PATTERN.exec(line)?.[0] ?? "";
@@ -6125,12 +6782,11 @@ function wrapOneLine(line, limit) {
6125
6782
  rows.push(prefix + rest);
6126
6783
  break;
6127
6784
  }
6128
- let cut = room;
6129
- const space = rest.slice(0, room).lastIndexOf(" ");
6130
- if (space > 0) cut = space;
6131
- const taken = rest.slice(0, cut).trimEnd();
6132
- rows.push(`${prefix}${taken.length > 0 ? taken : rest.slice(0, cut)}`);
6133
- rest = rest.slice(cut).trimStart();
6785
+ const { head, tail } = sliceByDisplayWidth(rest, room);
6786
+ rows.push(
6787
+ `${prefix}${head.length > 0 ? head : rest.slice(0, 1)}`
6788
+ );
6789
+ rest = tail;
6134
6790
  prefix = continuation;
6135
6791
  }
6136
6792
  return rows;
@@ -6201,7 +6857,7 @@ function keyReader(input) {
6201
6857
  next() {
6202
6858
  const queued = queue.shift();
6203
6859
  if (queued) return Promise.resolve(queued);
6204
- return new Promise((resolve9) => waiters.push(resolve9));
6860
+ return new Promise((resolve10) => waiters.push(resolve10));
6205
6861
  },
6206
6862
  close() {
6207
6863
  input.off("keypress", onKey);
@@ -6418,17 +7074,25 @@ var CONFIG_CANDIDATES = [
6418
7074
  ".snapshotrc.json",
6419
7075
  ".snapshotrc"
6420
7076
  ];
6421
- function chooseConfigFileName(cwd) {
6422
- if (!supportsTypeScriptImports()) return "snapshot.config.mjs";
6423
- const pkgPath = path11.join(cwd, "package.json");
6424
- if (!fs10.existsSync(pkgPath)) return "snapshot.config.mjs";
7077
+ function parsePackageJson(raw) {
7078
+ const parsed = JSON.parse(stripJsonComments2(raw));
7079
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
7080
+ throw new Error("package.json is not a JSON object");
7081
+ }
7082
+ return parsed;
7083
+ }
7084
+ function readPackageJson(cwd) {
6425
7085
  try {
6426
- const parsed = JSON.parse(fs10.readFileSync(pkgPath, "utf8"));
6427
- return parsed.type === "module" ? "snapshot.config.ts" : "snapshot.config.mjs";
7086
+ return parsePackageJson(fs10.readFileSync(path11.join(cwd, "package.json"), "utf8"));
6428
7087
  } catch {
6429
- return "snapshot.config.mjs";
7088
+ return null;
6430
7089
  }
6431
7090
  }
7091
+ function chooseConfigFileName(cwd) {
7092
+ if (!supportsTypeScriptImports()) return "snapshot.config.mjs";
7093
+ const parsed = readPackageJson(cwd);
7094
+ return parsed?.type === "module" ? "snapshot.config.ts" : "snapshot.config.mjs";
7095
+ }
6432
7096
  var SIZE_CHOICES = [
6433
7097
  { value: "60k", label: "Small", hint: "60 KB \xB7 ~15k tokens \xB7 tight context windows" },
6434
7098
  { value: "120k", label: "Medium", hint: "120 KB \xB7 ~30k tokens \xB7 recommended" },
@@ -6436,12 +7100,9 @@ var SIZE_CHOICES = [
6436
7100
  { value: "custom", label: "Custom\u2026", hint: "type a size like 150k or 1.5mb" }
6437
7101
  ];
6438
7102
  function packageJsonHasConfig(cwd) {
6439
- try {
6440
- const parsed = JSON.parse(fs10.readFileSync(path11.join(cwd, "package.json"), "utf8"));
6441
- return typeof parsed.snapshot === "object" && parsed.snapshot !== null && !Array.isArray(parsed.snapshot);
6442
- } catch {
6443
- return false;
6444
- }
7103
+ const parsed = readPackageJson(cwd);
7104
+ if (parsed === null) return false;
7105
+ return typeof parsed.snapshot === "object" && parsed.snapshot !== null && !Array.isArray(parsed.snapshot);
6445
7106
  }
6446
7107
  function artifactAnswers(options) {
6447
7108
  const artifacts = { ...DEFAULT_ANSWERS.artifacts };
@@ -6482,12 +7143,7 @@ function writeFileOrExplain(target, content) {
6482
7143
  function canWriteModuleConfig(name, cwd) {
6483
7144
  if (name.endsWith(".mjs") || name.endsWith(".ts")) return true;
6484
7145
  if (!name.endsWith(".js")) return false;
6485
- try {
6486
- const parsed = JSON.parse(fs10.readFileSync(path11.join(cwd, "package.json"), "utf8"));
6487
- return parsed.type === "module";
6488
- } catch {
6489
- return false;
6490
- }
7146
+ return readPackageJson(cwd)?.type === "module";
6491
7147
  }
6492
7148
  function configFormatLabel(name) {
6493
7149
  if (name.endsWith(".js")) return 'CommonJS `.js` (package.json has no "type": "module")';
@@ -6515,7 +7171,8 @@ function serializePackageJson(raw, value) {
6515
7171
  const crlf = raw.includes("\r\n");
6516
7172
  const body = JSON.stringify(value, null, spacing);
6517
7173
  const text2 = crlf ? body.replace(/\n/g, "\r\n") : body;
6518
- return `${text2}${raw.endsWith("\n") ? crlf ? "\r\n" : "\n" : ""}`;
7174
+ const bom = raw.startsWith("\uFEFF") ? "\uFEFF" : "";
7175
+ return `${bom}${text2}${raw.endsWith("\n") ? crlf ? "\r\n" : "\n" : ""}`;
6519
7176
  }
6520
7177
  function updatePackageJson(cwd, notes) {
6521
7178
  const packagePath = path11.join(cwd, "package.json");
@@ -6531,7 +7188,7 @@ function updatePackageJson(cwd, notes) {
6531
7188
  let parsed;
6532
7189
  try {
6533
7190
  raw = fs10.readFileSync(packagePath, "utf8");
6534
- parsed = JSON.parse(raw);
7191
+ parsed = parsePackageJson(raw);
6535
7192
  } catch {
6536
7193
  notes.push("Could not parse package.json; npm scripts and the devDependency were not added.");
6537
7194
  return unchanged;
@@ -6953,155 +7610,73 @@ function hasPriorSnapshot(cwd, outDir) {
6953
7610
 
6954
7611
  // src/index.ts
6955
7612
  import * as crypto4 from "crypto";
6956
- import { AsyncLocalStorage } from "async_hooks";
6957
- import * as fs14 from "fs";
6958
- import * as os2 from "os";
6959
- import * as path16 from "path";
6960
7613
 
6961
- // src/ast/structured.ts
6962
- function stripJsonComments2(content) {
6963
- const text2 = content.replace(/^\uFEFF/, "");
6964
- let out = "";
6965
- let inString = false;
6966
- let inLineComment = false;
6967
- let inBlockComment = false;
6968
- for (let i = 0; i < text2.length; i++) {
6969
- const char = text2[i];
6970
- const next = text2[i + 1];
6971
- if (inLineComment) {
6972
- if (char === "\n") {
6973
- inLineComment = false;
6974
- out += char;
6975
- }
6976
- continue;
6977
- }
6978
- if (inBlockComment) {
6979
- if (char === "*" && next === "/") {
6980
- inBlockComment = false;
6981
- i += 1;
7614
+ // src/stdout.ts
7615
+ import { AsyncLocalStorage } from "async_hooks";
7616
+ var hookStdoutScope = new AsyncLocalStorage();
7617
+ var captureScope = new AsyncLocalStorage();
7618
+ var installs = 0;
7619
+ var underlying = null;
7620
+ var router = null;
7621
+ var asText = (chunk) => typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
7622
+ var callbackIn = (rest) => {
7623
+ for (const argument of rest) {
7624
+ if (typeof argument === "function") return argument;
7625
+ }
7626
+ return void 0;
7627
+ };
7628
+ function installStdoutRouter() {
7629
+ if (installs === 0) {
7630
+ underlying = process.stdout.write;
7631
+ const realStdout = underlying.bind(process.stdout);
7632
+ const realStderr = process.stderr.write.bind(process.stderr);
7633
+ router = ((...args) => {
7634
+ if (hookStdoutScope.getStore() === true) return realStderr(...args);
7635
+ const capture = captureScope.getStore();
7636
+ if (capture !== void 0) {
7637
+ capture.write(asText(args[0]));
7638
+ const callback = callbackIn(args.slice(1));
7639
+ if (callback) callback(null);
7640
+ return true;
6982
7641
  }
6983
- continue;
6984
- }
6985
- if (inString) {
6986
- out += char;
6987
- if (char === "\\") {
6988
- if (next !== void 0) {
6989
- out += next;
6990
- i += 1;
6991
- }
6992
- } else if (char === '"') {
6993
- inString = false;
7642
+ return realStdout(...args);
7643
+ });
7644
+ process.stdout.write = router;
7645
+ }
7646
+ installs += 1;
7647
+ let released = false;
7648
+ return () => {
7649
+ if (released) return;
7650
+ released = true;
7651
+ installs -= 1;
7652
+ if (installs === 0) {
7653
+ if (process.stdout.write === router && underlying !== null) {
7654
+ process.stdout.write = underlying;
6994
7655
  }
6995
- continue;
6996
- }
6997
- if (char === '"') {
6998
- inString = true;
6999
- out += char;
7000
- continue;
7656
+ underlying = null;
7657
+ router = null;
7001
7658
  }
7002
- if (char === "/" && next === "/") {
7003
- inLineComment = true;
7004
- i += 1;
7005
- continue;
7006
- }
7007
- if (char === "/" && next === "*") {
7008
- inBlockComment = true;
7009
- i += 1;
7010
- continue;
7011
- }
7012
- out += char;
7013
- }
7014
- return out;
7659
+ };
7015
7660
  }
7016
- function summarizeJson(content) {
7661
+ async function runWithStdoutCapture(fn) {
7662
+ let text2 = "";
7663
+ const release = installStdoutRouter();
7017
7664
  try {
7018
- const parsed = JSON.parse(stripJsonComments2(content));
7019
- if (Array.isArray(parsed)) {
7020
- const sample = parsed[0];
7021
- const sampleKeys = sample && typeof sample === "object" && !Array.isArray(sample) ? Object.keys(sample).slice(0, 10).sort() : [];
7022
- return {
7023
- shape: "array",
7024
- itemCount: parsed.length,
7025
- keys: [],
7026
- sampleKeys
7027
- };
7028
- }
7029
- if (parsed && typeof parsed === "object") {
7030
- const keys = Object.keys(parsed).sort();
7031
- return {
7032
- shape: "object",
7033
- itemCount: keys.length,
7034
- keys: keys.slice(0, 30),
7035
- sampleKeys: []
7036
- };
7037
- }
7038
- return {
7039
- shape: typeof parsed,
7040
- itemCount: null,
7041
- keys: [],
7042
- sampleKeys: []
7043
- };
7044
- } catch {
7045
- return {
7046
- shape: "invalid-json",
7047
- itemCount: null,
7048
- keys: [],
7049
- sampleKeys: []
7050
- };
7051
- }
7052
- }
7053
- function summarizeMarkdown(content) {
7054
- const headings = [];
7055
- const frontmatterKeys = [];
7056
- const lines = content.replace(/^\uFEFF/, "").split("\n");
7057
- let inFrontmatter = false;
7058
- let fence = null;
7059
- let closesFrontmatter = false;
7060
- for (let index = 1; index < lines.length; index++) {
7061
- if (lines[index].trim() === "---") {
7062
- closesFrontmatter = true;
7063
- break;
7064
- }
7065
- }
7066
- for (let index = 0; index < lines.length; index++) {
7067
- const line = lines[index];
7068
- if (index === 0 && line.trim() === "---" && closesFrontmatter) {
7069
- inFrontmatter = true;
7070
- continue;
7071
- }
7072
- if (inFrontmatter) {
7073
- if (line.trim() === "---") {
7074
- inFrontmatter = false;
7075
- continue;
7076
- }
7077
- const match = /^([a-zA-Z0-9_-]+):/.exec(line);
7078
- if (match) frontmatterKeys.push(match[1]);
7079
- continue;
7080
- }
7081
- const trimmed = line.trim();
7082
- const fenceMatch = /^(`{3,}|~{3,})(.*)$/.exec(trimmed);
7083
- if (fenceMatch) {
7084
- const run = fenceMatch[1];
7085
- const rest = fenceMatch[2].trim();
7086
- if (fence === null) {
7087
- fence = { marker: run[0], length: run.length };
7088
- } else if (run[0] === fence.marker && run.length >= fence.length && rest === "") {
7089
- fence = null;
7090
- }
7091
- continue;
7092
- }
7093
- if (fence !== null) continue;
7094
- const headingMatch = /^(#{1,6})\s+(.+)$/.exec(trimmed);
7095
- if (headingMatch) {
7096
- headings.push(`${headingMatch[1]} ${headingMatch[2].trim()}`);
7097
- }
7665
+ const value = await captureScope.run(
7666
+ { write: (chunk) => void (text2 += chunk) },
7667
+ fn
7668
+ );
7669
+ return { value, text: text2 };
7670
+ } finally {
7671
+ release();
7098
7672
  }
7099
- return {
7100
- headings: headings.slice(0, 40),
7101
- frontmatterKeys: Array.from(new Set(frontmatterKeys)).sort()
7102
- };
7103
7673
  }
7104
7674
 
7675
+ // src/index.ts
7676
+ import * as fs14 from "fs";
7677
+ import * as os2 from "os";
7678
+ import * as path16 from "path";
7679
+
7105
7680
  // src/ast/skeleton.ts
7106
7681
  import ts2 from "typescript";
7107
7682
  function hasCollapsibleBody(node) {
@@ -7109,25 +7684,36 @@ function hasCollapsibleBody(node) {
7109
7684
  const body = node.body;
7110
7685
  return body !== void 0 && ts2.isBlock(body);
7111
7686
  }
7112
- function isTsxFileName(fileName) {
7113
- return fileName.toLowerCase().endsWith(".tsx");
7687
+ function scriptKindFor(fileName) {
7688
+ const lower = fileName.toLowerCase();
7689
+ if (lower.endsWith(".tsx")) return ts2.ScriptKind.TSX;
7690
+ if (lower.endsWith(".jsx")) return ts2.ScriptKind.JSX;
7691
+ if (lower.endsWith(".js") || lower.endsWith(".mjs") || lower.endsWith(".cjs")) {
7692
+ return ts2.ScriptKind.JS;
7693
+ }
7694
+ return ts2.ScriptKind.TS;
7114
7695
  }
7115
7696
  function skeletonizeTypeScript(source, fileName = "file.ts") {
7116
- const scriptKind = isTsxFileName(fileName) ? ts2.ScriptKind.TSX : ts2.ScriptKind.TS;
7117
7697
  const sourceFile = ts2.createSourceFile(
7118
7698
  fileName,
7119
7699
  source,
7120
7700
  ts2.ScriptTarget.Latest,
7121
- true,
7122
- scriptKind
7701
+ // `setParentNodes: false`. Nothing here reads `.parent` — the one `getStart` call is given the
7702
+ // source file explicitly, which is the reason that argument exists. Asking for parent pointers
7703
+ // makes the parser run a second full pass over every node in the file to set them, on top of
7704
+ // the summary parse this same file already pays for.
7705
+ false,
7706
+ scriptKindFor(fileName)
7123
7707
  );
7124
7708
  const spans = [];
7125
7709
  const visit = (node) => {
7126
7710
  if ((ts2.isFunctionDeclaration(node) || ts2.isMethodDeclaration(node) || ts2.isConstructorDeclaration(node) || ts2.isGetAccessorDeclaration(node) || ts2.isSetAccessorDeclaration(node) || ts2.isFunctionExpression(node) || ts2.isArrowFunction(node)) && hasCollapsibleBody(node)) {
7127
7711
  const body = node.body;
7128
- const start = body.getStart(sourceFile);
7129
- const end = body.getEnd();
7130
- if (end > start) spans.push({ start, end });
7712
+ if (body.statements.length > 0) {
7713
+ const start = body.getStart(sourceFile);
7714
+ const end = body.getEnd();
7715
+ if (end > start) spans.push({ start, end });
7716
+ }
7131
7717
  }
7132
7718
  ts2.forEachChild(node, visit);
7133
7719
  };
@@ -7139,16 +7725,21 @@ function skeletonizeTypeScript(source, fileName = "file.ts") {
7139
7725
  if (last && span.start < last.end) continue;
7140
7726
  outermost.push(span);
7141
7727
  }
7142
- let text2 = source;
7143
- for (let index = outermost.length - 1; index >= 0; index -= 1) {
7144
- const span = outermost[index];
7145
- text2 = `${text2.slice(0, span.start)}{ /* ... */ }${text2.slice(span.end)}`;
7728
+ const chunks = [];
7729
+ let cursor = 0;
7730
+ for (const span of outermost) {
7731
+ chunks.push(source.slice(cursor, span.start), "{ /* ... */ }");
7732
+ cursor = span.end;
7146
7733
  }
7147
- return { text: text2, collapsed: outermost.length };
7734
+ chunks.push(source.slice(cursor));
7735
+ return { text: chunks.join(""), collapsed: outermost.length };
7148
7736
  }
7149
7737
  function isSkeletonizable(filePath) {
7150
7738
  const lower = filePath.toLowerCase();
7151
- return lower.endsWith(".ts") || lower.endsWith(".tsx") || lower.endsWith(".mts") || lower.endsWith(".cts");
7739
+ if (lower.endsWith(".d.ts") || lower.endsWith(".d.mts") || lower.endsWith(".d.cts")) {
7740
+ return false;
7741
+ }
7742
+ return lower.endsWith(".ts") || lower.endsWith(".tsx") || lower.endsWith(".mts") || lower.endsWith(".cts") || lower.endsWith(".js") || lower.endsWith(".jsx") || lower.endsWith(".mjs") || lower.endsWith(".cjs");
7152
7743
  }
7153
7744
 
7154
7745
  // src/generator/audit.ts
@@ -7422,23 +8013,55 @@ function truncateWithBudgetMarker(content, maxBytes, budget, originalLines) {
7422
8013
  };
7423
8014
  }
7424
8015
  function partitionFiles(files, maxPartBytes, contentFingerprint) {
7425
- if (files.length === 0) return [];
7426
- const budget = Math.max(MIN_SECTION_BUDGET_BYTES + HEADER_RESERVE_BYTES, maxPartBytes);
7427
- const sectionBudget = budget - HEADER_RESERVE_BYTES;
7428
- const prepared = files.map((file) => prepareSection(file, sectionBudget));
7429
- let groups = greedyGroups(prepared, budget);
8016
+ return partitionFilesForBuckets([{ files, budgetBytes: maxPartBytes }], contentFingerprint);
8017
+ }
8018
+ function partitionFilesForBuckets(buckets, contentFingerprint) {
8019
+ const groups = [];
8020
+ for (const bucket of buckets) {
8021
+ if (bucket.files.length === 0) continue;
8022
+ const budget = Math.max(
8023
+ MIN_SECTION_BUDGET_BYTES + HEADER_RESERVE_BYTES,
8024
+ bucket.budgetBytes
8025
+ );
8026
+ const sectionBudget = budget - HEADER_RESERVE_BYTES;
8027
+ const prepared = bucket.files.map((file) => prepareSection(file, sectionBudget, budget));
8028
+ for (const sections of greedyGroups(prepared, budget)) groups.push({ sections, budget });
8029
+ }
8030
+ if (groups.length === 0) return [];
8031
+ const measurements = /* @__PURE__ */ new Map();
8032
+ const widthOf = (total) => Math.max(3, String(total).length);
8033
+ const measure = (group, index, total) => {
8034
+ const cached = measurements.get(group);
8035
+ const width = widthOf(total);
8036
+ if (cached !== void 0 && cached.index === index && cached.width === width) {
8037
+ return cached.size;
8038
+ }
8039
+ const { content } = assembleGroup(group, index, total, contentFingerprint);
8040
+ const size2 = Buffer.byteLength(content, "utf8");
8041
+ measurements.set(group, { index, width, size: size2 });
8042
+ return size2;
8043
+ };
7430
8044
  for (let pass = 0; pass < MAX_SPLIT_PASSES; pass++) {
7431
- const rendered = renderGroups(groups, budget, contentFingerprint);
7432
- const oversized = rendered.findIndex((part) => part.metadata.byteSize > budget);
7433
- if (oversized === -1) return rendered;
8045
+ const total = groups.length;
8046
+ let oversized = -1;
8047
+ for (let index = 0; index < total; index += 1) {
8048
+ const group2 = groups[index];
8049
+ if (measure(group2, index, total) > group2.budget) {
8050
+ oversized = index;
8051
+ break;
8052
+ }
8053
+ }
8054
+ if (oversized === -1) return renderGroups(groups, contentFingerprint);
7434
8055
  const group = groups[oversized];
7435
- if (group.length > 1) {
7436
- const moved = group.pop();
7437
- groups.splice(oversized + 1, 0, [moved]);
8056
+ if (group.sections.length > 1) {
8057
+ const moved = group.sections.pop();
8058
+ groups.splice(oversized + 1, 0, { sections: [moved], budget: group.budget });
8059
+ measurements.delete(group);
7438
8060
  continue;
7439
8061
  }
7440
- const [section] = group;
7441
- const overflow = rendered[oversized].metadata.byteSize - budget;
8062
+ const [section] = group.sections;
8063
+ if (section === void 0) return renderGroups(groups, contentFingerprint);
8064
+ const overflow = measure(group, oversized, total) - group.budget;
7442
8065
  const currentContent = section.file.content ?? "";
7443
8066
  const shrinkTo = Math.max(
7444
8067
  0,
@@ -7447,26 +8070,33 @@ function partitionFiles(files, maxPartBytes, contentFingerprint) {
7447
8070
  const shrunk = truncateWithBudgetMarker(
7448
8071
  currentContent,
7449
8072
  shrinkTo,
7450
- budget,
8073
+ group.budget,
7451
8074
  section.file.originalLines
7452
8075
  );
7453
8076
  if (shrunk.isTruncated) {
7454
8077
  applyTruncatedContent(section.file, shrunk.content);
7455
8078
  section.text = renderFileSection(section.file);
7456
8079
  section.byteSize = Buffer.byteLength(section.text, "utf8");
8080
+ measurements.delete(group);
7457
8081
  continue;
7458
8082
  }
8083
+ const rendered = renderGroups(groups, contentFingerprint);
7459
8084
  const marker2 = TRUNCATION_MARKER;
7460
- assertBudgetHoldsMarker(budget);
8085
+ assertBudgetHoldsMarker(group.budget);
7461
8086
  const target = Math.max(
7462
8087
  0,
7463
- budget - Buffer.byteLength(marker2, "utf8") - TOKEN_LINE_SLACK
8088
+ group.budget - Buffer.byteLength(marker2, "utf8") - TOKEN_LINE_SLACK
7464
8089
  );
7465
8090
  const clipped = truncateToBytes(rendered[oversized].markdown, target);
7466
- rendered[oversized] = rehashPart(rendered[oversized], clipped.content + marker2);
8091
+ rendered[oversized] = rehashPart(
8092
+ rendered[oversized],
8093
+ clipped.content + marker2
8094
+ );
7467
8095
  return rendered;
7468
8096
  }
7469
- return enforceBudget(renderGroups(groups, budget, contentFingerprint), budget);
8097
+ return renderGroups(groups, contentFingerprint).flatMap(
8098
+ (part) => enforceBudget([part], part.metadata.budgetBytes)
8099
+ );
7470
8100
  }
7471
8101
  var TRUNCATION_MARKER = "\n... [part truncated: cannot fit budget] ...\n";
7472
8102
  function assertBudgetHoldsMarker(budget) {
@@ -7489,69 +8119,7 @@ function enforceBudget(parts, budget) {
7489
8119
  return rehashPart(part, clipped.content + TRUNCATION_MARKER);
7490
8120
  });
7491
8121
  }
7492
- function renumberParts(parts, contentFingerprint) {
7493
- const total = parts.length;
7494
- if (total === 0) return [];
7495
- const zeroPad = (index) => String(index).padStart(Math.max(3, String(total).length), "0");
7496
- const nameFor = (position) => `part-${zeroPad(position)}.md`;
7497
- const marker2 = "## Contents\n";
7498
- const renumbered = parts.map((part, index) => {
7499
- const markerIndex = part.markdown.indexOf(marker2);
7500
- const body = markerIndex === -1 ? "" : part.markdown.slice(markerIndex + marker2.length);
7501
- const included = part.metadata.includedFiles;
7502
- if (markerIndex === -1) {
7503
- throw new Error(`${part.filename} has no "## Contents" section to re-number.`);
7504
- }
7505
- const layerCounts = {};
7506
- const kindCounts = {};
7507
- for (const file of included) {
7508
- layerCounts[file.layer] = (layerCounts[file.layer] || 0) + 1;
7509
- kindCounts[file.kind] = (kindCounts[file.kind] || 0) + 1;
7510
- }
7511
- const pathLines = included.map((file) => displayPath(file.relativePath));
7512
- const listFence = fenceForText(pathLines.join("\n"), 3);
7513
- const header = [
7514
- `# Codebase Snapshot Part ${zeroPad(index + 1)} of ${zeroPad(total)}`,
7515
- "",
7516
- `- Previous: ${index === 0 ? "none" : nameFor(index)}`,
7517
- `- Next: ${index === total - 1 ? "none" : nameFor(index + 2)}`,
7518
- `- Files: ${included.length}`,
7519
- `- Content Fingerprint: ${contentFingerprint || "none"}`,
7520
- `- Layers: ${topEntries(layerCounts, 6) || "none"}`,
7521
- `- Kinds: ${topEntries(kindCounts, 8) || "none"}`,
7522
- "",
7523
- UNTRUSTED_CONTENT_NOTICE,
7524
- "",
7525
- "## Files",
7526
- "",
7527
- `${listFence}text`,
7528
- ...pathLines,
7529
- listFence,
7530
- "",
7531
- "## Contents",
7532
- ""
7533
- ].join("\n");
7534
- const assembled = (header + body).replace(/\r\n/g, "\n");
7535
- const estimatedTokens = estimateTokens(assembled);
7536
- const markdown = insertTokenLine(assembled, estimatedTokens);
7537
- const metadata = {
7538
- ...part.metadata,
7539
- index: index + 1,
7540
- filename: nameFor(index + 1),
7541
- byteSize: Buffer.byteLength(markdown, "utf8"),
7542
- estimatedTokens,
7543
- sha256: crypto3.createHash("sha256").update(markdown).digest("hex"),
7544
- lines: countLines(markdown),
7545
- fileCount: included.length,
7546
- layersCovered: Object.keys(layerCounts).sort()
7547
- };
7548
- return { filename: metadata.filename, markdown, metadata };
7549
- });
7550
- return renumbered.map(
7551
- (part) => enforceBudget([part], part.metadata.budgetBytes)[0] ?? part
7552
- );
7553
- }
7554
- var SECTION_TRUNCATION_NOTICE = "\n... [section truncated: metadata alone exceeds the part budget] ...\n";
8122
+ var SECTION_TRUNCATION_NOTICE = "... [section truncated: the fixed metadata and a code fence did not fit the part budget] ...";
7555
8123
  var METADATA_VALUE_MAX = 200;
7556
8124
  var DISPLAY_PATH_MAX = 300;
7557
8125
  function capValue(value, max) {
@@ -7564,7 +8132,7 @@ var displayPath = (value) => capValue(escapeControls(value), DISPLAY_PATH_MAX);
7564
8132
  function topEntries(counts, limit) {
7565
8133
  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(", ");
7566
8134
  }
7567
- function prepareSection(file, sectionBudget) {
8135
+ function prepareSection(file, sectionBudget, partBudget) {
7568
8136
  let text2 = renderFileSection(file);
7569
8137
  let byteSize = Buffer.byteLength(text2, "utf8");
7570
8138
  if (byteSize <= sectionBudget) return { file, text: text2, byteSize };
@@ -7576,7 +8144,7 @@ function prepareSection(file, sectionBudget) {
7576
8144
  const truncated = truncateWithBudgetMarker(
7577
8145
  content,
7578
8146
  allowed,
7579
- sectionBudget,
8147
+ partBudget,
7580
8148
  file.originalLines
7581
8149
  );
7582
8150
  if (!truncated.isTruncated) return;
@@ -7593,13 +8161,57 @@ function prepareSection(file, sectionBudget) {
7593
8161
  shrinkBody();
7594
8162
  }
7595
8163
  if (byteSize > sectionBudget) {
7596
- const target = sectionBudget - Buffer.byteLength(SECTION_TRUNCATION_NOTICE, "utf8");
7597
- const truncated = truncateToBytes(text2, Math.max(0, target));
7598
- text2 = truncated.content + SECTION_TRUNCATION_NOTICE;
8164
+ applyTruncatedContent(file, SECTION_TRUNCATION_NOTICE);
8165
+ file.summary = void 0;
8166
+ file.summaryOmitted = true;
8167
+ text2 = renderFileSection(file);
7599
8168
  byteSize = Buffer.byteLength(text2, "utf8");
8169
+ if (byteSize > sectionBudget) {
8170
+ text2 = truncateRenderedSection(text2, sectionBudget, fenceForContent(file.content ?? ""));
8171
+ byteSize = Buffer.byteLength(text2, "utf8");
8172
+ }
7600
8173
  }
7601
8174
  return { file, text: text2, byteSize };
7602
8175
  }
8176
+ function truncateRenderedSection(text2, sectionBudget, fence) {
8177
+ const closing = `
8178
+ ${SECTION_TRUNCATION_NOTICE}
8179
+ ${fence}
8180
+ `;
8181
+ const bodyRoom = sectionBudget - Buffer.byteLength(closing, "utf8");
8182
+ if (bodyRoom > 0) {
8183
+ const cut2 = truncateToBytes(text2, bodyRoom).content;
8184
+ const lastBreak2 = cut2.lastIndexOf("\n");
8185
+ const kept = lastBreak2 >= 0 ? cut2.slice(0, lastBreak2 + 1) : "";
8186
+ if (fenceIsOpen(kept, fence)) return `${kept}${closing}`;
8187
+ }
8188
+ const probe = text2.slice(0, 512);
8189
+ const emptyFence = fenceForText(probe.slice(0, Math.max(0, probe.lastIndexOf("\n") + 1)), 4);
8190
+ const block = `
8191
+ ${emptyFence}
8192
+ ${SECTION_TRUNCATION_NOTICE}
8193
+ ${emptyFence}
8194
+ `;
8195
+ const prefixRoom = sectionBudget - Buffer.byteLength(block, "utf8");
8196
+ const cut = prefixRoom > 0 ? truncateToBytes(text2, prefixRoom).content : "";
8197
+ const lastBreak = cut.lastIndexOf("\n");
8198
+ const prefix = lastBreak >= 0 ? cut.slice(0, lastBreak + 1) : "";
8199
+ return `${dropTrailingOpenFence(prefix, fence)}${block}`;
8200
+ }
8201
+ function dropTrailingOpenFence(text2, fence) {
8202
+ if (!fenceIsOpen(text2, fence)) return text2;
8203
+ const lines = text2.split("\n");
8204
+ const opening = lines.findIndex((line) => line.startsWith(fence));
8205
+ if (opening < 0) return text2;
8206
+ return lines.slice(0, opening).join("\n") + (opening > 0 ? "\n" : "");
8207
+ }
8208
+ function fenceIsOpen(text2, fence) {
8209
+ let open = false;
8210
+ for (const line of text2.split("\n")) {
8211
+ if (line.startsWith(fence)) open = !open;
8212
+ }
8213
+ return open;
8214
+ }
7603
8215
  function applyTruncatedContent(file, content) {
7604
8216
  file.content = content;
7605
8217
  file.isPreviewTruncated = true;
@@ -7647,52 +8259,64 @@ function greedyGroups(sections, budget) {
7647
8259
  if (current.length > 0) groups.push(current);
7648
8260
  return groups;
7649
8261
  }
7650
- function renderGroups(groups, budget, contentFingerprint) {
8262
+ function assembleGroup(group, index, total, contentFingerprint) {
8263
+ const width = Math.max(3, String(total).length);
8264
+ const zeroPad = (value) => String(value).padStart(width, "0");
8265
+ const filename = `part-${zeroPad(index + 1)}.md`;
8266
+ const prev = index === 0 ? "none" : `part-${zeroPad(index)}.md`;
8267
+ const next = index === total - 1 ? "none" : `part-${zeroPad(index + 2)}.md`;
8268
+ for (const section of group.sections) {
8269
+ section.file.part = filename;
8270
+ }
8271
+ const layerCounts = {};
8272
+ const kindCounts = {};
8273
+ for (const section of group.sections) {
8274
+ layerCounts[section.file.layer] = (layerCounts[section.file.layer] || 0) + 1;
8275
+ kindCounts[section.file.kind] = (kindCounts[section.file.kind] || 0) + 1;
8276
+ }
8277
+ const pathLines = group.sections.map((s) => displayPath(s.file.relativePath));
8278
+ const listFence = fenceForText(pathLines.join("\n"), 3);
8279
+ const header = [
8280
+ `# Codebase Snapshot Part ${zeroPad(index + 1)} of ${zeroPad(total)}`,
8281
+ "",
8282
+ `- Previous: ${prev}`,
8283
+ `- Next: ${next}`,
8284
+ `- Files: ${group.sections.length}`,
8285
+ `- Content Fingerprint: ${contentFingerprint || "none"}`,
8286
+ `- Layers: ${topEntries(layerCounts, 6) || "none"}`,
8287
+ `- Kinds: ${topEntries(kindCounts, 8) || "none"}`,
8288
+ "",
8289
+ UNTRUSTED_CONTENT_NOTICE,
8290
+ "",
8291
+ "## Files",
8292
+ "",
8293
+ `${listFence}text`,
8294
+ ...pathLines,
8295
+ listFence,
8296
+ "",
8297
+ "## Contents",
8298
+ ""
8299
+ ].join("\n");
8300
+ const assembled = (header + group.sections.map((s) => s.text).join("")).replace(
8301
+ /\r\n|\r/g,
8302
+ "\n"
8303
+ );
8304
+ const estimatedTokens = estimateTokens(assembled);
8305
+ return { filename, content: insertTokenLine(assembled, estimatedTokens), estimatedTokens };
8306
+ }
8307
+ function renderGroups(groups, contentFingerprint) {
7651
8308
  const total = groups.length;
7652
- const zeroPad = (index) => String(index).padStart(Math.max(3, String(total).length), "0");
7653
8309
  return groups.map((group, index) => {
7654
- const filename = `part-${zeroPad(index + 1)}.md`;
7655
- const prev = index === 0 ? "none" : `part-${zeroPad(index)}.md`;
7656
- const next = index === total - 1 ? "none" : `part-${zeroPad(index + 2)}.md`;
7657
- for (const section of group) {
7658
- section.file.part = filename;
7659
- }
7660
- const layersCovered = Array.from(new Set(group.map((s) => s.file.layer))).sort();
7661
- const layerCounts = {};
7662
- const kindCounts = {};
7663
- for (const section of group) {
7664
- layerCounts[section.file.layer] = (layerCounts[section.file.layer] || 0) + 1;
7665
- kindCounts[section.file.kind] = (kindCounts[section.file.kind] || 0) + 1;
7666
- }
7667
- const pathLines = group.map((s) => displayPath(s.file.relativePath));
7668
- const listFence = fenceForText(pathLines.join("\n"), 3);
7669
- const header = [
7670
- `# Codebase Snapshot Part ${zeroPad(index + 1)} of ${zeroPad(total)}`,
7671
- "",
7672
- `- Previous: ${prev}`,
7673
- `- Next: ${next}`,
7674
- `- Files: ${group.length}`,
7675
- `- Content Fingerprint: ${contentFingerprint || "none"}`,
7676
- `- Layers: ${topEntries(layerCounts, 6) || "none"}`,
7677
- `- Kinds: ${topEntries(kindCounts, 8) || "none"}`,
7678
- "",
7679
- UNTRUSTED_CONTENT_NOTICE,
7680
- "",
7681
- "## Files",
7682
- "",
7683
- `${listFence}text`,
7684
- ...pathLines,
7685
- listFence,
7686
- "",
7687
- "## Contents",
7688
- ""
7689
- ].join("\n");
7690
- const assembled = (header + group.map((s) => s.text).join("")).replace(/\r\n/g, "\n");
7691
- const estimatedTokens = estimateTokens(assembled);
7692
- const content = insertTokenLine(assembled, estimatedTokens);
8310
+ const { filename, content, estimatedTokens } = assembleGroup(
8311
+ group,
8312
+ index,
8313
+ total,
8314
+ contentFingerprint
8315
+ );
7693
8316
  const byteSize = Buffer.byteLength(content, "utf8");
7694
8317
  const sha256 = crypto3.createHash("sha256").update(content).digest("hex");
7695
- const includedFiles = group.map(({ file }) => ({
8318
+ const layersCovered = Array.from(new Set(group.sections.map((s) => s.file.layer))).sort();
8319
+ const includedFiles = group.sections.map(({ file }) => ({
7696
8320
  relativePath: file.relativePath,
7697
8321
  sourceBytes: file.sizeBytes,
7698
8322
  includedBytes: file.includedBytes,
@@ -7705,10 +8329,10 @@ function renderGroups(groups, budget, contentFingerprint) {
7705
8329
  filename,
7706
8330
  byteSize,
7707
8331
  estimatedTokens,
7708
- budgetBytes: budget,
8332
+ budgetBytes: group.budget,
7709
8333
  sha256,
7710
8334
  lines: countLines(content),
7711
- fileCount: group.length,
8335
+ fileCount: group.sections.length,
7712
8336
  layersCovered,
7713
8337
  includedFiles
7714
8338
  };
@@ -7716,7 +8340,7 @@ function renderGroups(groups, budget, contentFingerprint) {
7716
8340
  });
7717
8341
  }
7718
8342
  function emittedBody(content) {
7719
- const normalised = content.replace(/\r\n/g, "\n");
8343
+ const normalised = content.replace(/\r\n|\r/g, "\n");
7720
8344
  return normalised.endsWith("\n") ? normalised.slice(0, -1) : normalised;
7721
8345
  }
7722
8346
  function compactMetadata(file) {
@@ -7784,7 +8408,7 @@ function generateMonolithJson(manifest, filesWithContent) {
7784
8408
  }
7785
8409
  function generateMonolithMarkdown(manifest, filesWithContent) {
7786
8410
  const sections = filesWithContent.map((file) => {
7787
- const content = (file.content ?? "").replace(/\r\n/g, "\n");
8411
+ const content = (file.content ?? "").replace(/\r\n|\r/g, "\n");
7788
8412
  const fence = fenceForContent(content);
7789
8413
  return [
7790
8414
  `## File: ${escapeControls(file.relativePath)}`,
@@ -8026,6 +8650,7 @@ function generateProjectTree(filePaths) {
8026
8650
 
8027
8651
  // src/update-check.ts
8028
8652
  import * as fs12 from "fs";
8653
+ import * as http from "http";
8029
8654
  import * as https from "https";
8030
8655
  import * as os from "os";
8031
8656
  import * as path13 from "path";
@@ -8050,22 +8675,28 @@ function updateCommand(kind) {
8050
8675
  if (kind === "local") return "npm install codebase-snapshot@latest";
8051
8676
  return "npm install -g codebase-snapshot";
8052
8677
  }
8053
- function versionParts(value) {
8054
- const core = value.trim().replace(/^v/i, "").split("-")[0];
8055
- return core.split(".").map((part) => {
8678
+ function parseSemver(value) {
8679
+ const cleaned = value.trim().replace(/^v/i, "").split("+")[0] ?? "";
8680
+ const dash = cleaned.indexOf("-");
8681
+ const corePart = dash === -1 ? cleaned : cleaned.slice(0, dash);
8682
+ const prerelease = dash === -1 ? null : cleaned.slice(dash + 1);
8683
+ const core = corePart.split(".").map((part) => {
8056
8684
  const parsed = Number(part);
8057
8685
  return Number.isFinite(parsed) ? parsed : 0;
8058
8686
  });
8687
+ return { core, prerelease };
8059
8688
  }
8060
8689
  function isNewer(candidate, current) {
8061
- const left = versionParts(candidate);
8062
- const right = versionParts(current);
8063
- const length = Math.max(left.length, right.length);
8690
+ const left = parseSemver(candidate);
8691
+ const right = parseSemver(current);
8692
+ if (left.prerelease !== null && right.prerelease === null) return false;
8693
+ const length = Math.max(left.core.length, right.core.length);
8064
8694
  for (let index = 0; index < length; index += 1) {
8065
- const a = left[index] ?? 0;
8066
- const b = right[index] ?? 0;
8695
+ const a = left.core[index] ?? 0;
8696
+ const b = right.core[index] ?? 0;
8067
8697
  if (a !== b) return a > b;
8068
8698
  }
8699
+ if (left.prerelease === null && right.prerelease !== null) return true;
8069
8700
  return false;
8070
8701
  }
8071
8702
  function cacheDirectory(env = process.env, platform = process.platform) {
@@ -8133,14 +8764,22 @@ function writeCache(file, entry) {
8133
8764
  }
8134
8765
  }
8135
8766
  function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOUT_MS) {
8136
- return new Promise((resolve9) => {
8767
+ return new Promise((resolve10) => {
8137
8768
  let settled = false;
8769
+ let request = null;
8138
8770
  const finish = (value) => {
8139
8771
  if (settled) return;
8140
8772
  settled = true;
8141
- resolve9(value);
8773
+ clearTimeout(deadline);
8774
+ resolve10(value);
8142
8775
  };
8143
- const request = https.get(
8776
+ const deadline = setTimeout(() => {
8777
+ request?.destroy();
8778
+ finish(null);
8779
+ }, timeoutMs);
8780
+ deadline.unref();
8781
+ const transport = url.startsWith("http:") ? http : https;
8782
+ request = transport.get(
8144
8783
  url,
8145
8784
  {
8146
8785
  headers: {
@@ -8159,7 +8798,7 @@ function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOU
8159
8798
  response.on("data", (chunk) => {
8160
8799
  body += chunk;
8161
8800
  if (body.length > 64 * 1024) {
8162
- request.destroy();
8801
+ request?.destroy();
8163
8802
  finish(null);
8164
8803
  }
8165
8804
  });
@@ -8174,10 +8813,6 @@ function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOU
8174
8813
  }
8175
8814
  );
8176
8815
  request.on("error", () => finish(null));
8177
- request.setTimeout(timeoutMs, () => {
8178
- request.destroy();
8179
- finish(null);
8180
- });
8181
8816
  });
8182
8817
  }
8183
8818
  async function checkForUpdate(options) {
@@ -8345,7 +8980,10 @@ const { parentPort, workerData } = require("node:worker_threads");
8345
8980
  parentPort.postMessage({ ok: false, message: loaded.errors.join("; ") });
8346
8981
  return;
8347
8982
  }
8348
- const config = mod.resolveConfig(loaded.config, workerData.cliOptions, workerData.cwd);
8983
+ // \`hooks: {}\` is a value, not an absence: the config is applied with the hook list emptied,
8984
+ // so the run is the documented MCP run rather than the CLI run with one setting removed.
8985
+ const base = loaded.config ? { ...loaded.config, hooks: {} } : null;
8986
+ const config = mod.resolveConfig(base, workerData.cliOptions, workerData.cwd);
8349
8987
  const manifest = mod.generateSnapshot(config);
8350
8988
  parentPort.postMessage({
8351
8989
  ok: true,
@@ -8368,14 +9006,15 @@ const { parentPort, workerData } = require("node:worker_threads");
8368
9006
  })();
8369
9007
  `;
8370
9008
  function generateInWorker(cwd, cliOptions) {
8371
- return new Promise((resolve9) => {
9009
+ return new Promise((resolve10) => {
8372
9010
  let settled = false;
9011
+ let worker = null;
8373
9012
  const finish = (result) => {
8374
9013
  if (settled) return;
8375
9014
  settled = true;
8376
- resolve9(result);
9015
+ if (worker !== null) void worker.terminate();
9016
+ resolve10(result);
8377
9017
  };
8378
- let worker;
8379
9018
  const isCjs = typeof __dirname !== "undefined";
8380
9019
  const directory = isCjs ? __dirname : path15.dirname(fileURLToPath(import.meta.url));
8381
9020
  try {
@@ -8408,7 +9047,100 @@ function generateInWorker(cwd, cliOptions) {
8408
9047
 
8409
9048
  // src/index.ts
8410
9049
  var SCHEMA_VERSION = "3.0.0";
8411
- var SUMMARY_MAX_SOURCE_BYTES = 2 * 1024 * 1024;
9050
+ var SUMMARY_MAX_SOURCE_BYTES2 = SUMMARY_MAX_SOURCE_BYTES;
9051
+ var FILE_DERIVATIONS = /* @__PURE__ */ new Map();
9052
+ var FILE_DERIVATION_LIMIT_BYTES = 64 * 1024 * 1024;
9053
+ var fileDerivationBytes = 0;
9054
+ function takeDerivation(path22, hash, settings) {
9055
+ const cached = FILE_DERIVATIONS.get(path22);
9056
+ if (cached === void 0 || cached.hash !== hash || cached.settings !== settings) return void 0;
9057
+ return cached;
9058
+ }
9059
+ function rememberDerivation(path22, hash, settings, derivation) {
9060
+ const bodyBytes = derivation.finalContent === derivation.redacted ? derivation.redacted.length : derivation.redacted.length + derivation.finalContent.length;
9061
+ const bytes = bodyBytes * 2 + 512;
9062
+ if (bytes > FILE_DERIVATION_LIMIT_BYTES / 4) return;
9063
+ while (fileDerivationBytes + bytes > FILE_DERIVATION_LIMIT_BYTES) {
9064
+ const oldest = FILE_DERIVATIONS.keys().next();
9065
+ if (oldest.done === true) break;
9066
+ const evicted = FILE_DERIVATIONS.get(oldest.value);
9067
+ FILE_DERIVATIONS.delete(oldest.value);
9068
+ if (evicted !== void 0) fileDerivationBytes -= evicted.bytes;
9069
+ }
9070
+ FILE_DERIVATIONS.set(path22, { ...derivation, hash, settings, bytes });
9071
+ fileDerivationBytes += bytes;
9072
+ }
9073
+ function derivationSettings(config) {
9074
+ const rules = config.secretRules.map(
9075
+ (rule) => `${rule.rule}\0${rule.pattern.source}\0${rule.pattern.flags}\0${rule.valueGroup ?? ""}`
9076
+ ).join("");
9077
+ return `${GENERATOR_VERSION}${configDigest(config)}${sha256Hex2(rules)}`;
9078
+ }
9079
+ function deriveFile(relativePath, rawContent, sizeBytes, config) {
9080
+ const lineCount = countLines(rawContent);
9081
+ const { redacted, findings } = scanAndRedactSecrets(rawContent, config.secretRules, relativePath);
9082
+ const isLarge = sizeBytes > config.largeFileBytes;
9083
+ let finalContent = redacted;
9084
+ let isPreviewTruncated = false;
9085
+ let includedLines = lineCount;
9086
+ let inclusionMode = "full";
9087
+ if (config.skeleton === true && isSkeletonizable(relativePath)) {
9088
+ const skeleton = skeletonizeTypeScript(redacted, relativePath);
9089
+ if (skeleton.collapsed > 0) {
9090
+ finalContent = skeleton.text;
9091
+ inclusionMode = "signatures";
9092
+ includedLines = countLines(skeleton.text);
9093
+ }
9094
+ }
9095
+ if (isLarge && inclusionMode !== "signatures") {
9096
+ const preview = truncatePreview(redacted, config.previewHeadLines, config.previewTailLines);
9097
+ finalContent = preview.content;
9098
+ isPreviewTruncated = preview.isTruncated;
9099
+ includedLines = preview.includedLines;
9100
+ inclusionMode = isPreviewTruncated ? "preview" : "full";
9101
+ }
9102
+ let summary;
9103
+ let summaryQuality;
9104
+ let summarySkip = null;
9105
+ let summaryWarning = null;
9106
+ let dependentImports = null;
9107
+ if (Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES2) {
9108
+ summarySkip = "oversize";
9109
+ dependentImports = [];
9110
+ } else if (SKIP_PREVIEW_SUMMARIES && isPreviewTruncated && hasStructuralSummary(relativePath)) {
9111
+ summarySkip = "preview";
9112
+ dependentImports = importsOfText(relativePath, rawContent);
9113
+ } else {
9114
+ try {
9115
+ const outcome = summarizeFile(relativePath, rawContent);
9116
+ summary = outcome?.summary ? maskSummaryStrings(outcome.summary, config.secretRules) : void 0;
9117
+ summaryQuality = outcome?.quality;
9118
+ if (isSourceSummary(summary) && summary.parseErrors) {
9119
+ summaryWarning = `Parse errors in ${maskPathText(relativePath, config.secretRules)} (${summary.parseErrors}); its summary is incomplete.`;
9120
+ }
9121
+ } catch (err) {
9122
+ summaryWarning = `Summary skipped for ${maskPathText(relativePath, config.secretRules)}: ${err.message}`.replace(
9123
+ /\s+/g,
9124
+ " "
9125
+ );
9126
+ }
9127
+ }
9128
+ return {
9129
+ redacted,
9130
+ findings,
9131
+ lineCount,
9132
+ finalContent,
9133
+ inclusionMode,
9134
+ isPreviewTruncated,
9135
+ includedLines,
9136
+ isLarge,
9137
+ summary,
9138
+ summaryQuality,
9139
+ summarySkip,
9140
+ summaryWarning,
9141
+ dependentImports
9142
+ };
9143
+ }
8412
9144
  function sha256Hex2(input) {
8413
9145
  return crypto4.createHash("sha256").update(input).digest("hex");
8414
9146
  }
@@ -8598,6 +9330,7 @@ function isProcessAlive(pid) {
8598
9330
  var OWNERSHIP_MARKER = ".codebase-snapshot";
8599
9331
  var SUPPORTED_MARKER_SCHEMAS = /* @__PURE__ */ new Set([SCHEMA_VERSION]);
8600
9332
  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;
9333
+ var SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/;
8601
9334
  function listEntries(dir) {
8602
9335
  const entries = [];
8603
9336
  const walk = (absolute, prefix) => {
@@ -8616,7 +9349,32 @@ function listEntries(dir) {
8616
9349
  walk(dir, "");
8617
9350
  return entries.sort();
8618
9351
  }
9352
+ function markerInventory(dir) {
9353
+ const entries = listEntries(dir);
9354
+ const files = [];
9355
+ for (const entry of entries) {
9356
+ if (entry === OWNERSHIP_MARKER) continue;
9357
+ if (IGNORABLE_ENTRIES.has(entry.slice(entry.lastIndexOf("/") + 1))) continue;
9358
+ const full = path16.join(dir, ...entry.split("/"));
9359
+ let stats;
9360
+ try {
9361
+ stats = fs14.lstatSync(full);
9362
+ } catch {
9363
+ continue;
9364
+ }
9365
+ if (!stats.isFile()) continue;
9366
+ let digest;
9367
+ try {
9368
+ digest = sha256Hex2(fs14.readFileSync(full));
9369
+ } catch {
9370
+ continue;
9371
+ }
9372
+ files.push({ path: entry, bytes: stats.size, sha256: digest });
9373
+ }
9374
+ return { entries, files };
9375
+ }
8619
9376
  function markerPayload(dir, state, id, createdAt) {
9377
+ const { entries, files } = markerInventory(dir);
8620
9378
  const marker2 = {
8621
9379
  generator: GENERATOR_NAME,
8622
9380
  version: GENERATOR_VERSION,
@@ -8625,7 +9383,8 @@ function markerPayload(dir, state, id, createdAt) {
8625
9383
  state,
8626
9384
  id,
8627
9385
  pid: process.pid,
8628
- entries: listEntries(dir)
9386
+ entries,
9387
+ files
8629
9388
  };
8630
9389
  const manifestPath = path16.join(dir, "manifest.json");
8631
9390
  if (fs14.existsSync(manifestPath)) {
@@ -8685,6 +9444,33 @@ function readOwnershipMarker(dir) {
8685
9444
  if (candidate.state !== "staging" && candidate.state !== "complete") {
8686
9445
  return { marker: null, problem: "its .codebase-snapshot marker records no run state" };
8687
9446
  }
9447
+ const rawFiles = candidate.files;
9448
+ let files;
9449
+ if (rawFiles !== void 0) {
9450
+ if (!Array.isArray(rawFiles)) {
9451
+ return {
9452
+ marker: null,
9453
+ problem: "its .codebase-snapshot marker's file inventory is not an array"
9454
+ };
9455
+ }
9456
+ files = [];
9457
+ for (const item of rawFiles) {
9458
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
9459
+ return {
9460
+ marker: null,
9461
+ problem: "its .codebase-snapshot marker's file inventory holds an entry that is not an object"
9462
+ };
9463
+ }
9464
+ const record = item;
9465
+ 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)) {
9466
+ return {
9467
+ marker: null,
9468
+ problem: "its .codebase-snapshot marker's file inventory holds an entry this build cannot read"
9469
+ };
9470
+ }
9471
+ files.push({ path: record.path, bytes: record.bytes, sha256: record.sha256 });
9472
+ }
9473
+ }
8688
9474
  return {
8689
9475
  marker: {
8690
9476
  generator: GENERATOR_NAME,
@@ -8695,7 +9481,8 @@ function readOwnershipMarker(dir) {
8695
9481
  id: candidate.id,
8696
9482
  pid: typeof candidate.pid === "number" ? candidate.pid : void 0,
8697
9483
  manifestSha256: typeof candidate.manifestSha256 === "string" ? candidate.manifestSha256 : void 0,
8698
- entries: Array.isArray(candidate.entries) && candidate.entries.every((entry) => typeof entry === "string") ? candidate.entries : void 0
9484
+ entries: Array.isArray(candidate.entries) && candidate.entries.every((entry) => typeof entry === "string") ? candidate.entries : void 0,
9485
+ files
8699
9486
  },
8700
9487
  problem: null
8701
9488
  };
@@ -8710,6 +9497,59 @@ function describeManifestProblem(value) {
8710
9497
  if (!Array.isArray(candidate.files)) return "has no files array";
8711
9498
  return null;
8712
9499
  }
9500
+ function verifyMarkerInventory(dir, entries, files) {
9501
+ const diskEntries = new Set(entries);
9502
+ const recorded = /* @__PURE__ */ new Map();
9503
+ for (const record of files) {
9504
+ if (recorded.has(record.path)) {
9505
+ return `its .codebase-snapshot inventory records ${record.path} twice`;
9506
+ }
9507
+ if (!diskEntries.has(record.path)) {
9508
+ return `its .codebase-snapshot inventory records ${record.path}, which is missing from the directory`;
9509
+ }
9510
+ recorded.set(record.path, record);
9511
+ }
9512
+ for (const entry of entries) {
9513
+ if (entry === OWNERSHIP_MARKER) continue;
9514
+ if (IGNORABLE_ENTRIES.has(entry.slice(entry.lastIndexOf("/") + 1))) continue;
9515
+ const full = path16.join(dir, ...entry.split("/"));
9516
+ let stats;
9517
+ try {
9518
+ stats = fs14.lstatSync(full);
9519
+ } catch {
9520
+ return `its .codebase-snapshot inventory lists ${entry}, which cannot be read`;
9521
+ }
9522
+ if (stats.isDirectory()) {
9523
+ if (recorded.has(entry)) {
9524
+ return `its .codebase-snapshot inventory records the directory ${entry} as a file`;
9525
+ }
9526
+ continue;
9527
+ }
9528
+ if (!stats.isFile()) {
9529
+ if (recorded.has(entry)) {
9530
+ return `its .codebase-snapshot inventory records ${entry} as a regular file, but it is not one`;
9531
+ }
9532
+ continue;
9533
+ }
9534
+ const record = recorded.get(entry);
9535
+ if (record === void 0) {
9536
+ return `its .codebase-snapshot inventory does not record the file ${entry}`;
9537
+ }
9538
+ if (record.bytes !== stats.size) {
9539
+ return `its .codebase-snapshot inventory records ${entry} as ${record.bytes} B, but it is ${stats.size} B`;
9540
+ }
9541
+ let digest;
9542
+ try {
9543
+ digest = sha256Hex2(fs14.readFileSync(full));
9544
+ } catch {
9545
+ return `its .codebase-snapshot inventory cannot verify ${entry}: the file could not be read`;
9546
+ }
9547
+ if (digest !== record.sha256) {
9548
+ return `its .codebase-snapshot inventory's digest for ${entry} does not match the file`;
9549
+ }
9550
+ }
9551
+ return null;
9552
+ }
8713
9553
  function assessSnapshotDirectory(dir) {
8714
9554
  const { marker: marker2, problem } = readOwnershipMarker(dir);
8715
9555
  if (!marker2) return { owned: false, problem, foreignEntries: [], marker: null };
@@ -8722,7 +9562,8 @@ function assessSnapshotDirectory(dir) {
8722
9562
  };
8723
9563
  }
8724
9564
  const manifestPath = path16.join(dir, "manifest.json");
8725
- if (fs14.existsSync(manifestPath)) {
9565
+ const hasManifest = fs14.existsSync(manifestPath);
9566
+ if (hasManifest) {
8726
9567
  let raw;
8727
9568
  try {
8728
9569
  raw = fs14.readFileSync(manifestPath, "utf8");
@@ -8778,6 +9619,14 @@ function assessSnapshotDirectory(dir) {
8778
9619
  marker: marker2
8779
9620
  };
8780
9621
  }
9622
+ if (marker2.files === void 0 && !hasManifest) {
9623
+ return {
9624
+ owned: false,
9625
+ problem: "its .codebase-snapshot marker records neither per-file digests nor a manifest digest, so it cannot prove this generator wrote the directory",
9626
+ foreignEntries: [],
9627
+ marker: marker2
9628
+ };
9629
+ }
8781
9630
  const recorded = new Set(marker2.entries ?? []);
8782
9631
  if (recorded.size === 0) {
8783
9632
  return {
@@ -8787,13 +9636,18 @@ function assessSnapshotDirectory(dir) {
8787
9636
  marker: marker2
8788
9637
  };
8789
9638
  }
8790
- const foreignEntries = listEntries(dir).filter(
9639
+ const entries = listEntries(dir);
9640
+ const foreignEntries = entries.filter(
8791
9641
  (entry) => !recorded.has(entry) && !IGNORABLE_ENTRIES.has(entry)
8792
9642
  );
9643
+ if (foreignEntries.length > 0) {
9644
+ return { owned: false, problem: null, foreignEntries, marker: marker2 };
9645
+ }
9646
+ const inventoryProblem = marker2.files === void 0 ? null : verifyMarkerInventory(dir, entries, marker2.files);
8793
9647
  return {
8794
- owned: foreignEntries.length === 0,
8795
- problem: null,
8796
- foreignEntries,
9648
+ owned: inventoryProblem === null,
9649
+ problem: inventoryProblem,
9650
+ foreignEntries: [],
8797
9651
  marker: marker2
8798
9652
  };
8799
9653
  }
@@ -8953,26 +9807,34 @@ function acquireRunLock(stagingRoot) {
8953
9807
  };
8954
9808
  } catch (err) {
8955
9809
  if (err.code !== "EEXIST") throw err;
8956
- if (attempt === 0 && lockOwnerIsGone(lockPath)) {
8957
- fs14.rmSync(lockPath, { force: true });
8958
- continue;
8959
- }
9810
+ if (attempt === 0 && reclaimStaleLock(lockPath)) continue;
8960
9811
  throw new Error(
8961
9812
  `Another generate run is already using the staging directory ${stagingRoot}. Wait for it to finish, or delete ${lockPath} if no other run is active.`
8962
9813
  );
8963
9814
  }
8964
9815
  }
8965
9816
  throw new Error(`Could not acquire the generate lock for ${stagingRoot}.`);
8966
- }
8967
- function lockKeyFor(stagingRoot) {
8968
- let key = stagingRoot;
8969
- try {
8970
- key = fs14.realpathSync(stagingRoot);
8971
- } catch {
8972
- }
9817
+ }
9818
+ function lockKeyFor(stagingRoot) {
9819
+ let key = canonicalLockTarget(stagingRoot);
8973
9820
  if (process.platform === "win32" || process.platform === "darwin") key = key.toLowerCase();
8974
9821
  return sha256Hex2(key).slice(0, 16);
8975
9822
  }
9823
+ function canonicalLockTarget(targetPath2) {
9824
+ const resolved = path16.resolve(targetPath2);
9825
+ let existing = resolved;
9826
+ const tail = [];
9827
+ for (; ; ) {
9828
+ try {
9829
+ return path16.join(fs14.realpathSync(existing), ...tail);
9830
+ } catch {
9831
+ const parent = path16.dirname(existing);
9832
+ if (parent === existing) return resolved;
9833
+ tail.unshift(path16.basename(existing));
9834
+ existing = parent;
9835
+ }
9836
+ }
9837
+ }
8976
9838
  function lockPathFor(stagingRoot) {
8977
9839
  return path16.join(os2.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
8978
9840
  }
@@ -8997,6 +9859,24 @@ function lockOwnerIsGone(lockPath) {
8997
9859
  return err.code === "ESRCH";
8998
9860
  }
8999
9861
  }
9862
+ function reclaimStaleLock(lockPath) {
9863
+ let before;
9864
+ try {
9865
+ before = fs14.statSync(lockPath);
9866
+ } catch {
9867
+ return true;
9868
+ }
9869
+ if (!lockOwnerIsGone(lockPath)) return false;
9870
+ try {
9871
+ const current = fs14.statSync(lockPath);
9872
+ const sameFile = current.ino === before.ino && current.birthtimeMs === before.birthtimeMs && current.mtimeMs === before.mtimeMs;
9873
+ if (!sameFile) return false;
9874
+ fs14.rmSync(lockPath, { force: true });
9875
+ return true;
9876
+ } catch {
9877
+ return false;
9878
+ }
9879
+ }
9000
9880
  function lockFileIsAncient(lockPath) {
9001
9881
  try {
9002
9882
  return Date.now() - fs14.statSync(lockPath).mtimeMs > STALE_RUN_MS;
@@ -9054,7 +9934,6 @@ function swapOnce(stagingDir, outDir) {
9054
9934
  throw copyErr;
9055
9935
  }
9056
9936
  }
9057
- if (hadPrevious) fs14.rmSync(backupDir, { recursive: true, force: true });
9058
9937
  } catch (err) {
9059
9938
  if (hadPrevious && fs14.existsSync(backupDir)) {
9060
9939
  if (fs14.existsSync(outDir)) fs14.rmSync(outDir, { recursive: true, force: true });
@@ -9062,6 +9941,16 @@ function swapOnce(stagingDir, outDir) {
9062
9941
  }
9063
9942
  throw err;
9064
9943
  }
9944
+ if (hadPrevious) {
9945
+ try {
9946
+ fs14.rmSync(backupDir, { recursive: true, force: true });
9947
+ } catch (err) {
9948
+ process.stderr.write(
9949
+ `\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.
9950
+ `
9951
+ );
9952
+ }
9953
+ }
9065
9954
  }
9066
9955
  function sleepSync(milliseconds) {
9067
9956
  const buffer = new Int32Array(new SharedArrayBuffer(4));
@@ -9084,22 +9973,18 @@ function artifactWarnings(artifacts, sarif) {
9084
9973
  }
9085
9974
  return messages;
9086
9975
  }
9976
+ function installHookStdoutRedirect() {
9977
+ return installStdoutRouter();
9978
+ }
9087
9979
  function runAfterGenerate(config, manifest) {
9088
9980
  const hook = config.hooks.afterGenerate;
9089
9981
  if (!hook) return null;
9090
- const stdoutWrite = process.stdout.write.bind(process.stdout);
9091
- const stderrWrite = process.stderr.write.bind(process.stderr);
9092
- const hookScope = new AsyncLocalStorage();
9093
- const patchedWrite = ((...args) => hookScope.getStore() === true ? stderrWrite(...args) : stdoutWrite(...args));
9094
- const restoreStdout = () => {
9095
- if (process.stdout.write === patchedWrite) process.stdout.write = stdoutWrite;
9096
- };
9982
+ const releaseRedirect = installHookStdoutRedirect();
9097
9983
  let returned;
9098
9984
  try {
9099
- process.stdout.write = patchedWrite;
9100
- returned = hookScope.run(true, () => hook(manifest));
9985
+ returned = hookStdoutScope.run(true, () => hook(manifest));
9101
9986
  } catch (err) {
9102
- restoreStdout();
9987
+ releaseRedirect();
9103
9988
  const message = maskPathText(err.message, config.secretRules);
9104
9989
  manifest.warnings.push(`hooks.afterGenerate failed: ${message}`);
9105
9990
  manifest.totals.warningCount = manifest.warnings.length;
@@ -9107,10 +9992,10 @@ function runAfterGenerate(config, manifest) {
9107
9992
  }
9108
9993
  const thenable = returned;
9109
9994
  if (!thenable || typeof thenable.then !== "function") {
9110
- restoreStdout();
9995
+ releaseRedirect();
9111
9996
  return null;
9112
9997
  }
9113
- return Promise.resolve(returned).finally(restoreStdout);
9998
+ return Promise.resolve(returned).finally(releaseRedirect);
9114
9999
  }
9115
10000
  function partitionByBudget(files, config, fingerprint) {
9116
10001
  const budgetFor = (file) => config.budgets.byLayer[file.layer] ?? config.budgets.default;
@@ -9121,23 +10006,14 @@ function partitionByBudget(files, config, fingerprint) {
9121
10006
  if (bucket) bucket.push(file);
9122
10007
  else buckets.set(budget, [file]);
9123
10008
  }
9124
- if (buckets.size <= 1) {
9125
- const only = buckets.size === 1 ? Array.from(buckets.keys())[0] : config.maxPartBytes;
9126
- return partitionFiles(files, only, fingerprint);
9127
- }
9128
- const parts = [];
9129
- for (const budget of Array.from(buckets.keys()).sort((a, b) => a - b)) {
9130
- parts.push(...partitionFiles(buckets.get(budget) ?? [], budget, fingerprint));
9131
- }
9132
- const merged = renumberParts(parts, fingerprint);
9133
- const byPath = new Map(files.map((file) => [file.relativePath, file]));
9134
- for (const part of merged) {
9135
- for (const included of part.metadata.includedFiles) {
9136
- const file = byPath.get(included.relativePath);
9137
- if (file) file.part = part.filename;
9138
- }
10009
+ if (buckets.size === 0) return [];
10010
+ if (buckets.size === 1) {
10011
+ return partitionFiles(files, Array.from(buckets.keys())[0], fingerprint);
9139
10012
  }
9140
- return merged;
10013
+ return partitionFilesForBuckets(
10014
+ Array.from(buckets.entries()).sort(([left], [right]) => left - right).map(([budgetBytes, bucketFiles]) => ({ files: bucketFiles, budgetBytes })),
10015
+ fingerprint
10016
+ );
9141
10017
  }
9142
10018
  function generateSnapshot(configInput, options) {
9143
10019
  assertUsableConfigInput(configInput);
@@ -9169,6 +10045,7 @@ function generateSnapshot(configInput, options) {
9169
10045
  return false;
9170
10046
  }) : collection.files;
9171
10047
  const files = [];
10048
+ const derivationKey = derivationSettings(config);
9172
10049
  const monolithBodies = /* @__PURE__ */ new Map();
9173
10050
  const skipped = maskSkipRecords([...collection.skipped], config.secretRules);
9174
10051
  const secretFindings = [];
@@ -9181,6 +10058,7 @@ function generateSnapshot(configInput, options) {
9181
10058
  const fileWarnings = [];
9182
10059
  const oversizeSummaryPaths = [];
9183
10060
  const previewSummaryPaths = [];
10061
+ const skippedSummaryImports = /* @__PURE__ */ new Map();
9184
10062
  const layerCounts = {};
9185
10063
  const kindCounts = {};
9186
10064
  let totalLines = 0;
@@ -9245,8 +10123,6 @@ function generateSnapshot(configInput, options) {
9245
10123
  }
9246
10124
  const hashSha256 = sha256Hex2(buffer);
9247
10125
  const rawContent = decoded.text;
9248
- const lineCount = countLines(rawContent);
9249
- totalLines += lineCount;
9250
10126
  totalSizeBytes += stats.size;
9251
10127
  if (decoded.encoding !== "utf-8") {
9252
10128
  encodingNotes.push({
@@ -9260,66 +10136,25 @@ function generateSnapshot(configInput, options) {
9260
10136
  const language = detectLanguage(relativePath);
9261
10137
  bump(layerCounts, layer2);
9262
10138
  bump(kindCounts, kind);
9263
- const { redacted, findings } = scanAndRedactSecrets(
9264
- rawContent,
9265
- config.secretRules,
9266
- relativePath
9267
- );
9268
- secretFindings.push(...findings);
9269
- const isLarge = stats.size > config.largeFileBytes;
9270
- if (isLarge) largeFileCount += 1;
9271
- let finalContent = redacted;
9272
- let isPreviewTruncated = false;
9273
- let includedLines = lineCount;
9274
- let inclusionMode = "full";
9275
- if (config.skeleton === true && isSkeletonizable(relativePath)) {
9276
- const skeleton = skeletonizeTypeScript(redacted, relativePath);
9277
- if (skeleton.collapsed > 0) {
9278
- finalContent = skeleton.text;
9279
- inclusionMode = "signatures";
9280
- includedLines = countLines(skeleton.text);
9281
- }
9282
- }
9283
- if (isLarge && inclusionMode !== "signatures") {
9284
- const preview = truncatePreview(
9285
- redacted,
9286
- config.previewHeadLines,
9287
- config.previewTailLines
9288
- );
9289
- finalContent = preview.content;
9290
- isPreviewTruncated = preview.isTruncated;
9291
- includedLines = preview.includedLines;
9292
- inclusionMode = isPreviewTruncated ? "preview" : "full";
9293
- }
9294
- if (config.includeMonolith && (isPreviewTruncated || inclusionMode === "signatures")) {
9295
- monolithBodies.set(relativePath, redacted);
9296
- }
9297
- let summary;
9298
- let summaryQuality;
9299
- if (Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES) {
9300
- oversizeSummaryPaths.push(relativePath);
9301
- } else if (SKIP_PREVIEW_SUMMARIES && isPreviewTruncated && hasStructuralSummary(relativePath)) {
9302
- previewSummaryPaths.push(relativePath);
9303
- } else {
9304
- try {
9305
- const outcome = summarizeFile(relativePath, rawContent);
9306
- summary = outcome?.summary ? maskSummaryStrings(outcome.summary, config.secretRules) : void 0;
9307
- summaryQuality = outcome?.quality;
9308
- if (isSourceSummary(summary) && summary.parseErrors) {
9309
- fileWarnings.push({
9310
- path: relativePath,
9311
- message: `Parse errors in ${maskPathText(relativePath, config.secretRules)} (${summary.parseErrors}); its summary is incomplete.`
9312
- });
9313
- }
9314
- } catch (err) {
9315
- fileWarnings.push({
9316
- path: relativePath,
9317
- message: `Summary skipped for ${maskPathText(relativePath, config.secretRules)}: ${err.message}`.replace(
9318
- /\s+/g,
9319
- " "
9320
- )
9321
- });
9322
- }
10139
+ const derivation = takeDerivation(absolutePath, hashSha256, derivationKey) ?? (() => {
10140
+ const fresh = deriveFile(relativePath, rawContent, stats.size, config);
10141
+ rememberDerivation(absolutePath, hashSha256, derivationKey, fresh);
10142
+ return fresh;
10143
+ })();
10144
+ const { lineCount } = derivation;
10145
+ totalLines += lineCount;
10146
+ secretFindings.push(...derivation.findings);
10147
+ if (derivation.isLarge) largeFileCount += 1;
10148
+ if (derivation.summarySkip === "oversize") oversizeSummaryPaths.push(relativePath);
10149
+ else if (derivation.summarySkip === "preview") previewSummaryPaths.push(relativePath);
10150
+ if (derivation.dependentImports !== null) {
10151
+ skippedSummaryImports.set(relativePath, derivation.dependentImports);
10152
+ }
10153
+ if (derivation.summaryWarning !== null) {
10154
+ fileWarnings.push({ path: relativePath, message: derivation.summaryWarning });
10155
+ }
10156
+ if (config.includeMonolith && (derivation.isPreviewTruncated || derivation.inclusionMode === "signatures")) {
10157
+ monolithBodies.set(relativePath, derivation.redacted);
9323
10158
  }
9324
10159
  files.push({
9325
10160
  relativePath,
@@ -9330,24 +10165,25 @@ function generateSnapshot(configInput, options) {
9330
10165
  layer: layer2,
9331
10166
  kind,
9332
10167
  language,
9333
- inclusionMode,
9334
- isLarge,
9335
- isPreviewTruncated,
10168
+ inclusionMode: derivation.inclusionMode,
10169
+ isLarge: derivation.isLarge,
10170
+ isPreviewTruncated: derivation.isPreviewTruncated,
9336
10171
  originalLines: lineCount,
9337
- includedLines,
9338
- includedBytes: Buffer.byteLength(finalContent, "utf8"),
9339
- summary,
9340
- summaryQuality,
10172
+ includedLines: derivation.includedLines,
10173
+ includedBytes: Buffer.byteLength(derivation.finalContent, "utf8"),
10174
+ summary: derivation.summary,
10175
+ summaryQuality: derivation.summaryQuality,
9341
10176
  ...decoded.encoding === "utf-8" ? {} : { encoding: decoded.encoding },
9342
- content: finalContent
10177
+ content: derivation.finalContent
9343
10178
  });
9344
10179
  }
9345
10180
  if (changedScope !== null && changedPaths !== null && config.withDependents === true) {
9346
10181
  const keep = new Set(changedPaths);
9347
10182
  const resolver = buildImportResolver(files);
9348
10183
  for (const file of files) {
9349
- if (!isSourceSummary(file.summary)) continue;
9350
- if (importsChangedFile(file.relativePath, file.summary.imports, changedPaths, resolver)) {
10184
+ const fileImports = isSourceSummary(file.summary) ? file.summary.imports : skippedSummaryImports.get(file.relativePath) ?? [];
10185
+ if (fileImports.length === 0) continue;
10186
+ if (importsChangedFile(file.relativePath, fileImports, changedPaths, resolver)) {
9351
10187
  keep.add(file.relativePath);
9352
10188
  }
9353
10189
  }
@@ -9378,6 +10214,9 @@ function generateSnapshot(configInput, options) {
9378
10214
  for (const path22 of [...monolithBodies.keys()]) {
9379
10215
  if (!keep.has(path22)) monolithBodies.delete(path22);
9380
10216
  }
10217
+ for (const path22 of [...skippedSummaryImports.keys()]) {
10218
+ if (!keep.has(path22)) skippedSummaryImports.delete(path22);
10219
+ }
9381
10220
  }
9382
10221
  if (changedScope !== null) {
9383
10222
  for (const relativePath of unchangedPaths) {
@@ -9413,7 +10252,7 @@ function generateSnapshot(configInput, options) {
9413
10252
  const shown = oversizeSummaryPaths.slice(0, ENCODING_PATHS_SHOWN).map((entry) => maskPathText(entry, config.secretRules));
9414
10253
  const hidden = oversizeSummaryPaths.length - ENCODING_PATHS_SHOWN;
9415
10254
  warnings.push(
9416
- `${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.`
10255
+ `${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.`
9417
10256
  );
9418
10257
  }
9419
10258
  for (const [encoding, bucket] of encodingBuckets) {
@@ -9432,16 +10271,21 @@ function generateSnapshot(configInput, options) {
9432
10271
  }
9433
10272
  }
9434
10273
  const fingerprint = sha256Hex2(
9435
- files.map(
9436
- (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
9437
- ).join("\n")
10274
+ [
10275
+ ...files.map(
10276
+ (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
10277
+ ),
10278
+ `settings:${configDigest(config)}`
10279
+ ].join("\n")
9438
10280
  );
9439
10281
  const fullContents = /* @__PURE__ */ new Map();
9440
- for (const file of files) {
9441
- fullContents.set(
9442
- file.relativePath,
9443
- monolithBodies.get(file.relativePath) ?? file.content ?? ""
9444
- );
10282
+ if (config.includeMonolith) {
10283
+ for (const file of files) {
10284
+ fullContents.set(
10285
+ file.relativePath,
10286
+ monolithBodies.get(file.relativePath) ?? file.content ?? ""
10287
+ );
10288
+ }
9445
10289
  }
9446
10290
  const parts = partitionByBudget(files, config, fingerprint);
9447
10291
  const truncatedPreviewCount = files.filter((file) => file.isPreviewTruncated).length;
@@ -9700,9 +10544,9 @@ function generateSnapshot(configInput, options) {
9700
10544
  }
9701
10545
  writeOwnershipMarker(outDir, markerPayload(outDir, "complete", snapshotId, createdAt));
9702
10546
  };
9703
- shipHookState();
10547
+ if (config.hooks.afterGenerate) shipHookState();
9704
10548
  if (pendingHook) {
9705
- pendingHook.then(
10549
+ const tracked = pendingHook.then(
9706
10550
  () => {
9707
10551
  try {
9708
10552
  shipHookState();
@@ -9721,8 +10565,10 @@ function generateSnapshot(configInput, options) {
9721
10565
  } catch {
9722
10566
  }
9723
10567
  }
9724
- );
9725
- pendingHooks.set(outDir, pendingHook);
10568
+ ).finally(() => {
10569
+ if (pendingHooks.get(outDir) === tracked) pendingHooks.delete(outDir);
10570
+ });
10571
+ pendingHooks.set(outDir, tracked);
9726
10572
  }
9727
10573
  return manifest;
9728
10574
  } catch (err) {
@@ -9748,7 +10594,17 @@ import * as path18 from "path";
9748
10594
  var FILE_HEADING = "### FILE: ";
9749
10595
  var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
9750
10596
  var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
10597
+ var META_PREFIX = "- Meta: ";
10598
+ var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
10599
+ var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
9751
10600
  var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
10601
+ var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
10602
+ function readIncludedLines(fields) {
10603
+ const last = fields[fields.length - 1];
10604
+ if (last === void 0) return null;
10605
+ const counts = COMPACT_COUNTS.exec(last.trim());
10606
+ return counts === null ? null : Number(counts[1]);
10607
+ }
9752
10608
  function parsePartSections(partText) {
9753
10609
  const lines = partText.split("\n");
9754
10610
  const sections = [];
@@ -9766,20 +10622,17 @@ function parsePartSections(partText) {
9766
10622
  while (cursor < lines.length && !CONTENT_MARKERS.has(lines[cursor])) {
9767
10623
  const line = lines[cursor];
9768
10624
  if (line.startsWith(FILE_HEADING)) break;
9769
- if (line.startsWith("- Meta: ")) {
9770
- for (const field of line.slice("- Meta: ".length).split("|")) {
10625
+ if (line.startsWith(META_PREFIX)) {
10626
+ const fields = line.slice(META_PREFIX.length).split("|");
10627
+ for (const field of fields) {
9771
10628
  const value = field.trim();
9772
10629
  if (INCLUSION_MODES.has(value)) inclusion = value;
9773
10630
  }
9774
- const counts = /(-?\d+) of (-?\d+) lines|(\d+) lines/.exec(line);
9775
- if (counts) {
9776
- const emitted = counts[1] ?? counts[3];
9777
- includedLines = Number.isFinite(Number(emitted)) ? Number(emitted) : null;
9778
- }
9779
- } else if (line.startsWith("- Inclusion: ")) {
9780
- inclusion = line.slice("- Inclusion: ".length).trim();
9781
- } else if (line.startsWith("- Included Lines: ")) {
9782
- const value = Number(line.slice("- Included Lines: ".length).trim());
10631
+ includedLines = readIncludedLines(fields);
10632
+ } else if (line.startsWith(LEGACY_INCLUSION_PREFIX)) {
10633
+ inclusion = line.slice(LEGACY_INCLUSION_PREFIX.length).trim();
10634
+ } else if (line.startsWith(LEGACY_INCLUDED_LINES_PREFIX)) {
10635
+ const value = Number(line.slice(LEGACY_INCLUDED_LINES_PREFIX.length).trim());
9783
10636
  includedLines = Number.isFinite(value) ? value : null;
9784
10637
  }
9785
10638
  cursor += 1;
@@ -9860,6 +10713,18 @@ function isInside2(parent, child) {
9860
10713
  const foldedChild = foldForComparison(child);
9861
10714
  return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path17.sep}`);
9862
10715
  }
10716
+ function resolveThroughExistingAncestor(target) {
10717
+ let existing = target;
10718
+ const missing = [];
10719
+ while (!fs15.existsSync(existing)) {
10720
+ missing.unshift(path17.basename(existing));
10721
+ const parent = path17.dirname(existing);
10722
+ if (parent === existing) break;
10723
+ existing = parent;
10724
+ }
10725
+ const resolved = canonicalPath(existing);
10726
+ return missing.length === 0 ? resolved : path17.join(resolved, ...missing);
10727
+ }
9863
10728
  function resolveRoot(requested, context) {
9864
10729
  if (requested !== void 0 && (typeof requested !== "string" || requested.trim().length === 0)) {
9865
10730
  return { ok: false, message: '"root" must be a non-empty string when provided.' };
@@ -9882,10 +10747,10 @@ function resolveRoot(requested, context) {
9882
10747
  const shown = context.roots.join(", ");
9883
10748
  return {
9884
10749
  ok: false,
9885
- message: `"${wanted}" resolves outside the directories this server may read (${shown}). Restart it with --root <path> to add a repository.`
10750
+ 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.`
9886
10751
  };
9887
10752
  }
9888
- async function openWorkspace(root, overrides = {}) {
10753
+ async function openWorkspace(root, overrides = {}, allowedRoots) {
9889
10754
  const loaded = await loadConfigFileDetailed(root);
9890
10755
  if (loaded.errors.length > 0) {
9891
10756
  return {
@@ -9904,12 +10769,45 @@ async function openWorkspace(root, overrides = {}) {
9904
10769
  }
9905
10770
  cliOptions.maxPartBytes = parsed;
9906
10771
  }
10772
+ if (overrides.maxPartTokens !== void 0) {
10773
+ const parsed = parseByteSize(overrides.maxPartTokens);
10774
+ if (parsed === void 0) {
10775
+ return {
10776
+ ok: false,
10777
+ message: '"maxPartTokens" must be a token count, for example 32000 or "32k".'
10778
+ };
10779
+ }
10780
+ cliOptions.maxPartTokens = parsed;
10781
+ }
9907
10782
  if (overrides.outDir !== void 0) {
9908
10783
  if (typeof overrides.outDir !== "string" || overrides.outDir.trim().length === 0) {
9909
10784
  return { ok: false, message: '"outDir" must be a non-empty string.' };
9910
10785
  }
9911
- cliOptions.outDir = overrides.outDir.trim();
10786
+ const requested = overrides.outDir.trim();
10787
+ const permitted = allowedRoots !== void 0 && allowedRoots.length > 0 ? allowedRoots : [root];
10788
+ const resolved = resolveThroughExistingAncestor(path17.resolve(root, requested));
10789
+ if (!permitted.some((allowed) => isInside2(canonicalPath(allowed), resolved))) {
10790
+ const shown = permitted.map((allowed) => canonicalPath(allowed)).join(", ");
10791
+ return {
10792
+ ok: false,
10793
+ 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.`
10794
+ };
10795
+ }
10796
+ cliOptions.outDir = requested;
10797
+ }
10798
+ if (overrides.changedSince !== void 0) {
10799
+ if (typeof overrides.changedSince !== "string" || overrides.changedSince.trim().length === 0) {
10800
+ return {
10801
+ ok: false,
10802
+ message: '"changedSince" must be a git ref such as "main" or "HEAD~3".'
10803
+ };
10804
+ }
10805
+ cliOptions.changedSince = overrides.changedSince.trim();
9912
10806
  }
10807
+ if (overrides.skeleton === true) cliOptions.skeleton = true;
10808
+ if (overrides.sarif === true) cliOptions.sarif = true;
10809
+ if (overrides.staged === true) cliOptions.staged = true;
10810
+ if (overrides.withDependents === true) cliOptions.withDependents = true;
9913
10811
  try {
9914
10812
  const config = resolveConfig(loaded.config, cliOptions, root);
9915
10813
  return { ok: true, workspace: { root, config, configFile: loaded.file, cliOptions } };
@@ -9921,6 +10819,16 @@ var manifestCache = /* @__PURE__ */ new Map();
9921
10819
  function manifestPathFor(workspace) {
9922
10820
  return path17.resolve(workspace.root, workspace.config.outDir, "manifest.json");
9923
10821
  }
10822
+ function partPathFor(workspace, filename) {
10823
+ if (filename.length === 0 || filename.includes("\0")) return null;
10824
+ const partsDir = path17.resolve(workspace.root, workspace.config.outDir, "parts");
10825
+ const resolved = path17.resolve(partsDir, filename);
10826
+ const relative12 = path17.relative(partsDir, resolved);
10827
+ if (relative12.length === 0 || relative12.includes(path17.sep) || relative12.includes("/") || relative12.includes("\\") || path17.isAbsolute(relative12)) {
10828
+ return null;
10829
+ }
10830
+ return resolved;
10831
+ }
9924
10832
  function readManifest3(workspace) {
9925
10833
  const file = manifestPathFor(workspace);
9926
10834
  const shown = path17.relative(workspace.root, file).split(path17.sep).join("/") || file;
@@ -9988,9 +10896,47 @@ var ROOT_PROPERTY = {
9988
10896
  };
9989
10897
  var OUT_DIR_PROPERTY = {
9990
10898
  type: "string",
9991
- description: "Snapshot directory, relative to the root. Defaults to the project configuration's outDir."
10899
+ description: "Snapshot directory, relative to the root, and it must resolve inside the served repository. Defaults to the project configuration's outDir."
9992
10900
  };
9993
10901
  var outDirOverride = (args) => ({ outDir: args.outDir });
10902
+ var SCOPE_PROPERTIES = {
10903
+ maxPartTokens: {
10904
+ type: "string",
10905
+ description: 'Token ceiling per part, for example 32000 or "32k". Narrower than maxPartBytes; it converts at four bytes per token.'
10906
+ },
10907
+ skeleton: {
10908
+ type: "boolean",
10909
+ description: "Replace every function body with `{ /* ... */ }`, keeping signatures, imports and exports. Applies to TypeScript, JavaScript and JSX."
10910
+ },
10911
+ sarif: {
10912
+ type: "boolean",
10913
+ description: "Also write reports/audit.sarif beside reports/audit.md, for CI code scanning."
10914
+ },
10915
+ changedSince: {
10916
+ type: "string",
10917
+ description: 'Only files changed since this git ref, for example "main" or "HEAD~3".'
10918
+ },
10919
+ staged: {
10920
+ type: "boolean",
10921
+ description: "Only files staged in the git index."
10922
+ },
10923
+ withDependents: {
10924
+ type: "boolean",
10925
+ description: "With staged or changedSince, also include the files that import the changed ones (one hop)."
10926
+ }
10927
+ };
10928
+ function workspaceOverrides(args) {
10929
+ return {
10930
+ outDir: args.outDir,
10931
+ maxPartBytes: args.maxPartBytes,
10932
+ maxPartTokens: args.maxPartTokens,
10933
+ skeleton: args.skeleton,
10934
+ sarif: args.sarif,
10935
+ changedSince: args.changedSince,
10936
+ staged: args.staged,
10937
+ withDependents: args.withDependents
10938
+ };
10939
+ }
9994
10940
  function failure(message) {
9995
10941
  return { text: message, isError: true };
9996
10942
  }
@@ -10021,12 +10967,13 @@ function summarizeDrift(drift) {
10021
10967
  }
10022
10968
  function toRelativePath(root, value) {
10023
10969
  const cleaned = value.trim();
10024
- if (cleaned.length === 0) return null;
10025
- if (!path18.isAbsolute(cleaned)) {
10026
- return cleaned.replace(/\\/g, "/").replace(/^\.\//, "");
10970
+ if (cleaned.length === 0 || cleaned.includes("\0")) return null;
10971
+ const resolvedRoot = path18.resolve(root);
10972
+ const absolute = path18.resolve(resolvedRoot, cleaned);
10973
+ const relative12 = path18.relative(resolvedRoot, absolute);
10974
+ if (relative12 === "" || relative12 === ".." || relative12.startsWith(`..${path18.sep}`) || path18.isAbsolute(relative12)) {
10975
+ return null;
10027
10976
  }
10028
- const relative12 = path18.relative(root, cleaned);
10029
- if (relative12.startsWith("..") || path18.isAbsolute(relative12)) return null;
10030
10977
  return relative12.split(path18.sep).join("/");
10031
10978
  }
10032
10979
  function symbolsOf(entry) {
@@ -10068,7 +11015,7 @@ function symbolsOf(entry) {
10068
11015
  async function prepare(args, context, overrides = {}) {
10069
11016
  const rootOutcome = resolveRoot(args.root, context);
10070
11017
  if (!rootOutcome.ok) return { ok: false, outcome: failure(rootOutcome.message) };
10071
- const opened = await openWorkspace(rootOutcome.root, overrides);
11018
+ const opened = await openWorkspace(rootOutcome.root, overrides, context.roots);
10072
11019
  if (!opened.ok) return { ok: false, outcome: failure(opened.message) };
10073
11020
  return { ok: true, workspace: opened.workspace };
10074
11021
  }
@@ -10162,7 +11109,8 @@ var planTool = {
10162
11109
  maxPartBytes: {
10163
11110
  type: "string",
10164
11111
  description: 'Byte budget per part, for example 307200 or "300k". Defaults to the project configuration.'
10165
- }
11112
+ },
11113
+ ...SCOPE_PROPERTIES
10166
11114
  },
10167
11115
  additionalProperties: false
10168
11116
  },
@@ -10179,7 +11127,7 @@ var planTool = {
10179
11127
  },
10180
11128
  annotations: READ_ONLY,
10181
11129
  async handler(args, context) {
10182
- const prepared = await prepare(args, context, { maxPartBytes: args.maxPartBytes, outDir: args.outDir });
11130
+ const prepared = await prepare(args, context, workspaceOverrides(args));
10183
11131
  if (!prepared.ok) return prepared.outcome;
10184
11132
  const workspace = prepared.workspace;
10185
11133
  let manifest;
@@ -10237,7 +11185,8 @@ var generateTool = {
10237
11185
  maxPartBytes: {
10238
11186
  type: "string",
10239
11187
  description: 'Byte budget per part, for example 307200 or "300k". Defaults to the project configuration.'
10240
- }
11188
+ },
11189
+ ...SCOPE_PROPERTIES
10241
11190
  },
10242
11191
  additionalProperties: false
10243
11192
  },
@@ -10253,10 +11202,7 @@ var generateTool = {
10253
11202
  },
10254
11203
  annotations: WRITES,
10255
11204
  async handler(args, context) {
10256
- const prepared = await prepare(args, context, {
10257
- maxPartBytes: args.maxPartBytes,
10258
- outDir: args.outDir
10259
- });
11205
+ const prepared = await prepare(args, context, workspaceOverrides(args));
10260
11206
  if (!prepared.ok) return prepared.outcome;
10261
11207
  const workspace = prepared.workspace;
10262
11208
  const result = await generateInWorker(workspace.root, workspace.cliOptions);
@@ -10295,7 +11241,7 @@ var validateTool = {
10295
11241
  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.",
10296
11242
  inputSchema: {
10297
11243
  type: "object",
10298
- properties: { root: ROOT_PROPERTY, outDir: OUT_DIR_PROPERTY },
11244
+ properties: { root: ROOT_PROPERTY, outDir: OUT_DIR_PROPERTY, ...SCOPE_PROPERTIES },
10299
11245
  additionalProperties: false
10300
11246
  },
10301
11247
  outputSchema: {
@@ -10307,7 +11253,7 @@ var validateTool = {
10307
11253
  },
10308
11254
  annotations: READ_ONLY,
10309
11255
  async handler(args, context) {
10310
- const prepared = await prepare(args, context, outDirOverride(args));
11256
+ const prepared = await prepare(args, context, workspaceOverrides(args));
10311
11257
  if (!prepared.ok) return prepared.outcome;
10312
11258
  const workspace = prepared.workspace;
10313
11259
  let result;
@@ -10652,7 +11598,12 @@ var readTool = {
10652
11598
  `${relativePath} is not in the snapshot. Call snapshot_locate to find the path, or snapshot_explain to learn why it was excluded.`
10653
11599
  );
10654
11600
  }
10655
- const partPath = path18.resolve(workspace.root, workspace.config.outDir, "parts", entry.part);
11601
+ const partPath = partPathFor(workspace, entry.part);
11602
+ if (partPath === null) {
11603
+ return failure(
11604
+ `${entry.part} is not a part of this snapshot: its name leaves ${workspace.config.outDir}/parts. Run snapshot_generate to rebuild it.`
11605
+ );
11606
+ }
10656
11607
  let partText;
10657
11608
  try {
10658
11609
  partText = fs16.readFileSync(partPath, "utf8");
@@ -10732,7 +11683,8 @@ var explainTool = {
10732
11683
  description: "Path relative to the repository root. Directories are explained as a whole."
10733
11684
  },
10734
11685
  root: ROOT_PROPERTY,
10735
- outDir: OUT_DIR_PROPERTY
11686
+ outDir: OUT_DIR_PROPERTY,
11687
+ ...SCOPE_PROPERTIES
10736
11688
  },
10737
11689
  required: ["path"],
10738
11690
  additionalProperties: false
@@ -10747,7 +11699,7 @@ var explainTool = {
10747
11699
  },
10748
11700
  annotations: READ_ONLY,
10749
11701
  async handler(args, context) {
10750
- const prepared = await prepare(args, context, outDirOverride(args));
11702
+ const prepared = await prepare(args, context, workspaceOverrides(args));
10751
11703
  if (!prepared.ok) return prepared.outcome;
10752
11704
  const workspace = prepared.workspace;
10753
11705
  if (typeof args.path !== "string") return failure('"path" must be a string.');
@@ -10860,6 +11812,16 @@ var ERROR_CODES = {
10860
11812
  methodNotFound: -32601,
10861
11813
  invalidParams: -32602,
10862
11814
  internalError: -32603,
11815
+ /**
11816
+ * A resource whose complete text is larger than one read may return.
11817
+ *
11818
+ * `-32000` is JSON-RPC's range for implementation-defined server errors, which is what this is:
11819
+ * there is no standard code for "the document is too large", and answering with -32602 would tell
11820
+ * a client its request was malformed when it was not. The message names the size, the limit and
11821
+ * the tool to use instead, because a resource read that cannot return the whole resource must not
11822
+ * invent a partial one.
11823
+ */
11824
+ resourceTooLarge: -32e3,
10863
11825
  unsupportedProtocolVersion: -32022
10864
11826
  };
10865
11827
  var METHOD3 = {
@@ -10972,16 +11934,14 @@ var COMMAND_OPTION_SCOPE = {
10972
11934
  "version"
10973
11935
  ],
10974
11936
  validate: VALIDATE_OPTIONS,
11937
+ // `report` reads `manifest.json` and prints what is there; a generation setting would change
11938
+ // nothing. The seven generation flags used to be listed here and were accepted as silent no-ops
11939
+ // — the exact "flag that parses but changes nothing" this table exists to prevent — while
11940
+ // `--discovery` was already rejected. Both the parser and `describe`'s `appliesTo` read this
11941
+ // list, so removing them narrows the two together.
10975
11942
  report: [
10976
11943
  "cwd",
10977
11944
  "out-dir",
10978
- "max-part-bytes",
10979
- "large-file-bytes",
10980
- "max-monolith-bytes",
10981
- "include-monolith",
10982
- "include-sensitive-files",
10983
- "skip-artifacts",
10984
- "only-artifacts",
10985
11945
  "no-config",
10986
11946
  "no-update-check",
10987
11947
  "format",
@@ -11452,7 +12412,7 @@ function buildAgentContract() {
11452
12412
  type: "string",
11453
12413
  default: "generate",
11454
12414
  appliesTo: optionAppliesTo("mode"),
11455
- 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)."
12415
+ 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)."
11456
12416
  },
11457
12417
  {
11458
12418
  flag: "--cwd",
@@ -11589,7 +12549,7 @@ function buildAgentContract() {
11589
12549
  { key: "preset", type: "string", default: "detected", summary: "Force a preset. Unknown names are an error." },
11590
12550
  { key: "maxPartBytes", type: "number | string", default: 307200, summary: "Per-part byte budget." },
11591
12551
  { key: "maxPartTokens", type: "number | string | null", default: null, summary: "Per-part token ceiling; narrows maxPartBytes. Minimum 1024." },
11592
- { key: "skeleton", type: "boolean", default: false, summary: "Collapse function bodies to `{ /* ... */ }` in TypeScript files." },
12552
+ { key: "skeleton", type: "boolean", default: false, summary: "Collapse function bodies to `{ /* ... */ }` in TS, JS, TSX and JSX files." },
11593
12553
  { key: "sarif", type: "boolean", default: false, summary: "Also write reports/audit.sarif." },
11594
12554
  { key: "changedSince", type: "string | null", default: null, summary: "Snapshot only files that differ from this git ref." },
11595
12555
  { key: "staged", type: "boolean", default: false, summary: "Snapshot only files staged in the index." },
@@ -12017,25 +12977,209 @@ function classifyRequest(method, params, session) {
12017
12977
  data: unsupportedVersionData(inspection.meta.version)
12018
12978
  };
12019
12979
  }
12020
- return { kind: "era", era: "modern", version: inspection.meta.version };
12021
- }
12022
- if (inspection.kind === "incomplete") {
12023
- return {
12024
- kind: "error",
12025
- code: ERROR_CODES.invalidParams,
12026
- message: `The request _meta is missing the required key "${inspection.missing}".`
12027
- };
12028
- }
12029
- if (method === METHOD3.discover) {
12030
- return { kind: "era", era: "modern", version: MODERN_PROTOCOL_VERSIONS[0] };
12031
- }
12032
- return { kind: "era", era: "legacy", version: null };
12033
- }
12034
- function negotiateLegacyVersion(requested) {
12035
- if (typeof requested === "string" && isLegacyVersion(requested)) {
12036
- return { version: requested, matched: true };
12037
- }
12038
- return { version: DEFAULT_LEGACY_PROTOCOL_VERSION, matched: false };
12980
+ return { kind: "era", era: "modern", version: inspection.meta.version };
12981
+ }
12982
+ if (inspection.kind === "incomplete") {
12983
+ return {
12984
+ kind: "error",
12985
+ code: ERROR_CODES.invalidParams,
12986
+ message: `The request _meta is missing the required key "${inspection.missing}".`
12987
+ };
12988
+ }
12989
+ if (method === METHOD3.discover) {
12990
+ return { kind: "era", era: "modern", version: MODERN_PROTOCOL_VERSIONS[0] };
12991
+ }
12992
+ return { kind: "era", era: "legacy", version: null };
12993
+ }
12994
+ function negotiateLegacyVersion(requested) {
12995
+ if (typeof requested === "string" && isLegacyVersion(requested)) {
12996
+ return { version: requested, matched: true };
12997
+ }
12998
+ return { version: DEFAULT_LEGACY_PROTOCOL_VERSION, matched: false };
12999
+ }
13000
+
13001
+ // src/mcp/resources.ts
13002
+ import * as fs18 from "fs";
13003
+ import * as path20 from "path";
13004
+ var MAX_RESOURCE_BYTES = 512 * 1024;
13005
+ var ResourceTooLargeError = class extends Error {
13006
+ constructor(uri, bytes, limit, message) {
13007
+ super(message);
13008
+ this.uri = uri;
13009
+ this.bytes = bytes;
13010
+ this.limit = limit;
13011
+ this.name = "ResourceTooLargeError";
13012
+ }
13013
+ uri;
13014
+ bytes;
13015
+ limit;
13016
+ };
13017
+ function refuseTooLarge(uri, bytes, advice) {
13018
+ throw new ResourceTooLargeError(
13019
+ uri,
13020
+ bytes,
13021
+ MAX_RESOURCE_BYTES,
13022
+ `${uri} is ${formatBytes2(bytes)}, above the ${formatBytes2(MAX_RESOURCE_BYTES)} single-read limit, so it was not returned. ${advice}`
13023
+ );
13024
+ }
13025
+ function ensureSingleRead(uri, text2, advice) {
13026
+ const bytes = Buffer.byteLength(text2, "utf8");
13027
+ if (bytes > MAX_RESOURCE_BYTES) refuseTooLarge(uri, bytes, advice);
13028
+ return text2;
13029
+ }
13030
+ 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.";
13031
+ 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.";
13032
+ 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.";
13033
+ var PART_URI = /^snapshot:\/\/parts\/(\d+)$/;
13034
+ var REPORT_URIS = /* @__PURE__ */ new Map([
13035
+ ["snapshot://reports/audit", { file: "audit.md", title: "Secret audit and risk findings" }],
13036
+ ["snapshot://reports/tree", { file: "project-tree.md", title: "Project tree" }],
13037
+ ["snapshot://reports/navigation", { file: "navigation.md", title: "Navigation index" }]
13038
+ ]);
13039
+ function formatBytes2(bytes) {
13040
+ if (bytes < 1024) return `${bytes} B`;
13041
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;
13042
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
13043
+ }
13044
+ async function workspaceFor(context) {
13045
+ const root = resolveRoot(void 0, context);
13046
+ if (!root.ok) return { error: root.message };
13047
+ const opened = await openWorkspace(root.root);
13048
+ if (!opened.ok) return { error: opened.message };
13049
+ return opened.workspace;
13050
+ }
13051
+ function readFileIfPresent(file) {
13052
+ try {
13053
+ return fs18.readFileSync(file, "utf8");
13054
+ } catch {
13055
+ return null;
13056
+ }
13057
+ }
13058
+ function buildResourceProvider() {
13059
+ return {
13060
+ async list(context) {
13061
+ const resources = [
13062
+ {
13063
+ uri: "snapshot://manifest",
13064
+ name: "manifest",
13065
+ title: "Snapshot manifest",
13066
+ 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.",
13067
+ mimeType: "application/json"
13068
+ },
13069
+ {
13070
+ uri: "snapshot://contract",
13071
+ name: "contract",
13072
+ title: "Tool contract",
13073
+ description: "The machine-readable description of the codebase-snapshot command line.",
13074
+ mimeType: "application/json"
13075
+ },
13076
+ {
13077
+ uri: "snapshot://skill",
13078
+ name: "skill",
13079
+ title: "Agent skill",
13080
+ description: "Usage guidance for an agent working with this tool.",
13081
+ mimeType: "text/markdown"
13082
+ }
13083
+ ];
13084
+ for (const [uri, report] of REPORT_URIS) {
13085
+ resources.push({
13086
+ uri,
13087
+ name: report.file.replace(/\.md$/, ""),
13088
+ title: report.title,
13089
+ 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.`,
13090
+ mimeType: "text/markdown"
13091
+ });
13092
+ }
13093
+ const workspace = await workspaceFor(context);
13094
+ if ("error" in workspace) return resources;
13095
+ const read = readManifest3(workspace);
13096
+ if (!read.ok) return resources;
13097
+ for (const part of read.manifest.parts) {
13098
+ const readable = part.byteSize <= MAX_RESOURCE_BYTES;
13099
+ resources.push({
13100
+ uri: `snapshot://parts/${part.index}`,
13101
+ name: `part-${String(part.index).padStart(3, "0")}`,
13102
+ title: `Part ${part.index} (${part.fileCount} files, ${formatBytes2(part.byteSize)})`,
13103
+ 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.`),
13104
+ mimeType: "text/markdown"
13105
+ });
13106
+ }
13107
+ return resources;
13108
+ },
13109
+ templates() {
13110
+ return [
13111
+ {
13112
+ uriTemplate: "snapshot://parts/{index}",
13113
+ name: "part",
13114
+ title: "Snapshot part",
13115
+ description: "One budgeted part of the snapshot, by its 1-based index.",
13116
+ mimeType: "text/markdown"
13117
+ }
13118
+ ];
13119
+ },
13120
+ async read(uri, context) {
13121
+ if (uri === "snapshot://contract") {
13122
+ const contract = buildAgentContract();
13123
+ return {
13124
+ uri,
13125
+ mimeType: "application/json",
13126
+ text: ensureSingleRead(
13127
+ uri,
13128
+ JSON.stringify(contract, null, 2),
13129
+ "Run 'codebase-snapshot describe --format json' for the complete contract."
13130
+ )
13131
+ };
13132
+ }
13133
+ if (uri === "snapshot://skill") {
13134
+ return {
13135
+ uri,
13136
+ mimeType: "text/markdown",
13137
+ text: ensureSingleRead(
13138
+ uri,
13139
+ renderSkill(),
13140
+ "Print it with 'codebase-snapshot skill'."
13141
+ )
13142
+ };
13143
+ }
13144
+ const workspace = await workspaceFor(context);
13145
+ if ("error" in workspace) return null;
13146
+ const report = REPORT_URIS.get(uri);
13147
+ if (report) {
13148
+ const text2 = readFileIfPresent(
13149
+ path20.resolve(workspace.root, workspace.config.outDir, "reports", report.file)
13150
+ );
13151
+ if (text2 === null) return null;
13152
+ return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, REPORT_ADVICE) };
13153
+ }
13154
+ if (uri === "snapshot://manifest") {
13155
+ const read = readManifest3(workspace);
13156
+ if (!read.ok) return null;
13157
+ const text2 = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
13158
+ return { uri, mimeType: "application/json", text: ensureSingleRead(uri, text2, MANIFEST_ADVICE) };
13159
+ }
13160
+ const partMatch = PART_URI.exec(uri);
13161
+ if (partMatch) {
13162
+ const read = readManifest3(workspace);
13163
+ if (!read.ok) return null;
13164
+ const index = Number(partMatch[1]);
13165
+ const part = read.manifest.parts.find((candidate) => candidate.index === index);
13166
+ if (!part) return null;
13167
+ const partPath = partPathFor(workspace, part.filename);
13168
+ if (partPath === null) return null;
13169
+ let partBytes;
13170
+ try {
13171
+ partBytes = fs18.statSync(partPath).size;
13172
+ } catch {
13173
+ return null;
13174
+ }
13175
+ if (partBytes > MAX_RESOURCE_BYTES) refuseTooLarge(uri, partBytes, PART_ADVICE);
13176
+ const text2 = readFileIfPresent(partPath);
13177
+ if (text2 === null) return null;
13178
+ return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, PART_ADVICE) };
13179
+ }
13180
+ return null;
13181
+ }
13182
+ };
12039
13183
  }
12040
13184
 
12041
13185
  // src/mcp/schema.ts
@@ -12264,7 +13408,22 @@ function createMcpServer(options) {
12264
13408
  if (typeof uri !== "string") {
12265
13409
  return errorResponse(id, ERROR_CODES.invalidParams, 'resources/read requires a "uri" string.');
12266
13410
  }
12267
- const contents = await options.resources.read(uri, options.context);
13411
+ let contents;
13412
+ try {
13413
+ contents = await options.resources.read(uri, options.context);
13414
+ } catch (error) {
13415
+ if (error instanceof ResourceTooLargeError) {
13416
+ options.context.log(
13417
+ `mcp: refused ${error.uri} (${error.bytes} bytes, limit ${error.limit}); returning it would truncate it`
13418
+ );
13419
+ return errorResponse(id, ERROR_CODES.resourceTooLarge, error.message, {
13420
+ uri: error.uri,
13421
+ bytes: error.bytes,
13422
+ limit: error.limit
13423
+ });
13424
+ }
13425
+ throw error;
13426
+ }
12268
13427
  if (!contents) {
12269
13428
  return errorResponse(id, ERROR_CODES.invalidParams, `Unknown resource "${uri}".`);
12270
13429
  }
@@ -12347,7 +13506,11 @@ function createMcpServer(options) {
12347
13506
  }
12348
13507
  async function dispatch(message) {
12349
13508
  if (!isJsonObject(message)) {
12350
- return errorResponse(null, ERROR_CODES.parseError, "Message is not a JSON object.");
13509
+ return errorResponse(
13510
+ null,
13511
+ ERROR_CODES.invalidRequest,
13512
+ Array.isArray(message) ? "Batch requests are not supported: send one JSON-RPC message per line." : "Message is not a JSON object."
13513
+ );
12351
13514
  }
12352
13515
  const isRequest = Object.prototype.hasOwnProperty.call(message, "id");
12353
13516
  const method = message.method;
@@ -12400,150 +13563,6 @@ function createMcpServer(options) {
12400
13563
  };
12401
13564
  }
12402
13565
 
12403
- // src/mcp/resources.ts
12404
- import * as fs18 from "fs";
12405
- import * as path20 from "path";
12406
- var MAX_RESOURCE_BYTES = 512 * 1024;
12407
- var PART_URI = /^snapshot:\/\/parts\/(\d+)$/;
12408
- var REPORT_URIS = /* @__PURE__ */ new Map([
12409
- ["snapshot://reports/audit", { file: "audit.md", title: "Secret audit and risk findings" }],
12410
- ["snapshot://reports/tree", { file: "project-tree.md", title: "Project tree" }],
12411
- ["snapshot://reports/navigation", { file: "navigation.md", title: "Navigation index" }]
12412
- ]);
12413
- function formatBytes2(bytes) {
12414
- if (bytes < 1024) return `${bytes} B`;
12415
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;
12416
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
12417
- }
12418
- function truncationMarker(originalBytes) {
12419
- return `
12420
-
12421
- [truncated: ${formatBytes2(originalBytes)} total. Use the snapshot_read tool for a line window.]
12422
- `;
12423
- }
12424
- function capUtf8(text2, limit) {
12425
- const size2 = Buffer.byteLength(text2, "utf8");
12426
- if (size2 <= limit) return { text: text2, truncated: false };
12427
- const cut = Buffer.from(text2, "utf8").subarray(0, limit).toString("utf8").replace(/\uFFFD+$/, "");
12428
- return { text: `${cut}${truncationMarker(size2)}`, truncated: true };
12429
- }
12430
- async function workspaceFor(context) {
12431
- const root = resolveRoot(void 0, context);
12432
- if (!root.ok) return { error: root.message };
12433
- const opened = await openWorkspace(root.root);
12434
- if (!opened.ok) return { error: opened.message };
12435
- return opened.workspace;
12436
- }
12437
- function readFileIfPresent(file) {
12438
- try {
12439
- return fs18.readFileSync(file, "utf8");
12440
- } catch {
12441
- return null;
12442
- }
12443
- }
12444
- function buildResourceProvider() {
12445
- return {
12446
- async list(context) {
12447
- const resources = [
12448
- {
12449
- uri: "snapshot://manifest",
12450
- name: "manifest",
12451
- title: "Snapshot manifest",
12452
- description: "Every file in the snapshot with its layer, kind, language, part and hash, plus the reason each excluded file was excluded.",
12453
- mimeType: "application/json"
12454
- },
12455
- {
12456
- uri: "snapshot://contract",
12457
- name: "contract",
12458
- title: "Tool contract",
12459
- description: "The machine-readable description of the codebase-snapshot command line.",
12460
- mimeType: "application/json"
12461
- },
12462
- {
12463
- uri: "snapshot://skill",
12464
- name: "skill",
12465
- title: "Agent skill",
12466
- description: "Usage guidance for an agent working with this tool.",
12467
- mimeType: "text/markdown"
12468
- }
12469
- ];
12470
- for (const [uri, report] of REPORT_URIS) {
12471
- resources.push({
12472
- uri,
12473
- name: report.file.replace(/\.md$/, ""),
12474
- title: report.title,
12475
- description: `${report.title} from the most recent snapshot.`,
12476
- mimeType: "text/markdown"
12477
- });
12478
- }
12479
- const workspace = await workspaceFor(context);
12480
- if ("error" in workspace) return resources;
12481
- const read = readManifest3(workspace);
12482
- if (!read.ok) return resources;
12483
- for (const part of read.manifest.parts) {
12484
- resources.push({
12485
- uri: `snapshot://parts/${part.index}`,
12486
- name: `part-${String(part.index).padStart(3, "0")}`,
12487
- title: `Part ${part.index} (${part.fileCount} files, ${formatBytes2(part.byteSize)})`,
12488
- description: `Part ${part.index} of ${read.manifest.parts.length}: ${part.fileCount} file(s), ${part.lines} line(s), ${formatBytes2(part.byteSize)}.`,
12489
- mimeType: "text/markdown"
12490
- });
12491
- }
12492
- return resources;
12493
- },
12494
- templates() {
12495
- return [
12496
- {
12497
- uriTemplate: "snapshot://parts/{index}",
12498
- name: "part",
12499
- title: "Snapshot part",
12500
- description: "One budgeted part of the snapshot, by its 1-based index.",
12501
- mimeType: "text/markdown"
12502
- }
12503
- ];
12504
- },
12505
- async read(uri, context) {
12506
- if (uri === "snapshot://contract") {
12507
- const contract = buildAgentContract();
12508
- return { uri, mimeType: "application/json", text: JSON.stringify(contract, null, 2) };
12509
- }
12510
- if (uri === "snapshot://skill") {
12511
- return { uri, mimeType: "text/markdown", text: renderSkill() };
12512
- }
12513
- const workspace = await workspaceFor(context);
12514
- if ("error" in workspace) return null;
12515
- const report = REPORT_URIS.get(uri);
12516
- if (report) {
12517
- const text2 = readFileIfPresent(
12518
- path20.resolve(workspace.root, workspace.config.outDir, "reports", report.file)
12519
- );
12520
- if (text2 === null) return null;
12521
- return { uri, mimeType: "text/markdown", text: capUtf8(text2, MAX_RESOURCE_BYTES).text };
12522
- }
12523
- if (uri === "snapshot://manifest") {
12524
- const read = readManifest3(workspace);
12525
- if (!read.ok) return null;
12526
- const text2 = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
12527
- return { uri, mimeType: "application/json", text: capUtf8(text2, MAX_RESOURCE_BYTES).text };
12528
- }
12529
- const partMatch = PART_URI.exec(uri);
12530
- if (partMatch) {
12531
- const read = readManifest3(workspace);
12532
- if (!read.ok) return null;
12533
- const index = Number(partMatch[1]);
12534
- const part = read.manifest.parts.find((candidate) => candidate.index === index);
12535
- if (!part) return null;
12536
- const text2 = readFileIfPresent(
12537
- path20.resolve(workspace.root, workspace.config.outDir, "parts", part.filename)
12538
- );
12539
- if (text2 === null) return null;
12540
- return { uri, mimeType: "text/markdown", text: capUtf8(text2, MAX_RESOURCE_BYTES).text };
12541
- }
12542
- return null;
12543
- }
12544
- };
12545
- }
12546
-
12547
13566
  // src/mcp/instructions.ts
12548
13567
  var SERVER_INSTRUCTIONS = [
12549
13568
  "codebase-snapshot serves this repository as a size-budgeted snapshot, not as a directory walk.",
@@ -12567,11 +13586,11 @@ var MAX_LINE_BYTES = 32 * 1024 * 1024;
12567
13586
  function createWriter(output) {
12568
13587
  return {
12569
13588
  write(value) {
12570
- return new Promise((resolve9, reject) => {
13589
+ return new Promise((resolve10, reject) => {
12571
13590
  output.write(`${JSON.stringify(value)}
12572
13591
  `, (error) => {
12573
13592
  if (error) reject(error);
12574
- else resolve9();
13593
+ else resolve10();
12575
13594
  });
12576
13595
  });
12577
13596
  }
@@ -12579,6 +13598,7 @@ function createWriter(output) {
12579
13598
  }
12580
13599
  function createLineReader(input, options) {
12581
13600
  let buffer = "";
13601
+ let bufferBytes = 0;
12582
13602
  let discarding = false;
12583
13603
  let discardedBytes = 0;
12584
13604
  const deliver = (line) => {
@@ -12591,6 +13611,13 @@ function createLineReader(input, options) {
12591
13611
  if (trimmed.trim().length === 0) return;
12592
13612
  options.onLine(trimmed);
12593
13613
  };
13614
+ const discardBuffered = () => {
13615
+ discarding = true;
13616
+ discardedBytes += bufferBytes;
13617
+ buffer = "";
13618
+ bufferBytes = 0;
13619
+ options.onOverflow?.(discardedBytes);
13620
+ };
12594
13621
  const drain = () => {
12595
13622
  let index = buffer.indexOf("\n");
12596
13623
  while (index >= 0) {
@@ -12598,42 +13625,57 @@ function createLineReader(input, options) {
12598
13625
  buffer = buffer.slice(index + 1);
12599
13626
  if (discarding) {
12600
13627
  deliver(line);
12601
- } else if (line.length > MAX_LINE_BYTES) {
12602
- options.onOverflow?.(line.length);
12603
13628
  } else {
12604
- deliver(line);
13629
+ const lineBytes = Buffer.byteLength(line, "utf8");
13630
+ if (lineBytes > MAX_LINE_BYTES) options.onOverflow?.(lineBytes);
13631
+ else deliver(line);
12605
13632
  }
12606
13633
  index = buffer.indexOf("\n");
12607
13634
  }
13635
+ bufferBytes = Buffer.byteLength(buffer, "utf8");
13636
+ if (!discarding && bufferBytes > MAX_LINE_BYTES) discardBuffered();
12608
13637
  };
12609
13638
  const onData = (chunk) => {
13639
+ const chunkBytes = Buffer.byteLength(chunk, "utf8");
12610
13640
  if (discarding) {
12611
13641
  const index = chunk.indexOf("\n");
12612
13642
  if (index < 0) {
12613
- discardedBytes += chunk.length;
13643
+ discardedBytes += chunkBytes;
12614
13644
  return;
12615
13645
  }
12616
13646
  buffer = chunk.slice(index + 1);
13647
+ bufferBytes = Buffer.byteLength(buffer, "utf8");
12617
13648
  deliver("");
12618
13649
  drain();
12619
13650
  return;
12620
13651
  }
12621
- buffer += chunk;
12622
- drain();
12623
- if (buffer.length > MAX_LINE_BYTES) {
13652
+ if (chunk.indexOf("\n") < 0 && bufferBytes + chunkBytes > MAX_LINE_BYTES) {
12624
13653
  discarding = true;
12625
- discardedBytes = buffer.length;
13654
+ discardedBytes = bufferBytes + chunkBytes;
12626
13655
  buffer = "";
13656
+ bufferBytes = 0;
12627
13657
  options.onOverflow?.(discardedBytes);
12628
13658
  return;
12629
13659
  }
13660
+ buffer += chunk;
13661
+ drain();
12630
13662
  };
12631
13663
  const onEnd = () => {
12632
- if (buffer.length > 0) {
12633
- const rest = buffer;
12634
- buffer = "";
12635
- deliver(rest);
13664
+ const rest = buffer;
13665
+ const restBytes = bufferBytes || Buffer.byteLength(rest, "utf8");
13666
+ buffer = "";
13667
+ bufferBytes = 0;
13668
+ if (rest.length === 0) return;
13669
+ if (discarding) {
13670
+ discarding = false;
13671
+ discardedBytes = 0;
13672
+ return;
13673
+ }
13674
+ if (restBytes > MAX_LINE_BYTES) {
13675
+ options.onOverflow?.(restBytes);
13676
+ return;
12636
13677
  }
13678
+ deliver(rest);
12637
13679
  };
12638
13680
  input.setEncoding("utf8");
12639
13681
  input.on("data", onData);
@@ -12684,8 +13726,8 @@ async function runStdioServer(options) {
12684
13726
  let inFlight = 0;
12685
13727
  let inputEnded = false;
12686
13728
  let resolveDone = () => void 0;
12687
- const finished = new Promise((resolve9) => {
12688
- resolveDone = resolve9;
13729
+ const finished = new Promise((resolve10) => {
13730
+ resolveDone = resolve10;
12689
13731
  });
12690
13732
  const finishIfIdle = () => {
12691
13733
  if (inputEnded && inFlight === 0) resolveDone(0);
@@ -12978,7 +14020,24 @@ function parseCliArgs(argv) {
12978
14020
  let args = [];
12979
14021
  const explicitMode = values.mode ? String(values.mode) : void 0;
12980
14022
  const firstPositional = positionals[0];
12981
- if (firstPositional !== void 0) {
14023
+ const modeCommand = explicitMode === void 0 ? void 0 : COMMAND_ALIASES.get(explicitMode);
14024
+ if (explicitMode !== void 0 && modeCommand === void 0) {
14025
+ throw new UsageError(
14026
+ `Unknown --mode "${explicitMode}". Expected one of: ${Array.from(COMMAND_ALIASES.keys()).join(", ")}.`
14027
+ );
14028
+ }
14029
+ if (modeCommand !== void 0) {
14030
+ command = modeCommand;
14031
+ if (firstPositional !== void 0) {
14032
+ const named = COMMAND_ALIASES.get(firstPositional);
14033
+ if (named !== void 0 && named !== modeCommand) {
14034
+ throw new UsageError(
14035
+ `--mode ${explicitMode} contradicts the command "${firstPositional}". Pass one or the other.`
14036
+ );
14037
+ }
14038
+ args = named !== void 0 ? positionals.slice(1) : positionals;
14039
+ }
14040
+ } else if (firstPositional !== void 0) {
12982
14041
  const resolved = COMMAND_ALIASES.get(firstPositional);
12983
14042
  if (!resolved) {
12984
14043
  throw new UsageError(
@@ -12987,27 +14046,6 @@ function parseCliArgs(argv) {
12987
14046
  }
12988
14047
  command = resolved;
12989
14048
  args = positionals.slice(1);
12990
- } else if (explicitMode !== void 0) {
12991
- const resolved = COMMAND_ALIASES.get(explicitMode);
12992
- if (!resolved) {
12993
- throw new UsageError(
12994
- `Unknown --mode "${explicitMode}". Expected one of: ${Array.from(COMMAND_ALIASES.keys()).join(", ")}.`
12995
- );
12996
- }
12997
- command = resolved;
12998
- }
12999
- if (explicitMode !== void 0) {
13000
- const resolvedMode = COMMAND_ALIASES.get(explicitMode);
13001
- if (!resolvedMode) {
13002
- throw new UsageError(
13003
- `Unknown --mode "${explicitMode}". Expected one of: ${Array.from(COMMAND_ALIASES.keys()).join(", ")}.`
13004
- );
13005
- }
13006
- if (firstPositional !== void 0 && resolvedMode !== command) {
13007
- throw new UsageError(
13008
- `--mode ${explicitMode} contradicts the command "${firstPositional}". Pass one or the other.`
13009
- );
13010
- }
13011
14049
  }
13012
14050
  const expectedArgs = COMMAND_ARITY[command];
13013
14051
  if (args.length !== expectedArgs) {
@@ -13197,7 +14235,9 @@ function nextStepHint(cwd, scriptsAddedNow) {
13197
14235
  let hasScript = scriptsAddedNow;
13198
14236
  if (!hasScript) {
13199
14237
  try {
13200
- const parsed = JSON.parse(fs19.readFileSync(path21.join(cwd, "package.json"), "utf8"));
14238
+ const parsed = JSON.parse(
14239
+ stripJsonComments2(fs19.readFileSync(path21.join(cwd, "package.json"), "utf8"))
14240
+ );
13201
14241
  hasScript = typeof parsed.scripts?.snapshot === "string";
13202
14242
  } catch {
13203
14243
  hasScript = false;
@@ -13298,19 +14338,19 @@ function installDependencies(cwd) {
13298
14338
  }
13299
14339
  return { manager: manager.name, command, ok: true, detail: seconds };
13300
14340
  }
13301
- async function captureStdout(fn) {
13302
- const original = process.stdout.write.bind(process.stdout);
13303
- let text2 = "";
13304
- process.stdout.write = ((chunk) => {
13305
- text2 += typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
13306
- return true;
13307
- });
13308
- try {
13309
- const code = await fn();
13310
- return { code, text: text2 };
13311
- } finally {
13312
- process.stdout.write = original;
14341
+ async function setupHookOutDir(invocation, init) {
14342
+ if (!init.reused || invocation.outDir !== void 0) return init.outDir;
14343
+ const loaded = await loadConfigFileDetailed(invocation.cwd);
14344
+ if (loaded.errors.length > 0) {
14345
+ throw new Error(
14346
+ `The config file could not be read: ${loaded.errors.join("; ")}. Fix it, or delete it to use the defaults.`
14347
+ );
13313
14348
  }
14349
+ return resolveConfig(loaded.config, {}, invocation.cwd).outDir;
14350
+ }
14351
+ async function captureStdout(fn) {
14352
+ const { value, text: text2 } = await runWithStdoutCapture(fn);
14353
+ return { code: value, text: text2 };
13314
14354
  }
13315
14355
  async function runSetupCommand(invocation, options = {}) {
13316
14356
  try {
@@ -13341,7 +14381,13 @@ async function runSetupCommand(invocation, options = {}) {
13341
14381
  reuseConfig: true,
13342
14382
  dryRun: invocation.dryRun
13343
14383
  });
13344
- const hook = invocation.installHook === true ? installPreCommitHook(invocation.cwd, init.outDir) : null;
14384
+ const keptConfigPath = init.reused ? findConfigFile(invocation.cwd) ?? init.configPath : init.configPath;
14385
+ const appliedPreset = init.reused ? null : init.preset;
14386
+ if (init.reused && invocation.preset !== void 0) {
14387
+ init.notes.push(
14388
+ `--preset ${invocation.preset} was not applied: the existing config is kept. Edit its preset setting, or run \`init --force\` to write a new one.`
14389
+ );
14390
+ }
13345
14391
  if (invocation.dryRun) {
13346
14392
  const manager = invocation.noInstall ? null : detectPackageManager(invocation.cwd).name;
13347
14393
  if (invocation.format === "json") {
@@ -13349,9 +14395,9 @@ async function runSetupCommand(invocation, options = {}) {
13349
14395
  `${JSON.stringify(
13350
14396
  {
13351
14397
  dryRun: true,
13352
- configPath: init.configPath,
14398
+ configPath: keptConfigPath,
13353
14399
  configReused: init.reused,
13354
- preset: init.preset,
14400
+ preset: appliedPreset,
13355
14401
  install: manager,
13356
14402
  configText: init.configText
13357
14403
  },
@@ -13364,7 +14410,7 @@ async function runSetupCommand(invocation, options = {}) {
13364
14410
  }
13365
14411
  info("\n\u{1F9EA} Dry run \u2014 setup would:");
13366
14412
  info(
13367
- ` 1. ${init.reused ? `keep ${path21.basename(init.configPath)}` : `write ${path21.basename(init.configPath)} (preset: ${init.preset})`}`
14413
+ ` 1. ${init.reused ? `keep ${path21.basename(keptConfigPath)}` : `write ${path21.basename(keptConfigPath)} (preset: ${appliedPreset})`}`
13368
14414
  );
13369
14415
  info(" 2. add the npm scripts, the devDependency and the .gitignore entries");
13370
14416
  if (manager !== null) info(` 3. install with ${manager}`);
@@ -13373,12 +14419,13 @@ async function runSetupCommand(invocation, options = {}) {
13373
14419
  info(init.configText);
13374
14420
  return 0;
13375
14421
  }
14422
+ const hook = invocation.installHook === true ? installPreCommitHook(invocation.cwd, await setupHookOutDir(invocation, init)) : null;
13376
14423
  if (invocation.format !== "json") {
13377
14424
  if (!interactive) info(`\u{1F680} Setup for: ${invocation.cwd}`);
13378
14425
  if (init.reused) {
13379
- info(`\u267B Keeping ${path21.basename(init.configPath)} (${presetSummary(init)})`);
14426
+ info(`\u267B Keeping ${path21.basename(keptConfigPath)}`);
13380
14427
  } else {
13381
- info(`\u2705 Created ${path21.basename(init.configPath)} (${presetSummary(init)})`);
14428
+ info(`\u2705 Created ${path21.basename(keptConfigPath)} (${presetSummary(init)})`);
13382
14429
  }
13383
14430
  if (init.scripts.length > 0) info(` Added npm scripts: ${init.scripts.join(", ")}`);
13384
14431
  if (init.dependency.added && init.dependency.range !== null) {
@@ -13388,6 +14435,9 @@ async function runSetupCommand(invocation, options = {}) {
13388
14435
  info(` Added to .gitignore: ${init.gitignoreEntries.join(", ")}`);
13389
14436
  }
13390
14437
  if (hook) for (const note of hook.notes) info(` ${note}`);
14438
+ if (init.reused && invocation.preset !== void 0) {
14439
+ info(` \u26A0 --preset ${invocation.preset} was not applied: the existing config is kept.`);
14440
+ }
13391
14441
  }
13392
14442
  let install = null;
13393
14443
  if (invocation.noInstall) {
@@ -13405,7 +14455,9 @@ async function runSetupCommand(invocation, options = {}) {
13405
14455
  if (invocation.includeSensitiveFiles === true) generateArgs.push("--include-sensitive-files");
13406
14456
  const budget = invocation.maxPartBytesRaw ?? invocation.maxPartBytes;
13407
14457
  if (budget !== void 0) generateArgs.push("--max-part-bytes", String(budget));
13408
- if ((invocation.skipArtifacts ?? []).length > 0) {
14458
+ if ((invocation.onlyArtifacts ?? []).length > 0) {
14459
+ generateArgs.push("--only-artifacts", (invocation.onlyArtifacts ?? []).join(","));
14460
+ } else if ((invocation.skipArtifacts ?? []).length > 0) {
13409
14461
  generateArgs.push("--skip-artifacts", (invocation.skipArtifacts ?? []).join(","));
13410
14462
  }
13411
14463
  if (invocation.includeMonolith === true) generateArgs.push("--include-monolith");
@@ -13425,31 +14477,33 @@ async function runSetupCommand(invocation, options = {}) {
13425
14477
  if (invocation.watch) generateArgs.push("--watch");
13426
14478
  if (invocation.format === "json") {
13427
14479
  const generated = await captureStdout(() => main(generateArgs));
13428
- let manifest = null;
14480
+ let parsed = null;
13429
14481
  try {
13430
- manifest = JSON.parse(generated.text);
14482
+ parsed = JSON.parse(generated.text);
13431
14483
  } catch {
13432
- manifest = null;
14484
+ parsed = null;
14485
+ }
14486
+ const setup = {
14487
+ configPath: keptConfigPath,
14488
+ configReused: init.reused,
14489
+ preset: appliedPreset,
14490
+ scripts: init.scripts,
14491
+ dependency: init.dependency,
14492
+ gitignoreEntries: init.gitignoreEntries,
14493
+ install,
14494
+ notes: init.notes,
14495
+ hook
14496
+ };
14497
+ if (generated.code !== 0) {
14498
+ const inner = parsed && typeof parsed.error === "object" && parsed.error !== null ? parsed.error : { message: "Snapshot generation failed during setup.", exitCode: generated.code };
14499
+ process.stdout.write(
14500
+ `${JSON.stringify({ error: inner, setup, manifest: null }, null, 2)}
14501
+ `
14502
+ );
14503
+ return generated.code;
13433
14504
  }
13434
14505
  process.stdout.write(
13435
- `${JSON.stringify(
13436
- {
13437
- setup: {
13438
- configPath: init.configPath,
13439
- configReused: init.reused,
13440
- preset: init.preset,
13441
- scripts: init.scripts,
13442
- dependency: init.dependency,
13443
- gitignoreEntries: init.gitignoreEntries,
13444
- install,
13445
- notes: init.notes,
13446
- hook
13447
- },
13448
- manifest
13449
- },
13450
- null,
13451
- 2
13452
- )}
14506
+ `${JSON.stringify({ setup, manifest: parsed }, null, 2)}
13453
14507
  `
13454
14508
  );
13455
14509
  return generated.code;
@@ -13565,7 +14619,19 @@ function requestsJsonFormat(argv) {
13565
14619
  }
13566
14620
  return format === "json";
13567
14621
  }
14622
+ var closedStdoutGuarded = false;
14623
+ function guardClosedStdout() {
14624
+ if (closedStdoutGuarded) return;
14625
+ closedStdoutGuarded = true;
14626
+ process.stdout.on("error", (error) => {
14627
+ if (error.code === "EPIPE" || error.code === "ECONNRESET") {
14628
+ process.exit(0);
14629
+ }
14630
+ throw error;
14631
+ });
14632
+ }
13568
14633
  async function main(argv = process.argv.slice(2)) {
14634
+ guardClosedStdout();
13569
14635
  const pending = process.stdout.isTTY === true && shouldCheck(argv, process.env) ? checkForUpdate({ current: GENERATOR_VERSION, cacheFile: cacheFilePath() }) : null;
13570
14636
  const code = await runCommand(argv);
13571
14637
  if (pending) {
@@ -13621,51 +14687,49 @@ ${USAGE}
13621
14687
  const skipConfig = invocation.noConfig || invocation.command === "diff";
13622
14688
  const loaded = skipConfig ? { config: null, warnings: [], errors: [], file: null } : await loadConfigFileDetailed(invocation.cwd);
13623
14689
  if (invocation.noConfig) info("\u2699 --no-config: using built-in defaults, config file ignored");
13624
- for (const warning of loaded.warnings) warn(`\u26A0 Config: ${warning}`);
13625
14690
  if (loaded.errors.length > 0) {
13626
- warn("\u274C The config file could not be read. Fix it, or delete it to use the defaults.");
13627
- return 1;
14691
+ return fail(
14692
+ invocation.format,
14693
+ `The config file could not be read: ${loaded.errors.join("; ")}. Fix it, or delete it to use the defaults.`
14694
+ );
13628
14695
  }
14696
+ for (const warning of loaded.warnings) warn(`\u26A0 Config: ${warning}`);
13629
14697
  if (loaded.file) info(`\u2699 Using config ${path21.relative(process.cwd(), loaded.file) || loaded.file}`);
13630
- const resolved = resolveConfig(
13631
- loaded.config,
13632
- {
13633
- mode: invocation.command,
13634
- format: invocation.format,
13635
- dryRun: invocation.dryRun,
13636
- cwd: invocation.cwd,
13637
- outDir: invocation.outDir,
13638
- includeMonolith: invocation.includeMonolith,
13639
- includeSensitiveFiles: invocation.includeSensitiveFiles,
13640
- maxPartBytes: invocation.maxPartBytes,
13641
- maxPartTokens: invocation.maxPartTokens,
13642
- largeFileBytes: invocation.largeFileBytes,
13643
- maxMonolithBytes: invocation.maxMonolithBytes,
13644
- skipArtifacts: invocation.skipArtifacts,
13645
- discovery: invocation.discovery,
13646
- changedSince: invocation.changedSince,
13647
- staged: invocation.staged,
13648
- withDependents: invocation.withDependents,
13649
- skeleton: invocation.skeleton,
13650
- sarif: invocation.sarif
13651
- },
13652
- invocation.cwd
13653
- );
14698
+ let resolved;
14699
+ try {
14700
+ resolved = resolveConfig(
14701
+ loaded.config,
14702
+ {
14703
+ mode: invocation.command,
14704
+ format: invocation.format,
14705
+ dryRun: invocation.dryRun,
14706
+ cwd: invocation.cwd,
14707
+ outDir: invocation.outDir,
14708
+ includeMonolith: invocation.includeMonolith,
14709
+ includeSensitiveFiles: invocation.includeSensitiveFiles,
14710
+ maxPartBytes: invocation.maxPartBytes,
14711
+ maxPartTokens: invocation.maxPartTokens,
14712
+ largeFileBytes: invocation.largeFileBytes,
14713
+ maxMonolithBytes: invocation.maxMonolithBytes,
14714
+ skipArtifacts: invocation.skipArtifacts,
14715
+ // `--only-artifacts` is forwarded as itself, not only as the derived suppression list:
14716
+ // suppression cannot switch an artifact *on*, so a config that had turned one of the
14717
+ // requested artifacts off left the run with nothing to write.
14718
+ onlyArtifacts: invocation.onlyArtifacts,
14719
+ discovery: invocation.discovery,
14720
+ changedSince: invocation.changedSince,
14721
+ staged: invocation.staged,
14722
+ withDependents: invocation.withDependents,
14723
+ skeleton: invocation.skeleton,
14724
+ sarif: invocation.sarif
14725
+ },
14726
+ invocation.cwd
14727
+ );
14728
+ } catch (err) {
14729
+ return fail(invocation.format, err.message);
14730
+ }
13654
14731
  if (invocation.command === "validate") {
13655
14732
  const result = validateSnapshot(resolved);
13656
- if (result.valid) {
13657
- const manifestPath = path21.resolve(resolved.cwd, resolved.outDir, "manifest.json");
13658
- let manifest;
13659
- try {
13660
- manifest = JSON.parse(fs19.readFileSync(manifestPath, "utf8"));
13661
- } catch {
13662
- manifest = void 0;
13663
- }
13664
- const shapeError = manifest === void 0 ? null : describeManifestShapeProblem(manifest);
13665
- if (shapeError) {
13666
- return fail(invocation.format, `${manifestPath} is not a snapshot manifest: ${shapeError}`);
13667
- }
13668
- }
13669
14733
  emit(invocation.format, result, () => renderValidateText(result));
13670
14734
  return result.valid ? 0 : 1;
13671
14735
  }
@@ -13860,10 +14924,13 @@ function isGeneratedWatchPath(candidate, paths) {
13860
14924
  const outDir = comparablePath(path21.resolve(paths.cwd, paths.outDir));
13861
14925
  const tmpDir = comparablePath(path21.resolve(paths.cwd, paths.tmpDir));
13862
14926
  if (isSameOrInside(outDir, absolute) || isSameOrInside(tmpDir, absolute)) return true;
13863
- const parent = path21.dirname(absolute);
13864
- if (parent === path21.dirname(outDir) && path21.basename(absolute).startsWith(`${path21.basename(outDir)}.backup-`)) {
13865
- return true;
13866
- }
14927
+ const offsets = [path21.basename(outDir), path21.basename(tmpDir)].filter((name) => name.length > 0);
14928
+ const leftover = absolute.split(/[\\/]+/).some(
14929
+ (segment) => offsets.some(
14930
+ (name) => segment.startsWith(`${name}.backup-`) || segment.startsWith(`${name}.partial-`)
14931
+ )
14932
+ );
14933
+ if (leftover) return true;
13867
14934
  return absolute.split(/[\\/]+/).some((segment) => VCS_SEGMENTS.has(segment));
13868
14935
  }
13869
14936
  function decideWatchEvent(state, event, paths) {
@@ -13938,6 +15005,7 @@ async function runWatchLoop(invocation, resolved, options) {
13938
15005
  largeFileBytes: invocation.largeFileBytes,
13939
15006
  maxMonolithBytes: invocation.maxMonolithBytes,
13940
15007
  skipArtifacts: invocation.skipArtifacts,
15008
+ onlyArtifacts: invocation.onlyArtifacts,
13941
15009
  discovery: invocation.discovery,
13942
15010
  changedSince: invocation.changedSince,
13943
15011
  staged: invocation.staged,
@@ -13995,12 +15063,12 @@ async function runWatchLoop(invocation, resolved, options) {
13995
15063
  info(`\u26A0 Watch error: ${err.message}`);
13996
15064
  info(" The watcher may have missed changes. Restart with Ctrl+C if they stop arriving.");
13997
15065
  });
13998
- await new Promise((resolve9) => {
15066
+ await new Promise((resolve10) => {
13999
15067
  const stop = () => {
14000
15068
  stopped = true;
14001
15069
  if (timer) clearTimeout(timer);
14002
15070
  watcher.close();
14003
- resolve9();
15071
+ resolve10();
14004
15072
  };
14005
15073
  process.once("SIGINT", stop);
14006
15074
  process.once("SIGTERM", stop);