codebase-snapshot 0.9.14 → 0.9.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js CHANGED
@@ -180,6 +180,14 @@ function scanWorkspacePackages(cwd, patterns) {
180
180
  }
181
181
  return { files, dependencies };
182
182
  }
183
+ var SNAPSHOT_MARKER = ".codebase-snapshot";
184
+ function isToolOwnedDirectory(dir) {
185
+ try {
186
+ return fs.statSync(dir).isDirectory() && fs.existsSync(path.join(dir, SNAPSHOT_MARKER));
187
+ } catch {
188
+ return false;
189
+ }
190
+ }
183
191
  function countMarkdownFiles(cwd) {
184
192
  let count = 0;
185
193
  let directoriesSeen = 0;
@@ -201,7 +209,9 @@ function countMarkdownFiles(cwd) {
201
209
  }
202
210
  if (!entry.isDirectory() || current.depth >= 2) continue;
203
211
  if (entry.name.startsWith(".") || SKIPPED_WALK_DIRS.has(entry.name)) continue;
204
- queue.push({ dir: path.join(current.dir, entry.name), depth: current.depth + 1 });
212
+ const child = path.join(current.dir, entry.name);
213
+ if (isToolOwnedDirectory(child)) continue;
214
+ queue.push({ dir: child, depth: current.depth + 1 });
205
215
  }
206
216
  }
207
217
  return count;
@@ -1070,18 +1080,24 @@ function detectPreset(cwd, forced) {
1070
1080
  }
1071
1081
 
1072
1082
  // src/security/patterns.ts
1073
- var STRONG_CREDENTIAL_NAME = "(?:password|passwd|passphrase|pwd|api[_-]?key|api[_-]?secret|secret[_-]?access[_-]?key|secret[_-]?key|client[_-]?secret[_-]?key|client[_-]?secret|private[_-]?key|aws[_-]?secret[_-]?access[_-]?key|access[_-]?token|refresh[_-]?token|auth[_-]?token|session[_-]?token|secret|token)";
1074
- var WEAK_CREDENTIAL_NAME = "(?:pass|id[_-]?token|credentials?)";
1083
+ var STRONG_CREDENTIAL_NAME = "(?:password|passwd|passphrase|pwd|api[_-]?key|api[_-]?secret|access[_-]?key|secret[_-]?access[_-]?key|secret[_-]?key|client[_-]?secret[_-]?key|client[_-]?secret|private[_-]?key|aws[_-]?secret[_-]?access[_-]?key|access[_-]?token|refresh[_-]?token|auth[_-]?token|session[_-]?token|session[_-]?key|secret|token)";
1084
+ var WEAK_CREDENTIAL_NAME = "(?:pass|credentials?)";
1075
1085
  var NOT_A_LITERAL_VALUE = "(?!(?:string|number|boolean|bigint|symbol|unknown|any|never|void|null|undefined|true|false|await|async|new|this|typeof|delete|yield|function|return|process\\.env|Buffer|Record|object)\\b)";
1076
1086
  var UNQUOTED_MIN_LENGTH = 2;
1077
1087
  var PROSE_CONTINUATION = String.raw`(?!\s+[a-z])`;
1078
- var UNQUOTED_LITERAL = String.raw`(?![0-9]+(?![A-Za-z0-9_+=/%:.~-]))([A-Za-z0-9_][A-Za-z0-9_+=/%:~-]{${UNQUOTED_MIN_LENGTH - 1},511})(?![A-Za-z0-9_+=/%:.~-]|[({[])` + PROSE_CONTINUATION;
1079
- var UNQUOTED_AMBIGUOUS_LITERAL = String.raw`(?![0-9]+(?![A-Za-z0-9_+=/%:.~-]))([A-Za-z0-9_][A-Za-z0-9_+=/%:~-]{7,511})(?![A-Za-z0-9_+=/%:.~-]|[({[])` + PROSE_CONTINUATION;
1088
+ var UNQUOTED_VALUE_CHARS = String.raw`A-Za-z0-9_+=/%:~$!@#^*?-`;
1089
+ var UNQUOTED_VALUE_END = String.raw`[A-Za-z0-9_+=/%:.~$!@#^*?-]`;
1090
+ var UNQUOTED_VALUE_START = String.raw`[$!@#%^&*~+]`;
1091
+ var UNQUOTED_LITERAL = String.raw`(` + // one capture, whichever branch matched: valueGroup is 1
1092
+ String.raw`(?![0-9]+(?!${UNQUOTED_VALUE_END}))[A-Za-z0-9_][${UNQUOTED_VALUE_CHARS}]{${UNQUOTED_MIN_LENGTH - 1},511}(?!${UNQUOTED_VALUE_END}|[({[]|[<>|\\])` + String.raw`|(?=${UNQUOTED_VALUE_START}[^ \t]{0,62}(?:[0-9]|${UNQUOTED_VALUE_START}))${UNQUOTED_VALUE_START}[${UNQUOTED_VALUE_CHARS}]{2,511}(?!${UNQUOTED_VALUE_END}|[({[]|[<>|\\])` + String.raw`|\([^()\s]{1,510}\)|\[[^\[\]\s]{1,510}\]|\{[^{}\s]{1,510}\}` + String.raw`)` + PROSE_CONTINUATION;
1093
+ var UNQUOTED_AMBIGUOUS_LITERAL = String.raw`(?![0-9]+(?!${UNQUOTED_VALUE_END}))([A-Za-z0-9_][${UNQUOTED_VALUE_CHARS}]{7,511})(?!${UNQUOTED_VALUE_END}|[({[]|[<>|\\])` + PROSE_CONTINUATION;
1080
1094
  var ASSIGN = String.raw`(?<![=!<>])[:=](?!=)`;
1081
1095
  var NOT_AFTER_QUOTE = String.raw`(?<!["'])`;
1082
1096
  var NOT_A_NAMESPACED_IDENTIFIER = String.raw`(?![a-z][a-z0-9]*(?:\.[a-z][a-z0-9-]*)+/)`;
