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/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(
@@ -1263,9 +1307,31 @@ var DEFAULT_SECRET_PATTERNS = [
1263
1307
  // character, so `["awsSecret:", "apiKey:"]` — the list of key names the lookbehind was added
1264
1308
  // for — cannot match here anyway. `redact.ts` still refuses a match whose separator is inside
1265
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).
1266
1331
  rule: "credential-assignment-unquoted",
1267
1332
  pattern: new RegExp(
1268
- `${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}`,
1269
1335
  "i"
1270
1336
  ),
1271
1337
  valueGroup: 1
@@ -1288,8 +1354,14 @@ var DEFAULT_SECRET_PATTERNS = [
1288
1354
  // needs no `valueGroup`. A lone `Bearer`/`Basic`, and a word after it that
1289
1355
  // cannot be a credential (`Bearer authentication`), stay readable: the value
1290
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.
1291
1363
  rule: "authorization-header",
1292
- 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_.+/=-])/
1293
1365
  },
1294
1366
  {
1295
1367
  // Broader names than before (`apiKey`, `clientSecret`, `privateKey` were
@@ -1501,6 +1573,32 @@ function scanAndRedactSecrets(content, rules, filePath) {
1501
1573
  continue;
1502
1574
  }
1503
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
+ }
1504
1602
  spans.push(
1505
1603
  group ? { start: group[0], end: group[1], rule } : { start: match.index, end: match.index + match[0].length, rule }
1506
1604
  );
@@ -1518,6 +1616,8 @@ function scanAndRedactSecrets(content, rules, filePath) {
1518
1616
  }
1519
1617
  var TOKEN_CHARS_LEFT = /[A-Za-z0-9_+/-]/;
1520
1618
  var TOKEN_CHARS_RIGHT = /[A-Za-z0-9_+/=-]/;
