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.
@@ -1822,6 +1822,14 @@ function scanWorkspacePackages(cwd, patterns) {
1822
1822
  }
1823
1823
  return { files, dependencies };
1824
1824
  }
1825
+ var SNAPSHOT_MARKER = ".codebase-snapshot";
1826
+ function isToolOwnedDirectory(dir) {
1827
+ try {
1828
+ return fs14.statSync(dir).isDirectory() && fs14.existsSync(path16.join(dir, SNAPSHOT_MARKER));
1829
+ } catch {
1830
+ return false;
1831
+ }
1832
+ }
1825
1833
  function countMarkdownFiles(cwd) {
1826
1834
  let count = 0;
1827
1835
  let directoriesSeen = 0;
@@ -1843,7 +1851,9 @@ function countMarkdownFiles(cwd) {
1843
1851
  }
1844
1852
  if (!entry.isDirectory() || current.depth >= 2) continue;
1845
1853
  if (entry.name.startsWith(".") || SKIPPED_WALK_DIRS.has(entry.name)) continue;
1846
- queue.push({ dir: path16.join(current.dir, entry.name), depth: current.depth + 1 });
1854
+ const child = path16.join(current.dir, entry.name);
1855
+ if (isToolOwnedDirectory(child)) continue;
1856
+ queue.push({ dir: child, depth: current.depth + 1 });
1847
1857
  }
1848
1858
  }
1849
1859
  return count;
@@ -2712,18 +2722,24 @@ function detectPreset(cwd, forced) {
2712
2722
  }
2713
2723
 
2714
2724
  // src/security/patterns.ts
2715
- 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)";
2716
- var WEAK_CREDENTIAL_NAME = "(?:pass|id[_-]?token|credentials?)";
2725
+ 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)";
2726
+ var WEAK_CREDENTIAL_NAME = "(?:pass|credentials?)";
2717
2727
  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)";
2718
2728
  var UNQUOTED_MIN_LENGTH = 2;
2719
2729
  var PROSE_CONTINUATION = String.raw`(?!\s+[a-z])`;
2720
- 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;
2721
- 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;
2730
+ var UNQUOTED_VALUE_CHARS = String.raw`A-Za-z0-9_+=/%:~$!@#^*?-`;
2731
+ var UNQUOTED_VALUE_END = String.raw`[A-Za-z0-9_+=/%:.~$!@#^*?-]`;
2732
+ var UNQUOTED_VALUE_START = String.raw`[$!@#%^&*~+]`;
2733
+ var UNQUOTED_LITERAL = String.raw`(` + // one capture, whichever branch matched: valueGroup is 1
2734
+ 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;
2735
+ 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;
2722
2736
  var ASSIGN = String.raw`(?<![=!<>])[:=](?!=)`;
2723
2737
  var NOT_AFTER_QUOTE = String.raw`(?<!["'])`;
2724
2738
  var NOT_A_NAMESPACED_IDENTIFIER = String.raw`(?![a-z][a-z0-9]*(?:\.[a-z][a-z0-9-]*)+/)`;
2739
+ var QUOTED_CREDENTIAL_KEY = `["'](?!id[-_]token["'])[A-Za-z0-9_$-]{0,64}${STRONG_CREDENTIAL_NAME}["']`;
2725
2740
  var QUOTED_VALUE = String.raw`((?:[^"'\\\n]|\\\\["'](?=[A-Za-z0-9_])|\\.){1,512})`;
2726
2741
  var UNQUOTED_STRONG_NAME = `(?<!id[-_])${STRONG_CREDENTIAL_NAME}`;
