codebase-snapshot 0.9.14 → 0.9.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -209,6 +209,14 @@ function scanWorkspacePackages(cwd, patterns) {
209
209
  }
210
210
  return { files, dependencies };
211
211
  }
212
+ var SNAPSHOT_MARKER = ".codebase-snapshot";
213
+ function isToolOwnedDirectory(dir) {
214
+ try {
215
+ return fs14__namespace.statSync(dir).isDirectory() && fs14__namespace.existsSync(path16__namespace.join(dir, SNAPSHOT_MARKER));
216
+ } catch {
217
+ return false;
218
+ }
219
+ }
212
220
  function countMarkdownFiles(cwd) {
213
221
  let count = 0;
214
222
  let directoriesSeen = 0;
@@ -230,7 +238,9 @@ function countMarkdownFiles(cwd) {
230
238
  }
231
239
  if (!entry.isDirectory() || current.depth >= 2) continue;
232
240
  if (entry.name.startsWith(".") || SKIPPED_WALK_DIRS.has(entry.name)) continue;
233
- queue.push({ dir: path16__namespace.join(current.dir, entry.name), depth: current.depth + 1 });
241
+ const child = path16__namespace.join(current.dir, entry.name);
242
+ if (isToolOwnedDirectory(child)) continue;
243
+ queue.push({ dir: child, depth: current.depth + 1 });
234
244
  }
235
245
  }
236
246
  return count;
@@ -1099,18 +1109,24 @@ function detectPreset(cwd, forced) {
1099
1109
  }
1100
1110
 
1101
1111
  // src/security/patterns.ts
1102
- 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)";
1103
- var WEAK_CREDENTIAL_NAME = "(?:pass|id[_-]?token|credentials?)";
1112
+ var STRONG_CREDENTIAL_NAME = "(?:password|passwd|passphrase|pwd|api[_-]?key|api[_-]?secret|access[_-]?key|secret[_-]?access[_-]?key|secret[_-]?key|client[_-]?secret[_-]?key|client[_-]?secret|private[_-]?key|aws[_-]?secret[_-]?access[_-]?key|access[_-]?token|refresh[_-]?token|auth[_-]?token|session[_-]?token|session[_-]?key|secret|token)";
1113
+ var WEAK_CREDENTIAL_NAME = "(?:pass|credentials?)";
1104
1114
  var NOT_A_LITERAL_VALUE = "(?!(?:string|number|boolean|bigint|symbol|unknown|any|never|void|null|undefined|true|false|await|async|new|this|typeof|delete|yield|function|return|process\\.env|Buffer|Record|object)\\b)";
1105
1115
  var UNQUOTED_MIN_LENGTH = 2;
1106
1116
  var PROSE_CONTINUATION = String.raw`(?!\s+[a-z])`;
1107
- 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;
1108
- var UNQUOTED_AMBIGUOUS_LITERAL = String.raw`(?![0-9]+(?![A-Za-z0-9_+=/%:.~-]))([A-Za-z0-9_][A-Za-z0-9_+=/%:~-]{7,511})(?![A-Za-z0-9_+=/%:.~-]|[({[])` + PROSE_CONTINUATION;
1117
+ var UNQUOTED_VALUE_CHARS = String.raw`A-Za-z0-9_+=/%:~$!@#^*?-`;
1118
+ var UNQUOTED_VALUE_END = String.raw`[A-Za-z0-9_+=/%:.~$!@#^*?-]`;
1119
+ var UNQUOTED_VALUE_START = String.raw`[$!@#%^&*~+]`;
1120
+ var UNQUOTED_LITERAL = String.raw`(` + // one capture, whichever branch matched: valueGroup is 1
1121
+ String.raw`(?![0-9]+(?!${UNQUOTED_VALUE_END}))[A-Za-z0-9_][${UNQUOTED_VALUE_CHARS}]{${UNQUOTED_MIN_LENGTH - 1},511}(?!${UNQUOTED_VALUE_END}|[({[]|[<>|\\])` + String.raw`|(?=${UNQUOTED_VALUE_START}[^ \t]{0,62}(?:[0-9]|${UNQUOTED_VALUE_START}))${UNQUOTED_VALUE_START}[${UNQUOTED_VALUE_CHARS}]{2,511}(?!${UNQUOTED_VALUE_END}|[({[]|[<>|\\])` + String.raw`|\([^()\s]{1,510}\)|\[[^\[\]\s]{1,510}\]|\{[^{}\s]{1,510}\}` + String.raw`)` + PROSE_CONTINUATION;
1122
+ var UNQUOTED_AMBIGUOUS_LITERAL = String.raw`(?![0-9]+(?!${UNQUOTED_VALUE_END}))([A-Za-z0-9_][${UNQUOTED_VALUE_CHARS}]{7,511})(?!${UNQUOTED_VALUE_END}|[({[]|[<>|\\])` + PROSE_CONTINUATION;
1109
1123
  var ASSIGN = String.raw`(?<![=!<>])[:=](?!=)`;
1110
1124
  var NOT_AFTER_QUOTE = String.raw`(?<!["'])`;
1111
1125
  var NOT_A_NAMESPACED_IDENTIFIER = String.raw`(?![a-z][a-z0-9]*(?:\.[a-z][a-z0-9-]*)+/)`;
1126
+ var QUOTED_CREDENTIAL_KEY = `["'](?!id[-_]token["'])[A-Za-z0-9_$-]{0,64}${STRONG_CREDENTIAL_NAME}["']`;
1112
1127
  var QUOTED_VALUE = String.raw`((?:[^"'\\\n]|\\\\["'](?=[A-Za-z0-9_])|\\.){1,512})`;
1113
1128
  var UNQUOTED_STRONG_NAME = `(?<!id[-_])${STRONG_CREDENTIAL_NAME}`;