1619
+ var TRUNCATING_VALUE_CHARS = /[<>|\\]/;
1620
+ var OPENER_LED_VALUE = /^[(\\[{]/;
1521
1621
  function expandOverToken(line, start, end) {
1522
1622
  let left = start;
1523
1623
  let right = end;
@@ -1564,6 +1664,31 @@ function isSelfNamingConstant(line, start, end) {
1564
1664
  }
1565
1665
  return line.endsWith(value, index);
1566
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
+ }
1567
1692
  function isUnquotedValue(line, start) {
1568
1693
  const before = start > 0 ? line[start - 1] : "";
1569
1694
  return before !== '"' && before !== "'" && before !== "`";
@@ -4995,16 +5120,14 @@ function emptyDrift() {
4995
5120
  function sha256Hex(buffer) {
4996
5121
  return crypto.createHash("sha256").update(buffer).digest("hex");
4997
5122
  }
4998
- var VERIFY_SNIFF_MAX_BYTES = 8 * 1024 * 1024;
4999
5123
  function wouldNowBeIncluded(cwd, relativePath) {
5000
5124
  const absolutePath = path6.join(cwd, relativePath);
5001
5125
  try {
5002
5126
  const stats = fs6.statSync(absolutePath);
5003
5127
  if (!stats.isFile()) return false;
5004
- if (stats.size <= VERIFY_SNIFF_MAX_BYTES) {
5005
- return !decodeText(fs6.readFileSync(absolutePath)).binary;
5006
- }
5007
- 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;
5008
5131
  } catch {
5009
5132
  return false;
5010
5133
  }
@@ -5677,7 +5800,7 @@ function describePayloadDiff(before, after, sourceFilesIdentical) {
5677
5800
  }
5678
5801
  if (fingerprintDiffers && (sourceFilesIdentical || configurationDiffers)) {
5679
5802
  reasons.push(
5680
- `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)" : "")
5681
5804
  );
5682
5805
  }
5683
5806
  if (partsDiffer) {
@@ -6117,6 +6240,12 @@ function explainPath(config, target) {
6117
6240
  return result;
6118
6241
  }
6119
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
+ }
6120
6249
  let sizeOnDisk = null;
6121
6250
  try {
6122
6251
  sizeOnDisk = fs8.statSync(absolute).size;
@@ -6129,13 +6258,6 @@ function explainPath(config, target) {
6129
6258
  result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
6130
6259
  return result;
6131
6260
  }
6132
- result.layer = classifyLayer(relative12, config.layers);
6133
- result.kind = classifyKind(relative12, config.kinds);
6134
- result.language = detectLanguage(relative12);
6135
- const layerRule = findRuleMatch(config.layers, relative12);
6136
- if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
6137
- const kindRule = findRuleMatch(config.kinds, relative12);
6138
- if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
6139
6261
  if (fs8.existsSync(absolute) && fs8.statSync(absolute).isFile()) {
6140
6262
  const buffer = fs8.readFileSync(absolute);
6141
6263
  const decoded = decodeText(buffer);
@@ -6153,6 +6275,13 @@ function explainPath(config, target) {
6153
6275
  result.secretCount = findings.length;
6154
6276
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
6155
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);
6156
6285
  const manifest = readManifest2(config);
6157
6286
  const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative12) : void 0;
6158
6287
  result.part = entry?.part ?? null;
@@ -6410,7 +6539,7 @@ function gitignorePath(cwd, filePath) {
6410
6539
 
6411
6540
  // src/version.ts
6412
6541
  var GENERATOR_NAME = "codebase-snapshot";
6413
- var GENERATOR_VERSION = "0.9.14";
6542
+ var GENERATOR_VERSION = "0.9.16";
6414
6543
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
6415
6544
  function isOurGeneratorName(name) {
6416
6545
  if (typeof name !== "string") return false;
@@ -6501,7 +6630,8 @@ function renderConfig(answers) {
6501
6630
  // matched value is never included \u2014 only the path, the line and the rule.
6502
6631
  sarif: ${answers.sarif},
6503
6632
  // Snapshot only the files that differ from a git ref (for example "main"),
6504
- // 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.
6505
6635
  changedSince: null,
6506
6636
  // Snapshot only what is staged in the index: the pre-commit counterpart.
6507
6637
  staged: false,
@@ -7894,7 +8024,7 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
7894
8024
  bucket.budgetBytes
7895
8025
  );
7896
8026
  const sectionBudget = budget - HEADER_RESERVE_BYTES;
7897
- const prepared = bucket.files.map((file) => prepareSection(file, sectionBudget));
8027
+ const prepared = bucket.files.map((file) => prepareSection(file, sectionBudget, budget));
7898
8028
  for (const sections of greedyGroups(prepared, budget)) groups.push({ sections, budget });
7899
8029
  }
7900
8030
  if (groups.length === 0) return [];
@@ -8002,7 +8132,7 @@ var displayPath = (value) => capValue(escapeControls(value), DISPLAY_PATH_MAX);
8002
8132
  function topEntries(counts, limit) {
8003
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(", ");
8004
8134
  }
8005
- function prepareSection(file, sectionBudget) {
8135
+ function prepareSection(file, sectionBudget, partBudget) {
8006
8136
  let text2 = renderFileSection(file);
8007
8137
  let byteSize = Buffer.byteLength(text2, "utf8");
8008
8138
  if (byteSize <= sectionBudget) return { file, text: text2, byteSize };
@@ -8014,7 +8144,7 @@ function prepareSection(file, sectionBudget) {
8014
8144
  const truncated = truncateWithBudgetMarker(
8015
8145
  content,
8016
8146
  allowed,
8017
- sectionBudget,
8147
+ partBudget,
8018
8148
  file.originalLines
8019
8149
  );
8020
8150
  if (!truncated.isTruncated) return;
@@ -9200,6 +9330,7 @@ function isProcessAlive(pid) {
9200
9330
  var OWNERSHIP_MARKER = ".codebase-snapshot";
9201
9331
  var SUPPORTED_MARKER_SCHEMAS = /* @__PURE__ */ new Set([SCHEMA_VERSION]);
9202
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}$/;
9203
9334
  function listEntries(dir) {
9204
9335
  const entries = [];
9205
9336
  const walk = (absolute, prefix) => {
@@ -9218,7 +9349,32 @@ function listEntries(dir) {
9218
9349
  walk(dir, "");
9219
9350
  return entries.sort();
9220
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
+ }
9221
9376
  function markerPayload(dir, state, id, createdAt) {
9377
+ const { entries, files } = markerInventory(dir);
9222
9378
  const marker2 = {
9223
9379
  generator: GENERATOR_NAME,
9224
9380
  version: GENERATOR_VERSION,
@@ -9227,7 +9383,8 @@ function markerPayload(dir, state, id, createdAt) {
9227
9383
  state,
9228
9384
  id,
9229
9385
  pid: process.pid,
9230
- entries: listEntries(dir)
9386
+ entries,
9387
+ files
9231
9388
  };
9232
9389
  const manifestPath = path16.join(dir, "manifest.json");
9233
9390
  if (fs14.existsSync(manifestPath)) {
@@ -9287,6 +9444,33 @@ function readOwnershipMarker(dir) {
9287
9444
  if (candidate.state !== "staging" && candidate.state !== "complete") {
9288
9445
  return { marker: null, problem: "its .codebase-snapshot marker records no run state" };
9289
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
+ }
9290
9474
  return {
9291
9475
  marker: {
9292
9476
  generator: GENERATOR_NAME,
@@ -9297,7 +9481,8 @@ function readOwnershipMarker(dir) {
9297
9481
  id: candidate.id,
9298
9482
  pid: typeof candidate.pid === "number" ? candidate.pid : void 0,
9299
9483
  manifestSha256: typeof candidate.manifestSha256 === "string" ? candidate.manifestSha256 : void 0,
9300
- 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
9301
9486
  },
9302
9487
  problem: null
9303
9488
  };
@@ -9312,6 +9497,59 @@ function describeManifestProblem(value) {
9312
9497
  if (!Array.isArray(candidate.files)) return "has no files array";
9313
9498
  return null;
9314
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
+ }
9315
9553
  function assessSnapshotDirectory(dir) {
9316
9554
  const { marker: marker2, problem } = readOwnershipMarker(dir);
9317
9555
  if (!marker2) return { owned: false, problem, foreignEntries: [], marker: null };
@@ -9324,7 +9562,8 @@ function assessSnapshotDirectory(dir) {
9324
9562
  };
9325
9563
  }
9326
9564
  const manifestPath = path16.join(dir, "manifest.json");
9327
- if (fs14.existsSync(manifestPath)) {
9565
+ const hasManifest = fs14.existsSync(manifestPath);
9566
+ if (hasManifest) {
9328
9567
  let raw;
9329
9568
  try {
9330
9569
  raw = fs14.readFileSync(manifestPath, "utf8");
@@ -9380,6 +9619,14 @@ function assessSnapshotDirectory(dir) {
9380
9619
  marker: marker2
9381
9620
  };
9382
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
+ }
9383
9630
  const recorded = new Set(marker2.entries ?? []);
9384
9631
  if (recorded.size === 0) {
9385
9632
  return {
@@ -9389,13 +9636,18 @@ function assessSnapshotDirectory(dir) {
9389
9636
  marker: marker2
9390
9637
  };
9391
9638
  }
9392
- const foreignEntries = listEntries(dir).filter(
9639
+ const entries = listEntries(dir);
9640
+ const foreignEntries = entries.filter(
9393
9641
  (entry) => !recorded.has(entry) && !IGNORABLE_ENTRIES.has(entry)
9394
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);
9395
9647
  return {
9396
- owned: foreignEntries.length === 0,
9397
- problem: null,
9398
- foreignEntries,
9648
+ owned: inventoryProblem === null,
9649
+ problem: inventoryProblem,
9650
+ foreignEntries: [],
9399
9651
  marker: marker2
9400
9652
  };
9401
9653
  }
@@ -10019,9 +10271,12 @@ function generateSnapshot(configInput, options) {
10019
10271
  }
10020
10272
  }
10021
10273
  const fingerprint = sha256Hex2(
10022
- files.map(
10023
- (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
10024
- ).join("\n")
10274
+ [
10275
+ ...files.map(
10276
+ (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
10277
+ ),
10278
+ `settings:${configDigest(config)}`
10279
+ ].join("\n")
10025
10280
  );
10026
10281
  const fullContents = /* @__PURE__ */ new Map();
10027
10282
  if (config.includeMonolith) {
@@ -10216,7 +10471,13 @@ function generateSnapshot(configInput, options) {
10216
10471
  return manifest;
10217
10472
  }
10218
10473
  const lockKeys = Array.from(/* @__PURE__ */ new Set([tmpDir, outDir])).sort();
10219
- const releases = lockKeys.map((key) => acquireRunLock(key));
10474
+ const releases = [];
10475
+ try {
10476
+ for (const key of lockKeys) releases.push(acquireRunLock(key));
10477
+ } catch (error) {
10478
+ for (const release of [...releases].reverse()) release();
10479
+ throw error;
10480
+ }
10220
10481
  const releaseLock = () => {
10221
10482
  for (const release of [...releases].reverse()) release();
10222
10483
  };
@@ -10289,7 +10550,7 @@ function generateSnapshot(configInput, options) {
10289
10550
  }
10290
10551
  writeOwnershipMarker(outDir, markerPayload(outDir, "complete", snapshotId, createdAt));
10291
10552
  };
10292
- shipHookState();
10553
+ if (config.hooks.afterGenerate) shipHookState();
10293
10554
  if (pendingHook) {
10294
10555
  const tracked = pendingHook.then(
10295
10556
  () => {
@@ -10339,7 +10600,17 @@ import * as path18 from "path";
10339
10600
  var FILE_HEADING = "### FILE: ";
10340
10601
  var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
10341
10602
  var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
10603
+ var META_PREFIX = "- Meta: ";
10604
+ var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
10605
+ var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
10342
10606
  var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
10607
+ var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
10608
+ function readIncludedLines(fields) {
10609
+ const last = fields[fields.length - 1];
10610
+ if (last === void 0) return null;
10611
+ const counts = COMPACT_COUNTS.exec(last.trim());
10612
+ return counts === null ? null : Number(counts[1]);
10613
+ }
10343
10614
  function parsePartSections(partText) {
10344
10615
  const lines = partText.split("\n");
10345
10616
  const sections = [];
@@ -10357,20 +10628,17 @@ function parsePartSections(partText) {
10357
10628
  while (cursor < lines.length && !CONTENT_MARKERS.has(lines[cursor])) {
10358
10629
  const line = lines[cursor];
10359
10630
  if (line.startsWith(FILE_HEADING)) break;
10360
- if (line.startsWith("- Meta: ")) {
10361
- for (const field of line.slice("- Meta: ".length).split("|")) {
10631
+ if (line.startsWith(META_PREFIX)) {
10632
+ const fields = line.slice(META_PREFIX.length).split("|");
10633
+ for (const field of fields) {
10362
10634
  const value = field.trim();
10363
10635
  if (INCLUSION_MODES.has(value)) inclusion = value;
10364
10636
  }
10365
- const counts = /(-?\d+) of (-?\d+) lines|(\d+) lines/.exec(line);
10366
- if (counts) {
10367
- const emitted = counts[1] ?? counts[3];
10368
- includedLines = Number.isFinite(Number(emitted)) ? Number(emitted) : null;
10369
- }
10370
- } else if (line.startsWith("- Inclusion: ")) {
10371
- inclusion = line.slice("- Inclusion: ".length).trim();
10372
- } else if (line.startsWith("- Included Lines: ")) {
10373
- const value = Number(line.slice("- Included Lines: ".length).trim());
10637
+ includedLines = readIncludedLines(fields);
10638
+ } else if (line.startsWith(LEGACY_INCLUSION_PREFIX)) {
10639
+ inclusion = line.slice(LEGACY_INCLUSION_PREFIX.length).trim();
10640
+ } else if (line.startsWith(LEGACY_INCLUDED_LINES_PREFIX)) {
10641
+ const value = Number(line.slice(LEGACY_INCLUDED_LINES_PREFIX.length).trim());
10374
10642
  includedLines = Number.isFinite(value) ? value : null;
10375
10643
  }
10376
10644
  cursor += 1;
@@ -10451,6 +10719,18 @@ function isInside2(parent, child) {
10451
10719
  const foldedChild = foldForComparison(child);
10452
10720
  return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path17.sep}`);
10453
10721
  }
10722
+ function resolveThroughExistingAncestor(target) {
10723
+ let existing = target;
10724
+ const missing = [];
10725
+ while (!fs15.existsSync(existing)) {
10726
+ missing.unshift(path17.basename(existing));
10727
+ const parent = path17.dirname(existing);
10728
+ if (parent === existing) break;
10729
+ existing = parent;
10730
+ }
10731
+ const resolved = canonicalPath(existing);
10732
+ return missing.length === 0 ? resolved : path17.join(resolved, ...missing);
10733
+ }
10454
10734
  function resolveRoot(requested, context) {
10455
10735
  if (requested !== void 0 && (typeof requested !== "string" || requested.trim().length === 0)) {
10456
10736
  return { ok: false, message: '"root" must be a non-empty string when provided.' };
@@ -10473,10 +10753,10 @@ function resolveRoot(requested, context) {
10473
10753
  const shown = context.roots.join(", ");
10474
10754
  return {
10475
10755
  ok: false,
10476
- message: `"${wanted}" resolves outside the directories this server may read (${shown}). Restart it with --root <path> to add a repository.`
10756
+ 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.`
10477
10757
  };
10478
10758
  }
10479
- async function openWorkspace(root, overrides = {}) {
10759
+ async function openWorkspace(root, overrides = {}, allowedRoots) {
10480
10760
  const loaded = await loadConfigFileDetailed(root);
10481
10761
  if (loaded.errors.length > 0) {
10482
10762
  return {
@@ -10509,7 +10789,17 @@ async function openWorkspace(root, overrides = {}) {
10509
10789
  if (typeof overrides.outDir !== "string" || overrides.outDir.trim().length === 0) {
10510
10790
  return { ok: false, message: '"outDir" must be a non-empty string.' };
10511
10791
  }
10512
- cliOptions.outDir = overrides.outDir.trim();
10792
+ const requested = overrides.outDir.trim();
10793
+ const permitted = allowedRoots !== void 0 && allowedRoots.length > 0 ? allowedRoots : [root];
10794
+ const resolved = resolveThroughExistingAncestor(path17.resolve(root, requested));
10795
+ if (!permitted.some((allowed) => isInside2(canonicalPath(allowed), resolved))) {
10796
+ const shown = permitted.map((allowed) => canonicalPath(allowed)).join(", ");
10797
+ return {
10798
+ ok: false,
10799
+ 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.`
10800
+ };
10801
+ }
10802
+ cliOptions.outDir = requested;
10513
10803
  }
10514
10804
  if (overrides.changedSince !== void 0) {
10515
10805
  if (typeof overrides.changedSince !== "string" || overrides.changedSince.trim().length === 0) {
@@ -10612,7 +10902,7 @@ var ROOT_PROPERTY = {
10612
10902
  };
10613
10903
  var OUT_DIR_PROPERTY = {
10614
10904
  type: "string",
10615
- description: "Snapshot directory, relative to the root. Defaults to the project configuration's outDir."
10905
+ description: "Snapshot directory, relative to the root, and it must resolve inside the served repository. Defaults to the project configuration's outDir."
10616
10906
  };
10617
10907
  var outDirOverride = (args) => ({ outDir: args.outDir });
10618
10908
  var SCOPE_PROPERTIES = {
@@ -10731,7 +11021,7 @@ function symbolsOf(entry) {
10731
11021
  async function prepare(args, context, overrides = {}) {
10732
11022
  const rootOutcome = resolveRoot(args.root, context);
10733
11023
  if (!rootOutcome.ok) return { ok: false, outcome: failure(rootOutcome.message) };
10734
- const opened = await openWorkspace(rootOutcome.root, overrides);
11024
+ const opened = await openWorkspace(rootOutcome.root, overrides, context.roots);
10735
11025
  if (!opened.ok) return { ok: false, outcome: failure(opened.message) };
10736
11026
  return { ok: true, workspace: opened.workspace };
10737
11027
  }
@@ -11528,6 +11818,16 @@ var ERROR_CODES = {
11528
11818
  methodNotFound: -32601,
11529
11819
  invalidParams: -32602,
11530
11820
  internalError: -32603,
11821
+ /**
11822
+ * A resource whose complete text is larger than one read may return.
11823
+ *
11824
+ * `-32000` is JSON-RPC's range for implementation-defined server errors, which is what this is:
11825
+ * there is no standard code for "the document is too large", and answering with -32602 would tell
11826
+ * a client its request was malformed when it was not. The message names the size, the limit and
11827
+ * the tool to use instead, because a resource read that cannot return the whole resource must not
11828
+ * invent a partial one.
11829
+ */
11830
+ resourceTooLarge: -32e3,
11531
11831
  unsupportedProtocolVersion: -32022
11532
11832
  };
11533
11833
  var METHOD3 = {
@@ -11640,16 +11940,14 @@ var COMMAND_OPTION_SCOPE = {
11640
11940
  "version"
11641
11941
  ],
11642
11942
  validate: VALIDATE_OPTIONS,
11943
+ // `report` reads `manifest.json` and prints what is there; a generation setting would change
11944
+ // nothing. The seven generation flags used to be listed here and were accepted as silent no-ops
11945
+ // — the exact "flag that parses but changes nothing" this table exists to prevent — while
11946
+ // `--discovery` was already rejected. Both the parser and `describe`'s `appliesTo` read this
11947
+ // list, so removing them narrows the two together.
11643
11948
  report: [
11644
11949
  "cwd",
11645
11950
  "out-dir",
11646
- "max-part-bytes",
11647
- "large-file-bytes",
11648
- "max-monolith-bytes",
11649
- "include-monolith",
11650
- "include-sensitive-files",
11651
- "skip-artifacts",
11652
- "only-artifacts",
11653
11951
  "no-config",
11654
11952
  "no-update-check",
11655
11953
  "format",
@@ -12120,7 +12418,7 @@ function buildAgentContract() {
12120
12418
  type: "string",
12121
12419
  default: "generate",
12122
12420
  appliesTo: optionAppliesTo("mode"),
12123
- 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)."
12421
+ 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)."
12124
12422
  },
12125
12423
  {
12126
12424
  flag: "--cwd",
@@ -12706,6 +13004,190 @@ function negotiateLegacyVersion(requested) {
12706
13004
  return { version: DEFAULT_LEGACY_PROTOCOL_VERSION, matched: false };
12707
13005
  }
12708
13006
 
13007
+ // src/mcp/resources.ts
13008
+ import * as fs18 from "fs";
13009
+ import * as path20 from "path";
13010
+ var MAX_RESOURCE_BYTES = 512 * 1024;
13011
+ var ResourceTooLargeError = class extends Error {
13012
+ constructor(uri, bytes, limit, message) {
13013
+ super(message);
13014
+ this.uri = uri;
13015
+ this.bytes = bytes;
13016
+ this.limit = limit;
13017
+ this.name = "ResourceTooLargeError";
13018
+ }
13019
+ uri;
13020
+ bytes;
13021
+ limit;
13022
+ };
13023
+ function refuseTooLarge(uri, bytes, advice) {
13024
+ throw new ResourceTooLargeError(
13025
+ uri,
13026
+ bytes,
13027
+ MAX_RESOURCE_BYTES,
13028
+ `${uri} is ${formatBytes2(bytes)}, above the ${formatBytes2(MAX_RESOURCE_BYTES)} single-read limit, so it was not returned. ${advice}`
13029
+ );
13030
+ }
13031
+ function ensureSingleRead(uri, text2, advice) {
13032
+ const bytes = Buffer.byteLength(text2, "utf8");
13033
+ if (bytes > MAX_RESOURCE_BYTES) refuseTooLarge(uri, bytes, advice);
13034
+ return text2;
13035
+ }
13036
+ 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.";
13037
+ 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.";
13038
+ 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.";
13039
+ var PART_URI = /^snapshot:\/\/parts\/(\d+)$/;
13040
+ var REPORT_URIS = /* @__PURE__ */ new Map([
13041
+ ["snapshot://reports/audit", { file: "audit.md", title: "Secret audit and risk findings" }],
13042
+ ["snapshot://reports/tree", { file: "project-tree.md", title: "Project tree" }],
13043
+ ["snapshot://reports/navigation", { file: "navigation.md", title: "Navigation index" }]
13044
+ ]);
13045
+ function formatBytes2(bytes) {
13046
+ if (bytes < 1024) return `${bytes} B`;
13047
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;
13048
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
13049
+ }
13050
+ async function workspaceFor(context) {
13051
+ const root = resolveRoot(void 0, context);
13052
+ if (!root.ok) return { error: root.message };
13053
+ const opened = await openWorkspace(root.root);
13054
+ if (!opened.ok) return { error: opened.message };
13055
+ return opened.workspace;
13056
+ }
13057
+ function readFileIfPresent(file) {
13058
+ try {
13059
+ return fs18.readFileSync(file, "utf8");
13060
+ } catch {
13061
+ return null;
13062
+ }
13063
+ }
13064
+ function buildResourceProvider() {
13065
+ return {
13066
+ async list(context) {
13067
+ const resources = [
13068
+ {
13069
+ uri: "snapshot://manifest",
13070
+ name: "manifest",
13071
+ title: "Snapshot manifest",
13072
+ 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.",
13073
+ mimeType: "application/json"
13074
+ },
13075
+ {
13076
+ uri: "snapshot://contract",
13077
+ name: "contract",
13078
+ title: "Tool contract",
13079
+ description: "The machine-readable description of the codebase-snapshot command line.",
13080
+ mimeType: "application/json"
13081
+ },
13082
+ {
13083
+ uri: "snapshot://skill",
13084
+ name: "skill",
13085
+ title: "Agent skill",
13086
+ description: "Usage guidance for an agent working with this tool.",
13087
+ mimeType: "text/markdown"
13088
+ }
13089
+ ];
13090
+ for (const [uri, report] of REPORT_URIS) {
13091
+ resources.push({
13092
+ uri,
13093
+ name: report.file.replace(/\.md$/, ""),
13094
+ title: report.title,
13095
+ 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.`,
13096
+ mimeType: "text/markdown"
13097
+ });
13098
+ }
13099
+ const workspace = await workspaceFor(context);
13100
+ if ("error" in workspace) return resources;
13101
+ const read = readManifest3(workspace);
13102
+ if (!read.ok) return resources;
13103
+ for (const part of read.manifest.parts) {
13104
+ const readable = part.byteSize <= MAX_RESOURCE_BYTES;
13105
+ resources.push({
13106
+ uri: `snapshot://parts/${part.index}`,
13107
+ name: `part-${String(part.index).padStart(3, "0")}`,
13108
+ title: `Part ${part.index} (${part.fileCount} files, ${formatBytes2(part.byteSize)})`,
13109
+ 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.`),
13110
+ mimeType: "text/markdown"
13111
+ });
13112
+ }
13113
+ return resources;
13114
+ },
13115
+ templates() {
13116
+ return [
13117
+ {
13118
+ uriTemplate: "snapshot://parts/{index}",
13119
+ name: "part",
13120
+ title: "Snapshot part",
13121
+ description: "One budgeted part of the snapshot, by its 1-based index.",
13122
+ mimeType: "text/markdown"
13123
+ }
13124
+ ];
13125
+ },
13126
+ async read(uri, context) {
13127
+ if (uri === "snapshot://contract") {
13128
+ const contract = buildAgentContract();
13129
+ return {
13130
+ uri,
13131
+ mimeType: "application/json",
13132
+ text: ensureSingleRead(
13133
+ uri,
13134
+ JSON.stringify(contract, null, 2),
13135
+ "Run 'codebase-snapshot describe --format json' for the complete contract."
13136
+ )
13137
+ };
13138
+ }
13139
+ if (uri === "snapshot://skill") {
13140
+ return {
13141
+ uri,
13142
+ mimeType: "text/markdown",
13143
+ text: ensureSingleRead(
13144
+ uri,
13145
+ renderSkill(),
13146
+ "Print it with 'codebase-snapshot skill'."
13147
+ )
13148
+ };
13149
+ }
13150
+ const workspace = await workspaceFor(context);
13151
+ if ("error" in workspace) return null;
13152
+ const report = REPORT_URIS.get(uri);
13153
+ if (report) {
13154
+ const text2 = readFileIfPresent(
13155
+ path20.resolve(workspace.root, workspace.config.outDir, "reports", report.file)
13156
+ );
13157
+ if (text2 === null) return null;
13158
+ return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, REPORT_ADVICE) };
13159
+ }
13160
+ if (uri === "snapshot://manifest") {
13161
+ const read = readManifest3(workspace);
13162
+ if (!read.ok) return null;
13163
+ const text2 = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
13164
+ return { uri, mimeType: "application/json", text: ensureSingleRead(uri, text2, MANIFEST_ADVICE) };
13165
+ }
13166
+ const partMatch = PART_URI.exec(uri);
13167
+ if (partMatch) {
13168
+ const read = readManifest3(workspace);
13169
+ if (!read.ok) return null;
13170
+ const index = Number(partMatch[1]);
13171
+ const part = read.manifest.parts.find((candidate) => candidate.index === index);
13172
+ if (!part) return null;
13173
+ const partPath = partPathFor(workspace, part.filename);
13174
+ if (partPath === null) return null;
13175
+ let partBytes;
13176
+ try {
13177
+ partBytes = fs18.statSync(partPath).size;
13178
+ } catch {
13179
+ return null;
13180
+ }
13181
+ if (partBytes > MAX_RESOURCE_BYTES) refuseTooLarge(uri, partBytes, PART_ADVICE);
13182
+ const text2 = readFileIfPresent(partPath);
13183
+ if (text2 === null) return null;
13184
+ return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, PART_ADVICE) };
13185
+ }
13186
+ return null;
13187
+ }
13188
+ };
13189
+ }
13190
+
12709
13191
  // src/mcp/schema.ts
12710
13192
  function validateArguments(schema, value) {
12711
13193
  if (value === void 0) value = {};
@@ -12932,7 +13414,22 @@ function createMcpServer(options) {
12932
13414
  if (typeof uri !== "string") {
12933
13415
  return errorResponse(id, ERROR_CODES.invalidParams, 'resources/read requires a "uri" string.');
12934
13416
  }
12935
- const contents = await options.resources.read(uri, options.context);
13417
+ let contents;
13418
+ try {
13419
+ contents = await options.resources.read(uri, options.context);
13420
+ } catch (error) {
13421
+ if (error instanceof ResourceTooLargeError) {
13422
+ options.context.log(
13423
+ `mcp: refused ${error.uri} (${error.bytes} bytes, limit ${error.limit}); returning it would truncate it`
13424
+ );
13425
+ return errorResponse(id, ERROR_CODES.resourceTooLarge, error.message, {
13426
+ uri: error.uri,
13427
+ bytes: error.bytes,
13428
+ limit: error.limit
13429
+ });
13430
+ }
13431
+ throw error;
13432
+ }
12936
13433
  if (!contents) {
12937
13434
  return errorResponse(id, ERROR_CODES.invalidParams, `Unknown resource "${uri}".`);
12938
13435
  }
@@ -13015,7 +13512,11 @@ function createMcpServer(options) {
13015
13512
  }
13016
13513
  async function dispatch(message) {
13017
13514
  if (!isJsonObject(message)) {
13018
- return errorResponse(null, ERROR_CODES.parseError, "Message is not a JSON object.");
13515
+ return errorResponse(
13516
+ null,
13517
+ ERROR_CODES.invalidRequest,
13518
+ Array.isArray(message) ? "Batch requests are not supported: send one JSON-RPC message per line." : "Message is not a JSON object."
13519
+ );
13019
13520
  }
13020
13521
  const isRequest = Object.prototype.hasOwnProperty.call(message, "id");
13021
13522
  const method = message.method;
@@ -13068,150 +13569,6 @@ function createMcpServer(options) {
13068
13569
  };
13069
13570
  }
13070
13571
 
13071
- // src/mcp/resources.ts
13072
- import * as fs18 from "fs";
13073
- import * as path20 from "path";
13074
- var MAX_RESOURCE_BYTES = 512 * 1024;
13075
- var PART_URI = /^snapshot:\/\/parts\/(\d+)$/;
13076
- var REPORT_URIS = /* @__PURE__ */ new Map([
13077
- ["snapshot://reports/audit", { file: "audit.md", title: "Secret audit and risk findings" }],
13078
- ["snapshot://reports/tree", { file: "project-tree.md", title: "Project tree" }],
13079
- ["snapshot://reports/navigation", { file: "navigation.md", title: "Navigation index" }]
13080
- ]);
13081
- function formatBytes2(bytes) {
13082
- if (bytes < 1024) return `${bytes} B`;
13083
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;
13084
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
13085
- }
13086
- function truncationMarker(originalBytes) {
13087
- return `
13088
-
13089
- [truncated: ${formatBytes2(originalBytes)} total. Use the snapshot_read tool for a line window.]
13090
- `;
13091
- }
13092
- function capUtf8(text2, limit) {
13093
- const size2 = Buffer.byteLength(text2, "utf8");
13094
- if (size2 <= limit) return { text: text2, truncated: false };
13095
- const cut = Buffer.from(text2, "utf8").subarray(0, limit).toString("utf8").replace(/\uFFFD+$/, "");
13096
- return { text: `${cut}${truncationMarker(size2)}`, truncated: true };
13097
- }
13098
- async function workspaceFor(context) {
13099
- const root = resolveRoot(void 0, context);
13100
- if (!root.ok) return { error: root.message };
13101
- const opened = await openWorkspace(root.root);
13102
- if (!opened.ok) return { error: opened.message };
13103
- return opened.workspace;
13104
- }
13105
- function readFileIfPresent(file) {
13106
- try {
13107
- return fs18.readFileSync(file, "utf8");
13108
- } catch {
13109
- return null;
13110
- }
13111
- }
13112
- function buildResourceProvider() {
13113
- return {
13114
- async list(context) {
13115
- const resources = [
13116
- {
13117
- uri: "snapshot://manifest",
13118
- name: "manifest",
13119
- title: "Snapshot manifest",
13120
- description: "Every file in the snapshot with its layer, kind, language, part and hash, plus the reason each excluded file was excluded.",
13121
- mimeType: "application/json"
13122
- },
13123
- {
13124
- uri: "snapshot://contract",
13125
- name: "contract",
13126
- title: "Tool contract",
13127
- description: "The machine-readable description of the codebase-snapshot command line.",
13128
- mimeType: "application/json"
13129
- },
13130
- {
13131
- uri: "snapshot://skill",
13132
- name: "skill",
13133
- title: "Agent skill",
13134
- description: "Usage guidance for an agent working with this tool.",
13135
- mimeType: "text/markdown"
13136
- }
13137
- ];
13138
- for (const [uri, report] of REPORT_URIS) {
13139
- resources.push({
13140
- uri,
13141
- name: report.file.replace(/\.md$/, ""),
13142
- title: report.title,
13143
- description: `${report.title} from the most recent snapshot.`,
13144
- mimeType: "text/markdown"
13145
- });
13146
- }
13147
- const workspace = await workspaceFor(context);
13148
- if ("error" in workspace) return resources;
13149
- const read = readManifest3(workspace);
13150
- if (!read.ok) return resources;
13151
- for (const part of read.manifest.parts) {
13152
- resources.push({
13153
- uri: `snapshot://parts/${part.index}`,
13154
- name: `part-${String(part.index).padStart(3, "0")}`,
13155
- title: `Part ${part.index} (${part.fileCount} files, ${formatBytes2(part.byteSize)})`,
13156
- description: `Part ${part.index} of ${read.manifest.parts.length}: ${part.fileCount} file(s), ${part.lines} line(s), ${formatBytes2(part.byteSize)}.`,
13157
- mimeType: "text/markdown"
13158
- });
13159
- }
13160
- return resources;
13161
- },
13162
- templates() {
13163
- return [
13164
- {
13165
- uriTemplate: "snapshot://parts/{index}",
13166
- name: "part",
13167
- title: "Snapshot part",
13168
- description: "One budgeted part of the snapshot, by its 1-based index.",
13169
- mimeType: "text/markdown"
13170
- }
13171
- ];
13172
- },
13173
- async read(uri, context) {
13174
- if (uri === "snapshot://contract") {
13175
- const contract = buildAgentContract();
13176
- return { uri, mimeType: "application/json", text: JSON.stringify(contract, null, 2) };
13177
- }
13178
- if (uri === "snapshot://skill") {
13179
- return { uri, mimeType: "text/markdown", text: renderSkill() };
13180
- }
13181
- const workspace = await workspaceFor(context);
13182
- if ("error" in workspace) return null;
13183
- const report = REPORT_URIS.get(uri);
13184
- if (report) {
13185
- const text2 = readFileIfPresent(
13186
- path20.resolve(workspace.root, workspace.config.outDir, "reports", report.file)
13187
- );
13188
- if (text2 === null) return null;
13189
- return { uri, mimeType: "text/markdown", text: capUtf8(text2, MAX_RESOURCE_BYTES).text };
13190
- }
13191
- if (uri === "snapshot://manifest") {
13192
- const read = readManifest3(workspace);
13193
- if (!read.ok) return null;
13194
- const text2 = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
13195
- return { uri, mimeType: "application/json", text: capUtf8(text2, MAX_RESOURCE_BYTES).text };
13196
- }
13197
- const partMatch = PART_URI.exec(uri);
13198
- if (partMatch) {
13199
- const read = readManifest3(workspace);
13200
- if (!read.ok) return null;
13201
- const index = Number(partMatch[1]);
13202
- const part = read.manifest.parts.find((candidate) => candidate.index === index);
13203
- if (!part) return null;
13204
- const partPath = partPathFor(workspace, part.filename);
13205
- if (partPath === null) return null;
13206
- const text2 = readFileIfPresent(partPath);
13207
- if (text2 === null) return null;
13208
- return { uri, mimeType: "text/markdown", text: capUtf8(text2, MAX_RESOURCE_BYTES).text };
13209
- }
13210
- return null;
13211
- }
13212
- };
13213
- }
13214
-
13215
13572
  // src/mcp/instructions.ts
13216
13573
  var SERVER_INSTRUCTIONS = [
13217
13574
  "codebase-snapshot serves this repository as a size-budgeted snapshot, not as a directory walk.",
@@ -13669,7 +14026,24 @@ function parseCliArgs(argv) {
13669
14026
  let args = [];
13670
14027
  const explicitMode = values.mode ? String(values.mode) : void 0;
13671
14028
  const firstPositional = positionals[0];
13672
- if (firstPositional !== void 0) {
14029
+ const modeCommand = explicitMode === void 0 ? void 0 : COMMAND_ALIASES.get(explicitMode);
14030
+ if (explicitMode !== void 0 && modeCommand === void 0) {
14031
+ throw new UsageError(
14032
+ `Unknown --mode "${explicitMode}". Expected one of: ${Array.from(COMMAND_ALIASES.keys()).join(", ")}.`
14033
+ );
14034
+ }
14035
+ if (modeCommand !== void 0) {
14036
+ command = modeCommand;
14037
+ if (firstPositional !== void 0) {
14038
+ const named = COMMAND_ALIASES.get(firstPositional);
14039
+ if (named !== void 0 && named !== modeCommand) {
14040
+ throw new UsageError(
14041
+ `--mode ${explicitMode} contradicts the command "${firstPositional}". Pass one or the other.`
14042
+ );
14043
+ }
14044
+ args = named !== void 0 ? positionals.slice(1) : positionals;
14045
+ }
14046
+ } else if (firstPositional !== void 0) {
13673
14047
  const resolved = COMMAND_ALIASES.get(firstPositional);
13674
14048
  if (!resolved) {
13675
14049
  throw new UsageError(
@@ -13678,27 +14052,6 @@ function parseCliArgs(argv) {
13678
14052
  }
13679
14053
  command = resolved;
13680
14054
  args = positionals.slice(1);
13681
- } else if (explicitMode !== void 0) {
13682
- const resolved = COMMAND_ALIASES.get(explicitMode);
13683
- if (!resolved) {
13684
- throw new UsageError(
13685
- `Unknown --mode "${explicitMode}". Expected one of: ${Array.from(COMMAND_ALIASES.keys()).join(", ")}.`
13686
- );
13687
- }
13688
- command = resolved;
13689
- }
13690
- if (explicitMode !== void 0) {
13691
- const resolvedMode = COMMAND_ALIASES.get(explicitMode);
13692
- if (!resolvedMode) {
13693
- throw new UsageError(
13694
- `Unknown --mode "${explicitMode}". Expected one of: ${Array.from(COMMAND_ALIASES.keys()).join(", ")}.`
13695
- );
13696
- }
13697
- if (firstPositional !== void 0 && resolvedMode !== command) {
13698
- throw new UsageError(
13699
- `--mode ${explicitMode} contradicts the command "${firstPositional}". Pass one or the other.`
13700
- );
13701
- }
13702
14055
  }
13703
14056
  const expectedArgs = COMMAND_ARITY[command];
13704
14057
  if (args.length !== expectedArgs) {
@@ -13991,6 +14344,16 @@ function installDependencies(cwd) {
13991
14344
  }
13992
14345
  return { manager: manager.name, command, ok: true, detail: seconds };
13993
14346
  }
14347
+ async function setupHookOutDir(invocation, init) {
14348
+ if (!init.reused || invocation.outDir !== void 0) return init.outDir;
14349
+ const loaded = await loadConfigFileDetailed(invocation.cwd);
14350
+ if (loaded.errors.length > 0) {
14351
+ throw new Error(
14352
+ `The config file could not be read: ${loaded.errors.join("; ")}. Fix it, or delete it to use the defaults.`
14353
+ );
14354
+ }
14355
+ return resolveConfig(loaded.config, {}, invocation.cwd).outDir;
14356
+ }
13994
14357
  async function captureStdout(fn) {
13995
14358
  const { value, text: text2 } = await runWithStdoutCapture(fn);
13996
14359
  return { code: value, text: text2 };
@@ -14024,7 +14387,13 @@ async function runSetupCommand(invocation, options = {}) {
14024
14387
  reuseConfig: true,
14025
14388
  dryRun: invocation.dryRun
14026
14389
  });
14027
- const hook = invocation.installHook === true ? installPreCommitHook(invocation.cwd, init.outDir) : null;
14390
+ const keptConfigPath = init.reused ? findConfigFile(invocation.cwd) ?? init.configPath : init.configPath;
14391
+ const appliedPreset = init.reused ? null : init.preset;
14392
+ if (init.reused && invocation.preset !== void 0) {
14393
+ init.notes.push(
14394
+ `--preset ${invocation.preset} was not applied: the existing config is kept. Edit its preset setting, or run \`init --force\` to write a new one.`
14395
+ );
14396
+ }
14028
14397
  if (invocation.dryRun) {
14029
14398
  const manager = invocation.noInstall ? null : detectPackageManager(invocation.cwd).name;
14030
14399
  if (invocation.format === "json") {
@@ -14032,9 +14401,9 @@ async function runSetupCommand(invocation, options = {}) {
14032
14401
  `${JSON.stringify(
14033
14402
  {
14034
14403
  dryRun: true,
14035
- configPath: init.configPath,
14404
+ configPath: keptConfigPath,
14036
14405
  configReused: init.reused,
14037
- preset: init.preset,
14406
+ preset: appliedPreset,
14038
14407
  install: manager,
14039
14408
  configText: init.configText
14040
14409
  },
@@ -14047,7 +14416,7 @@ async function runSetupCommand(invocation, options = {}) {
14047
14416
  }
14048
14417
  info("\n\u{1F9EA} Dry run \u2014 setup would:");
14049
14418
  info(
14050
- ` 1. ${init.reused ? `keep ${path21.basename(init.configPath)}` : `write ${path21.basename(init.configPath)} (preset: ${init.preset})`}`
14419
+ ` 1. ${init.reused ? `keep ${path21.basename(keptConfigPath)}` : `write ${path21.basename(keptConfigPath)} (preset: ${appliedPreset})`}`
14051
14420
  );
14052
14421
  info(" 2. add the npm scripts, the devDependency and the .gitignore entries");
14053
14422
  if (manager !== null) info(` 3. install with ${manager}`);
@@ -14056,12 +14425,13 @@ async function runSetupCommand(invocation, options = {}) {
14056
14425
  info(init.configText);
14057
14426
  return 0;
14058
14427
  }
14428
+ const hook = invocation.installHook === true ? installPreCommitHook(invocation.cwd, await setupHookOutDir(invocation, init)) : null;
14059
14429
  if (invocation.format !== "json") {
14060
14430
  if (!interactive) info(`\u{1F680} Setup for: ${invocation.cwd}`);
14061
14431
  if (init.reused) {
14062
- info(`\u267B Keeping ${path21.basename(init.configPath)} (${presetSummary(init)})`);
14432
+ info(`\u267B Keeping ${path21.basename(keptConfigPath)}`);
14063
14433
  } else {
14064
- info(`\u2705 Created ${path21.basename(init.configPath)} (${presetSummary(init)})`);
14434
+ info(`\u2705 Created ${path21.basename(keptConfigPath)} (${presetSummary(init)})`);
14065
14435
  }
14066
14436
  if (init.scripts.length > 0) info(` Added npm scripts: ${init.scripts.join(", ")}`);
14067
14437
  if (init.dependency.added && init.dependency.range !== null) {
@@ -14071,6 +14441,9 @@ async function runSetupCommand(invocation, options = {}) {
14071
14441
  info(` Added to .gitignore: ${init.gitignoreEntries.join(", ")}`);
14072
14442
  }
14073
14443
  if (hook) for (const note of hook.notes) info(` ${note}`);
14444
+ if (init.reused && invocation.preset !== void 0) {
14445
+ info(` \u26A0 --preset ${invocation.preset} was not applied: the existing config is kept.`);
14446
+ }
14074
14447
  }
14075
14448
  let install = null;
14076
14449
  if (invocation.noInstall) {
@@ -14088,7 +14461,9 @@ async function runSetupCommand(invocation, options = {}) {
14088
14461
  if (invocation.includeSensitiveFiles === true) generateArgs.push("--include-sensitive-files");
14089
14462
  const budget = invocation.maxPartBytesRaw ?? invocation.maxPartBytes;
14090
14463
  if (budget !== void 0) generateArgs.push("--max-part-bytes", String(budget));
14091
- if ((invocation.skipArtifacts ?? []).length > 0) {
14464
+ if ((invocation.onlyArtifacts ?? []).length > 0) {
14465
+ generateArgs.push("--only-artifacts", (invocation.onlyArtifacts ?? []).join(","));
14466
+ } else if ((invocation.skipArtifacts ?? []).length > 0) {
14092
14467
  generateArgs.push("--skip-artifacts", (invocation.skipArtifacts ?? []).join(","));
14093
14468
  }
14094
14469
  if (invocation.includeMonolith === true) generateArgs.push("--include-monolith");
@@ -14115,9 +14490,9 @@ async function runSetupCommand(invocation, options = {}) {
14115
14490
  parsed = null;
14116
14491
  }
14117
14492
  const setup = {
14118
- configPath: init.configPath,
14493
+ configPath: keptConfigPath,
14119
14494
  configReused: init.reused,
14120
- preset: init.preset,
14495
+ preset: appliedPreset,
14121
14496
  scripts: init.scripts,
14122
14497
  dependency: init.dependency,
14123
14498
  gitignoreEntries: init.gitignoreEntries,
@@ -14250,7 +14625,19 @@ function requestsJsonFormat(argv) {
14250
14625
  }
14251
14626
  return format === "json";
14252
14627
  }
14628
+ var closedStdoutGuarded = false;
14629
+ function guardClosedStdout() {
14630
+ if (closedStdoutGuarded) return;
14631
+ closedStdoutGuarded = true;
14632
+ process.stdout.on("error", (error) => {
14633
+ if (error.code === "EPIPE" || error.code === "ECONNRESET") {
14634
+ process.exit(0);
14635
+ }
14636
+ throw error;
14637
+ });
14638
+ }
14253
14639
  async function main(argv = process.argv.slice(2)) {
14640
+ guardClosedStdout();
14254
14641
  const pending = process.stdout.isTTY === true && shouldCheck(argv, process.env) ? checkForUpdate({ current: GENERATOR_VERSION, cacheFile: cacheFilePath() }) : null;
14255
14642
  const code = await runCommand(argv);
14256
14643
  if (pending) {
@@ -14306,40 +14693,47 @@ ${USAGE}
14306
14693
  const skipConfig = invocation.noConfig || invocation.command === "diff";
14307
14694
  const loaded = skipConfig ? { config: null, warnings: [], errors: [], file: null } : await loadConfigFileDetailed(invocation.cwd);
14308
14695
  if (invocation.noConfig) info("\u2699 --no-config: using built-in defaults, config file ignored");
14309
- for (const warning of loaded.warnings) warn(`\u26A0 Config: ${warning}`);
14310
14696
  if (loaded.errors.length > 0) {
14311
- warn("\u274C The config file could not be read. Fix it, or delete it to use the defaults.");
14312
- return 1;
14697
+ return fail(
14698
+ invocation.format,
14699
+ `The config file could not be read: ${loaded.errors.join("; ")}. Fix it, or delete it to use the defaults.`
14700
+ );
14313
14701
  }
14702
+ for (const warning of loaded.warnings) warn(`\u26A0 Config: ${warning}`);
14314
14703
  if (loaded.file) info(`\u2699 Using config ${path21.relative(process.cwd(), loaded.file) || loaded.file}`);
14315
- const resolved = resolveConfig(
14316
- loaded.config,
14317
- {
14318
- mode: invocation.command,
14319
- format: invocation.format,
14320
- dryRun: invocation.dryRun,
14321
- cwd: invocation.cwd,
14322
- outDir: invocation.outDir,
14323
- includeMonolith: invocation.includeMonolith,
14324
- includeSensitiveFiles: invocation.includeSensitiveFiles,
14325
- maxPartBytes: invocation.maxPartBytes,
14326
- maxPartTokens: invocation.maxPartTokens,
14327
- largeFileBytes: invocation.largeFileBytes,
14328
- maxMonolithBytes: invocation.maxMonolithBytes,
14329
- skipArtifacts: invocation.skipArtifacts,
14330
- // `--only-artifacts` is forwarded as itself, not only as the derived suppression list:
14331
- // suppression cannot switch an artifact *on*, so a config that had turned one of the
14332
- // requested artifacts off left the run with nothing to write.
14333
- onlyArtifacts: invocation.onlyArtifacts,
14334
- discovery: invocation.discovery,
14335
- changedSince: invocation.changedSince,
14336
- staged: invocation.staged,
14337
- withDependents: invocation.withDependents,
14338
- skeleton: invocation.skeleton,
14339
- sarif: invocation.sarif
14340
- },
14341
- invocation.cwd
14342
- );
14704
+ let resolved;
14705
+ try {
14706
+ resolved = resolveConfig(
14707
+ loaded.config,
14708
+ {
14709
+ mode: invocation.command,
14710
+ format: invocation.format,
14711
+ dryRun: invocation.dryRun,
14712
+ cwd: invocation.cwd,
14713
+ outDir: invocation.outDir,
14714
+ includeMonolith: invocation.includeMonolith,
14715
+ includeSensitiveFiles: invocation.includeSensitiveFiles,
14716
+ maxPartBytes: invocation.maxPartBytes,
14717
+ maxPartTokens: invocation.maxPartTokens,
14718
+ largeFileBytes: invocation.largeFileBytes,
14719
+ maxMonolithBytes: invocation.maxMonolithBytes,
14720
+ skipArtifacts: invocation.skipArtifacts,
14721
+ // `--only-artifacts` is forwarded as itself, not only as the derived suppression list:
14722
+ // suppression cannot switch an artifact *on*, so a config that had turned one of the
14723
+ // requested artifacts off left the run with nothing to write.
14724
+ onlyArtifacts: invocation.onlyArtifacts,
14725
+ discovery: invocation.discovery,
14726
+ changedSince: invocation.changedSince,
14727
+ staged: invocation.staged,
14728
+ withDependents: invocation.withDependents,
14729
+ skeleton: invocation.skeleton,
14730
+ sarif: invocation.sarif
14731
+ },
14732
+ invocation.cwd
14733
+ );
14734
+ } catch (err) {
14735
+ return fail(invocation.format, err.message);
14736
+ }
14343
14737
  if (invocation.command === "validate") {
14344
14738
  const result = validateSnapshot(resolved);
14345
14739
  emit(invocation.format, result, () => renderValidateText(result));