2742
+ var CREDENTIAL_KEY_TAIL = new RegExp(`(?:${STRONG_CREDENTIAL_NAME})$`, "i");
2727
2743
  var DEFAULT_SECRET_PATTERNS = [
2728
2744
  {
2729
2745
  rule: "private-key-header",
@@ -2790,13 +2806,28 @@ var DEFAULT_SECRET_PATTERNS = [
2790
2806
  pattern: /xox[baprsdc]-[0-9A-Za-z-]{10,250}/
2791
2807
  },
2792
2808
  {
2793
- // Prefix-only vendors. Each prefix below is documented, globally unique and
2794
- // cannot collide with an ordinary identifier, which is what makes a bare
2795
- // prefix rule cheap and safe: `glpat-` (GitLab), `hvs.`/`s.` (Vault service
2796
- // and batch tokens), `whsec_` (Stripe webhook secret), `dckr_pat_` (Docker
2797
- // Hub), `hf_` (HuggingFace), `ya29.` (Google OAuth access token).
2809
+ // Known vendor token shapes: prefix-unique tokens, plus the few fixed layouts whose format is
2810
+ // documented and cannot collide with an ordinary identifier.
2811
+ //
2812
+ // Each prefix below is globally unique, which is what makes a bare prefix rule cheap and
2813
+ // safe: `glpat-` (GitLab), `hvs.`/`s.` (Vault service and batch tokens), `whsec_`
2814
+ // (Stripe webhook secret), `dckr_pat_` (Docker Hub), `hf_` (HuggingFace), `ya29.`
2815
+ // (Google OAuth access token), `shpat_`/`shpca_`/`shppa_`/`shpss_` (Shopify admin and
2816
+ // storefront tokens).
2817
+ //
2818
+ // The fixed shapes have no prefix to anchor on and were each emitted in clear:
2819
+ // - Telegram bot token: `<8-10 digit bot id>:<35-character secret>`.
2820
+ // - Discord bot token: `<base64 user id>.<6-8 char hmac>.<25-45 char signature>`; demanding
2821
+ // all three segments keeps ordinary dotted identifiers out.
2822
+ // - Azure DevOps personal access token: exactly 52 alphanumerics that always mix case and
2823
+ // digits, so a hash, a UUID or a plain identifier — all single-case or a different length —
2824
+ // does not match.
2825
+ //
2826
+ // The rule name still says "prefix" because that is how the catalogue began; it is the
2827
+ // vendor-token rule, and growing a new named rule per vendor would make the documented
2828
+ // pattern count drift on every release.
2798
2829
  rule: "known-vendor-token-prefix",
2799
- 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})/
2830
+ 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])/
2800
2831
  },
2801
2832
  {
2802
2833
  rule: "slack-webhook-url",
@@ -2851,39 +2882,52 @@ var DEFAULT_SECRET_PATTERNS = [
2851
2882
  // (including one invented tomorrow) is covered, provided the `//` is followed
2852
2883
  // immediately by the userinfo: `// see the docs` and a bare reminder comment
2853
2884
  // never match, because a space or the comment wording breaks the shape.
2885
+ //
2886
+ // Three shapes joined it, all the same fact — a URL carries the credential in plain sight —
2887
+ // and each cost a leak while it was elsewhere:
2888
+ // - The user part may be **empty**: Redis, SMTP, AMQP and FTP URLs routinely omit the username
2889
+ // (`redis://:password@host`), and a `{1,128}` prefix made every one of those invisible.
2890
+ // - `curl -u user:password` sends the same userinfo without a scheme; the lookbehind
2891
+ // consumes the flag so the match is the credential alone.
2892
+ // - An Azure SAS link authenticates with `?sig=`; the signature *is* the credential.
2854
2893
  rule: "uri-credentials",
2855
- pattern: /\/\/[^\s:/@"'`;()<>,]{1,128}:[^\s:/@"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/
2894
+ 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%._=~-])/
2856
2895
  },
2857
2896
  {
2858
2897
  // The host tail stops at quotes, `;`, `)`, `<`, `>` and `,`: an unbounded
2859
2898
  // `[^\s/]` used to swallow the closing quote and the statement separator of
2860
2899
  // the string the URL was written in.
2900
+ // The user part may be empty here too: `redis://:password@host` and `amqp://:password@host`
2901
+ // are how those services are configured when the account is the server's default.
2861
2902
  rule: "database-uri-credentials",
2862
- 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}/
2903
+ 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}/
2863
2904
  },