1097
+ var QUOTED_CREDENTIAL_KEY = `["'](?!id[-_]token["'])[A-Za-z0-9_$-]{0,64}${STRONG_CREDENTIAL_NAME}["']`;
1083
1098
  var QUOTED_VALUE = String.raw`((?:[^"'\\\n]|\\\\["'](?=[A-Za-z0-9_])|\\.){1,512})`;
1084
1099
  var UNQUOTED_STRONG_NAME = `(?<!id[-_])${STRONG_CREDENTIAL_NAME}`;
1100
+ var CREDENTIAL_KEY_TAIL = new RegExp(`(?:${STRONG_CREDENTIAL_NAME})$`, "i");
1085
1101
  var DEFAULT_SECRET_PATTERNS = [
1086
1102
  {
1087
1103
  rule: "private-key-header",
@@ -1148,13 +1164,28 @@ var DEFAULT_SECRET_PATTERNS = [
1148
1164
  pattern: /xox[baprsdc]-[0-9A-Za-z-]{10,250}/
1149
1165
  },
1150
1166
  {
1151
- // Prefix-only vendors. Each prefix below is documented, globally unique and
1152
- // cannot collide with an ordinary identifier, which is what makes a bare
1153
- // prefix rule cheap and safe: `glpat-` (GitLab), `hvs.`/`s.` (Vault service
1154
- // and batch tokens), `whsec_` (Stripe webhook secret), `dckr_pat_` (Docker
1155
- // Hub), `hf_` (HuggingFace), `ya29.` (Google OAuth access token).
1167
+ // Known vendor token shapes: prefix-unique tokens, plus the few fixed layouts whose format is
1168
+ // documented and cannot collide with an ordinary identifier.
1169
+ //
1170
+ // Each prefix below is globally unique, which is what makes a bare prefix rule cheap and
1171
+ // safe: `glpat-` (GitLab), `hvs.`/`s.` (Vault service and batch tokens), `whsec_`
1172
+ // (Stripe webhook secret), `dckr_pat_` (Docker Hub), `hf_` (HuggingFace), `ya29.`
1173
+ // (Google OAuth access token), `shpat_`/`shpca_`/`shppa_`/`shpss_` (Shopify admin and
1174
+ // storefront tokens).
1175
+ //
1176
+ // The fixed shapes have no prefix to anchor on and were each emitted in clear:
1177
+ // - Telegram bot token: `<8-10 digit bot id>:<35-character secret>`.
1178
+ // - Discord bot token: `<base64 user id>.<6-8 char hmac>.<25-45 char signature>`; demanding
1179
+ // all three segments keeps ordinary dotted identifiers out.
1180
+ // - Azure DevOps personal access token: exactly 52 alphanumerics that always mix case and
1181
+ // digits, so a hash, a UUID or a plain identifier — all single-case or a different length —
1182
+ // does not match.
1183
+ //
1184
+ // The rule name still says "prefix" because that is how the catalogue began; it is the
1185
+ // vendor-token rule, and growing a new named rule per vendor would make the documented
1186
+ // pattern count drift on every release.
1156
1187
  rule: "known-vendor-token-prefix",
1157
- pattern: /\b(?:glpat-[A-Za-z0-9_-]{20,64}|glrt-[A-Za-z0-9_-]{20,64}|hvs\.[A-Za-z0-9_-]{20,128}|hvb\.[A-Za-z0-9_-]{20,128}|s\.[A-Za-z0-9]{20,64}|whsec_[A-Za-z0-9]{20,64}|dckr_pat_[A-Za-z0-9_-]{20,64}|hf_[A-Za-z0-9]{30,64}|ya29\.[A-Za-z0-9_-]{20,128}|sk_test_[A-Za-z0-9]{16,64}|1\/\/0[A-Za-z0-9_-]{20,64})/
1188
+ pattern: /\b(?:glpat-[A-Za-z0-9_-]{20,64}|glrt-[A-Za-z0-9_-]{20,64}|hvs\.[A-Za-z0-9_-]{20,128}|hvb\.[A-Za-z0-9_-]{20,128}|s\.[A-Za-z0-9]{20,64}|whsec_[A-Za-z0-9]{20,64}|dckr_pat_[A-Za-z0-9_-]{20,64}|hf_[A-Za-z0-9]{30,64}|ya29\.[A-Za-z0-9_-]{20,128}|sk_test_[A-Za-z0-9]{16,64}|1\/\/0[A-Za-z0-9_-]{20,64}|shpat_[A-Za-z0-9]{20,64}|shpca_[A-Za-z0-9]{20,64}|shppa_[A-Za-z0-9]{20,64}|shpss_[A-Za-z0-9]{20,64}|[0-9]{8,10}:[A-Za-z0-9_-]{35}|[A-Za-z0-9]{20,30}\.[A-Za-z0-9_-]{5,8}\.[A-Za-z0-9_-]{25,45}|(?=[A-Za-z0-9]{0,51}[a-z])(?=[A-Za-z0-9]{0,51}[A-Z])(?=[A-Za-z0-9]{0,51}[0-9])[A-Za-z0-9]{52})(?![A-Za-z0-9])/
1158
1189
  },
1159
1190
  {
1160
1191
  rule: "slack-webhook-url",
@@ -1209,39 +1240,52 @@ var DEFAULT_SECRET_PATTERNS = [
1209
1240
  // (including one invented tomorrow) is covered, provided the `//` is followed
1210
1241
  // immediately by the userinfo: `// see the docs` and a bare reminder comment
1211
1242
  // never match, because a space or the comment wording breaks the shape.
1243
+ //
1244
+ // Three shapes joined it, all the same fact — a URL carries the credential in plain sight —
1245
+ // and each cost a leak while it was elsewhere:
1246
+ // - The user part may be **empty**: Redis, SMTP, AMQP and FTP URLs routinely omit the username
1247
+ // (`redis://:password@host`), and a `{1,128}` prefix made every one of those invisible.
1248
+ // - `curl -u user:password` sends the same userinfo without a scheme; the lookbehind
1249
+ // consumes the flag so the match is the credential alone.
1250
+ // - An Azure SAS link authenticates with `?sig=`; the signature *is* the credential.
1212
1251
  rule: "uri-credentials",
1213
- pattern: /\/\/[^\s:/@"'`;()<>,]{1,128}:[^\s:/@"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/
1252
+ pattern: /\/\/[^\s:/@"'`;()<>,]{0,128}:[^\s:/@"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}|(?<=(?:^|[\s;|&(])--?u(?:ser)?[ \t=]{1,8})["']?[^\s"']{1,300}:[^\s"']{0,256}["']?|(?<=[?&])sig=[A-Za-z0-9%._=~-]{20,300}(?![A-Za-z0-9%._=~-])/
1214
1253
  },
1215
1254
  {
1216
1255
  // The host tail stops at quotes, `;`, `)`, `<`, `>` and `,`: an unbounded
1217
1256
  // `[^\s/]` used to swallow the closing quote and the statement separator of
1218
1257
  // the string the URL was written in.
1258
+ // The user part may be empty here too: `redis://:password@host` and `amqp://:password@host`
1259
+ // are how those services are configured when the account is the server's default.
1219
1260
  rule: "database-uri-credentials",
1220
- pattern: /(?:mongodb(?:\+srv)?|postgres(?:ql)?|mysql|maria(?:db)?|redis(?:s)?|amqp(?:s)?|clickhouse|mssql|sqlserver|oracle):\/\/[^\s:@/"'`;()<>,]{1,128}:[^\s@/"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/
1261
+ pattern: /(?:mongodb(?:\+srv)?|postgres(?:ql)?|mysql|maria(?:db)?|redis(?:s)?|amqp(?:s)?|clickhouse|mssql|sqlserver|oracle):\/\/[^\s:@/"'`;()<>,]{0,128}:[^\s@/"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/
1221
1262
  },
1222
1263
  {
1264
+ // An empty user part is valid userinfo (`smtp://:password@host`: the account is the server's
1265
+ // default), and it used to be the one shape every scheme-listed rule refused.
1223
1266
  rule: "basic-auth-url",
1224
- pattern: /(?:https?|ftp|sftp|ssh|git|smtp|smtps|ldap|ldaps):\/\/[^\s:@/"'`;()<>,]{1,128}:[^\s@/"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/i
1267
+ pattern: /(?:https?|ftp|sftp|ssh|git|smtp|smtps|ldap|ldaps):\/\/[^\s:@/"'`;()<>,]{0,128}:[^\s@/"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/i
1225
1268
  },
1226
1269
  {
1227
1270
  // Quoted credentials in any common key spelling. The value may be as short
1228
1271
  // as one character: `password: "hunter2"` is a credential whatever its
1229
1272
  // entropy, and a length floor was exactly how it survived into `parts`.
1230
1273
  //
1231
- // The key is either bare (`dbPassword:`) or wholly quoted (`"dbPassword":`).
1274
+ // The key is bare (`dbPassword:`), wholly quoted (`"password":`), or quoted with a
1275
+ // camelCase prefix (`"dbPassword":`) — the last one is {@link QUOTED_CREDENTIAL_KEY}.
1232
1276
  // There is deliberately no optional quote *before* the separator: that let a
1233
1277
  // previous string's closing quote stand in for the key's, so
1234
1278
  // ``${pass ? " PASS" : " FAIL"}`` had `" FAIL"` masked as if `PASS` were
1235
1279
  // the key name.
1236
1280
  rule: "credential-assignment",
1237
1281
  pattern: new RegExp(
1238
- `(?:["']${STRONG_CREDENTIAL_NAME}["']|${NOT_AFTER_QUOTE}${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_NAMESPACED_IDENTIFIER}(["'\`])${QUOTED_VALUE}\\1`,
1282
+ `(?:${QUOTED_CREDENTIAL_KEY}|${NOT_AFTER_QUOTE}(?<!id[-_])${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_NAMESPACED_IDENTIFIER}(["'\`])${QUOTED_VALUE}\\1`,
1239
1283
  "i"
1240
1284
  ),
1241
1285
  valueGroup: 2
1242
1286
  },
1243
1287
  {
1244
- // `pass`, `id-token` and `credentials` are ambiguous on their own, so they
1288
+ // `pass` and `credentials` are ambiguous on their own, so they
1245
1289
  // are accepted only against a quoted value long enough to be a credential.
1246
1290
  rule: "credential-assignment-weak",
1247
1291
  pattern: new RegExp(
@@ -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.15";
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) {
@@ -10289,7 +10544,7 @@ function generateSnapshot(configInput, options) {
10289
10544
  }
10290
10545
  writeOwnershipMarker(outDir, markerPayload(outDir, "complete", snapshotId, createdAt));
10291
10546
  };
10292
- shipHookState();
10547
+ if (config.hooks.afterGenerate) shipHookState();
10293
10548
  if (pendingHook) {
10294
10549
  const tracked = pendingHook.then(
10295
10550
  () => {
@@ -10339,7 +10594,17 @@ import * as path18 from "path";
10339
10594
  var FILE_HEADING = "### FILE: ";
10340
10595
  var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
10341
10596
  var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
10597
+ var META_PREFIX = "- Meta: ";
10598
+ var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
10599
+ var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
10342
10600
  var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
10601
+ var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
10602
+ function readIncludedLines(fields) {
10603
+ const last = fields[fields.length - 1];
10604
+ if (last === void 0) return null;
10605
+ const counts = COMPACT_COUNTS.exec(last.trim());
10606
+ return counts === null ? null : Number(counts[1]);
10607
+ }
10343
10608
  function parsePartSections(partText) {
10344
10609
  const lines = partText.split("\n");
10345
10610
  const sections = [];
@@ -10357,20 +10622,17 @@ function parsePartSections(partText) {
10357
10622
  while (cursor < lines.length && !CONTENT_MARKERS.has(lines[cursor])) {
10358
10623
  const line = lines[cursor];
10359
10624
  if (line.startsWith(FILE_HEADING)) break;
10360
- if (line.startsWith("- Meta: ")) {
10361
- for (const field of line.slice("- Meta: ".length).split("|")) {
10625
+ if (line.startsWith(META_PREFIX)) {
10626
+ const fields = line.slice(META_PREFIX.length).split("|");
10627
+ for (const field of fields) {
10362
10628
  const value = field.trim();
10363
10629
  if (INCLUSION_MODES.has(value)) inclusion = value;
10364
10630
  }
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());
10631
+ includedLines = readIncludedLines(fields);
10632
+ } else if (line.startsWith(LEGACY_INCLUSION_PREFIX)) {
10633
+ inclusion = line.slice(LEGACY_INCLUSION_PREFIX.length).trim();
10634
+ } else if (line.startsWith(LEGACY_INCLUDED_LINES_PREFIX)) {
10635
+ const value = Number(line.slice(LEGACY_INCLUDED_LINES_PREFIX.length).trim());
10374
10636
  includedLines = Number.isFinite(value) ? value : null;
10375
10637
  }
10376
10638
  cursor += 1;
@@ -10451,6 +10713,18 @@ function isInside2(parent, child) {
10451
10713
  const foldedChild = foldForComparison(child);
10452
10714
  return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path17.sep}`);
10453
10715
  }
10716
+ function resolveThroughExistingAncestor(target) {
10717
+ let existing = target;
10718
+ const missing = [];
10719
+ while (!fs15.existsSync(existing)) {
10720
+ missing.unshift(path17.basename(existing));
10721
+ const parent = path17.dirname(existing);
10722
+ if (parent === existing) break;
10723
+ existing = parent;
10724
+ }
10725
+ const resolved = canonicalPath(existing);
10726
+ return missing.length === 0 ? resolved : path17.join(resolved, ...missing);
10727
+ }
10454
10728
  function resolveRoot(requested, context) {
10455
10729
  if (requested !== void 0 && (typeof requested !== "string" || requested.trim().length === 0)) {
10456
10730
  return { ok: false, message: '"root" must be a non-empty string when provided.' };
@@ -10473,10 +10747,10 @@ function resolveRoot(requested, context) {
10473
10747
  const shown = context.roots.join(", ");
10474
10748
  return {
10475
10749
  ok: false,
10476
- message: `"${wanted}" resolves outside the directories this server may read (${shown}). Restart it with --root <path> to add a repository.`
10750
+ message: `"${wanted}" resolves outside the directories this server may read (${shown}). The server reads the directory it was started for; restart it with --cwd <directory> to serve a different repository.`
10477
10751
  };
10478
10752
  }
10479
- async function openWorkspace(root, overrides = {}) {
10753
+ async function openWorkspace(root, overrides = {}, allowedRoots) {
10480
10754
  const loaded = await loadConfigFileDetailed(root);
10481
10755
  if (loaded.errors.length > 0) {
10482
10756
  return {
@@ -10509,7 +10783,17 @@ async function openWorkspace(root, overrides = {}) {
10509
10783
  if (typeof overrides.outDir !== "string" || overrides.outDir.trim().length === 0) {
10510
10784
  return { ok: false, message: '"outDir" must be a non-empty string.' };
10511
10785
  }
10512
- cliOptions.outDir = overrides.outDir.trim();
10786
+ const requested = overrides.outDir.trim();
10787
+ const permitted = allowedRoots !== void 0 && allowedRoots.length > 0 ? allowedRoots : [root];
10788
+ const resolved = resolveThroughExistingAncestor(path17.resolve(root, requested));
10789
+ if (!permitted.some((allowed) => isInside2(canonicalPath(allowed), resolved))) {
10790
+ const shown = permitted.map((allowed) => canonicalPath(allowed)).join(", ");
10791
+ return {
10792
+ ok: false,
10793
+ message: `"outDir" must resolve inside the repository this server serves (${shown}). A tool argument may not place the snapshot outside it; pass a directory inside the root, or restart the server with --cwd pointing at the repository you want to write.`
10794
+ };
10795
+ }
10796
+ cliOptions.outDir = requested;
10513
10797
  }
10514
10798
  if (overrides.changedSince !== void 0) {
10515
10799
  if (typeof overrides.changedSince !== "string" || overrides.changedSince.trim().length === 0) {
@@ -10612,7 +10896,7 @@ var ROOT_PROPERTY = {
10612
10896
  };
10613
10897
  var OUT_DIR_PROPERTY = {
10614
10898
  type: "string",
10615
- description: "Snapshot directory, relative to the root. Defaults to the project configuration's outDir."
10899
+ description: "Snapshot directory, relative to the root, and it must resolve inside the served repository. Defaults to the project configuration's outDir."
10616
10900
  };
10617
10901
  var outDirOverride = (args) => ({ outDir: args.outDir });
10618
10902
  var SCOPE_PROPERTIES = {
@@ -10731,7 +11015,7 @@ function symbolsOf(entry) {
10731
11015
  async function prepare(args, context, overrides = {}) {
10732
11016
  const rootOutcome = resolveRoot(args.root, context);
10733
11017
  if (!rootOutcome.ok) return { ok: false, outcome: failure(rootOutcome.message) };
10734
- const opened = await openWorkspace(rootOutcome.root, overrides);
11018
+ const opened = await openWorkspace(rootOutcome.root, overrides, context.roots);
10735
11019
  if (!opened.ok) return { ok: false, outcome: failure(opened.message) };
10736
11020
  return { ok: true, workspace: opened.workspace };
10737
11021
  }
@@ -11528,6 +11812,16 @@ var ERROR_CODES = {
11528
11812
  methodNotFound: -32601,
11529
11813
  invalidParams: -32602,
11530
11814
  internalError: -32603,
11815
+ /**
11816
+ * A resource whose complete text is larger than one read may return.
11817
+ *
11818
+ * `-32000` is JSON-RPC's range for implementation-defined server errors, which is what this is:
11819
+ * there is no standard code for "the document is too large", and answering with -32602 would tell
11820
+ * a client its request was malformed when it was not. The message names the size, the limit and
11821
+ * the tool to use instead, because a resource read that cannot return the whole resource must not
11822
+ * invent a partial one.
11823
+ */
11824
+ resourceTooLarge: -32e3,
11531
11825
  unsupportedProtocolVersion: -32022
11532
11826
  };
11533
11827
  var METHOD3 = {
@@ -11640,16 +11934,14 @@ var COMMAND_OPTION_SCOPE = {
11640
11934
  "version"
11641
11935
  ],
11642
11936
  validate: VALIDATE_OPTIONS,
11937
+ // `report` reads `manifest.json` and prints what is there; a generation setting would change
11938
+ // nothing. The seven generation flags used to be listed here and were accepted as silent no-ops
11939
+ // — the exact "flag that parses but changes nothing" this table exists to prevent — while
11940
+ // `--discovery` was already rejected. Both the parser and `describe`'s `appliesTo` read this
11941
+ // list, so removing them narrows the two together.
11643
11942
  report: [
11644
11943
  "cwd",
11645
11944
  "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
11945
  "no-config",
11654
11946
  "no-update-check",
11655
11947
  "format",
@@ -12120,7 +12412,7 @@ function buildAgentContract() {
12120
12412
  type: "string",
12121
12413
  default: "generate",
12122
12414
  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)."
12415
+ summary: "Select the command when no command word is given. Values: generate, validate, check, report, init, setup, explain, diff, describe, skill, mcp. A command word and --mode must name the same command; a contradiction is a usage error (exit 2)."
12124
12416
  },
12125
12417
  {
12126
12418
  flag: "--cwd",
@@ -12706,6 +12998,190 @@ function negotiateLegacyVersion(requested) {
12706
12998
  return { version: DEFAULT_LEGACY_PROTOCOL_VERSION, matched: false };
12707
12999
  }
12708
13000
 
13001
+ // src/mcp/resources.ts
13002
+ import * as fs18 from "fs";
13003
+ import * as path20 from "path";
13004
+ var MAX_RESOURCE_BYTES = 512 * 1024;
13005
+ var ResourceTooLargeError = class extends Error {
13006
+ constructor(uri, bytes, limit, message) {
13007
+ super(message);
13008
+ this.uri = uri;
13009
+ this.bytes = bytes;
13010
+ this.limit = limit;
13011
+ this.name = "ResourceTooLargeError";
13012
+ }
13013
+ uri;
13014
+ bytes;
13015
+ limit;
13016
+ };
13017
+ function refuseTooLarge(uri, bytes, advice) {
13018
+ throw new ResourceTooLargeError(
13019
+ uri,
13020
+ bytes,
13021
+ MAX_RESOURCE_BYTES,
13022
+ `${uri} is ${formatBytes2(bytes)}, above the ${formatBytes2(MAX_RESOURCE_BYTES)} single-read limit, so it was not returned. ${advice}`
13023
+ );
13024
+ }
13025
+ function ensureSingleRead(uri, text2, advice) {
13026
+ const bytes = Buffer.byteLength(text2, "utf8");
13027
+ if (bytes > MAX_RESOURCE_BYTES) refuseTooLarge(uri, bytes, advice);
13028
+ return text2;
13029
+ }
13030
+ var MANIFEST_ADVICE = "Cutting a JSON document at the limit leaves invalid JSON, so this resource is never truncated. Use the snapshot_locate, snapshot_read and snapshot_status tools instead \u2014 they read the manifest directly \u2014 or read manifest.json from the snapshot directory.";
13031
+ var PART_ADVICE = "A part cut at the limit is a fragment of a file, not the file. Use snapshot_locate to find the file inside this part that you need, then snapshot_read for a bounded window of it.";
13032
+ var REPORT_ADVICE = "A report cut at the limit would look complete and would not be. Read it from the snapshot directory instead: the file on disk is complete.";
13033
+ var PART_URI = /^snapshot:\/\/parts\/(\d+)$/;
13034
+ var REPORT_URIS = /* @__PURE__ */ new Map([
13035
+ ["snapshot://reports/audit", { file: "audit.md", title: "Secret audit and risk findings" }],
13036
+ ["snapshot://reports/tree", { file: "project-tree.md", title: "Project tree" }],
13037
+ ["snapshot://reports/navigation", { file: "navigation.md", title: "Navigation index" }]
13038
+ ]);
13039
+ function formatBytes2(bytes) {
13040
+ if (bytes < 1024) return `${bytes} B`;
13041
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;
13042
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
13043
+ }
13044
+ async function workspaceFor(context) {
13045
+ const root = resolveRoot(void 0, context);
13046
+ if (!root.ok) return { error: root.message };
13047
+ const opened = await openWorkspace(root.root);
13048
+ if (!opened.ok) return { error: opened.message };
13049
+ return opened.workspace;
13050
+ }
13051
+ function readFileIfPresent(file) {
13052
+ try {
13053
+ return fs18.readFileSync(file, "utf8");
13054
+ } catch {
13055
+ return null;
13056
+ }
13057
+ }
13058
+ function buildResourceProvider() {
13059
+ return {
13060
+ async list(context) {
13061
+ const resources = [
13062
+ {
13063
+ uri: "snapshot://manifest",
13064
+ name: "manifest",
13065
+ title: "Snapshot manifest",
13066
+ description: "Every file in the snapshot with its layer, kind, language, part and hash, plus the reason each excluded file was excluded. A manifest larger than 512 kB is refused with its size instead of truncated: cut JSON does not parse. Use snapshot_locate, snapshot_read and snapshot_status for a large repository.",
13067
+ mimeType: "application/json"
13068
+ },
13069
+ {
13070
+ uri: "snapshot://contract",
13071
+ name: "contract",
13072
+ title: "Tool contract",
13073
+ description: "The machine-readable description of the codebase-snapshot command line.",
13074
+ mimeType: "application/json"
13075
+ },
13076
+ {
13077
+ uri: "snapshot://skill",
13078
+ name: "skill",
13079
+ title: "Agent skill",
13080
+ description: "Usage guidance for an agent working with this tool.",
13081
+ mimeType: "text/markdown"
13082
+ }
13083
+ ];
13084
+ for (const [uri, report] of REPORT_URIS) {
13085
+ resources.push({
13086
+ uri,
13087
+ name: report.file.replace(/\.md$/, ""),
13088
+ title: report.title,
13089
+ description: `${report.title} from the most recent snapshot. A report larger than 512 kB is refused rather than truncated; read the file from the snapshot directory.`,
13090
+ mimeType: "text/markdown"
13091
+ });
13092
+ }
13093
+ const workspace = await workspaceFor(context);
13094
+ if ("error" in workspace) return resources;
13095
+ const read = readManifest3(workspace);
13096
+ if (!read.ok) return resources;
13097
+ for (const part of read.manifest.parts) {
13098
+ const readable = part.byteSize <= MAX_RESOURCE_BYTES;
13099
+ resources.push({
13100
+ uri: `snapshot://parts/${part.index}`,
13101
+ name: `part-${String(part.index).padStart(3, "0")}`,
13102
+ title: `Part ${part.index} (${part.fileCount} files, ${formatBytes2(part.byteSize)})`,
13103
+ description: `Part ${part.index} of ${read.manifest.parts.length}: ${part.fileCount} file(s), ${part.lines} line(s), ${formatBytes2(part.byteSize)}.` + (readable ? "" : ` Above the ${formatBytes2(MAX_RESOURCE_BYTES)} single-read limit, so this resource is refused rather than truncated; use snapshot_locate and snapshot_read.`),
13104
+ mimeType: "text/markdown"
13105
+ });
13106
+ }
13107
+ return resources;
13108
+ },
13109
+ templates() {
13110
+ return [
13111
+ {
13112
+ uriTemplate: "snapshot://parts/{index}",
13113
+ name: "part",
13114
+ title: "Snapshot part",
13115
+ description: "One budgeted part of the snapshot, by its 1-based index.",
13116
+ mimeType: "text/markdown"
13117
+ }
13118
+ ];
13119
+ },
13120
+ async read(uri, context) {
13121
+ if (uri === "snapshot://contract") {
13122
+ const contract = buildAgentContract();
13123
+ return {
13124
+ uri,
13125
+ mimeType: "application/json",
13126
+ text: ensureSingleRead(
13127
+ uri,
13128
+ JSON.stringify(contract, null, 2),
13129
+ "Run 'codebase-snapshot describe --format json' for the complete contract."
13130
+ )
13131
+ };
13132
+ }
13133
+ if (uri === "snapshot://skill") {
13134
+ return {
13135
+ uri,
13136
+ mimeType: "text/markdown",
13137
+ text: ensureSingleRead(
13138
+ uri,
13139
+ renderSkill(),
13140
+ "Print it with 'codebase-snapshot skill'."
13141
+ )
13142
+ };
13143
+ }
13144
+ const workspace = await workspaceFor(context);
13145
+ if ("error" in workspace) return null;
13146
+ const report = REPORT_URIS.get(uri);
13147
+ if (report) {
13148
+ const text2 = readFileIfPresent(
13149
+ path20.resolve(workspace.root, workspace.config.outDir, "reports", report.file)
13150
+ );
13151
+ if (text2 === null) return null;
13152
+ return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, REPORT_ADVICE) };
13153
+ }
13154
+ if (uri === "snapshot://manifest") {
13155
+ const read = readManifest3(workspace);
13156
+ if (!read.ok) return null;
13157
+ const text2 = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
13158
+ return { uri, mimeType: "application/json", text: ensureSingleRead(uri, text2, MANIFEST_ADVICE) };
13159
+ }
13160
+ const partMatch = PART_URI.exec(uri);
13161
+ if (partMatch) {
13162
+ const read = readManifest3(workspace);
13163
+ if (!read.ok) return null;
13164
+ const index = Number(partMatch[1]);
13165
+ const part = read.manifest.parts.find((candidate) => candidate.index === index);
13166
+ if (!part) return null;
13167
+ const partPath = partPathFor(workspace, part.filename);
13168
+ if (partPath === null) return null;
13169
+ let partBytes;
13170
+ try {
13171
+ partBytes = fs18.statSync(partPath).size;
13172
+ } catch {
13173
+ return null;
13174
+ }
13175
+ if (partBytes > MAX_RESOURCE_BYTES) refuseTooLarge(uri, partBytes, PART_ADVICE);
13176
+ const text2 = readFileIfPresent(partPath);
13177
+ if (text2 === null) return null;
13178
+ return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, PART_ADVICE) };
13179
+ }
13180
+ return null;
13181
+ }
13182
+ };
13183
+ }
13184
+
12709
13185
  // src/mcp/schema.ts
12710
13186
  function validateArguments(schema, value) {
12711
13187
  if (value === void 0) value = {};
@@ -12932,7 +13408,22 @@ function createMcpServer(options) {
12932
13408
  if (typeof uri !== "string") {
12933
13409
  return errorResponse(id, ERROR_CODES.invalidParams, 'resources/read requires a "uri" string.');
12934
13410
  }
12935
- const contents = await options.resources.read(uri, options.context);
13411
+ let contents;
13412
+ try {
13413
+ contents = await options.resources.read(uri, options.context);
13414
+ } catch (error) {
13415
+ if (error instanceof ResourceTooLargeError) {
13416
+ options.context.log(
13417
+ `mcp: refused ${error.uri} (${error.bytes} bytes, limit ${error.limit}); returning it would truncate it`
13418
+ );
13419
+ return errorResponse(id, ERROR_CODES.resourceTooLarge, error.message, {
13420
+ uri: error.uri,
13421
+ bytes: error.bytes,
13422
+ limit: error.limit
13423
+ });
13424
+ }
13425
+ throw error;
13426
+ }
12936
13427
  if (!contents) {
12937
13428
  return errorResponse(id, ERROR_CODES.invalidParams, `Unknown resource "${uri}".`);
12938
13429
  }
@@ -13015,7 +13506,11 @@ function createMcpServer(options) {
13015
13506
  }
13016
13507
  async function dispatch(message) {
13017
13508
  if (!isJsonObject(message)) {
13018
- return errorResponse(null, ERROR_CODES.parseError, "Message is not a JSON object.");
13509
+ return errorResponse(
13510
+ null,
13511
+ ERROR_CODES.invalidRequest,
13512
+ Array.isArray(message) ? "Batch requests are not supported: send one JSON-RPC message per line." : "Message is not a JSON object."
13513
+ );
13019
13514
  }
13020
13515
  const isRequest = Object.prototype.hasOwnProperty.call(message, "id");
13021
13516
  const method = message.method;
@@ -13068,150 +13563,6 @@ function createMcpServer(options) {
13068
13563
  };
13069
13564
  }
13070
13565
 
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
13566
  // src/mcp/instructions.ts
13216
13567
  var SERVER_INSTRUCTIONS = [
13217
13568
  "codebase-snapshot serves this repository as a size-budgeted snapshot, not as a directory walk.",
@@ -13669,7 +14020,24 @@ function parseCliArgs(argv) {
13669
14020
  let args = [];
13670
14021
  const explicitMode = values.mode ? String(values.mode) : void 0;
13671
14022
  const firstPositional = positionals[0];
13672
- if (firstPositional !== void 0) {
14023
+ const modeCommand = explicitMode === void 0 ? void 0 : COMMAND_ALIASES.get(explicitMode);
14024
+ if (explicitMode !== void 0 && modeCommand === void 0) {
14025
+ throw new UsageError(
14026
+ `Unknown --mode "${explicitMode}". Expected one of: ${Array.from(COMMAND_ALIASES.keys()).join(", ")}.`
14027
+ );
14028
+ }
14029
+ if (modeCommand !== void 0) {
14030
+ command = modeCommand;
14031
+ if (firstPositional !== void 0) {
14032
+ const named = COMMAND_ALIASES.get(firstPositional);
14033
+ if (named !== void 0 && named !== modeCommand) {
14034
+ throw new UsageError(
14035
+ `--mode ${explicitMode} contradicts the command "${firstPositional}". Pass one or the other.`
14036
+ );
14037
+ }
14038
+ args = named !== void 0 ? positionals.slice(1) : positionals;
14039
+ }
14040
+ } else if (firstPositional !== void 0) {
13673
14041
  const resolved = COMMAND_ALIASES.get(firstPositional);
13674
14042
  if (!resolved) {
13675
14043
  throw new UsageError(
@@ -13678,27 +14046,6 @@ function parseCliArgs(argv) {
13678
14046
  }
13679
14047
  command = resolved;
13680
14048
  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
14049
  }
13703
14050
  const expectedArgs = COMMAND_ARITY[command];
13704
14051
  if (args.length !== expectedArgs) {
@@ -13991,6 +14338,16 @@ function installDependencies(cwd) {
13991
14338
  }
13992
14339
  return { manager: manager.name, command, ok: true, detail: seconds };
13993
14340
  }
14341
+ async function setupHookOutDir(invocation, init) {
14342
+ if (!init.reused || invocation.outDir !== void 0) return init.outDir;
14343
+ const loaded = await loadConfigFileDetailed(invocation.cwd);
14344
+ if (loaded.errors.length > 0) {
14345
+ throw new Error(
14346
+ `The config file could not be read: ${loaded.errors.join("; ")}. Fix it, or delete it to use the defaults.`
14347
+ );
14348
+ }
14349
+ return resolveConfig(loaded.config, {}, invocation.cwd).outDir;
14350
+ }
13994
14351
  async function captureStdout(fn) {
13995
14352
  const { value, text: text2 } = await runWithStdoutCapture(fn);
13996
14353
  return { code: value, text: text2 };
@@ -14024,7 +14381,13 @@ async function runSetupCommand(invocation, options = {}) {
14024
14381
  reuseConfig: true,
14025
14382
  dryRun: invocation.dryRun
14026
14383
  });
14027
- const hook = invocation.installHook === true ? installPreCommitHook(invocation.cwd, init.outDir) : null;
14384
+ const keptConfigPath = init.reused ? findConfigFile(invocation.cwd) ?? init.configPath : init.configPath;
14385
+ const appliedPreset = init.reused ? null : init.preset;
14386
+ if (init.reused && invocation.preset !== void 0) {
14387
+ init.notes.push(
14388
+ `--preset ${invocation.preset} was not applied: the existing config is kept. Edit its preset setting, or run \`init --force\` to write a new one.`
14389
+ );
14390
+ }
14028
14391
  if (invocation.dryRun) {
14029
14392
  const manager = invocation.noInstall ? null : detectPackageManager(invocation.cwd).name;
14030
14393
  if (invocation.format === "json") {
@@ -14032,9 +14395,9 @@ async function runSetupCommand(invocation, options = {}) {
14032
14395
  `${JSON.stringify(
14033
14396
  {
14034
14397
  dryRun: true,
14035
- configPath: init.configPath,
14398
+ configPath: keptConfigPath,
14036
14399
  configReused: init.reused,
14037
- preset: init.preset,
14400
+ preset: appliedPreset,
14038
14401
  install: manager,
14039
14402
  configText: init.configText
14040
14403
  },
@@ -14047,7 +14410,7 @@ async function runSetupCommand(invocation, options = {}) {
14047
14410
  }
14048
14411
  info("\n\u{1F9EA} Dry run \u2014 setup would:");
14049
14412
  info(
14050
- ` 1. ${init.reused ? `keep ${path21.basename(init.configPath)}` : `write ${path21.basename(init.configPath)} (preset: ${init.preset})`}`
14413
+ ` 1. ${init.reused ? `keep ${path21.basename(keptConfigPath)}` : `write ${path21.basename(keptConfigPath)} (preset: ${appliedPreset})`}`
14051
14414
  );
14052
14415
  info(" 2. add the npm scripts, the devDependency and the .gitignore entries");
14053
14416
  if (manager !== null) info(` 3. install with ${manager}`);
@@ -14056,12 +14419,13 @@ async function runSetupCommand(invocation, options = {}) {
14056
14419
  info(init.configText);
14057
14420
  return 0;
14058
14421
  }
14422
+ const hook = invocation.installHook === true ? installPreCommitHook(invocation.cwd, await setupHookOutDir(invocation, init)) : null;
14059
14423
  if (invocation.format !== "json") {
14060
14424
  if (!interactive) info(`\u{1F680} Setup for: ${invocation.cwd}`);
14061
14425
  if (init.reused) {
14062
- info(`\u267B Keeping ${path21.basename(init.configPath)} (${presetSummary(init)})`);
14426
+ info(`\u267B Keeping ${path21.basename(keptConfigPath)}`);
14063
14427
  } else {
14064
- info(`\u2705 Created ${path21.basename(init.configPath)} (${presetSummary(init)})`);
14428
+ info(`\u2705 Created ${path21.basename(keptConfigPath)} (${presetSummary(init)})`);
14065
14429
  }
14066
14430
  if (init.scripts.length > 0) info(` Added npm scripts: ${init.scripts.join(", ")}`);
14067
14431
  if (init.dependency.added && init.dependency.range !== null) {
@@ -14071,6 +14435,9 @@ async function runSetupCommand(invocation, options = {}) {
14071
14435
  info(` Added to .gitignore: ${init.gitignoreEntries.join(", ")}`);
14072
14436
  }
14073
14437
  if (hook) for (const note of hook.notes) info(` ${note}`);
14438
+ if (init.reused && invocation.preset !== void 0) {
14439
+ info(` \u26A0 --preset ${invocation.preset} was not applied: the existing config is kept.`);
14440
+ }
14074
14441
  }
14075
14442
  let install = null;
14076
14443
  if (invocation.noInstall) {
@@ -14088,7 +14455,9 @@ async function runSetupCommand(invocation, options = {}) {
14088
14455
  if (invocation.includeSensitiveFiles === true) generateArgs.push("--include-sensitive-files");
14089
14456
  const budget = invocation.maxPartBytesRaw ?? invocation.maxPartBytes;
14090
14457
  if (budget !== void 0) generateArgs.push("--max-part-bytes", String(budget));
14091
- if ((invocation.skipArtifacts ?? []).length > 0) {
14458
+ if ((invocation.onlyArtifacts ?? []).length > 0) {
14459
+ generateArgs.push("--only-artifacts", (invocation.onlyArtifacts ?? []).join(","));
14460
+ } else if ((invocation.skipArtifacts ?? []).length > 0) {
14092
14461
  generateArgs.push("--skip-artifacts", (invocation.skipArtifacts ?? []).join(","));
14093
14462
  }
14094
14463
  if (invocation.includeMonolith === true) generateArgs.push("--include-monolith");
@@ -14115,9 +14484,9 @@ async function runSetupCommand(invocation, options = {}) {
14115
14484
  parsed = null;
14116
14485
  }
14117
14486
  const setup = {
14118
- configPath: init.configPath,
14487
+ configPath: keptConfigPath,
14119
14488
  configReused: init.reused,
14120
- preset: init.preset,
14489
+ preset: appliedPreset,
14121
14490
  scripts: init.scripts,
14122
14491
  dependency: init.dependency,
14123
14492
  gitignoreEntries: init.gitignoreEntries,
@@ -14250,7 +14619,19 @@ function requestsJsonFormat(argv) {
14250
14619
  }
14251
14620
  return format === "json";
14252
14621
  }
14622
+ var closedStdoutGuarded = false;
14623
+ function guardClosedStdout() {
14624
+ if (closedStdoutGuarded) return;
14625
+ closedStdoutGuarded = true;
14626
+ process.stdout.on("error", (error) => {
14627
+ if (error.code === "EPIPE" || error.code === "ECONNRESET") {
14628
+ process.exit(0);
14629
+ }
14630
+ throw error;
14631
+ });
14632
+ }
14253
14633
  async function main(argv = process.argv.slice(2)) {
14634
+ guardClosedStdout();
14254
14635
  const pending = process.stdout.isTTY === true && shouldCheck(argv, process.env) ? checkForUpdate({ current: GENERATOR_VERSION, cacheFile: cacheFilePath() }) : null;
14255
14636
  const code = await runCommand(argv);
14256
14637
  if (pending) {
@@ -14306,40 +14687,47 @@ ${USAGE}
14306
14687
  const skipConfig = invocation.noConfig || invocation.command === "diff";
14307
14688
  const loaded = skipConfig ? { config: null, warnings: [], errors: [], file: null } : await loadConfigFileDetailed(invocation.cwd);
14308
14689
  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
14690
  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;
14691
+ return fail(
14692
+ invocation.format,
14693
+ `The config file could not be read: ${loaded.errors.join("; ")}. Fix it, or delete it to use the defaults.`
14694
+ );
14313
14695
  }
14696
+ for (const warning of loaded.warnings) warn(`\u26A0 Config: ${warning}`);
14314
14697
  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
- );
14698
+ let resolved;
14699
+ try {
14700
+ resolved = resolveConfig(
14701
+ loaded.config,
14702
+ {
14703
+ mode: invocation.command,
14704
+ format: invocation.format,
14705
+ dryRun: invocation.dryRun,
14706
+ cwd: invocation.cwd,
14707
+ outDir: invocation.outDir,
14708
+ includeMonolith: invocation.includeMonolith,
14709
+ includeSensitiveFiles: invocation.includeSensitiveFiles,
14710
+ maxPartBytes: invocation.maxPartBytes,
14711
+ maxPartTokens: invocation.maxPartTokens,
14712
+ largeFileBytes: invocation.largeFileBytes,
14713
+ maxMonolithBytes: invocation.maxMonolithBytes,
14714
+ skipArtifacts: invocation.skipArtifacts,
14715
+ // `--only-artifacts` is forwarded as itself, not only as the derived suppression list:
14716
+ // suppression cannot switch an artifact *on*, so a config that had turned one of the
14717
+ // requested artifacts off left the run with nothing to write.
14718
+ onlyArtifacts: invocation.onlyArtifacts,
14719
+ discovery: invocation.discovery,
14720
+ changedSince: invocation.changedSince,
14721
+ staged: invocation.staged,
14722
+ withDependents: invocation.withDependents,
14723
+ skeleton: invocation.skeleton,
14724
+ sarif: invocation.sarif
14725
+ },
14726
+ invocation.cwd
14727
+ );
14728
+ } catch (err) {
14729
+ return fail(invocation.format, err.message);
14730
+ }
14343
14731
  if (invocation.command === "validate") {
14344
14732
  const result = validateSnapshot(resolved);
14345
14733
  emit(invocation.format, result, () => renderValidateText(result));