codebase-snapshot 0.9.12 → 0.9.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -23,6 +23,519 @@ deprecated with an explanatory message instead. `latest` has pointed at 0.9.0 si
23
23
 
24
24
  ---
25
25
 
26
+ ## 0.9.15
27
+
28
+ A sixth audit, of the promises rather than the code paths the gate already covers. The gate was
29
+ green before this release and is green after it; every defect below lived somewhere the test suite
30
+ did not look. Two put credentials in the artifact, one broke the repeatability guarantee, and one
31
+ made `validate` fail on a snapshot it had just written.
32
+
33
+ ### Two credential shapes were left in clear text
34
+
35
+ **A quoted camelCase key in JSON or YAML was never redacted.** `{"dbPassword": "hunter2"}`,
36
+ `"discordToken"`, `"awsSecret"`, `"botToken"`, `"jwtSecret"` and `"sessionKey"` were emitted
37
+ verbatim, while the same names unquoted — and the short names `"password"` and `"apiKey"` — were
38
+ masked. The quoted rule wanted the whole key between quotes; the bare-tail rule was suppressed
39
+ after a quote. Every JSON configuration file has that shape.
40
+
41
+ **A mask could print `[REDACTED]` and keep most of the value.** Unquoted values stopped at `$`,
42
+ `!` and `@`, so `db_password: [REDACTED]$$w0rdSecr3t` shipped twelve characters of a seventeen
43
+ character password while looking redacted. A value that begins with punctuation was not matched at
44
+ all, so `!en$value` went out whole, and one containing `&` was masked as a prefix. A mask now
45
+ covers the whole value or nothing is emitted: a match that cannot be bounded is dropped in source
46
+ code and masked whole in a data file, never half-written.
47
+
48
+ The same pass closed narrower leaks: URL userinfo with an empty user part (`redis://:pass@host`),
49
+ `curl -u user:pass`, short unpadded Basic credentials, and fixed shapes for Discord, Telegram,
50
+ Azure DevOps, Shopify and Azure SAS tokens. The rule count stays 31 — the coverage folded into
51
+ existing rules rather than adding new ones.
52
+
53
+ ### The second run could change the preset, and drop a file
54
+
55
+ Preset detection counts markdown to decide whether a repository is `docs`. It excluded the output
56
+ directory only when that directory was literally named `snapshot`. With `--out-dir snap` on a
57
+ repository with no root `package.json`, run one detected `generic` and included `site/page.md`;
58
+ run two counted its own output, detected `docs`, applied that preset's `site/` exclusion, and
59
+ **silently dropped a source file** — with a different fingerprint, and in one variant with the same
60
+ fingerprint and different parts. The walk now skips any directory carrying an ownership marker,
61
+ whatever it is called, which is the same evidence the scanner already uses.
62
+
63
+ ### validate failed on a snapshot it had just generated
64
+
65
+ A text file with a binary extension — a Git-LFS pointer is the common case, three lines of plain
66
+ text ending in `.png` — was skipped by `generate` as binary and then reported by `validate` as
67
+ `new file`, exit 1, forever. Regenerating could not clear it, because the two commands asked
68
+ different questions. `validate` now applies `generate`'s decision order exactly, so they agree by
69
+ construction, and `explain` agrees with both: it no longer says `included: true` for a file the
70
+ snapshot skipped, and a skipped path no longer carries layer, kind or language.
71
+
72
+ ### A JSON consumer received nothing when the config was broken
73
+
74
+ `--format json` with an unparseable config, an unknown key, an invalid value or a bad preset exited
75
+ 1 with **zero bytes on stdout**, contradicting the documented error document and the contract in
76
+ `describe`. Every config failure now goes through the same writer as every other failure.
77
+
78
+ ### snapshot://manifest was not JSON on an ordinary repository
79
+
80
+ Above roughly 350 files the resource was cut at 512 kB with a truncation marker injected mid-document,
81
+ advertised as `application/json`. Resource reads are now all-or-nothing: a document that does not
82
+ fit one read fails with `-32000`, its size, the limit and the tool to use instead. The same rule
83
+ covers parts and reports.
84
+
85
+ ### Ownership evidence was a shape, not evidence
86
+
87
+ A hand-written `.codebase-snapshot` listing the directory's own files was accepted as proof that
88
+ this tool wrote the directory, and the next `generate` deleted those files. Markers now record the
89
+ sha256 and byte length of every file written, and replacement verifies them. A marker that cannot
90
+ prove a completed run is refused and nothing is deleted. Snapshots written by earlier releases are
91
+ still accepted on their manifest digest, so an upgrade does not strand the output directory a user
92
+ already has.
93
+
94
+ ### The rest
95
+
96
+ - **`setup`** honoured neither `--only-artifacts` over a reused config that disabled the artifact,
97
+ nor the config it actually kept: it reported a filename that did not exist and a preset it had not
98
+ applied. `--install-hook` baked `snapshot` as the output directory whatever the config said, and
99
+ `--dry-run --install-hook` wrote the hook anyway.
100
+ - **`--mode explain <path>`** and **`--mode diff <a> <b>`** could not work: the positional arguments
101
+ were parsed as the command word. Both forms now run.
102
+ - **`report`** accepted seven generation flags as silent no-ops while rejecting `--discovery`. It
103
+ rejects all of them now, and `describe` agrees.
104
+ - **A closed pipe** (`generate --format json | head`) was an uncaught `EPIPE` stack trace and exit 1;
105
+ it is now a quiet early exit.
106
+ - **The omission marker** named an internal section allowance (1887 B for a 4096 B part) instead of
107
+ the part budget the manifest and the CLI report.
108
+ - **The docs site** had heading elements with no `id` while carrying 49 anchor links: every table of
109
+ contents on all fifteen published pages was dead. The site generator emits GitHub-compatible ids
110
+ and the link checker now validates fragments, so the gate can see it.
111
+ - **`docs/install.md`** claimed the release check enforces the verified-client list "on every pull
112
+ request". There was no pull-request workflow and no client install test; the claim is gone.
113
+ - **The CLI reference** carried stale rows: `setup` missing from ten options, `report` advertised
114
+ with flags it rejects, `--mode` listing nine command names where there are eleven, "text-mode
115
+ stdout is empty" false for `skill`, and `validate` documented with five drift classes where there
116
+ are six. All corrected against the source.
117
+ - **`docs/configuration.md`**'s "complete example" omitted six settings that `init` writes.
118
+ - **The redaction section of `SECURITY.md`** described the old, narrower behaviour; it now states
119
+ what the rules do, including the shapes that are still not covered.
120
+ - **A pull-request workflow** now runs the same verify gate as a release, on Node 18, 20 and 22.
121
+ Until now that matrix ran only at release time, which is why 0.9.14 needed four publish attempts.
122
+ - **Publishing** asserts that the release tag agrees with `package.json`, ships the LICENSE the
123
+ `create` package declares, and no longer builds `dist` twice for one publish.
124
+
125
+ ### Verified
126
+
127
+ `npm run verify` — lint, typecheck, 1027 tests (0 failures), the docs sync check, the site build,
128
+ the site audit, the readme lint and the tarball check — on the release commit. Beyond the suite:
129
+ the published-install path, and real repositories in five languages where every part stays inside
130
+ its budget, repeat runs are byte-identical, `validate` is clean, and a snapshot written by 0.9.14
131
+ is upgraded in place without being refused.
132
+
133
+ An independent red-team pass then ran against the built artifact, trying to reproduce each of the
134
+ seven blockers from the outside. Six were closed outright; the seventh exposed a `.env` value whose
135
+ mask left a punctuation tail, and a quoted `id-token` that was over-redacted. Both were fixed and
136
+ re-tested before this release — which is the argument for a verifier who did not write the fix.
137
+
138
+ ### Three limitations became fixes instead
139
+
140
+ The first cut of these notes listed three known limitations. All three are fixed here, because a
141
+ release note that documents a leak is still a leak.
142
+
143
+ - `parsePartSections` reported the wrong count for a one-line file (`null`) and for a section that
144
+ collapsed to one line — `1 line of 3 lines` was read as 3, the source count. The counts are now
145
+ read from the metadata field that holds them, singular or plural, and free-form layer and language
146
+ names can no longer be mistaken for a count.
147
+ - `manifest.fingerprint` covered the input but not the settings, so two runs with different part
148
+ budgets over the same source shared a fingerprint while their parts differed. The settings digest
149
+ is folded in, so the fingerprint identifies the artifact set the documentation promises, and
150
+ `diff` says `packed or configured differently` when only the settings moved.
151
+ - A lowercase `key=value` credential in an INI or properties file was masked only while its value
152
+ fitted the rules' alphabet. In a data or shell file the whole value is masked now, whatever it
153
+ contains; the same line in source code is still left alone.
154
+
155
+ Two deliberate behaviours remain. A YAML value that is really a reference
156
+ (`password: !Ref SomeParam`) is masked, because in a data file the fail-closed choice is the right
157
+ one. And no rule set can promise that every credential shape is recognised — a clean audit is
158
+ evidence that the known patterns did not fire, not a guarantee, which `SECURITY.md` says plainly.
159
+
160
+ ## 0.9.14
161
+
162
+ A fifth audit, of what the tool does to text it did not write. Three of the defects below were
163
+ editing the user's code: a redaction rule erased 36 lines of source, a truncation left a code fence
164
+ open, and a preview budget did not apply to a file with CR line endings. The rest are credentials
165
+ left in clear text, two records that disagreed with the files beside them, and the performance work
166
+ the previous audits kept deferring.
167
+
168
+ Every item has a test that fails without it, with the exception of two performance changes that have
169
+ no behavioural signal — both are named.
170
+
171
+ ### A redaction rule erased source code
172
+
173
+ `PEM_BLOCK_PATTERN` is lazy over `[\s\S]`, which places no restriction on what may lie between a
174
+ `BEGIN` and the next `END`. A file holding an *unterminated* header — a truncated key, a fixture, a
175
+ half-written file — and, later, a properly terminated block had **everything between the two
176
+ headers replaced with blank lines**, including the source code that happened to sit there.
177
+
178
+ This repository did it to its own test suite: the security fixture's "unterminated key" test was
179
+ followed by another test whose key was terminated, and the generator bridged the two — 36 lines of
180
+ assertions, braces and the second test's declaration, replaced with 36 empty newlines.
181
+
182
+ The body may no longer contain another `-----BEGIN`. A header with no `END` before the next `BEGIN`
183
+ does not match as a block, and `PEM_UNTERMINATED_PATTERN` handles its header and its own base64 body,
184
+ which is what that pattern is for. The newline after the header is deliberately still not required:
185
+ a PEM inside a JSON or `.env` value is written with escaped `\n`, two characters rather than a line
186
+ break, and a rule that insisted on one would mask the header alone and leave the base64 in clear.
187
+
188
+ ### A truncated section left its code fence open
189
+
190
+ When the fixed metadata of a section would not fit the part budget, the *rendered* section was cut at
191
+ a byte offset. The cut lands in the body or in the opening fence, and the closing fence it removes is
192
+ the one that ends the block: every section after it was rendered inside this file's code block, and
193
+ `parsePartSections` merged the next file into this one's body.
194
+
195
+ The body now goes and the notice takes its place inside the block, with the file marked `preview`
196
+ first so the re-rendered `- Meta:` line describes what the reader will actually find. A section that
197
+ is a closed, empty, labelled block is readable; an unclosed fence corrupts the files after it, and no
198
+ block at all is invisible to the part reader.
199
+
200
+ ### A file with CR line endings was never previewed
201
+
202
+ `countLines` and `truncatePreview` split on `\n` alone, so a CR-only file — an old Mac file, anything
203
+ written by a tool that predates LF on that platform — counted as **one line**. `largeFileBytes`
204
+ therefore never fired: a 5 MB CR file went into a part whole, with its carriage returns intact, and
205
+ `manifest.json` reported `lines: 1` for a 40 000-line file. The redaction pass counted terminators
206
+ with `/\r\n|\n|\r/g`, so `reports/audit.md` reported line numbers the manifest disagreed with.
207
+
208
+ All four places now normalise CR, LF and CRLF, and `countLines` counts by scanning rather than
209
+ splitting — it runs on every file body and every part, and normalising first allocated a second copy
210
+ of a multi-megabyte string to answer a question about its terminators.
211
+
212
+ ### Four credential shapes were left in clear text
213
+
214
+ **`${VAR:-fallback}`, unquoted.** `POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-MyProdPassword123!}`
215
+ defeated every rule, and each refusal was individually reasonable: the quoted rules need a quote
216
+ after the separator, and the unquoted ones need the value to begin with a word character — a
217
+ fallback begins with `$`. That idiom is the norm in `.env` files, docker-compose, GitHub Actions and
218
+ shell scripts. A rule for the shape now masks the fallback and keeps the variable name.
219
+
220
+ **`readonly` and `declare` in shell files.** Those words introduce a binding in TypeScript and an
221
+ assignment in POSIX sh and `.envrc` — the same word, opposite meaning. The guard that suppresses
222
+ redaction for declarations therefore suppressed it for exactly the files most likely to hold a
223
+ credential. Bare `declare` is gone from the keyword list (the form that can initialise a binding in
224
+ TS is `declare const`, matched through `const`), and the guard now knows which files are assignments.
225
+
226
+ **A credential inside a string literal.** `startsInsideStringLiteral` rejected any match whose name
227
+ began immediately after a quote, which is right for a list of key names and wrong for every
228
+ connection string: `const dsn = "password=Secret;host=db"` and `curl -d "password=Secret"` were
229
+ emitted in clear. The test now also asks whether the literal closes between the name and the value.
230
+
231
+ **The MCP line cap.** `createLineReader` checked `MAX_LINE_BYTES` only on the buffer it had just
232
+ appended to, so a chunk carrying a discarded line's terminator *and* the start of the next message
233
+ left that remainder unmeasured until the stream ended — and `onEnd` delivered it whole to
234
+ `JSON.parse`. It also compared `.length`, which is UTF-16 code units: a line of astral characters
235
+ could be twice the ceiling in bytes and still pass. The cap is applied at every path that can
236
+ deliver, and measured in bytes.
237
+
238
+ ### `--with-dependents` lost an importer, and three languages had no import graph
239
+
240
+ The closure was computed from `file.summary.imports`, and a previewed or oversized file has no
241
+ summary. An importer over `largeFileBytes` was therefore dropped as unchanged while `validate` and
242
+ `explain`, which read the same file from disk, called it a dependent — generate and validate
243
+ disagreed about the snapshot generate had just written. Import specifiers are cheap to extract from
244
+ text already in hand, so they are now collected for files whose summary was refused, and the size
245
+ ceiling lives in one place so all three commands refuse the same files.
246
+
247
+ `resolveSpecifier` only understood JavaScript's `./x` shape, so the Python, Ruby, C/C++ and Dart
248
+ imports the profiles have been recording for several releases resolved to nothing. Each language
249
+ spells "this directory" differently — Python with dots, Ruby with `require_relative`, C with a
250
+ quoted include, Dart with nothing at all — and each is now resolved on its own terms. Package-rooted
251
+ languages (Go modules, Rust `crate::`, PHP PSR-4, JVM packages, Swift modules) stay unresolved on
252
+ purpose: their specifiers go through a manifest, and guessing a path would fabricate edges that
253
+ `validate` then has to disagree about.
254
+
255
+ ### `setup --format json` could corrupt its own output
256
+
257
+ `setup` replaced `process.stdout.write` with a capture and restored the function it had captured on
258
+ entry. A nested generate with an `async` hook installed the hook diversion inside that window, so
259
+ `setup`'s restore ran first and removed it — the hook's `console.log`, after its first `await`, went
260
+ straight to the real stdout — and the hook's restore then put back `setup`'s *finished* capture.
261
+ Every later write in the process was appended to a dead string and silently discarded.
262
+
263
+ Both borrow stdout and neither can own it, so there is now one router, installed at most once and
264
+ released by reference counting, consulting two `AsyncLocalStorage` scopes.
265
+
266
+ The same function also merged a failed nested generate in as `manifest`: `{ setup, manifest: { error } }`
267
+ came out with exit code 1 and no top-level `error`. The failure is now at the top level.
268
+
269
+ ### A transient lock on the old snapshot could cost the new one
270
+
271
+ `fs.rmSync(backupDir)` ran inside the `try` whose `catch` restores the previous snapshot. `rmSync`
272
+ throws EPERM or EBUSY on Windows and on network filesystems when an indexer, an antivirus or an
273
+ editor holds a handle in the old snapshot — and by then `outDir` already holds the new one. The catch
274
+ deleted the new snapshot, restored the old one and rethrew; the retry then failed with ENOENT
275
+ because the staging directory no longer existed. Removing the backup is no longer part of the
276
+ transaction.
277
+
278
+ ### Two runs could take two different lock files
279
+
280
+ `realpathSync(stagingRoot)` was used when the root existed and the unresolved path when it did not —
281
+ and the run creates the root *after* taking the lock. On macOS, where `/var` is a symlink to
282
+ `/private/var`, process 1 hashed `/var/folders/…/snapshot.tmp` and process 2, starting once the
283
+ directory existed, hashed `/private/var/…`: two locks, no mutual exclusion, two concurrent writers.
284
+ The key now resolves the nearest existing ancestor. Reclaiming a stale lock also re-checks the file's
285
+ identity immediately before unlinking it, so two runs that both find the same dead lock cannot
286
+ delete each other's.
287
+
288
+ ### The MCP worker ran the hook the docs say it does not
289
+
290
+ `docs/mcp.md` tells the reader that `hooks.afterGenerate` does not run for a generation started from
291
+ MCP. It did: the worker resolved the config file with its hooks intact, so an after-generate script
292
+ ran from inside an MCP tool call, and a hook still running when the worker posted its result kept
293
+ the thread alive for as long as the server did. The worker now empties `hooks` before resolving, and
294
+ is terminated as soon as the result is settled.
295
+
296
+ ### A byte-order mark in `package.json` broke four readers
297
+
298
+ `findConfigFile` reads `package.json` through `stripJsonComments`, which drops a BOM, so `generate`
299
+ loaded a BOM'd project happily. Every other reader used bare `JSON.parse`, which throws on `\uFEFF`,
300
+ and every one of them caught the throw and reported the ordinary, wrong answer: an existing
301
+ `"snapshot"` block was invisible, `"type": "module"` was invisible, the scripts and devDependency
302
+ were skipped with a note, and `nextStepHint` told the user to run `npx codebase-snapshot generate` —
303
+ which resolves the *published* package instead of the one the run had just installed. The
304
+ `npm create` shim had the same bug in `hasSnapshotScript`.
305
+
306
+ A BOM is what a Windows editor writes when it saves UTF-8. All five readers now parse the same way
307
+ the config loader does, and `init` writes the mark back rather than silently removing it.
308
+
309
+ ### `validate` could not name seven of the settings it compared
310
+
311
+ `maxPartTokens`, `maxMonolithBytes`, `skeleton`, `sarif`, `changedSince`, `staged` and
312
+ `withDependents` were recorded in the manifest and folded into the configuration digest, but never
313
+ joined the field-by-field block. The digest can say *that* something changed; only the per-field
314
+ comparisons say *what*. Toggling `--skeleton` produced the generic "the settings differ" line and
315
+ nothing else.
316
+
317
+ ### A `.vue` or `.astro` script block was always parsed as `.ts`
318
+
319
+ `<Button onClick={() => go()}>` is a type assertion followed by six parse errors to the TypeScript
320
+ grammar, and no component at all, for a perfectly valid Vue `lang="tsx"` block. The script kind now
321
+ follows the component: Astro frontmatter is JSX-capable by construction, and a Vue or Svelte block
322
+ says so with `lang="tsx"`.
323
+
324
+ ### Performance
325
+
326
+ - **The split loop re-rendered every part on every pass.** `partitionFilesForBuckets` renders all
327
+ groups, finds the first one over budget, splits it, and goes round again — up to 64 times. Each
328
+ pass re-assembled, re-token-estimated and SHA-256 hashed *every* part. A group's rendered size
329
+ depends on its sections, its index and the *width* of the numbering, and the width only changes
330
+ when the part count crosses 1 000, so sizes are now measured instead of rendered and cached per
331
+ group. Each part is hashed exactly once.
332
+ - **The skeleton pass parsed with `setParentNodes: true`** and walked every node a second time to set
333
+ `.parent`, which nothing reads. It also expanded empty bodies from `{}` to `{ /* ... */ }`, making
334
+ small files larger, and rewrote the text once per span — 400 functions copied a 200 KB file 400
335
+ times.
336
+ - **`fullContents` retained every file body on runs that wrote no monolith.** The map held a
337
+ reference to every pre-partition body and was read only inside `if (config.includeMonolith)`,
338
+ pinning the multi-megabyte originals that the partitioner had just replaced with previews.
339
+ - **31 regexes were recompiled for every file.** `scanAndRedactSecrets` called `toGlobal` per rule
340
+ per call, and it is called once per file: a 20 000-file scan built 620 000 identical objects.
341
+ - **`--watch` re-derived the whole repository for one changed file.** The derivation — redaction,
342
+ findings, skeleton, preview, summary — is a pure function of (bytes, settings, path), so it is now
343
+ cached and reused when the content hash and a settings digest both match. Validity is the **content
344
+ hash**, not `mtime`: a formatter or a `git checkout` can rewrite a file within the same timestamp
345
+ tick at the same length. Measured on a synthetic 250-file TypeScript repository: cold 520 ms, warm
346
+ 196 ms of wall clock (2.65x) — the remainder is reading, hashing, partitioning and writing, which
347
+ a per-file cache cannot remove. The suite asserts the *work* instead, in CPU time on a denser
348
+ fixture: 1 046 ms against 48 ms, 21x, against a 3x floor.
349
+
350
+ ### What has no test, and why
351
+
352
+ The last two are structural. The regex cache and the `fullContents` change have no behavioural
353
+ signal — the output is byte-identical by construction — so they are covered by the existing suite
354
+ and by the reasoning above rather than by a new test. The `--watch` cache is different: four of its
355
+ five tests are correctness guards that pass on the previous build (that is the requirement — the
356
+ cache must be invisible), and the fifth measures the CPU time the cache saves and fails without it.
357
+
358
+ ---
359
+
360
+ ## 0.9.13
361
+
362
+ A fourth audit, this time of the seams: places where two code paths answer the same question with
363
+ different rules, and places where a command accepts something it does not apply. Every item below
364
+ has a test that fails without it, except one — the per-layer budget overflow, which I could not
365
+ reproduce and which is called out honestly at the end.
366
+
367
+ ### A scoped snapshot could expire and still validate
368
+
369
+ `validate` re-resolves the recorded changed-files scope and checks that every file it *skipped* as
370
+ `unchanged` is still outside that scope. It never asked the mirror question. So:
371
+
372
+ ```bash
373
+ git add src/a.ts
374
+ codebase-snapshot generate --staged # snapshot holds src/a.ts
375
+ git reset HEAD src/a.ts # same bytes on disk, nothing staged
376
+ codebase-snapshot validate --staged # said: "Snapshot is valid and up to date"
377
+ ```
378
+
379
+ The file on disk is byte-identical, so the hash comparison passed — and the scope the snapshot was
380
+ taken over had silently become empty. A file that is in the snapshot and would not be if it were
381
+ generated now is drift, and it is now reported, with `--with-dependents` still allowing for the
382
+ one-hop importer exception.
383
+
384
+ ### A part name in `manifest.json` could reach any file on the host
385
+
386
+ `validate` has confined part filenames since 0.9.9, but the **MCP server** resolved
387
+ `parts[].filename` with a bare `path.resolve`, in `snapshot_read` and in the `snapshot://parts/{n}`
388
+ resource. A repository under review could commit a manifest naming `../../../.env`, and a client
389
+ would read it — resource reads are auto-approved as read-only. A part name is bare by construction,
390
+ so `describeManifestShapeProblem` now requires one, which makes all five readers (`validate`,
391
+ `report`, `diff`, `snapshot_read`, the resource) refuse the same manifest for the same stated
392
+ reason.
393
+
394
+ `snapshot_explain` had the mirror problem. `toRelativePath` resolved *after* its "is it absolute?"
395
+ test and `normalizeTarget` returned anything starting with `..` unchanged, so `../other-repo/.env`
396
+ was joined to the root and passed to `existsSync`: one read-only, auto-approved call per probe, for
397
+ any path on the machine. Out-of-root targets now answer `outside-root` without touching the
398
+ filesystem. A file named `..foo.ts` is no longer mistaken for a traversal.
399
+
400
+ ### Four credentials that looked like code
401
+
402
+ - `password: "${DB_PASSWORD:-hunter2}"` — the shell and Compose idiom for a **default** — was
403
+ exempted as "an interpolation" because it starts with `${` and ends with `}`. So was
404
+ `${prefix}-real_secret-${suffix}` and any value with a `??` fallback. Only a value that is one
405
+ interpolation of a plain (optionally dotted) reference is exempt now; anything else in the braces
406
+ settles it the other way.
407
+ - `export api_key=hunter2` — bare `export` was in `DECLARATION_KEYWORDS`, so a shell assignment was
408
+ read as a JavaScript binding whose initializer is an expression. `export` can never be followed by
409
+ a bare assignment in JS or TS (`export foo = 1` does not parse), so the word only ever suppressed
410
+ redaction for the files most likely to hold a secret.
411
+ - An **indented, unterminated** private key — `privateKey: |` in YAML, or an indented template
412
+ literal — leaked every body line. The rule required base64 at column 0 and knew nothing about the
413
+ RFC 1421 header lines (`Proc-Type`, `DEK-Info`) that an encrypted key puts after the marker.
414
+ - A masked key block in a **CR-only** file swallowed its line breaks, because pass 1 counted `\n`
415
+ only, so every reported line number after it was wrong.
416
+
417
+ `.github/workflows/deprecate.yml` and `unpublish.yml` interpolated `${{ inputs.… }}` straight into
418
+ `run:` in jobs that carry `NPM_TOKEN`. GitHub expands an expression into the script *before* bash
419
+ parses it, so a dispatch input of `"; curl … $NODE_AUTH_TOKEN #` ran as a command. Inputs now arrive
420
+ through `env:` and are referenced quoted.
421
+
422
+ ### Two enumerations, two answers
423
+
424
+ The same repository produced different snapshots depending on `--discovery`, which is the one
425
+ property a reproducible snapshot tool cannot have:
426
+
427
+ - A tracked **file symlink** was dropped as `symlink` in `git` mode — the loop tested
428
+ `depth <= parts.length`, which includes the candidate itself — and emitted as a file by the walk.
429
+ - A **broken** symlink was `symlink` in `git` mode, because `targetReal` started at the link's own
430
+ path and so always compared as "inside the root". It is `read-error`, or `outside-root` when its
431
+ written target leaves the tree, in both modes now.
432
+
433
+ The output directory's crash leftovers had the same shape: the backup and partial-swap directories
434
+ were recognised by the hardcoded prefix `snapshot.backup-`. With `outDir: ".context"` an interrupted
435
+ run left `.context.backup-<pid>-<ts>` — a copy of the previous snapshot — to be scanned back in as
436
+ user source. The names now come from the resolved output and staging directories. `--watch` also
437
+ matched only `.backup-`, and only the directory itself, so an event for `part-001.md` *inside* a
438
+ `.partial-` copy was treated as a source edit: on a cross-device swap that is an infinite
439
+ regeneration loop.
440
+
441
+ ### The index described files that were not there
442
+
443
+ - `summarizeMarkdown` called a leading `---` a front-matter block if *any* later line was `---`,
444
+ so a document opening with a horizontal rule and using another as a section divider lost every
445
+ heading between them. The block must now also *be* YAML — a heading, a fence or prose means the
446
+ `---` was a rule. `...` closes a YAML document as well as `---`.
447
+ - The JSONC reader in `src/ast/structured.ts` ended a `//` comment only at `\n` and never removed a
448
+ trailing comma, so a `.jsonc` or an editor-reformatted `tsconfig.json` summarised as
449
+ `invalid-json` with no keys. Both are JSONC rather than extensions of it.
450
+ - `summarizeTypeScriptSource` looked at `ImportDeclaration` and `ExportDeclaration` and nothing
451
+ else, so `require("./x")`, `import("./x")` and `import fs = require("fs")` produced no import
452
+ edge. A CommonJS project had no import graph at all, and `--with-dependents` had nothing to walk.
453
+ `export { a } from "./x"` was not recorded as a re-export either.
454
+
455
+ ### Flags that were accepted and not applied
456
+
457
+ - `--only-artifacts audit` in a project whose config says `artifacts: { audit: false }` disabled the
458
+ other six and left audit off too: nothing written, exit 0. The flag was forwarded only as its
459
+ complement, and a suppression list cannot switch anything on.
460
+ - `findConfigFile` parsed `package.json` with bare `JSON.parse` while the loader used the JSONC
461
+ reader, so a BOM or a trailing comma made the two disagree about whether the project was
462
+ configured. And `"snapshot": []` counted as this tool's configuration, which skipped the setup
463
+ question entirely.
464
+ - `--skeleton` covered `.ts`, `.tsx`, `.mts` and `.cts` while `ts.createSourceFile` parses `.js`,
465
+ `.jsx`, `.mjs` and `.cjs` natively — so the files most repositories are made of were the ones it
466
+ could not compress, and `.d.ts` files, which have no bodies, were the ones it did parse.
467
+ - Over MCP, `WorkspaceOverrides` accepted only `maxPartBytes` and `outDir`. `snapshot_validate`
468
+ re-derives the configuration and compares digests, so a `--skeleton` snapshot could not be
469
+ validated at all. `maxPartTokens`, `skeleton`, `sarif`, `changedSince`, `staged` and
470
+ `withDependents` are now accepted by `snapshot_plan`, `snapshot_generate`, `snapshot_validate`
471
+ and `snapshot_explain` — schema and application coming from one definition, so a tool cannot
472
+ advertise a flag it would ignore.
473
+ - `npm create codebase-snapshot -- --preset=nextjs` ignored the preset: the shim parsed `argv` with
474
+ `indexOf`, which finds nothing for `--flag=value`, treats a missing value as "not given", and
475
+ ignores `--forse` entirely. `node:util.parseArgs` in strict mode now rejects all three by name.
476
+
477
+ ### Configuration answers that disagreed with each other
478
+
479
+ - `loadConfigFileDetailed` did not attach `CONFIG_DIR_SYMBOL` — only `loadConfigFile` did — so
480
+ `resolveConfig((await loadConfigFileDetailed(dir)).config)` scanned `process.cwd()`.
481
+ - `normalizeResolvedConfig` re-derived `artifacts` with `includeMonolith` as the default, so
482
+ `{ ...resolved, includeMonolith: true }` produced a config claiming `includeMonolith: true`
483
+ beside `artifacts.monolith: false`, and `generate` — which reads the map — wrote no monolith.
484
+ - `configDigest` hashed `budgets` with `JSON.stringify`, which preserves insertion order, so
485
+ `{ docs, api }` and `{ api, docs }` produced different digests and `validate` reported drift for
486
+ a snapshot nobody changed.
487
+
488
+ ### Cost
489
+
490
+ - `pathScanRules` returned `[...DEFAULT_SECRET_PATTERNS, ...extraRules]` although
491
+ `config.secretRules` already begins with those patterns: every file path, skip record and AST
492
+ summary string ran all 30 built-in rules twice. `disableDefaultPatterns` also had no effect on
493
+ paths while it worked on content.
494
+ - `globToRegExp` and `matchGitignorePattern` compiled a fresh `RegExp` per call — over a million per
495
+ run on a 20 000-file repository with 55 patterns. Both are cached by pattern. A malformed
496
+ character class no longer escapes as a raw `SyntaxError`: a `.gitignore` range like `[z-a]`
497
+ matches nothing (which is what git's own `fnmatch` does), while the same range in a configured
498
+ glob is reported as the configuration mistake it is, naming the pattern.
499
+ - `generateSnapshotAsync` resolved the configuration twice, and `validate` in the CLI re-read and
500
+ re-parsed `manifest.json` to re-run a shape check the validator had already run.
501
+ - `pendingHooks` was drained only by `generateSnapshotAsync`, so a synchronous caller left one
502
+ settled promise per output directory for the life of the process.
503
+
504
+ ### Lifecycle
505
+
506
+ - Each `hooks.afterGenerate` installed its own `process.stdout.write` wrapper and restored it only
507
+ if the current write was still its own. With two overlapping async hooks the first to finish never
508
+ restored, and the second put the first one's wrapper back — permanently. There is now one scope
509
+ and one wrapper, released by reference counting.
510
+ - The update check used `request.setTimeout`, an *idle socket* timeout that resets on every chunk:
511
+ a trickling proxy kept the CLI alive indefinitely. It has a wall-clock deadline now, `.unref()`d
512
+ so a pending check never holds the process open. And `isNewer` stripped prerelease tags before
513
+ comparing, so `0.9.13-alpha.1` was recommended to everyone on a stable release and a stable
514
+ release was never announced to anyone on a beta.
515
+
516
+ ### Smaller
517
+
518
+ - `wrapOneLine` measured `room` in terminal cells and cut with `String.prototype.slice`, which
519
+ counts UTF-16 code units. CJK text produced rows twice as wide as the frame believed, and a
520
+ surrogate pair could be cut in half. The cut advances by code point now.
521
+ - Part numbering is decided **before** rendering, in one pass over every budget bucket, instead of
522
+ partitioning each budget and re-numbering the merged set afterwards.
523
+
524
+ ### What I could not reproduce
525
+
526
+ The audit reported that per-layer budgets caused parts to overflow their budget by seven to twenty
527
+ bytes when `renumberParts` rewrote their headers, and were then hard-clipped into a broken document.
528
+ **I could not make that happen.** I swept file sizes against a two-budget configuration and again
529
+ with six layers and eight kinds whose names are 180 characters long, and no part ever came out over
530
+ its budget, with or without the clamp. The arithmetic explains why: `partitionFiles` reserves about
531
+ 2.2 kB of header room up front and shrinks sections to `budget - reserve`, so a rendered part sits
532
+ roughly 1.4 kB below its ceiling, and the header growth being reported is fourteen bytes.
533
+
534
+ The mechanism was removed anyway — the numbering pass now happens before rendering, so a fitted part
535
+ cannot be rewritten — but the claim was not verified, and this changelog will not pretend it was.
536
+ The four tests added with it pass on the previous build too; they pin the invariants the refactor
537
+ must not break rather than reproducing a defect.
538
+
26
539
  ## 0.9.12
27
540
 
28
541
  A third audit, this time of what the snapshot *costs* as well as what it gets wrong. Two of the
package/README.md CHANGED
@@ -31,7 +31,7 @@ with a manifest and a validator](https://raw.githubusercontent.com/ankurhalder/c
31
31
  <p align="center">
32
32
  <a href="#install">Install</a> ·
33
33
  <a href="#quick-start">Quick start</a> ·
34
- <a href="#built-to-be-trusted">Trust</a> ·
34
+ <a href="#built-to-be-trusted-with-a-whole-repository">Trust</a> ·
35
35
  <a href="#for-ai-agents">AI agents</a> ·
36
36
  <a href="#documentation">Docs</a> ·
37
37
  <a href="https://ankurhalder.github.io/codebase-snapshot/">Site</a>
@@ -200,7 +200,7 @@ Everything an agent needs is available as data, and the tool can install its own
200
200
  ```bash
201
201
  npx codebase-snapshot describe --format json # contract: workflow, options, exit codes
202
202
  npx codebase-snapshot skill --install # into .claude/skills + .cursor/rules
203
- npx -y codebase-snapshot@0.9.12 mcp # or serve it over MCP
203
+ npx -y codebase-snapshot@0.9.15 mcp # or serve it over MCP
204
204
  ```
205
205
 
206
206
  An agent told only "use `npx codebase-snapshot`" can read the contract, follow its ordered
package/SECURITY.md CHANGED
@@ -40,11 +40,29 @@ secret deliberately split across two string literals, joined with a backslash li
40
40
  continuation, or assembled by template-literal concatenation can be missed, because the
41
41
  pattern never sees the whole value on one line.
42
42
 
43
- In YAML and similar `key: value` files, an **unquoted** value that reads like an expression is
44
- treated as code rather than as a literal and is not masked: `password: opts.db.password` and
45
- `password: my.secret.value` are emitted as written, and so is a value that starts with
46
- punctuation, such as `token: !hunter2hunter2`. Quote the value — `password: "…"` — to have it
47
- redacted; a plain unquoted value with no dots or leading punctuation is masked.
43
+ In YAML and similar `key: value` files, the file type decides how an **unquoted** value is read.
44
+ A strong credential name in colon form — `password:`, `token:`, `api_key:` — makes the rest of
45
+ the line a value, and in a data or shell file that value is masked whole whatever symbols it
46
+ holds: `password: pa&ss` and `password: getPassword() & 0xff` are masked in a `.yaml`, while the
47
+ same lines in a `.ts` are left as written, because there they are expressions and the tool does
48
+ not edit expressions. In a source file a value that reads like a reference —
49
+ `password: opts.db.password` — is emitted as written; an unquoted value in a declaration is an
50
+ initializer, not a credential.
51
+
52
+ A punctuation-led value is masked when the token also carries a digit or a second punctuation
53
+ character — `token: !hunter2hunter2` is masked, while YAML tags such as `!Ref` and prose words such
54
+ as `!important` stay readable. Quote the value — `password: "…"` — when you need certainty: a
55
+ quoted value under a credential-shaped name is masked whatever it contains.
56
+
57
+ In a data or shell file a **colon-form** assignment is masked whole even when a symbol would make
58
+ the value impossible to bound — it runs to the end of the line (a trailing `#` comment is kept, and
59
+ the match is capped at 300 characters). In source code such a match is dropped instead, so no
60
+ marker is written in front of an expression. The `.env`/shell `NAME=value` rule also masks its
61
+ whole value, comment aside. The `=` form follows the same rule by file type: in a data or shell
62
+ file, a key whose name ends in a credential word — upper or lower case, `password`, `client_secret`,
63
+ `access_key`, `apiKey` — masks the whole value whatever symbols it contains; in source code the
64
+ same line is left alone unless it matches an existing source rule, and a key that merely contains a
65
+ credential word (`tokenCount`, `secretary`) is not a credential.
48
66
 
49
67
  A clean audit is therefore evidence that the known patterns did not fire — not a guarantee
50
68
  that the repository holds no credentials.