2864
2905
  {
2906
+ // An empty user part is valid userinfo (`smtp://:password@host`: the account is the server's
2907
+ // default), and it used to be the one shape every scheme-listed rule refused.
2865
2908
  rule: "basic-auth-url",
2866
- pattern: /(?:https?|ftp|sftp|ssh|git|smtp|smtps|ldap|ldaps):\/\/[^\s:@/"'`;()<>,]{1,128}:[^\s@/"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/i
2909
+ pattern: /(?:https?|ftp|sftp|ssh|git|smtp|smtps|ldap|ldaps):\/\/[^\s:@/"'`;()<>,]{0,128}:[^\s@/"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}/i
2867
2910
  },
2868
2911
  {
2869
2912
  // Quoted credentials in any common key spelling. The value may be as short
2870
2913
  // as one character: `password: "hunter2"` is a credential whatever its
2871
2914
  // entropy, and a length floor was exactly how it survived into `parts`.
2872
2915
  //
2873
- // The key is either bare (`dbPassword:`) or wholly quoted (`"dbPassword":`).
2916
+ // The key is bare (`dbPassword:`), wholly quoted (`"password":`), or quoted with a
2917
+ // camelCase prefix (`"dbPassword":`) — the last one is {@link QUOTED_CREDENTIAL_KEY}.
2874
2918
  // There is deliberately no optional quote *before* the separator: that let a
2875
2919
  // previous string's closing quote stand in for the key's, so
2876
2920
  // ``${pass ? " PASS" : " FAIL"}`` had `" FAIL"` masked as if `PASS` were
2877
2921
  // the key name.
2878
2922
  rule: "credential-assignment",
2879
2923
  pattern: new RegExp(
2880
- `(?:["']${STRONG_CREDENTIAL_NAME}["']|${NOT_AFTER_QUOTE}${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_NAMESPACED_IDENTIFIER}(["'\`])${QUOTED_VALUE}\\1`,
2924
+ `(?:${QUOTED_CREDENTIAL_KEY}|${NOT_AFTER_QUOTE}(?<!id[-_])${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_NAMESPACED_IDENTIFIER}(["'\`])${QUOTED_VALUE}\\1`,
2881
2925
  "i"
2882
2926
  ),
2883
2927
  valueGroup: 2
2884
2928
  },
2885
2929
  {
2886
- // `pass`, `id-token` and `credentials` are ambiguous on their own, so they
2930
+ // `pass` and `credentials` are ambiguous on their own, so they
2887
2931
  // are accepted only against a quoted value long enough to be a credential.
2888
2932
  rule: "credential-assignment-weak",
2889
2933
  pattern: new RegExp(
@@ -2905,9 +2949,31 @@ var DEFAULT_SECRET_PATTERNS = [
2905
2949
  // character, so `["awsSecret:", "apiKey:"]` — the list of key names the lookbehind was added
2906
2950
  // for — cannot match here anyway. `redact.ts` still refuses a match whose separator is inside
2907
2951
  // the literal, which is the case that list actually is.
2952
+ //
2953
+ // The name may also be a *quoted* key: YAML allows `"dbPassword": hunter2`, and JSON cannot
2954
+ // spell a key any other way, so the same {@link QUOTED_CREDENTIAL_KEY} fragment is used here.
2955
+ // Without it a quoted key whose value was not quoted emitted the value in clear.
2956
+ //
2957
+ // A colon-form assignment in a data file masks the whole remainder of the value to
2958
+ // end-of-line, whatever punctuation it holds. A strong credential name is the evidence that
2959
+ // the thing after it is a value, and the character classes above cannot cover every symbol a
2960
+ // password may contain — `password: pa&ss` used to stop at the `&`. This branch is a
2961
+ // lookbehind, so the match is the value alone, and `redact.ts` only applies it to a data or
2962
+ // shell file: in source code the same shape is an expression and stays untouched, and an `URL`
2963
+ // query string keeps its `&` separators because they are not a colon form.
2964
+ //
2965
+ // The `KEY=value` twin does the same for the `=` form, which INI, .properties and shell files
2966
+ // use: with a credential key the whole value is masked whatever symbols it contains
2967
+ // (`password=pa&ss`, `token=a<b`, `client_secret=x|y`). The value is bounded by whitespace
2968
+ // (end of line, or the space before a `# comment`), not by a symbol class — `envpass!@#$%^&*()` used
2969
+ // to stop before the parenthesis and leave the tail in clear. The lookbehind matches the value
2970
+ // alone and `redact.ts` decides, from the file and from the key, whether the line is an
2971
+ // assignment (it must be a data/shell file, the key must end in a credential name, and a URL
2972
+ // query parameter or `$VARIABLE` reference is not an assignment).
2908
2973
  rule: "credential-assignment-unquoted",
2909
2974
  pattern: new RegExp(
2910
- `${UNQUOTED_STRONG_NAME}\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_LITERAL_VALUE}${UNQUOTED_LITERAL}`,
2975
+ `(?:${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
2976
+ #]{1,300}`,
2911
2977
  "i"
2912
2978
  ),
2913
2979
  valueGroup: 1
@@ -2930,8 +2996,14 @@ var DEFAULT_SECRET_PATTERNS = [
2930
2996
  // needs no `valueGroup`. A lone `Bearer`/`Basic`, and a word after it that
2931
2997
  // cannot be a credential (`Bearer authentication`), stay readable: the value
2932
2998
  // must contain a digit, be at least 32 chars, or carry base64 `=` padding.
2999
+ //
3000
+ // A fourth shape was leaking: `Basic dXNlcjpwYXNz` is the base64 of `user:pass` — 12
3001
+ // characters, no digit, no padding — and the three tests above all said "not a
3002
+ // credential", so it reached the parts in clear. Mixed case is the discriminator: a base64
3003
+ // rendering of textual userinfo mixes cases, while the prose the earlier rules were
3004
+ // protecting (`Bearer authentication`) is a lowercase word.
2933
3005
  rule: "authorization-header",
2934
- 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_.+/=-])/
3006
+ 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_.+/=-])/
2935
3007
  },