1129
+ var CREDENTIAL_KEY_TAIL = new RegExp(`(?:${STRONG_CREDENTIAL_NAME})$`, "i");
1114
1130
  var DEFAULT_SECRET_PATTERNS = [
1115
1131
  {
1116
1132
  rule: "private-key-header",
@@ -1177,13 +1193,28 @@ var DEFAULT_SECRET_PATTERNS = [
1177
1193
  pattern: /xox[baprsdc]-[0-9A-Za-z-]{10,250}/
1178
1194
  },
1179
1195
  {
1180
- // Prefix-only vendors. Each prefix below is documented, globally unique and
1181
- // cannot collide with an ordinary identifier, which is what makes a bare
1182
- // prefix rule cheap and safe: `glpat-` (GitLab), `hvs.`/`s.` (Vault service
1183
- // and batch tokens), `whsec_` (Stripe webhook secret), `dckr_pat_` (Docker
1184
- // Hub), `hf_` (HuggingFace), `ya29.` (Google OAuth access token).
1196
+ // Known vendor token shapes: prefix-unique tokens, plus the few fixed layouts whose format is
1197
+ // documented and cannot collide with an ordinary identifier.
1198
+ //
1199
+ // Each prefix below is globally unique, which is what makes a bare prefix rule cheap and
1200
+ // safe: `glpat-` (GitLab), `hvs.`/`s.` (Vault service and batch tokens), `whsec_`
1201
+ // (Stripe webhook secret), `dckr_pat_` (Docker Hub), `hf_` (HuggingFace), `ya29.`
1202
+ // (Google OAuth access token), `shpat_`/`shpca_`/`shppa_`/`shpss_` (Shopify admin and
1203
+ // storefront tokens).
1204
+ //
1205
+ // The fixed shapes have no prefix to anchor on and were each emitted in clear:
1206
+ // - Telegram bot token: `<8-10 digit bot id>:<35-character secret>`.
1207
+ // - Discord bot token: `<base64 user id>.<6-8 char hmac>.<25-45 char signature>`; demanding
1208
+ // all three segments keeps ordinary dotted identifiers out.
1209
+ // - Azure DevOps personal access token: exactly 52 alphanumerics that always mix case and
1210
+ // digits, so a hash, a UUID or a plain identifier — all single-case or a different length —
1211
+ // does not match.
1212
+ //
1213
+ // The rule name still says "prefix" because that is how the catalogue began; it is the
1214
+ // vendor-token rule, and growing a new named rule per vendor would make the documented
1215
+ // pattern count drift on every release.
1185
1216
  rule: "known-vendor-token-prefix",
1186
- pattern: /\b(?:glpat-[A-Za-z0-9_-]{20,64}|glrt-[A-Za-z0-9_-]{20,64}|hvs\.[A-Za-z0-9_-]{20,128}|hvb\.[A-Za-z0-9_-]{20,128}|s\.[A-Za-z0-9]{20,64}|whsec_[A-Za-z0-9]{20,64}|dckr_pat_[A-Za-z0-9_-]{20,64}|hf_[A-Za-z0-9]{30,64}|ya29\.[A-Za-z0-9_-]{20,128}|sk_test_[A-Za-z0-9]{16,64}|1\/\/0[A-Za-z0-9_-]{20,64})/
1217
+ pattern: /\b(?:glpat-[A-Za-z0-9_-]{20,64}|glrt-[A-Za-z0-9_-]{20,64}|hvs\.[A-Za-z0-9_-]{20,128}|hvb\.[A-Za-z0-9_-]{20,128}|s\.[A-Za-z0-9]{20,64}|whsec_[A-Za-z0-9]{20,64}|dckr_pat_[A-Za-z0-9_-]{20,64}|hf_[A-Za-z0-9]{30,64}|ya29\.[A-Za-z0-9_-]{20,128}|sk_test_[A-Za-z0-9]{16,64}|1\/\/0[A-Za-z0-9_-]{20,64}|shpat_[A-Za-z0-9]{20,64}|shpca_[A-Za-z0-9]{20,64}|shppa_[A-Za-z0-9]{20,64}|shpss_[A-Za-z0-9]{20,64}|[0-9]{8,10}:[A-Za-z0-9_-]{35}|[A-Za-z0-9]{20,30}\.[A-Za-z0-9_-]{5,8}\.[A-Za-z0-9_-]{25,45}|(?=[A-Za-z0-9]{0,51}[a-z])(?=[A-Za-z0-9]{0,51}[A-Z])(?=[A-Za-z0-9]{0,51}[0-9])[A-Za-z0-9]{52})(?![A-Za-z0-9])/
1187
1218
  },
1188
1219
  {
1189
1220
  rule: "slack-webhook-url",
@@ -1238,39 +1269,52 @@ var DEFAULT_SECRET_PATTERNS = [
1238
1269
  // (including one invented tomorrow) is covered, provided the `//` is followed
1239
1270
  // immediately by the userinfo: `// see the docs` and a bare reminder comment
1240
1271
  // never match, because a space or the comment wording breaks the shape.
1272
+ //
1273
+ // Three shapes joined it, all the same fact — a URL carries the credential in plain sight —
1274
+ // and each cost a leak while it was elsewhere:
1275
+ // - The user part may be **empty**: Redis, SMTP, AMQP and FTP URLs routinely omit the username
1276
+ // (`redis://:password@host`), and a `{1,128}` prefix made every one of those invisible.
1277
+ // - `curl -u user:password` sends the same userinfo without a scheme; the lookbehind
1278
+ // consumes the flag so the match is the credential alone.
1279
+ // - An Azure SAS link authenticates with `?sig=`; the signature *is* the credential.
1241
1280
  rule: "uri-credentials",
1242
- pattern: /\/\/[^\s:/@"'`;()<>,]{1,128}:[^\s:/@"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/
1281
+ pattern: /\/\/[^\s:/@"'`;()<>,]{0,128}:[^\s:/@"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}|(?<=(?:^|[\s;|&(])--?u(?:ser)?[ \t=]{1,8})["']?[^\s"']{1,300}:[^\s"']{0,256}["']?|(?<=[?&])sig=[A-Za-z0-9%._=~-]{20,300}(?![A-Za-z0-9%._=~-])/
1243
1282
  },
1244
1283
  {
1245
1284
  // The host tail stops at quotes, `;`, `)`, `<`, `>` and `,`: an unbounded
1246
1285
  // `[^\s/]` used to swallow the closing quote and the statement separator of
1247
1286
  // the string the URL was written in.
1287
+ // The user part may be empty here too: `redis://:password@host` and `amqp://:password@host`
1288
+ // are how those services are configured when the account is the server's default.
1248
1289
  rule: "database-uri-credentials",
1249
- pattern: /(?:mongodb(?:\+srv)?|postgres(?:ql)?|mysql|maria(?:db)?|redis(?:s)?|amqp(?:s)?|clickhouse|mssql|sqlserver|oracle):\/\/[^\s:@/"'`;()<>,]{1,128}:[^\s@/"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/
1290
+ pattern: /(?:mongodb(?:\+srv)?|postgres(?:ql)?|mysql|maria(?:db)?|redis(?:s)?|amqp(?:s)?|clickhouse|mssql|sqlserver|oracle):\/\/[^\s:@/"'`;()<>,]{0,128}:[^\s@/"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/
1250
1291
  },
1251
1292
  {
1293
+ // An empty user part is valid userinfo (`smtp://:password@host`: the account is the server's
1294
+ // default), and it used to be the one shape every scheme-listed rule refused.
1252
1295
  rule: "basic-auth-url",
1253
- pattern: /(?:https?|ftp|sftp|ssh|git|smtp|smtps|ldap|ldaps):\/\/[^\s:@/"'`;()<>,]{1,128}:[^\s@/"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/i
1296
+ pattern: /(?:https?|ftp|sftp|ssh|git|smtp|smtps|ldap|ldaps):\/\/[^\s:@/"'`;()<>,]{0,128}:[^\s@/"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/i
1254
1297
  },
1255
1298
  {
1256
1299
  // Quoted credentials in any common key spelling. The value may be as short
1257
1300
  // as one character: `password: "hunter2"` is a credential whatever its
1258
1301
  // entropy, and a length floor was exactly how it survived into `parts`.
1259
1302
  //
1260
- // The key is either bare (`dbPassword:`) or wholly quoted (`"dbPassword":`).
1303
+ // The key is bare (`dbPassword:`), wholly quoted (`"password":`), or quoted with a
1304
+ // camelCase prefix (`"dbPassword":`) — the last one is {@link QUOTED_CREDENTIAL_KEY}.
1261
1305
  // There is deliberately no optional quote *before* the separator: that let a
1262
1306
  // previous string's closing quote stand in for the key's, so
1263
1307
  // ``${pass ? " PASS" : " FAIL"}`` had `" FAIL"` masked as if `PASS` were
1264
1308
  // the key name.
1265
1309
  rule: "credential-assignment",
1266
1310
  pattern: new RegExp(
1267
- `(?:["']${STRONG_CREDENTIAL_NAME}["']|${NOT_AFTER_QUOTE}${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_NAMESPACED_IDENTIFIER}(["'\`])${QUOTED_VALUE}\\1`,
1311
+ `(?:${QUOTED_CREDENTIAL_KEY}|${NOT_AFTER_QUOTE}(?<!id[-_])${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_NAMESPACED_IDENTIFIER}(["'\`])${QUOTED_VALUE}\\1`,
1268
1312
  "i"
1269
1313
  ),
1270
1314
  valueGroup: 2
1271
1315
  },
1272
1316
  {
1273
- // `pass`, `id-token` and `credentials` are ambiguous on their own, so they
1317
+ // `pass` and `credentials` are ambiguous on their own, so they
1274
1318
  // are accepted only against a quoted value long enough to be a credential.
1275
1319
  rule: "credential-assignment-weak",
1276
1320
  pattern: new RegExp(
@@ -1292,9 +1336,31 @@ var DEFAULT_SECRET_PATTERNS = [
1292
1336
  // character, so `["awsSecret:", "apiKey:"]` — the list of key names the lookbehind was added
1293
1337
  // for — cannot match here anyway. `redact.ts` still refuses a match whose separator is inside
1294
1338
  // the literal, which is the case that list actually is.
1339
+ //
1340
+ // The name may also be a *quoted* key: YAML allows `"dbPassword": hunter2`, and JSON cannot
1341
+ // spell a key any other way, so the same {@link QUOTED_CREDENTIAL_KEY} fragment is used here.
1342
+ // Without it a quoted key whose value was not quoted emitted the value in clear.
1343
+ //
1344
+ // A colon-form assignment in a data file masks the whole remainder of the value to
1345
+ // end-of-line, whatever punctuation it holds. A strong credential name is the evidence that
1346
+ // the thing after it is a value, and the character classes above cannot cover every symbol a
1347
+ // password may contain — `password: pa&ss` used to stop at the `&`. This branch is a
1348
+ // lookbehind, so the match is the value alone, and `redact.ts` only applies it to a data or
1349
+ // shell file: in source code the same shape is an expression and stays untouched, and an `URL`
1350
+ // query string keeps its `&` separators because they are not a colon form.
1351
+ //
1352
+ // The `KEY=value` twin does the same for the `=` form, which INI, .properties and shell files
1353
+ // use: with a credential key the whole value is masked whatever symbols it contains
1354
+ // (`password=pa&ss`, `token=a<b`, `client_secret=x|y`). The value is bounded by whitespace
1355
+ // (end of line, or the space before a `# comment`), not by a symbol class — `envpass!@#$%^&*()` used
1356
+ // to stop before the parenthesis and leave the tail in clear. The lookbehind matches the value
1357
+ // alone and `redact.ts` decides, from the file and from the key, whether the line is an
1358
+ // assignment (it must be a data/shell file, the key must end in a credential name, and a URL
1359
+ // query parameter or `$VARIABLE` reference is not an assignment).
1295
1360
  rule: "credential-assignment-unquoted",
1296
1361
  pattern: new RegExp(
1297
- `${UNQUOTED_STRONG_NAME}\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_LITERAL_VALUE}${UNQUOTED_LITERAL}`,
1362
+ `(?:${QUOTED_CREDENTIAL_KEY}|${UNQUOTED_STRONG_NAME})\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_LITERAL_VALUE}${UNQUOTED_LITERAL}|(?<=${UNQUOTED_STRONG_NAME}\\s{0,8}=(?!=)\\s{0,8})(?![\\s#$"'\`])[^\\s]{1,512}|(?<=${UNQUOTED_STRONG_NAME}\\s{0,8}:[ ]{1,8})(?![ ]*["'\`])(?![ ]*[|>])${NOT_A_LITERAL_VALUE}[^\r
1363
+ #]{1,300}`,
1298
1364
  "i"
1299
1365
  ),
1300
1366
  valueGroup: 1
@@ -1317,8 +1383,14 @@ var DEFAULT_SECRET_PATTERNS = [
1317
1383
  // needs no `valueGroup`. A lone `Bearer`/`Basic`, and a word after it that
1318
1384
  // cannot be a credential (`Bearer authentication`), stay readable: the value
1319
1385
  // must contain a digit, be at least 32 chars, or carry base64 `=` padding.
1386
+ //
1387
+ // A fourth shape was leaking: `Basic dXNlcjpwYXNz` is the base64 of `user:pass` — 12
1388
+ // characters, no digit, no padding — and the three tests above all said "not a
1389
+ // credential", so it reached the parts in clear. Mixed case is the discriminator: a base64
1390
+ // rendering of textual userinfo mixes cases, while the prose the earlier rules were
1391
+ // protecting (`Bearer authentication`) is a lowercase word.
1320
1392
  rule: "authorization-header",
1321
- pattern: /(?<=(?:Bearer|Basic)\s{1,8})(?:[A-Za-z0-9_.+/-]{0,31}[0-9][A-Za-z0-9_.+/-]{0,1024}|[A-Za-z0-9_.+/-]{32,1024}|[A-Za-z0-9_.+/-]{8,1024}={1,2})(?![A-Za-z0-9_.+/=-])/
1393
+ pattern: /(?<=(?:Bearer|Basic)\s{1,8})(?:[A-Za-z0-9_.+/-]{0,31}[0-9][A-Za-z0-9_.+/-]{0,1024}|[A-Za-z0-9_.+/-]{32,1024}|[A-Za-z0-9_.+/-]{8,1024}={1,2}|(?=[A-Za-z0-9_.+/-]{0,1023}[A-Z])(?=[A-Za-z0-9_.+/-]{0,1023}[a-z])[A-Za-z0-9_.+/-]{12,1024})(?![A-Za-z0-9_.+/=-])/
1322
1394
  },
1323
1395
  {
1324
1396
  // Broader names than before (`apiKey`, `clientSecret`, `privateKey` were
@@ -1530,6 +1602,32 @@ function scanAndRedactSecrets(content, rules, filePath) {
1530
1602
  continue;
1531
1603
  }
1532
1604
  if (group && isTemplateInterpolation(line, group[0], group[1])) continue;
1605
+ if (group && isUnquotedValue(line, group[0]) && TRUNCATING_VALUE_CHARS.test(line[group[1]] ?? "")) {
1606
+ continue;
1607
+ }
1608
+ if (valueGroup !== void 0 && group === void 0) {
1609
+ if (!isAssignmentFile(filePath)) continue;
1610
+ const assignment = assignmentAround(line, match.index);
1611
+ if (assignment.form === "=" && (assignment.reference || assignment.key === null || !CREDENTIAL_KEY_TAIL.test(assignment.key))) {
1612
+ continue;
1613
+ }
1614
+ }
1615
+ if (group && isUnquotedValue(line, group[0]) && OPENER_LED_VALUE.test(line.slice(group[0], group[1])) && !isAssignmentFile(filePath)) {
1616
+ continue;
1617
+ }
1618
+ if (group && isUnquotedValue(line, group[0])) {
1619
+ const assignment = assignmentAround(line, group[0]);
1620
+ const wholeValue = isAssignmentFile(filePath) && assignment.form !== null && !assignment.reference && !assignment.urlValue;
1621
+ if (wholeValue) {
1622
+ spans.push({
1623
+ start: group[0],
1624
+ end: Math.max(group[1], tokenEnd(line, group[0])),
1625
+ rule
1626
+ });
1627
+ matchedRules.add(rule);
1628
+ continue;
1629
+ }
1630
+ }
1533
1631
  spans.push(
1534
1632
  group ? { start: group[0], end: group[1], rule } : { start: match.index, end: match.index + match[0].length, rule }
1535
1633
  );
@@ -1547,6 +1645,8 @@ function scanAndRedactSecrets(content, rules, filePath) {
1547
1645
  }
1548
1646
  var TOKEN_CHARS_LEFT = /[A-Za-z0-9_+/-]/;
1549
1647
  var TOKEN_CHARS_RIGHT = /[A-Za-z0-9_+/=-]/;
1648
+ var TRUNCATING_VALUE_CHARS = /[<>|\\]/;
1649
+ var OPENER_LED_VALUE = /^[(\\[{]/;
1550
1650
  function expandOverToken(line, start, end) {
1551
1651
  let left = start;
1552
1652
  let right = end;
@@ -1593,6 +1693,31 @@ function isSelfNamingConstant(line, start, end) {
1593
1693
  }
1594
1694
  return line.endsWith(value, index);
1595
1695
  }
1696
+ function assignmentAround(line, valueStart) {
1697
+ let index = valueStart;
1698
+ while (index > 0 && (line[index - 1] === " " || line[index - 1] === " ")) index -= 1;
1699
+ const separator = index > 0 ? line[index - 1] : "";
1700
+ if (separator !== ":" && separator !== "=") {
1701
+ return { form: null, key: null, reference: false, rhsStart: -1, urlValue: false };
1702
+ }
1703
+ const separatorIndex = index - 1;
1704
+ index = separatorIndex;
1705
+ while (index > 0 && (line[index - 1] === " " || line[index - 1] === " ")) index -= 1;
1706
+ const keyEnd = index;
1707
+ while (index > 0 && /[A-Za-z0-9_$.-]/.test(line[index - 1])) index -= 1;
1708
+ const key = line.slice(index, keyEnd).replace(/^-+/, "");
1709
+ const before = index > 0 ? line[index - 1] : "";
1710
+ const reference = before === "?" || before === "&" || before === "$" || before === '"' || before === "'" || before === "`";
1711
+ let rhsStart = separatorIndex + 1;
1712
+ while (rhsStart < line.length && (line[rhsStart] === " " || line[rhsStart] === " ")) rhsStart += 1;
1713
+ const urlValue = /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(line.slice(rhsStart, tokenEnd(line, rhsStart)));
1714
+ return { form: separator === ":" ? ":" : "=", key, reference, rhsStart, urlValue };
1715
+ }
1716
+ function tokenEnd(line, start) {
1717
+ let end = start;
1718
+ while (end < line.length && !/\s/.test(line[end])) end += 1;
1719
+ return end;
1720
+ }
1596
1721
  function isUnquotedValue(line, start) {
1597
1722
  const before = start > 0 ? line[start - 1] : "";
1598
1723
  return before !== '"' && before !== "'" && before !== "`";
@@ -4996,16 +5121,14 @@ function emptyDrift() {
4996
5121
  function sha256Hex(buffer) {
4997
5122
  return crypto3__namespace.createHash("sha256").update(buffer).digest("hex");
4998
5123
  }
4999
- var VERIFY_SNIFF_MAX_BYTES = 8 * 1024 * 1024;
5000
5124
  function wouldNowBeIncluded(cwd, relativePath) {
5001
5125
  const absolutePath = path16__namespace.join(cwd, relativePath);
5002
5126
  try {
5003
5127
  const stats = fs14__namespace.statSync(absolutePath);
5004
5128
  if (!stats.isFile()) return false;
5005
- if (stats.size <= VERIFY_SNIFF_MAX_BYTES) {
5006
- return !decodeText(fs14__namespace.readFileSync(absolutePath)).binary;
5007
- }
5008
- return !isBinaryFile(absolutePath);
5129
+ if (isBinaryExtension(absolutePath)) return false;
5130
+ if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) return false;
5131
+ return !decodeText(fs14__namespace.readFileSync(absolutePath)).binary;
5009
5132
  } catch {
5010
5133
  return false;
5011
5134
  }
@@ -5678,7 +5801,7 @@ function describePayloadDiff(before, after, sourceFilesIdentical) {
5678
5801
  }
5679
5802
  if (fingerprintDiffers && (sourceFilesIdentical || configurationDiffers)) {
5680
5803
  reasons.push(
5681
- `content fingerprint ${shortDigest(before.fingerprint)} \u2192 ${shortDigest(after.fingerprint)}` + (sourceFilesIdentical ? " (same source files, packed differently)" : "")
5804
+ `content fingerprint ${shortDigest(before.fingerprint)} \u2192 ${shortDigest(after.fingerprint)}` + (sourceFilesIdentical ? " (same source files, packed or configured differently)" : "")
5682
5805
  );
5683
5806
  }
5684
5807
  if (partsDiffer) {
@@ -6111,6 +6234,12 @@ function explainPath(config, target) {
6111
6234
  return result;
6112
6235
  }
6113
6236
  }
6237
+ if (isBinaryExtension(absolute)) {
6238
+ result.included = false;
6239
+ result.reason = "binary";
6240
+ result.detail = "binary extension; generate skips it without reading and records `binary` in manifest.skipped[]";
6241
+ return result;
6242
+ }
6114
6243
  let sizeOnDisk = null;
6115
6244
  try {
6116
6245
  sizeOnDisk = fs14__namespace.statSync(absolute).size;
@@ -6123,13 +6252,6 @@ function explainPath(config, target) {
6123
6252
  result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
6124
6253
  return result;
6125
6254
  }
6126
- result.layer = classifyLayer(relative12, config.layers);
6127
- result.kind = classifyKind(relative12, config.kinds);
6128
- result.language = detectLanguage(relative12);
6129
- const layerRule = findRuleMatch(config.layers, relative12);
6130
- if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
6131
- const kindRule = findRuleMatch(config.kinds, relative12);
6132
- if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
6133
6255
  if (fs14__namespace.existsSync(absolute) && fs14__namespace.statSync(absolute).isFile()) {
6134
6256
  const buffer = fs14__namespace.readFileSync(absolute);
6135
6257
  const decoded = decodeText(buffer);
@@ -6147,6 +6269,13 @@ function explainPath(config, target) {
6147
6269
  result.secretCount = findings.length;
6148
6270
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
6149
6271
  }
6272
+ result.layer = classifyLayer(relative12, config.layers);
6273
+ result.kind = classifyKind(relative12, config.kinds);
6274
+ result.language = detectLanguage(relative12);
6275
+ const layerRule = findRuleMatch(config.layers, relative12);
6276
+ if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
6277
+ const kindRule = findRuleMatch(config.kinds, relative12);
6278
+ if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
6150
6279
  const manifest = readManifest2(config);
6151
6280
  const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative12) : void 0;
6152
6281
  result.part = entry?.part ?? null;
@@ -6396,7 +6525,7 @@ function gitignorePath(cwd, filePath) {
6396
6525
 
6397
6526
  // src/version.ts
6398
6527
  var GENERATOR_NAME = "codebase-snapshot";
6399
- var GENERATOR_VERSION = "0.9.14";
6528
+ var GENERATOR_VERSION = "0.9.16";
6400
6529
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
6401
6530
  function isOurGeneratorName(name) {
6402
6531
  if (typeof name !== "string") return false;
@@ -6483,7 +6612,8 @@ function renderConfig(answers) {
6483
6612
  // matched value is never included \u2014 only the path, the line and the rule.
6484
6613
  sarif: ${answers.sarif},
6485
6614
  // Snapshot only the files that differ from a git ref (for example "main"),
6486
- // plus untracked ones. null and false both mean "snapshot everything".
6615
+ // plus untracked ones. null means "snapshot everything"; any other value must
6616
+ // be a git ref string, and anything else is a configuration error.
6487
6617
  changedSince: null,
6488
6618
  // Snapshot only what is staged in the index: the pre-commit counterpart.
6489
6619
  staged: false,
@@ -7849,7 +7979,7 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
7849
7979
  bucket.budgetBytes
7850
7980
  );
7851
7981
  const sectionBudget = budget - HEADER_RESERVE_BYTES;
7852
- const prepared = bucket.files.map((file) => prepareSection(file, sectionBudget));
7982
+ const prepared = bucket.files.map((file) => prepareSection(file, sectionBudget, budget));
7853
7983
  for (const sections of greedyGroups(prepared, budget)) groups.push({ sections, budget });
7854
7984
  }
7855
7985
  if (groups.length === 0) return [];
@@ -7957,7 +8087,7 @@ var displayPath = (value) => capValue(escapeControls(value), DISPLAY_PATH_MAX);
7957
8087
  function topEntries(counts, limit) {
7958
8088
  return Object.entries(counts).sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).slice(0, limit).map(([key, value]) => `${capMetadata(key)} (${value})`).join(", ");
7959
8089
  }
7960
- function prepareSection(file, sectionBudget) {
8090
+ function prepareSection(file, sectionBudget, partBudget) {
7961
8091
  let text2 = renderFileSection(file);
7962
8092
  let byteSize = Buffer.byteLength(text2, "utf8");
7963
8093
  if (byteSize <= sectionBudget) return { file, text: text2, byteSize };
@@ -7969,7 +8099,7 @@ function prepareSection(file, sectionBudget) {
7969
8099
  const truncated = truncateWithBudgetMarker(
7970
8100
  content,
7971
8101
  allowed,
7972
- sectionBudget,
8102
+ partBudget,
7973
8103
  file.originalLines
7974
8104
  );
7975
8105
  if (!truncated.isTruncated) return;
@@ -9138,6 +9268,7 @@ function isProcessAlive(pid) {
9138
9268
  var OWNERSHIP_MARKER = ".codebase-snapshot";
9139
9269
  var SUPPORTED_MARKER_SCHEMAS = /* @__PURE__ */ new Set([SCHEMA_VERSION]);
9140
9270
  var SNAPSHOT_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
9271
+ var SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/;
9141
9272
  function listEntries(dir) {
9142
9273
  const entries = [];
9143
9274
  const walk = (absolute, prefix) => {
@@ -9156,7 +9287,32 @@ function listEntries(dir) {
9156
9287
  walk(dir, "");
9157
9288
  return entries.sort();
9158
9289
  }
9290
+ function markerInventory(dir) {
9291
+ const entries = listEntries(dir);
9292
+ const files = [];
9293
+ for (const entry of entries) {
9294
+ if (entry === OWNERSHIP_MARKER) continue;
9295
+ if (IGNORABLE_ENTRIES.has(entry.slice(entry.lastIndexOf("/") + 1))) continue;
9296
+ const full = path16__namespace.join(dir, ...entry.split("/"));
9297
+ let stats;
9298
+ try {
9299
+ stats = fs14__namespace.lstatSync(full);
9300
+ } catch {
9301
+ continue;
9302
+ }
9303
+ if (!stats.isFile()) continue;
9304
+ let digest;
9305
+ try {
9306
+ digest = sha256Hex2(fs14__namespace.readFileSync(full));
9307
+ } catch {
9308
+ continue;
9309
+ }
9310
+ files.push({ path: entry, bytes: stats.size, sha256: digest });
9311
+ }
9312
+ return { entries, files };
9313
+ }
9159
9314
  function markerPayload(dir, state, id, createdAt) {
9315
+ const { entries, files } = markerInventory(dir);
9160
9316
  const marker2 = {
9161
9317
  generator: GENERATOR_NAME,
9162
9318
  version: GENERATOR_VERSION,
@@ -9165,7 +9321,8 @@ function markerPayload(dir, state, id, createdAt) {
9165
9321
  state,
9166
9322
  id,
9167
9323
  pid: process.pid,
9168
- entries: listEntries(dir)
9324
+ entries,
9325
+ files
9169
9326
  };
9170
9327
  const manifestPath = path16__namespace.join(dir, "manifest.json");
9171
9328
  if (fs14__namespace.existsSync(manifestPath)) {
@@ -9225,6 +9382,33 @@ function readOwnershipMarker(dir) {
9225
9382
  if (candidate.state !== "staging" && candidate.state !== "complete") {
9226
9383
  return { marker: null, problem: "its .codebase-snapshot marker records no run state" };
9227
9384
  }
9385
+ const rawFiles = candidate.files;
9386
+ let files;
9387
+ if (rawFiles !== void 0) {
9388
+ if (!Array.isArray(rawFiles)) {
9389
+ return {
9390
+ marker: null,
9391
+ problem: "its .codebase-snapshot marker's file inventory is not an array"
9392
+ };
9393
+ }
9394
+ files = [];
9395
+ for (const item of rawFiles) {
9396
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
9397
+ return {
9398
+ marker: null,
9399
+ problem: "its .codebase-snapshot marker's file inventory holds an entry that is not an object"
9400
+ };
9401
+ }
9402
+ const record = item;
9403
+ if (typeof record.path !== "string" || typeof record.bytes !== "number" || !Number.isInteger(record.bytes) || record.bytes < 0 || typeof record.sha256 !== "string" || !SHA256_HEX_PATTERN.test(record.sha256)) {
9404
+ return {
9405
+ marker: null,
9406
+ problem: "its .codebase-snapshot marker's file inventory holds an entry this build cannot read"
9407
+ };
9408
+ }
9409
+ files.push({ path: record.path, bytes: record.bytes, sha256: record.sha256 });
9410
+ }
9411
+ }
9228
9412
  return {
9229
9413
  marker: {
9230
9414
  generator: GENERATOR_NAME,
@@ -9235,7 +9419,8 @@ function readOwnershipMarker(dir) {
9235
9419
  id: candidate.id,
9236
9420
  pid: typeof candidate.pid === "number" ? candidate.pid : void 0,
9237
9421
  manifestSha256: typeof candidate.manifestSha256 === "string" ? candidate.manifestSha256 : void 0,
9238
- entries: Array.isArray(candidate.entries) && candidate.entries.every((entry) => typeof entry === "string") ? candidate.entries : void 0
9422
+ entries: Array.isArray(candidate.entries) && candidate.entries.every((entry) => typeof entry === "string") ? candidate.entries : void 0,
9423
+ files
9239
9424
  },
9240
9425
  problem: null
9241
9426
  };
@@ -9250,6 +9435,59 @@ function describeManifestProblem(value) {
9250
9435
  if (!Array.isArray(candidate.files)) return "has no files array";
9251
9436
  return null;
9252
9437
  }
9438
+ function verifyMarkerInventory(dir, entries, files) {
9439
+ const diskEntries = new Set(entries);
9440
+ const recorded = /* @__PURE__ */ new Map();
9441
+ for (const record of files) {
9442
+ if (recorded.has(record.path)) {
9443
+ return `its .codebase-snapshot inventory records ${record.path} twice`;
9444
+ }
9445
+ if (!diskEntries.has(record.path)) {
9446
+ return `its .codebase-snapshot inventory records ${record.path}, which is missing from the directory`;
9447
+ }
9448
+ recorded.set(record.path, record);
9449
+ }
9450
+ for (const entry of entries) {
9451
+ if (entry === OWNERSHIP_MARKER) continue;
9452
+ if (IGNORABLE_ENTRIES.has(entry.slice(entry.lastIndexOf("/") + 1))) continue;
9453
+ const full = path16__namespace.join(dir, ...entry.split("/"));
9454
+ let stats;
9455
+ try {
9456
+ stats = fs14__namespace.lstatSync(full);
9457
+ } catch {
9458
+ return `its .codebase-snapshot inventory lists ${entry}, which cannot be read`;
9459
+ }
9460
+ if (stats.isDirectory()) {
9461
+ if (recorded.has(entry)) {
9462
+ return `its .codebase-snapshot inventory records the directory ${entry} as a file`;
9463
+ }
9464
+ continue;
9465
+ }
9466
+ if (!stats.isFile()) {
9467
+ if (recorded.has(entry)) {
9468
+ return `its .codebase-snapshot inventory records ${entry} as a regular file, but it is not one`;
9469
+ }
9470
+ continue;
9471
+ }
9472
+ const record = recorded.get(entry);
9473
+ if (record === void 0) {
9474
+ return `its .codebase-snapshot inventory does not record the file ${entry}`;
9475
+ }
9476
+ if (record.bytes !== stats.size) {
9477
+ return `its .codebase-snapshot inventory records ${entry} as ${record.bytes} B, but it is ${stats.size} B`;
9478
+ }
9479
+ let digest;
9480
+ try {
9481
+ digest = sha256Hex2(fs14__namespace.readFileSync(full));
9482
+ } catch {
9483
+ return `its .codebase-snapshot inventory cannot verify ${entry}: the file could not be read`;
9484
+ }
9485
+ if (digest !== record.sha256) {
9486
+ return `its .codebase-snapshot inventory's digest for ${entry} does not match the file`;
9487
+ }
9488
+ }
9489
+ return null;
9490
+ }
9253
9491
  function assessSnapshotDirectory(dir) {
9254
9492
  const { marker: marker2, problem } = readOwnershipMarker(dir);
9255
9493
  if (!marker2) return { owned: false, problem, foreignEntries: [], marker: null };
@@ -9262,7 +9500,8 @@ function assessSnapshotDirectory(dir) {
9262
9500
  };
9263
9501
  }
9264
9502
  const manifestPath = path16__namespace.join(dir, "manifest.json");
9265
- if (fs14__namespace.existsSync(manifestPath)) {
9503
+ const hasManifest = fs14__namespace.existsSync(manifestPath);
9504
+ if (hasManifest) {
9266
9505
  let raw;
9267
9506
  try {
9268
9507
  raw = fs14__namespace.readFileSync(manifestPath, "utf8");
@@ -9318,6 +9557,14 @@ function assessSnapshotDirectory(dir) {
9318
9557
  marker: marker2
9319
9558
  };
9320
9559
  }
9560
+ if (marker2.files === void 0 && !hasManifest) {
9561
+ return {
9562
+ owned: false,
9563
+ problem: "its .codebase-snapshot marker records neither per-file digests nor a manifest digest, so it cannot prove this generator wrote the directory",
9564
+ foreignEntries: [],
9565
+ marker: marker2
9566
+ };
9567
+ }
9321
9568
  const recorded = new Set(marker2.entries ?? []);
9322
9569
  if (recorded.size === 0) {
9323
9570
  return {
@@ -9327,13 +9574,18 @@ function assessSnapshotDirectory(dir) {
9327
9574
  marker: marker2
9328
9575
  };
9329
9576
  }
9330
- const foreignEntries = listEntries(dir).filter(
9577
+ const entries = listEntries(dir);
9578
+ const foreignEntries = entries.filter(
9331
9579
  (entry) => !recorded.has(entry) && !IGNORABLE_ENTRIES.has(entry)
9332
9580
  );
9581
+ if (foreignEntries.length > 0) {
9582
+ return { owned: false, problem: null, foreignEntries, marker: marker2 };
9583
+ }
9584
+ const inventoryProblem = marker2.files === void 0 ? null : verifyMarkerInventory(dir, entries, marker2.files);
9333
9585
  return {
9334
- owned: foreignEntries.length === 0,
9335
- problem: null,
9336
- foreignEntries,
9586
+ owned: inventoryProblem === null,
9587
+ problem: inventoryProblem,
9588
+ foreignEntries: [],
9337
9589
  marker: marker2
9338
9590
  };
9339
9591
  }
@@ -9957,9 +10209,12 @@ function generateSnapshot(configInput, options) {
9957
10209
  }
9958
10210
  }
9959
10211
  const fingerprint = sha256Hex2(
9960
- files.map(
9961
- (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
9962
- ).join("\n")
10212
+ [
10213
+ ...files.map(
10214
+ (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
10215
+ ),
10216
+ `settings:${configDigest(config)}`
10217
+ ].join("\n")
9963
10218
  );
9964
10219
  const fullContents = /* @__PURE__ */ new Map();
9965
10220
  if (config.includeMonolith) {
@@ -10154,7 +10409,13 @@ function generateSnapshot(configInput, options) {
10154
10409
  return manifest;
10155
10410
  }
10156
10411
  const lockKeys = Array.from(/* @__PURE__ */ new Set([tmpDir, outDir])).sort();
10157
- const releases = lockKeys.map((key) => acquireRunLock(key));
10412
+ const releases = [];
10413
+ try {
10414
+ for (const key of lockKeys) releases.push(acquireRunLock(key));
10415
+ } catch (error) {
10416
+ for (const release of [...releases].reverse()) release();
10417
+ throw error;
10418
+ }
10158
10419
  const releaseLock = () => {
10159
10420
  for (const release of [...releases].reverse()) release();
10160
10421
  };
@@ -10227,7 +10488,7 @@ function generateSnapshot(configInput, options) {
10227
10488
  }
10228
10489
  writeOwnershipMarker(outDir, markerPayload(outDir, "complete", snapshotId, createdAt));
10229
10490
  };
10230
- shipHookState();
10491
+ if (config.hooks.afterGenerate) shipHookState();
10231
10492
  if (pendingHook) {
10232
10493
  const tracked = pendingHook.then(
10233
10494
  () => {
@@ -10273,7 +10534,17 @@ var pendingHooks = /* @__PURE__ */ new Map();
10273
10534
  var FILE_HEADING = "### FILE: ";
10274
10535
  var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
10275
10536
  var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
10537
+ var META_PREFIX = "- Meta: ";
10538
+ var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
10539
+ var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
10276
10540
  var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
10541
+ var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
10542
+ function readIncludedLines(fields) {
10543
+ const last = fields[fields.length - 1];
10544
+ if (last === void 0) return null;
10545
+ const counts = COMPACT_COUNTS.exec(last.trim());
10546
+ return counts === null ? null : Number(counts[1]);
10547
+ }
10277
10548
  function parsePartSections(partText) {
10278
10549
  const lines = partText.split("\n");
10279
10550
  const sections = [];
@@ -10291,20 +10562,17 @@ function parsePartSections(partText) {
10291
10562
  while (cursor < lines.length && !CONTENT_MARKERS.has(lines[cursor])) {
10292
10563
  const line = lines[cursor];
10293
10564
  if (line.startsWith(FILE_HEADING)) break;
10294
- if (line.startsWith("- Meta: ")) {
10295
- for (const field of line.slice("- Meta: ".length).split("|")) {
10565
+ if (line.startsWith(META_PREFIX)) {
10566
+ const fields = line.slice(META_PREFIX.length).split("|");
10567
+ for (const field of fields) {
10296
10568
  const value = field.trim();
10297
10569
  if (INCLUSION_MODES.has(value)) inclusion = value;
10298
10570
  }
10299
- const counts = /(-?\d+) of (-?\d+) lines|(\d+) lines/.exec(line);
10300
- if (counts) {
10301
- const emitted = counts[1] ?? counts[3];
10302
- includedLines = Number.isFinite(Number(emitted)) ? Number(emitted) : null;
10303
- }
10304
- } else if (line.startsWith("- Inclusion: ")) {
10305
- inclusion = line.slice("- Inclusion: ".length).trim();
10306
- } else if (line.startsWith("- Included Lines: ")) {
10307
- const value = Number(line.slice("- Included Lines: ".length).trim());
10571
+ includedLines = readIncludedLines(fields);
10572
+ } else if (line.startsWith(LEGACY_INCLUSION_PREFIX)) {
10573
+ inclusion = line.slice(LEGACY_INCLUSION_PREFIX.length).trim();
10574
+ } else if (line.startsWith(LEGACY_INCLUDED_LINES_PREFIX)) {
10575
+ const value = Number(line.slice(LEGACY_INCLUDED_LINES_PREFIX.length).trim());
10308
10576
  includedLines = Number.isFinite(value) ? value : null;
10309
10577
  }
10310
10578
  cursor += 1;
@@ -10381,6 +10649,18 @@ function isInside2(parent, child) {
10381
10649
  const foldedChild = foldForComparison(child);
10382
10650
  return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path16__namespace.sep}`);
10383
10651
  }
10652
+ function resolveThroughExistingAncestor(target) {
10653
+ let existing = target;
10654
+ const missing = [];
10655
+ while (!fs14__namespace.existsSync(existing)) {
10656
+ missing.unshift(path16__namespace.basename(existing));
10657
+ const parent = path16__namespace.dirname(existing);
10658
+ if (parent === existing) break;
10659
+ existing = parent;
10660
+ }
10661
+ const resolved = canonicalPath(existing);
10662
+ return missing.length === 0 ? resolved : path16__namespace.join(resolved, ...missing);
10663
+ }
10384
10664
  function resolveRoot(requested, context) {
10385
10665
  if (requested !== void 0 && (typeof requested !== "string" || requested.trim().length === 0)) {
10386
10666
  return { ok: false, message: '"root" must be a non-empty string when provided.' };
@@ -10403,10 +10683,10 @@ function resolveRoot(requested, context) {
10403
10683
  const shown = context.roots.join(", ");
10404
10684
  return {
10405
10685
  ok: false,
10406
- message: `"${wanted}" resolves outside the directories this server may read (${shown}). Restart it with --root <path> to add a repository.`
10686
+ 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.`
10407
10687
  };
10408
10688
  }
10409
- async function openWorkspace(root, overrides = {}) {
10689
+ async function openWorkspace(root, overrides = {}, allowedRoots) {
10410
10690
  const loaded = await loadConfigFileDetailed(root);
10411
10691
  if (loaded.errors.length > 0) {
10412
10692
  return {
@@ -10439,7 +10719,17 @@ async function openWorkspace(root, overrides = {}) {
10439
10719
  if (typeof overrides.outDir !== "string" || overrides.outDir.trim().length === 0) {
10440
10720
  return { ok: false, message: '"outDir" must be a non-empty string.' };
10441
10721
  }
10442
- cliOptions.outDir = overrides.outDir.trim();
10722
+ const requested = overrides.outDir.trim();
10723
+ const permitted = allowedRoots !== void 0 && allowedRoots.length > 0 ? allowedRoots : [root];
10724
+ const resolved = resolveThroughExistingAncestor(path16__namespace.resolve(root, requested));
10725
+ if (!permitted.some((allowed) => isInside2(canonicalPath(allowed), resolved))) {
10726
+ const shown = permitted.map((allowed) => canonicalPath(allowed)).join(", ");
10727
+ return {
10728
+ ok: false,
10729
+ 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.`
10730
+ };
10731
+ }
10732
+ cliOptions.outDir = requested;
10443
10733
  }
10444
10734
  if (overrides.changedSince !== void 0) {
10445
10735
  if (typeof overrides.changedSince !== "string" || overrides.changedSince.trim().length === 0) {
@@ -10542,7 +10832,7 @@ var ROOT_PROPERTY = {
10542
10832
  };
10543
10833
  var OUT_DIR_PROPERTY = {
10544
10834
  type: "string",
10545
- description: "Snapshot directory, relative to the root. Defaults to the project configuration's outDir."
10835
+ description: "Snapshot directory, relative to the root, and it must resolve inside the served repository. Defaults to the project configuration's outDir."
10546
10836
  };
10547
10837
  var outDirOverride = (args) => ({ outDir: args.outDir });
10548
10838
  var SCOPE_PROPERTIES = {
@@ -10661,7 +10951,7 @@ function symbolsOf(entry) {
10661
10951
  async function prepare(args, context, overrides = {}) {
10662
10952
  const rootOutcome = resolveRoot(args.root, context);
10663
10953
  if (!rootOutcome.ok) return { ok: false, outcome: failure(rootOutcome.message) };
10664
- const opened = await openWorkspace(rootOutcome.root, overrides);
10954
+ const opened = await openWorkspace(rootOutcome.root, overrides, context.roots);
10665
10955
  if (!opened.ok) return { ok: false, outcome: failure(opened.message) };
10666
10956
  return { ok: true, workspace: opened.workspace };
10667
10957
  }
@@ -11458,6 +11748,16 @@ var ERROR_CODES = {
11458
11748
  methodNotFound: -32601,
11459
11749
  invalidParams: -32602,
11460
11750
  internalError: -32603,
11751
+ /**
11752
+ * A resource whose complete text is larger than one read may return.
11753
+ *
11754
+ * `-32000` is JSON-RPC's range for implementation-defined server errors, which is what this is:
11755
+ * there is no standard code for "the document is too large", and answering with -32602 would tell
11756
+ * a client its request was malformed when it was not. The message names the size, the limit and
11757
+ * the tool to use instead, because a resource read that cannot return the whole resource must not
11758
+ * invent a partial one.
11759
+ */
11760
+ resourceTooLarge: -32e3,
11461
11761
  unsupportedProtocolVersion: -32022
11462
11762
  };
11463
11763
  var METHOD3 = {
@@ -11566,16 +11866,14 @@ var COMMAND_OPTION_SCOPE = {
11566
11866
  "version"
11567
11867
  ],
11568
11868
  validate: VALIDATE_OPTIONS,
11869
+ // `report` reads `manifest.json` and prints what is there; a generation setting would change
11870
+ // nothing. The seven generation flags used to be listed here and were accepted as silent no-ops
11871
+ // — the exact "flag that parses but changes nothing" this table exists to prevent — while
11872
+ // `--discovery` was already rejected. Both the parser and `describe`'s `appliesTo` read this
11873
+ // list, so removing them narrows the two together.
11569
11874
  report: [
11570
11875
  "cwd",
11571
11876
  "out-dir",
11572
- "max-part-bytes",
11573
- "large-file-bytes",
11574
- "max-monolith-bytes",
11575
- "include-monolith",
11576
- "include-sensitive-files",
11577
- "skip-artifacts",
11578
- "only-artifacts",
11579
11877
  "no-config",
11580
11878
  "no-update-check",
11581
11879
  "format",
@@ -12046,7 +12344,7 @@ function buildAgentContract() {
12046
12344
  type: "string",
12047
12345
  default: "generate",
12048
12346
  appliesTo: optionAppliesTo("mode"),
12049
- 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)."
12347
+ 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)."
12050
12348
  },
12051
12349
  {
12052
12350
  flag: "--cwd",
@@ -12627,6 +12925,186 @@ function negotiateLegacyVersion(requested) {
12627
12925
  }
12628
12926
  return { version: DEFAULT_LEGACY_PROTOCOL_VERSION, matched: false };
12629
12927
  }
12928
+ var MAX_RESOURCE_BYTES = 512 * 1024;
12929
+ var ResourceTooLargeError = class extends Error {
12930
+ constructor(uri, bytes, limit, message) {
12931
+ super(message);
12932
+ this.uri = uri;
12933
+ this.bytes = bytes;
12934
+ this.limit = limit;
12935
+ this.name = "ResourceTooLargeError";
12936
+ }
12937
+ uri;
12938
+ bytes;
12939
+ limit;
12940
+ };
12941
+ function refuseTooLarge(uri, bytes, advice) {
12942
+ throw new ResourceTooLargeError(
12943
+ uri,
12944
+ bytes,
12945
+ MAX_RESOURCE_BYTES,
12946
+ `${uri} is ${formatBytes2(bytes)}, above the ${formatBytes2(MAX_RESOURCE_BYTES)} single-read limit, so it was not returned. ${advice}`
12947
+ );
12948
+ }
12949
+ function ensureSingleRead(uri, text2, advice) {
12950
+ const bytes = Buffer.byteLength(text2, "utf8");
12951
+ if (bytes > MAX_RESOURCE_BYTES) refuseTooLarge(uri, bytes, advice);
12952
+ return text2;
12953
+ }
12954
+ 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.";
12955
+ 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.";
12956
+ 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.";
12957
+ var PART_URI = /^snapshot:\/\/parts\/(\d+)$/;
12958
+ var REPORT_URIS = /* @__PURE__ */ new Map([
12959
+ ["snapshot://reports/audit", { file: "audit.md", title: "Secret audit and risk findings" }],
12960
+ ["snapshot://reports/tree", { file: "project-tree.md", title: "Project tree" }],
12961
+ ["snapshot://reports/navigation", { file: "navigation.md", title: "Navigation index" }]
12962
+ ]);
12963
+ function formatBytes2(bytes) {
12964
+ if (bytes < 1024) return `${bytes} B`;
12965
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;
12966
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
12967
+ }
12968
+ async function workspaceFor(context) {
12969
+ const root = resolveRoot(void 0, context);
12970
+ if (!root.ok) return { error: root.message };
12971
+ const opened = await openWorkspace(root.root);
12972
+ if (!opened.ok) return { error: opened.message };
12973
+ return opened.workspace;
12974
+ }
12975
+ function readFileIfPresent(file) {
12976
+ try {
12977
+ return fs14__namespace.readFileSync(file, "utf8");
12978
+ } catch {
12979
+ return null;
12980
+ }
12981
+ }
12982
+ function buildResourceProvider() {
12983
+ return {
12984
+ async list(context) {
12985
+ const resources = [
12986
+ {
12987
+ uri: "snapshot://manifest",
12988
+ name: "manifest",
12989
+ title: "Snapshot manifest",
12990
+ 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.",
12991
+ mimeType: "application/json"
12992
+ },
12993
+ {
12994
+ uri: "snapshot://contract",
12995
+ name: "contract",
12996
+ title: "Tool contract",
12997
+ description: "The machine-readable description of the codebase-snapshot command line.",
12998
+ mimeType: "application/json"
12999
+ },
13000
+ {
13001
+ uri: "snapshot://skill",
13002
+ name: "skill",
13003
+ title: "Agent skill",
13004
+ description: "Usage guidance for an agent working with this tool.",
13005
+ mimeType: "text/markdown"
13006
+ }
13007
+ ];
13008
+ for (const [uri, report] of REPORT_URIS) {
13009
+ resources.push({
13010
+ uri,
13011
+ name: report.file.replace(/\.md$/, ""),
13012
+ title: report.title,
13013
+ 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.`,
13014
+ mimeType: "text/markdown"
13015
+ });
13016
+ }
13017
+ const workspace = await workspaceFor(context);
13018
+ if ("error" in workspace) return resources;
13019
+ const read = readManifest3(workspace);
13020
+ if (!read.ok) return resources;
13021
+ for (const part of read.manifest.parts) {
13022
+ const readable = part.byteSize <= MAX_RESOURCE_BYTES;
13023
+ resources.push({
13024
+ uri: `snapshot://parts/${part.index}`,
13025
+ name: `part-${String(part.index).padStart(3, "0")}`,
13026
+ title: `Part ${part.index} (${part.fileCount} files, ${formatBytes2(part.byteSize)})`,
13027
+ 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.`),
13028
+ mimeType: "text/markdown"
13029
+ });
13030
+ }
13031
+ return resources;
13032
+ },
13033
+ templates() {
13034
+ return [
13035
+ {
13036
+ uriTemplate: "snapshot://parts/{index}",
13037
+ name: "part",
13038
+ title: "Snapshot part",
13039
+ description: "One budgeted part of the snapshot, by its 1-based index.",
13040
+ mimeType: "text/markdown"
13041
+ }
13042
+ ];
13043
+ },
13044
+ async read(uri, context) {
13045
+ if (uri === "snapshot://contract") {
13046
+ const contract = buildAgentContract();
13047
+ return {
13048
+ uri,
13049
+ mimeType: "application/json",
13050
+ text: ensureSingleRead(
13051
+ uri,
13052
+ JSON.stringify(contract, null, 2),
13053
+ "Run 'codebase-snapshot describe --format json' for the complete contract."
13054
+ )
13055
+ };
13056
+ }
13057
+ if (uri === "snapshot://skill") {
13058
+ return {
13059
+ uri,
13060
+ mimeType: "text/markdown",
13061
+ text: ensureSingleRead(
13062
+ uri,
13063
+ renderSkill(),
13064
+ "Print it with 'codebase-snapshot skill'."
13065
+ )
13066
+ };
13067
+ }
13068
+ const workspace = await workspaceFor(context);
13069
+ if ("error" in workspace) return null;
13070
+ const report = REPORT_URIS.get(uri);
13071
+ if (report) {
13072
+ const text2 = readFileIfPresent(
13073
+ path16__namespace.resolve(workspace.root, workspace.config.outDir, "reports", report.file)
13074
+ );
13075
+ if (text2 === null) return null;
13076
+ return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, REPORT_ADVICE) };
13077
+ }
13078
+ if (uri === "snapshot://manifest") {
13079
+ const read = readManifest3(workspace);
13080
+ if (!read.ok) return null;
13081
+ const text2 = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
13082
+ return { uri, mimeType: "application/json", text: ensureSingleRead(uri, text2, MANIFEST_ADVICE) };
13083
+ }
13084
+ const partMatch = PART_URI.exec(uri);
13085
+ if (partMatch) {
13086
+ const read = readManifest3(workspace);
13087
+ if (!read.ok) return null;
13088
+ const index = Number(partMatch[1]);
13089
+ const part = read.manifest.parts.find((candidate) => candidate.index === index);
13090
+ if (!part) return null;
13091
+ const partPath = partPathFor(workspace, part.filename);
13092
+ if (partPath === null) return null;
13093
+ let partBytes;
13094
+ try {
13095
+ partBytes = fs14__namespace.statSync(partPath).size;
13096
+ } catch {
13097
+ return null;
13098
+ }
13099
+ if (partBytes > MAX_RESOURCE_BYTES) refuseTooLarge(uri, partBytes, PART_ADVICE);
13100
+ const text2 = readFileIfPresent(partPath);
13101
+ if (text2 === null) return null;
13102
+ return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, PART_ADVICE) };
13103
+ }
13104
+ return null;
13105
+ }
13106
+ };
13107
+ }
12630
13108
 
12631
13109
  // src/mcp/schema.ts
12632
13110
  function validateArguments(schema, value) {
@@ -12854,7 +13332,22 @@ function createMcpServer(options) {
12854
13332
  if (typeof uri !== "string") {
12855
13333
  return errorResponse(id, ERROR_CODES.invalidParams, 'resources/read requires a "uri" string.');
12856
13334
  }
12857
- const contents = await options.resources.read(uri, options.context);
13335
+ let contents;
13336
+ try {
13337
+ contents = await options.resources.read(uri, options.context);
13338
+ } catch (error) {
13339
+ if (error instanceof ResourceTooLargeError) {
13340
+ options.context.log(
13341
+ `mcp: refused ${error.uri} (${error.bytes} bytes, limit ${error.limit}); returning it would truncate it`
13342
+ );
13343
+ return errorResponse(id, ERROR_CODES.resourceTooLarge, error.message, {
13344
+ uri: error.uri,
13345
+ bytes: error.bytes,
13346
+ limit: error.limit
13347
+ });
13348
+ }
13349
+ throw error;
13350
+ }
12858
13351
  if (!contents) {
12859
13352
  return errorResponse(id, ERROR_CODES.invalidParams, `Unknown resource "${uri}".`);
12860
13353
  }
@@ -12935,7 +13428,11 @@ function createMcpServer(options) {
12935
13428
  }
12936
13429
  async function dispatch(message) {
12937
13430
  if (!isJsonObject(message)) {
12938
- return errorResponse(null, ERROR_CODES.parseError, "Message is not a JSON object.");
13431
+ return errorResponse(
13432
+ null,
13433
+ ERROR_CODES.invalidRequest,
13434
+ Array.isArray(message) ? "Batch requests are not supported: send one JSON-RPC message per line." : "Message is not a JSON object."
13435
+ );
12939
13436
  }
12940
13437
  const isRequest = Object.prototype.hasOwnProperty.call(message, "id");
12941
13438
  const method = message.method;
@@ -12987,146 +13484,6 @@ function createMcpServer(options) {
12987
13484
  }
12988
13485
  };
12989
13486
  }
12990
- var MAX_RESOURCE_BYTES = 512 * 1024;
12991
- var PART_URI = /^snapshot:\/\/parts\/(\d+)$/;
12992
- var REPORT_URIS = /* @__PURE__ */ new Map([
12993
- ["snapshot://reports/audit", { file: "audit.md", title: "Secret audit and risk findings" }],
12994
- ["snapshot://reports/tree", { file: "project-tree.md", title: "Project tree" }],
12995
- ["snapshot://reports/navigation", { file: "navigation.md", title: "Navigation index" }]
12996
- ]);
12997
- function formatBytes2(bytes) {
12998
- if (bytes < 1024) return `${bytes} B`;
12999
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;
13000
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
13001
- }
13002
- function truncationMarker(originalBytes) {
13003
- return `
13004
-
13005
- [truncated: ${formatBytes2(originalBytes)} total. Use the snapshot_read tool for a line window.]
13006
- `;
13007
- }
13008
- function capUtf8(text2, limit) {
13009
- const size2 = Buffer.byteLength(text2, "utf8");
13010
- if (size2 <= limit) return { text: text2, truncated: false };
13011
- const cut = Buffer.from(text2, "utf8").subarray(0, limit).toString("utf8").replace(/\uFFFD+$/, "");
13012
- return { text: `${cut}${truncationMarker(size2)}`, truncated: true };
13013
- }
13014
- async function workspaceFor(context) {
13015
- const root = resolveRoot(void 0, context);
13016
- if (!root.ok) return { error: root.message };
13017
- const opened = await openWorkspace(root.root);
13018
- if (!opened.ok) return { error: opened.message };
13019
- return opened.workspace;
13020
- }
13021
- function readFileIfPresent(file) {
13022
- try {
13023
- return fs14__namespace.readFileSync(file, "utf8");
13024
- } catch {
13025
- return null;
13026
- }
13027
- }
13028
- function buildResourceProvider() {
13029
- return {
13030
- async list(context) {
13031
- const resources = [
13032
- {
13033
- uri: "snapshot://manifest",
13034
- name: "manifest",
13035
- title: "Snapshot manifest",
13036
- description: "Every file in the snapshot with its layer, kind, language, part and hash, plus the reason each excluded file was excluded.",
13037
- mimeType: "application/json"
13038
- },
13039
- {
13040
- uri: "snapshot://contract",
13041
- name: "contract",
13042
- title: "Tool contract",
13043
- description: "The machine-readable description of the codebase-snapshot command line.",
13044
- mimeType: "application/json"
13045
- },
13046
- {
13047
- uri: "snapshot://skill",
13048
- name: "skill",
13049
- title: "Agent skill",
13050
- description: "Usage guidance for an agent working with this tool.",
13051
- mimeType: "text/markdown"
13052
- }
13053
- ];
13054
- for (const [uri, report] of REPORT_URIS) {
13055
- resources.push({
13056
- uri,
13057
- name: report.file.replace(/\.md$/, ""),
13058
- title: report.title,
13059
- description: `${report.title} from the most recent snapshot.`,
13060
- mimeType: "text/markdown"
13061
- });
13062
- }
13063
- const workspace = await workspaceFor(context);
13064
- if ("error" in workspace) return resources;
13065
- const read = readManifest3(workspace);
13066
- if (!read.ok) return resources;
13067
- for (const part of read.manifest.parts) {
13068
- resources.push({
13069
- uri: `snapshot://parts/${part.index}`,
13070
- name: `part-${String(part.index).padStart(3, "0")}`,
13071
- title: `Part ${part.index} (${part.fileCount} files, ${formatBytes2(part.byteSize)})`,
13072
- description: `Part ${part.index} of ${read.manifest.parts.length}: ${part.fileCount} file(s), ${part.lines} line(s), ${formatBytes2(part.byteSize)}.`,
13073
- mimeType: "text/markdown"
13074
- });
13075
- }
13076
- return resources;
13077
- },
13078
- templates() {
13079
- return [
13080
- {
13081
- uriTemplate: "snapshot://parts/{index}",
13082
- name: "part",
13083
- title: "Snapshot part",
13084
- description: "One budgeted part of the snapshot, by its 1-based index.",
13085
- mimeType: "text/markdown"
13086
- }
13087
- ];
13088
- },
13089
- async read(uri, context) {
13090
- if (uri === "snapshot://contract") {
13091
- const contract = buildAgentContract();
13092
- return { uri, mimeType: "application/json", text: JSON.stringify(contract, null, 2) };
13093
- }
13094
- if (uri === "snapshot://skill") {
13095
- return { uri, mimeType: "text/markdown", text: renderSkill() };
13096
- }
13097
- const workspace = await workspaceFor(context);
13098
- if ("error" in workspace) return null;
13099
- const report = REPORT_URIS.get(uri);
13100
- if (report) {
13101
- const text2 = readFileIfPresent(
13102
- path16__namespace.resolve(workspace.root, workspace.config.outDir, "reports", report.file)
13103
- );
13104
- if (text2 === null) return null;
13105
- return { uri, mimeType: "text/markdown", text: capUtf8(text2, MAX_RESOURCE_BYTES).text };
13106
- }
13107
- if (uri === "snapshot://manifest") {
13108
- const read = readManifest3(workspace);
13109
- if (!read.ok) return null;
13110
- const text2 = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
13111
- return { uri, mimeType: "application/json", text: capUtf8(text2, MAX_RESOURCE_BYTES).text };
13112
- }
13113
- const partMatch = PART_URI.exec(uri);
13114
- if (partMatch) {
13115
- const read = readManifest3(workspace);
13116
- if (!read.ok) return null;
13117
- const index = Number(partMatch[1]);
13118
- const part = read.manifest.parts.find((candidate) => candidate.index === index);
13119
- if (!part) return null;
13120
- const partPath = partPathFor(workspace, part.filename);
13121
- if (partPath === null) return null;
13122
- const text2 = readFileIfPresent(partPath);
13123
- if (text2 === null) return null;
13124
- return { uri, mimeType: "text/markdown", text: capUtf8(text2, MAX_RESOURCE_BYTES).text };
13125
- }
13126
- return null;
13127
- }
13128
- };
13129
- }
13130
13487
 
13131
13488
  // src/mcp/instructions.ts
13132
13489
  var SERVER_INSTRUCTIONS = [
@@ -13597,7 +13954,24 @@ function parseCliArgs(argv) {
13597
13954
  let args = [];
13598
13955
  const explicitMode = values.mode ? String(values.mode) : void 0;
13599
13956
  const firstPositional = positionals[0];
13600
- if (firstPositional !== void 0) {
13957
+ const modeCommand = explicitMode === void 0 ? void 0 : COMMAND_ALIASES.get(explicitMode);
13958
+ if (explicitMode !== void 0 && modeCommand === void 0) {
13959
+ throw new UsageError(
13960
+ `Unknown --mode "${explicitMode}". Expected one of: ${Array.from(COMMAND_ALIASES.keys()).join(", ")}.`
13961
+ );
13962
+ }
13963
+ if (modeCommand !== void 0) {
13964
+ command = modeCommand;
13965
+ if (firstPositional !== void 0) {
13966
+ const named = COMMAND_ALIASES.get(firstPositional);
13967
+ if (named !== void 0 && named !== modeCommand) {
13968
+ throw new UsageError(
13969
+ `--mode ${explicitMode} contradicts the command "${firstPositional}". Pass one or the other.`
13970
+ );
13971
+ }
13972
+ args = named !== void 0 ? positionals.slice(1) : positionals;
13973
+ }
13974
+ } else if (firstPositional !== void 0) {
13601
13975
  const resolved = COMMAND_ALIASES.get(firstPositional);
13602
13976
  if (!resolved) {
13603
13977
  throw new UsageError(
@@ -13606,27 +13980,6 @@ function parseCliArgs(argv) {
13606
13980
  }
13607
13981
  command = resolved;
13608
13982
  args = positionals.slice(1);
13609
- } else if (explicitMode !== void 0) {
13610
- const resolved = COMMAND_ALIASES.get(explicitMode);
13611
- if (!resolved) {
13612
- throw new UsageError(
13613
- `Unknown --mode "${explicitMode}". Expected one of: ${Array.from(COMMAND_ALIASES.keys()).join(", ")}.`
13614
- );
13615
- }
13616
- command = resolved;
13617
- }
13618
- if (explicitMode !== void 0) {
13619
- const resolvedMode = COMMAND_ALIASES.get(explicitMode);
13620
- if (!resolvedMode) {
13621
- throw new UsageError(
13622
- `Unknown --mode "${explicitMode}". Expected one of: ${Array.from(COMMAND_ALIASES.keys()).join(", ")}.`
13623
- );
13624
- }
13625
- if (firstPositional !== void 0 && resolvedMode !== command) {
13626
- throw new UsageError(
13627
- `--mode ${explicitMode} contradicts the command "${firstPositional}". Pass one or the other.`
13628
- );
13629
- }
13630
13983
  }
13631
13984
  const expectedArgs = COMMAND_ARITY[command];
13632
13985
  if (args.length !== expectedArgs) {
@@ -13919,6 +14272,16 @@ function installDependencies(cwd) {
13919
14272
  }
13920
14273
  return { manager: manager.name, command, ok: true, detail: seconds };
13921
14274
  }
14275
+ async function setupHookOutDir(invocation, init) {
14276
+ if (!init.reused || invocation.outDir !== void 0) return init.outDir;
14277
+ const loaded = await loadConfigFileDetailed(invocation.cwd);
14278
+ if (loaded.errors.length > 0) {
14279
+ throw new Error(
14280
+ `The config file could not be read: ${loaded.errors.join("; ")}. Fix it, or delete it to use the defaults.`
14281
+ );
14282
+ }
14283
+ return resolveConfig(loaded.config, {}, invocation.cwd).outDir;
14284
+ }
13922
14285
  async function captureStdout(fn) {
13923
14286
  const { value, text: text2 } = await runWithStdoutCapture(fn);
13924
14287
  return { code: value, text: text2 };
@@ -13952,7 +14315,13 @@ async function runSetupCommand(invocation, options = {}) {
13952
14315
  reuseConfig: true,
13953
14316
  dryRun: invocation.dryRun
13954
14317
  });
13955
- const hook = invocation.installHook === true ? installPreCommitHook(invocation.cwd, init.outDir) : null;
14318
+ const keptConfigPath = init.reused ? findConfigFile(invocation.cwd) ?? init.configPath : init.configPath;
14319
+ const appliedPreset = init.reused ? null : init.preset;
14320
+ if (init.reused && invocation.preset !== void 0) {
14321
+ init.notes.push(
14322
+ `--preset ${invocation.preset} was not applied: the existing config is kept. Edit its preset setting, or run \`init --force\` to write a new one.`
14323
+ );
14324
+ }
13956
14325
  if (invocation.dryRun) {
13957
14326
  const manager = invocation.noInstall ? null : detectPackageManager(invocation.cwd).name;
13958
14327
  if (invocation.format === "json") {
@@ -13960,9 +14329,9 @@ async function runSetupCommand(invocation, options = {}) {
13960
14329
  `${JSON.stringify(
13961
14330
  {
13962
14331
  dryRun: true,
13963
- configPath: init.configPath,
14332
+ configPath: keptConfigPath,
13964
14333
  configReused: init.reused,
13965
- preset: init.preset,
14334
+ preset: appliedPreset,
13966
14335
  install: manager,
13967
14336
  configText: init.configText
13968
14337
  },
@@ -13975,7 +14344,7 @@ async function runSetupCommand(invocation, options = {}) {
13975
14344
  }
13976
14345
  info("\n\u{1F9EA} Dry run \u2014 setup would:");
13977
14346
  info(
13978
- ` 1. ${init.reused ? `keep ${path16__namespace.basename(init.configPath)}` : `write ${path16__namespace.basename(init.configPath)} (preset: ${init.preset})`}`
14347
+ ` 1. ${init.reused ? `keep ${path16__namespace.basename(keptConfigPath)}` : `write ${path16__namespace.basename(keptConfigPath)} (preset: ${appliedPreset})`}`
13979
14348
  );
13980
14349
  info(" 2. add the npm scripts, the devDependency and the .gitignore entries");
13981
14350
  if (manager !== null) info(` 3. install with ${manager}`);
@@ -13984,12 +14353,13 @@ async function runSetupCommand(invocation, options = {}) {
13984
14353
  info(init.configText);
13985
14354
  return 0;
13986
14355
  }
14356
+ const hook = invocation.installHook === true ? installPreCommitHook(invocation.cwd, await setupHookOutDir(invocation, init)) : null;
13987
14357
  if (invocation.format !== "json") {
13988
14358
  if (!interactive) info(`\u{1F680} Setup for: ${invocation.cwd}`);
13989
14359
  if (init.reused) {
13990
- info(`\u267B Keeping ${path16__namespace.basename(init.configPath)} (${presetSummary(init)})`);
14360
+ info(`\u267B Keeping ${path16__namespace.basename(keptConfigPath)}`);
13991
14361
  } else {
13992
- info(`\u2705 Created ${path16__namespace.basename(init.configPath)} (${presetSummary(init)})`);
14362
+ info(`\u2705 Created ${path16__namespace.basename(keptConfigPath)} (${presetSummary(init)})`);
13993
14363
  }
13994
14364
  if (init.scripts.length > 0) info(` Added npm scripts: ${init.scripts.join(", ")}`);
13995
14365
  if (init.dependency.added && init.dependency.range !== null) {
@@ -13999,6 +14369,9 @@ async function runSetupCommand(invocation, options = {}) {
13999
14369
  info(` Added to .gitignore: ${init.gitignoreEntries.join(", ")}`);
14000
14370
  }
14001
14371
  if (hook) for (const note of hook.notes) info(` ${note}`);
14372
+ if (init.reused && invocation.preset !== void 0) {
14373
+ info(` \u26A0 --preset ${invocation.preset} was not applied: the existing config is kept.`);
14374
+ }
14002
14375
  }
14003
14376
  let install = null;
14004
14377
  if (invocation.noInstall) {
@@ -14016,7 +14389,9 @@ async function runSetupCommand(invocation, options = {}) {
14016
14389
  if (invocation.includeSensitiveFiles === true) generateArgs.push("--include-sensitive-files");
14017
14390
  const budget = invocation.maxPartBytesRaw ?? invocation.maxPartBytes;
14018
14391
  if (budget !== void 0) generateArgs.push("--max-part-bytes", String(budget));
14019
- if ((invocation.skipArtifacts ?? []).length > 0) {
14392
+ if ((invocation.onlyArtifacts ?? []).length > 0) {
14393
+ generateArgs.push("--only-artifacts", (invocation.onlyArtifacts ?? []).join(","));
14394
+ } else if ((invocation.skipArtifacts ?? []).length > 0) {
14020
14395
  generateArgs.push("--skip-artifacts", (invocation.skipArtifacts ?? []).join(","));
14021
14396
  }
14022
14397
  if (invocation.includeMonolith === true) generateArgs.push("--include-monolith");
@@ -14043,9 +14418,9 @@ async function runSetupCommand(invocation, options = {}) {
14043
14418
  parsed = null;
14044
14419
  }
14045
14420
  const setup = {
14046
- configPath: init.configPath,
14421
+ configPath: keptConfigPath,
14047
14422
  configReused: init.reused,
14048
- preset: init.preset,
14423
+ preset: appliedPreset,
14049
14424
  scripts: init.scripts,
14050
14425
  dependency: init.dependency,
14051
14426
  gitignoreEntries: init.gitignoreEntries,
@@ -14178,7 +14553,19 @@ function requestsJsonFormat(argv) {
14178
14553
  }
14179
14554
  return format === "json";
14180
14555
  }
14556
+ var closedStdoutGuarded = false;
14557
+ function guardClosedStdout() {
14558
+ if (closedStdoutGuarded) return;
14559
+ closedStdoutGuarded = true;
14560
+ process.stdout.on("error", (error) => {
14561
+ if (error.code === "EPIPE" || error.code === "ECONNRESET") {
14562
+ process.exit(0);
14563
+ }
14564
+ throw error;
14565
+ });
14566
+ }
14181
14567
  async function main(argv = process.argv.slice(2)) {
14568
+ guardClosedStdout();
14182
14569
  const pending = process.stdout.isTTY === true && shouldCheck(argv, process.env) ? checkForUpdate({ current: GENERATOR_VERSION, cacheFile: cacheFilePath() }) : null;
14183
14570
  const code = await runCommand(argv);
14184
14571
  if (pending) {
@@ -14234,40 +14621,47 @@ ${USAGE}
14234
14621
  const skipConfig = invocation.noConfig || invocation.command === "diff";
14235
14622
  const loaded = skipConfig ? { config: null, warnings: [], errors: [], file: null } : await loadConfigFileDetailed(invocation.cwd);
14236
14623
  if (invocation.noConfig) info("\u2699 --no-config: using built-in defaults, config file ignored");
14237
- for (const warning of loaded.warnings) warn(`\u26A0 Config: ${warning}`);
14238
14624
  if (loaded.errors.length > 0) {
14239
- warn("\u274C The config file could not be read. Fix it, or delete it to use the defaults.");
14240
- return 1;
14625
+ return fail(
14626
+ invocation.format,
14627
+ `The config file could not be read: ${loaded.errors.join("; ")}. Fix it, or delete it to use the defaults.`
14628
+ );
14241
14629
  }
14630
+ for (const warning of loaded.warnings) warn(`\u26A0 Config: ${warning}`);
14242
14631
  if (loaded.file) info(`\u2699 Using config ${path16__namespace.relative(process.cwd(), loaded.file) || loaded.file}`);
14243
- const resolved = resolveConfig(
14244
- loaded.config,
14245
- {
14246
- mode: invocation.command,
14247
- format: invocation.format,
14248
- dryRun: invocation.dryRun,
14249
- cwd: invocation.cwd,
14250
- outDir: invocation.outDir,
14251
- includeMonolith: invocation.includeMonolith,
14252
- includeSensitiveFiles: invocation.includeSensitiveFiles,
14253
- maxPartBytes: invocation.maxPartBytes,
14254
- maxPartTokens: invocation.maxPartTokens,
14255
- largeFileBytes: invocation.largeFileBytes,
14256
- maxMonolithBytes: invocation.maxMonolithBytes,
14257
- skipArtifacts: invocation.skipArtifacts,
14258
- // `--only-artifacts` is forwarded as itself, not only as the derived suppression list:
14259
- // suppression cannot switch an artifact *on*, so a config that had turned one of the
14260
- // requested artifacts off left the run with nothing to write.
14261
- onlyArtifacts: invocation.onlyArtifacts,
14262
- discovery: invocation.discovery,
14263
- changedSince: invocation.changedSince,
14264
- staged: invocation.staged,
14265
- withDependents: invocation.withDependents,
14266
- skeleton: invocation.skeleton,
14267
- sarif: invocation.sarif
14268
- },
14269
- invocation.cwd
14270
- );
14632
+ let resolved;
14633
+ try {
14634
+ resolved = resolveConfig(
14635
+ loaded.config,
14636
+ {
14637
+ mode: invocation.command,
14638
+ format: invocation.format,
14639
+ dryRun: invocation.dryRun,
14640
+ cwd: invocation.cwd,
14641
+ outDir: invocation.outDir,
14642
+ includeMonolith: invocation.includeMonolith,
14643
+ includeSensitiveFiles: invocation.includeSensitiveFiles,
14644
+ maxPartBytes: invocation.maxPartBytes,
14645
+ maxPartTokens: invocation.maxPartTokens,
14646
+ largeFileBytes: invocation.largeFileBytes,
14647
+ maxMonolithBytes: invocation.maxMonolithBytes,
14648
+ skipArtifacts: invocation.skipArtifacts,
14649
+ // `--only-artifacts` is forwarded as itself, not only as the derived suppression list:
14650
+ // suppression cannot switch an artifact *on*, so a config that had turned one of the
14651
+ // requested artifacts off left the run with nothing to write.
14652
+ onlyArtifacts: invocation.onlyArtifacts,
14653
+ discovery: invocation.discovery,
14654
+ changedSince: invocation.changedSince,
14655
+ staged: invocation.staged,
14656
+ withDependents: invocation.withDependents,
14657
+ skeleton: invocation.skeleton,
14658
+ sarif: invocation.sarif
14659
+ },
14660
+ invocation.cwd
14661
+ );
14662
+ } catch (err) {
14663
+ return fail(invocation.format, err.message);
14664
+ }
14271
14665
  if (invocation.command === "validate") {
14272
14666
  const result = validateSnapshot(resolved);
14273
14667
  emit(invocation.format, result, () => renderValidateText(result));