2936
3008
  {
2937
3009
  // Broader names than before (`apiKey`, `clientSecret`, `privateKey` were
@@ -3143,6 +3215,32 @@ function scanAndRedactSecrets(content, rules, filePath) {
3143
3215
  continue;
3144
3216
  }
3145
3217
  if (group && isTemplateInterpolation(line, group[0], group[1])) continue;
3218
+ if (group && isUnquotedValue(line, group[0]) && TRUNCATING_VALUE_CHARS.test(line[group[1]] ?? "")) {
3219
+ continue;
3220
+ }
3221
+ if (valueGroup !== void 0 && group === void 0) {
3222
+ if (!isAssignmentFile(filePath)) continue;
3223
+ const assignment = assignmentAround(line, match.index);
3224
+ if (assignment.form === "=" && (assignment.reference || assignment.key === null || !CREDENTIAL_KEY_TAIL.test(assignment.key))) {
3225
+ continue;
3226
+ }
3227
+ }
3228
+ if (group && isUnquotedValue(line, group[0]) && OPENER_LED_VALUE.test(line.slice(group[0], group[1])) && !isAssignmentFile(filePath)) {
3229
+ continue;
3230
+ }
3231
+ if (group && isUnquotedValue(line, group[0])) {
3232
+ const assignment = assignmentAround(line, group[0]);
3233
+ const wholeValue = isAssignmentFile(filePath) && assignment.form !== null && !assignment.reference && !assignment.urlValue;
3234
+ if (wholeValue) {
3235
+ spans.push({
3236
+ start: group[0],
3237
+ end: Math.max(group[1], tokenEnd(line, group[0])),
3238
+ rule
3239
+ });
3240
+ matchedRules.add(rule);
3241
+ continue;
3242
+ }
3243
+ }
3146
3244
  spans.push(
3147
3245
  group ? { start: group[0], end: group[1], rule } : { start: match.index, end: match.index + match[0].length, rule }
3148
3246
  );
@@ -3160,6 +3258,8 @@ function scanAndRedactSecrets(content, rules, filePath) {
3160
3258
  }
3161
3259
  var TOKEN_CHARS_LEFT = /[A-Za-z0-9_+/-]/;
3162
3260
  var TOKEN_CHARS_RIGHT = /[A-Za-z0-9_+/=-]/;
3261
+ var TRUNCATING_VALUE_CHARS = /[<>|\\]/;
3262
+ var OPENER_LED_VALUE = /^[(\\[{]/;
3163
3263
  function expandOverToken(line, start, end) {
3164
3264
  let left = start;
3165
3265
  let right = end;
@@ -3206,6 +3306,31 @@ function isSelfNamingConstant(line, start, end) {
3206
3306
  }
3207
3307
  return line.endsWith(value, index);
3208
3308
  }
3309
+ function assignmentAround(line, valueStart) {
3310
+ let index = valueStart;
3311
+ while (index > 0 && (line[index - 1] === " " || line[index - 1] === " ")) index -= 1;
3312
+ const separator = index > 0 ? line[index - 1] : "";
3313
+ if (separator !== ":" && separator !== "=") {
3314
+ return { form: null, key: null, reference: false, rhsStart: -1, urlValue: false };
3315
+ }
3316
+ const separatorIndex = index - 1;
3317
+ index = separatorIndex;
3318
+ while (index > 0 && (line[index - 1] === " " || line[index - 1] === " ")) index -= 1;
3319
+ const keyEnd = index;
3320
+ while (index > 0 && /[A-Za-z0-9_$.-]/.test(line[index - 1])) index -= 1;
3321
+ const key = line.slice(index, keyEnd).replace(/^-+/, "");
3322
+ const before = index > 0 ? line[index - 1] : "";
3323
+ const reference = before === "?" || before === "&" || before === "$" || before === '"' || before === "'" || before === "`";
3324
+ let rhsStart = separatorIndex + 1;
3325
+ while (rhsStart < line.length && (line[rhsStart] === " " || line[rhsStart] === " ")) rhsStart += 1;
3326
+ const urlValue = /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(line.slice(rhsStart, tokenEnd(line, rhsStart)));
3327
+ return { form: separator === ":" ? ":" : "=", key, reference, rhsStart, urlValue };
3328
+ }
3329
+ function tokenEnd(line, start) {
3330
+ let end = start;
3331
+ while (end < line.length && !/\s/.test(line[end])) end += 1;
3332
+ return end;
3333
+ }
3209
3334
  function isUnquotedValue(line, start) {
3210
3335
  const before = start > 0 ? line[start - 1] : "";
3211
3336
  return before !== '"' && before !== "'" && before !== "`";
@@ -5400,7 +5525,7 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
5400
5525
  bucket.budgetBytes
5401
5526
  );
5402
5527
  const sectionBudget = budget - HEADER_RESERVE_BYTES;
5403
- const prepared = bucket.files.map((file) => prepareSection(file, sectionBudget));
5528
+ const prepared = bucket.files.map((file) => prepareSection(file, sectionBudget, budget));
5404
5529
  for (const sections of greedyGroups(prepared, budget)) groups.push({ sections, budget });
5405
5530
  }
5406
5531
  if (groups.length === 0) return [];
@@ -5570,7 +5695,7 @@ var displayPath = (value) => capValue(escapeControls(value), DISPLAY_PATH_MAX);
5570
5695
  function topEntries(counts, limit) {
5571
5696
  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(", ");
5572
5697
  }
5573
- function prepareSection(file, sectionBudget) {
5698
+ function prepareSection(file, sectionBudget, partBudget) {
5574
5699
  let text2 = renderFileSection(file);
5575
5700
  let byteSize = Buffer.byteLength(text2, "utf8");
5576
5701
  if (byteSize <= sectionBudget) return { file, text: text2, byteSize };
@@ -5582,7 +5707,7 @@ function prepareSection(file, sectionBudget) {
5582
5707
  const truncated = truncateWithBudgetMarker(
5583
5708
  content,
5584
5709
  allowed,
5585
- sectionBudget,
5710
+ partBudget,
5586
5711
  file.originalLines
5587
5712
  );
5588
5713
  if (!truncated.isTruncated) return;
@@ -6384,16 +6509,14 @@ function emptyDrift() {
6384
6509
  function sha256Hex(buffer) {
6385
6510
  return crypto2.createHash("sha256").update(buffer).digest("hex");
6386
6511
  }
6387
- var VERIFY_SNIFF_MAX_BYTES = 8 * 1024 * 1024;
6388
6512
  function wouldNowBeIncluded(cwd, relativePath) {
6389
6513
  const absolutePath = path16.join(cwd, relativePath);
6390
6514
  try {
6391
6515
  const stats = fs14.statSync(absolutePath);
6392
6516
  if (!stats.isFile()) return false;
6393
- if (stats.size <= VERIFY_SNIFF_MAX_BYTES) {
6394
- return !decodeText(fs14.readFileSync(absolutePath)).binary;
6395
- }
6396
- return !isBinaryFile(absolutePath);
6517
+ if (isBinaryExtension(absolutePath)) return false;
6518
+ if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) return false;
6519
+ return !decodeText(fs14.readFileSync(absolutePath)).binary;
6397
6520
  } catch {
6398
6521
  return false;
6399
6522
  }
@@ -6970,7 +7093,7 @@ function validateSnapshot(configInput) {
6970
7093
 
6971
7094
  // src/version.ts
6972
7095
  var GENERATOR_NAME = "codebase-snapshot";
6973
- var GENERATOR_VERSION = "0.9.14";
7096
+ var GENERATOR_VERSION = "0.9.15";
6974
7097
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
6975
7098
  function isOurGeneratorName(name) {
6976
7099
  if (typeof name !== "string") return false;
@@ -7297,6 +7420,12 @@ function explainPath(config, target) {
7297
7420
  return result;
7298
7421
  }
7299
7422
  }
7423
+ if (isBinaryExtension(absolute)) {
7424
+ result.included = false;
7425
+ result.reason = "binary";
7426
+ result.detail = "binary extension; generate skips it without reading and records `binary` in manifest.skipped[]";
7427
+ return result;
7428
+ }
7300
7429
  let sizeOnDisk = null;
7301
7430
  try {
7302
7431
  sizeOnDisk = fs14.statSync(absolute).size;
@@ -7309,13 +7438,6 @@ function explainPath(config, target) {
7309
7438
  result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
7310
7439
  return result;
7311
7440
  }
7312
- result.layer = classifyLayer(relative8, config.layers);
7313
- result.kind = classifyKind(relative8, config.kinds);
7314
- result.language = detectLanguage(relative8);
7315
- const layerRule = findRuleMatch(config.layers, relative8);
7316
- if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
7317
- const kindRule = findRuleMatch(config.kinds, relative8);
7318
- if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
7319
7441
  if (fs14.existsSync(absolute) && fs14.statSync(absolute).isFile()) {
7320
7442
  const buffer = fs14.readFileSync(absolute);
7321
7443
  const decoded = decodeText(buffer);
@@ -7333,6 +7455,13 @@ function explainPath(config, target) {
7333
7455
  result.secretCount = findings.length;
7334
7456
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
7335
7457
  }
7458
+ result.layer = classifyLayer(relative8, config.layers);
7459
+ result.kind = classifyKind(relative8, config.kinds);
7460
+ result.language = detectLanguage(relative8);
7461
+ const layerRule = findRuleMatch(config.layers, relative8);
7462
+ if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
7463
+ const kindRule = findRuleMatch(config.kinds, relative8);
7464
+ if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
7336
7465
  const manifest = readManifest2(config);
7337
7466
  const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative8) : void 0;
7338
7467
  result.part = entry?.part ?? null;
@@ -7470,7 +7599,7 @@ function describePayloadDiff(before, after, sourceFilesIdentical) {
7470
7599
  }
7471
7600
  if (fingerprintDiffers && (sourceFilesIdentical || configurationDiffers)) {
7472
7601
  reasons.push(
7473
- `content fingerprint ${shortDigest(before.fingerprint)} \u2192 ${shortDigest(after.fingerprint)}` + (sourceFilesIdentical ? " (same source files, packed differently)" : "")
7602
+ `content fingerprint ${shortDigest(before.fingerprint)} \u2192 ${shortDigest(after.fingerprint)}` + (sourceFilesIdentical ? " (same source files, packed or configured differently)" : "")
7474
7603
  );
7475
7604
  }
7476
7605
  if (partsDiffer) {
@@ -7745,7 +7874,8 @@ function renderConfig(answers) {
7745
7874
  // matched value is never included \u2014 only the path, the line and the rule.
7746
7875
  sarif: ${answers.sarif},
7747
7876
  // Snapshot only the files that differ from a git ref (for example "main"),
7748
- // plus untracked ones. null and false both mean "snapshot everything".
7877
+ // plus untracked ones. null means "snapshot everything"; any other value must
7878
+ // be a git ref string, and anything else is a configuration error.
7749
7879
  changedSince: null,
7750
7880
  // Snapshot only what is staged in the index: the pre-commit counterpart.
7751
7881
  staged: false,
@@ -9187,6 +9317,7 @@ function isProcessAlive(pid) {
9187
9317
  var OWNERSHIP_MARKER = ".codebase-snapshot";
9188
9318
  var SUPPORTED_MARKER_SCHEMAS = /* @__PURE__ */ new Set([SCHEMA_VERSION]);
9189
9319
  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;
9320
+ var SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/;
9190
9321
  function listEntries(dir) {
9191
9322
  const entries = [];
9192
9323
  const walk = (absolute, prefix) => {
@@ -9205,7 +9336,32 @@ function listEntries(dir) {
9205
9336
  walk(dir, "");
9206
9337
  return entries.sort();
9207
9338
  }
9339
+ function markerInventory(dir) {
9340
+ const entries = listEntries(dir);
9341
+ const files = [];
9342
+ for (const entry of entries) {
9343
+ if (entry === OWNERSHIP_MARKER) continue;
9344
+ if (IGNORABLE_ENTRIES.has(entry.slice(entry.lastIndexOf("/") + 1))) continue;
9345
+ const full = path16.join(dir, ...entry.split("/"));
9346
+ let stats;
9347
+ try {
9348
+ stats = fs14.lstatSync(full);
9349
+ } catch {
9350
+ continue;
9351
+ }
9352
+ if (!stats.isFile()) continue;
9353
+ let digest;
9354
+ try {
9355
+ digest = sha256Hex2(fs14.readFileSync(full));
9356
+ } catch {
9357
+ continue;
9358
+ }
9359
+ files.push({ path: entry, bytes: stats.size, sha256: digest });
9360
+ }
9361
+ return { entries, files };
9362
+ }
9208
9363
  function markerPayload(dir, state, id, createdAt) {
9364
+ const { entries, files } = markerInventory(dir);
9209
9365
  const marker2 = {
9210
9366
  generator: GENERATOR_NAME,
9211
9367
  version: GENERATOR_VERSION,
@@ -9214,7 +9370,8 @@ function markerPayload(dir, state, id, createdAt) {
9214
9370
  state,
9215
9371
  id,
9216
9372
  pid: process.pid,
9217
- entries: listEntries(dir)
9373
+ entries,
9374
+ files
9218
9375
  };
9219
9376
  const manifestPath = path16.join(dir, "manifest.json");
9220
9377
  if (fs14.existsSync(manifestPath)) {
@@ -9274,6 +9431,33 @@ function readOwnershipMarker(dir) {
9274
9431
  if (candidate.state !== "staging" && candidate.state !== "complete") {
9275
9432
  return { marker: null, problem: "its .codebase-snapshot marker records no run state" };
9276
9433
  }
9434
+ const rawFiles = candidate.files;
9435
+ let files;
9436
+ if (rawFiles !== void 0) {
9437
+ if (!Array.isArray(rawFiles)) {
9438
+ return {
9439
+ marker: null,
9440
+ problem: "its .codebase-snapshot marker's file inventory is not an array"
9441
+ };
9442
+ }
9443
+ files = [];
9444
+ for (const item of rawFiles) {
9445
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
9446
+ return {
9447
+ marker: null,
9448
+ problem: "its .codebase-snapshot marker's file inventory holds an entry that is not an object"
9449
+ };
9450
+ }
9451
+ const record = item;
9452
+ 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)) {
9453
+ return {
9454
+ marker: null,
9455
+ problem: "its .codebase-snapshot marker's file inventory holds an entry this build cannot read"
9456
+ };
9457
+ }
9458
+ files.push({ path: record.path, bytes: record.bytes, sha256: record.sha256 });
9459
+ }
9460
+ }
9277
9461
  return {
9278
9462
  marker: {
9279
9463
  generator: GENERATOR_NAME,
@@ -9284,7 +9468,8 @@ function readOwnershipMarker(dir) {
9284
9468
  id: candidate.id,
9285
9469
  pid: typeof candidate.pid === "number" ? candidate.pid : void 0,
9286
9470
  manifestSha256: typeof candidate.manifestSha256 === "string" ? candidate.manifestSha256 : void 0,
9287
- entries: Array.isArray(candidate.entries) && candidate.entries.every((entry) => typeof entry === "string") ? candidate.entries : void 0
9471
+ entries: Array.isArray(candidate.entries) && candidate.entries.every((entry) => typeof entry === "string") ? candidate.entries : void 0,
9472
+ files
9288
9473
  },
9289
9474
  problem: null
9290
9475
  };
@@ -9299,6 +9484,59 @@ function describeManifestProblem(value) {
9299
9484
  if (!Array.isArray(candidate.files)) return "has no files array";
9300
9485
  return null;
9301
9486
  }
9487
+ function verifyMarkerInventory(dir, entries, files) {
9488
+ const diskEntries = new Set(entries);
9489
+ const recorded = /* @__PURE__ */ new Map();
9490
+ for (const record of files) {
9491
+ if (recorded.has(record.path)) {
9492
+ return `its .codebase-snapshot inventory records ${record.path} twice`;
9493
+ }
9494
+ if (!diskEntries.has(record.path)) {
9495
+ return `its .codebase-snapshot inventory records ${record.path}, which is missing from the directory`;
9496
+ }
9497
+ recorded.set(record.path, record);
9498
+ }
9499
+ for (const entry of entries) {
9500
+ if (entry === OWNERSHIP_MARKER) continue;
9501
+ if (IGNORABLE_ENTRIES.has(entry.slice(entry.lastIndexOf("/") + 1))) continue;
9502
+ const full = path16.join(dir, ...entry.split("/"));
9503
+ let stats;
9504
+ try {
9505
+ stats = fs14.lstatSync(full);
9506
+ } catch {
9507
+ return `its .codebase-snapshot inventory lists ${entry}, which cannot be read`;
9508
+ }
9509
+ if (stats.isDirectory()) {
9510
+ if (recorded.has(entry)) {
9511
+ return `its .codebase-snapshot inventory records the directory ${entry} as a file`;
9512
+ }
9513
+ continue;
9514
+ }
9515
+ if (!stats.isFile()) {
9516
+ if (recorded.has(entry)) {
9517
+ return `its .codebase-snapshot inventory records ${entry} as a regular file, but it is not one`;
9518
+ }
9519
+ continue;
9520
+ }
9521
+ const record = recorded.get(entry);
9522
+ if (record === void 0) {
9523
+ return `its .codebase-snapshot inventory does not record the file ${entry}`;
9524
+ }
9525
+ if (record.bytes !== stats.size) {
9526
+ return `its .codebase-snapshot inventory records ${entry} as ${record.bytes} B, but it is ${stats.size} B`;
9527
+ }
9528
+ let digest;
9529
+ try {
9530
+ digest = sha256Hex2(fs14.readFileSync(full));
9531
+ } catch {
9532
+ return `its .codebase-snapshot inventory cannot verify ${entry}: the file could not be read`;
9533
+ }
9534
+ if (digest !== record.sha256) {
9535
+ return `its .codebase-snapshot inventory's digest for ${entry} does not match the file`;
9536
+ }
9537
+ }
9538
+ return null;
9539
+ }
9302
9540
  function assessSnapshotDirectory(dir) {
9303
9541
  const { marker: marker2, problem } = readOwnershipMarker(dir);
9304
9542
  if (!marker2) return { owned: false, problem, foreignEntries: [], marker: null };
@@ -9311,7 +9549,8 @@ function assessSnapshotDirectory(dir) {
9311
9549
  };
9312
9550
  }
9313
9551
  const manifestPath = path16.join(dir, "manifest.json");
9314
- if (fs14.existsSync(manifestPath)) {
9552
+ const hasManifest = fs14.existsSync(manifestPath);
9553
+ if (hasManifest) {
9315
9554
  let raw;
9316
9555
  try {
9317
9556
  raw = fs14.readFileSync(manifestPath, "utf8");
@@ -9367,6 +9606,14 @@ function assessSnapshotDirectory(dir) {
9367
9606
  marker: marker2
9368
9607
  };
9369
9608
  }
9609
+ if (marker2.files === void 0 && !hasManifest) {
9610
+ return {
9611
+ owned: false,
9612
+ problem: "its .codebase-snapshot marker records neither per-file digests nor a manifest digest, so it cannot prove this generator wrote the directory",
9613
+ foreignEntries: [],
9614
+ marker: marker2
9615
+ };
9616
+ }
9370
9617
  const recorded = new Set(marker2.entries ?? []);
9371
9618
  if (recorded.size === 0) {
9372
9619
  return {
@@ -9376,13 +9623,18 @@ function assessSnapshotDirectory(dir) {
9376
9623
  marker: marker2
9377
9624
  };
9378
9625
  }
9379
- const foreignEntries = listEntries(dir).filter(
9626
+ const entries = listEntries(dir);
9627
+ const foreignEntries = entries.filter(
9380
9628
  (entry) => !recorded.has(entry) && !IGNORABLE_ENTRIES.has(entry)
9381
9629
  );
9630
+ if (foreignEntries.length > 0) {
9631
+ return { owned: false, problem: null, foreignEntries, marker: marker2 };
9632
+ }
9633
+ const inventoryProblem = marker2.files === void 0 ? null : verifyMarkerInventory(dir, entries, marker2.files);
9382
9634
  return {
9383
- owned: foreignEntries.length === 0,
9384
- problem: null,
9385
- foreignEntries,
9635
+ owned: inventoryProblem === null,
9636
+ problem: inventoryProblem,
9637
+ foreignEntries: [],
9386
9638
  marker: marker2
9387
9639
  };
9388
9640
  }
@@ -10006,9 +10258,12 @@ function generateSnapshot(configInput, options) {
10006
10258
  }
10007
10259
  }
10008
10260
  const fingerprint = sha256Hex2(
10009
- files.map(
10010
- (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
10011
- ).join("\n")
10261
+ [
10262
+ ...files.map(
10263
+ (file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
10264
+ ),
10265
+ `settings:${configDigest(config)}`
10266
+ ].join("\n")
10012
10267
  );
10013
10268
  const fullContents = /* @__PURE__ */ new Map();
10014
10269
  if (config.includeMonolith) {
@@ -10276,7 +10531,7 @@ function generateSnapshot(configInput, options) {
10276
10531
  }
10277
10532
  writeOwnershipMarker(outDir, markerPayload(outDir, "complete", snapshotId, createdAt));
10278
10533
  };
10279
- shipHookState();
10534
+ if (config.hooks.afterGenerate) shipHookState();
10280
10535
  if (pendingHook) {
10281
10536
  const tracked = pendingHook.then(
10282
10537
  () => {