Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(secret-scan): one-pass correctedEntropy, ScanWork counters, allowlist peeled to its own module

garrytan3764b7bde27e
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.md
index 88a9b58d86..f12f41fd01 100644
--- a/docs/architecture/key-files/agent-bootstrap-continued.md
+++ b/docs/architecture/key-files/agent-bootstrap-continued.md
@@ -27,7 +27,7 @@
- `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: the `DELEGATED_SYNC_OPTION_FIELDS` table is the single source of truth for the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). #6317 (D1 a′), managed Postgres brains: `maybeDelegateManagedSyncToServe(engine, args, opts)` runs post-connect from `runSingleSourceSync` right before `performSync`; it probes the host's live full `serve` consumer through `persistence_consumers` (`consumer-heartbeat.ts`, the database, never a socket), admits the catch-up's flags (`--no-bulk`, `--lanes`/`--no-lanes`, `--json`, the processing flags), sends the CLI's durable `cli` registration in `sync_start`, prints the drain's own numbered lines from `sync_status` (`managed`, `lines`, `drain`, `next`) and returns the SyncResult to the in-process printers, so exit codes and the JSON envelope do not change. The serve verifies the registration (`withVerifiedLocalRegistration`) and runs `performSync({ drain: true })` as that writer under `withHumanLineSink`; the shared-secret lane stays under `withLegacySyncDelegation` and is still refused on a managed brain; a denied, revoked or stdio registration answers `sync_start` with `permission_denied` and the envelope (`refusal`), which the CLI rethrows. Every other rung (no owner, a non-serve owner, an unsupported flag, no socket, the kill switch, `stale_serve` / `unsupported_kind` from an older serve, `source_mismatch`, a serve lost mid-drain) keeps the CLI's own consumer with one actionable line. Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/serve-sync-handoff.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step) and `test/e2e/serve-delegated-managed-sync.serial.test.ts` (Postgres, spawned serve, MCP latency printed).
- `src/core/capability.ts` — config-plane keyless/keyed detection + the honest capability report (per-provider keyless banner: OpenAI = semantic search + auto-extraction, Voyage = semantic search, Anthropic = auto-extraction) rendered by verify and the runbook. The extraction probe resolves through the SAME shared `resolveEffectiveChatModel` the gateway's reconfigure fallback uses (`GBRAIN_MODEL` > servable file pin > key-aware tier default), so a stale unservable pin degrades identically in the report and at runtime. Key/env fold comes from `mergedProviderEnv` (`src/core/ai/provider-env.ts`). Accepted limitation (documented in the module): DB-plane overrides (`models.default`, `facts.extraction_model`) are invisible to this engine-less probe; the runtime gate in `facts/extract.ts` and the engine-aware pre-enqueue gate in `facts/backstop.ts` are the backstops.
- `src/core/readiness.ts` — capability readiness (agent operator contract A7): `ReadinessEntry {capability, state, reason, why, fix, tier, asset?, http_visible}` for embeddings, chat_llm, writeback, tool_surface, sync, harness_wiring (config tier) and worker, backup per asset, migrations, sync (probed tier); each capability's reasons are a closed exported const (`EMBEDDINGS_REASONS`, …). `configReadiness(cfg, {transport})` is synchronous and memoized per (config object, transport); its only file read is one memoized `peekLock()` (none when this process holds the lock, via `heldLockFor`), plus one process-wide gbrain-binary PATH lookup on the CLI transport only. The HTTP view drops `http_visible:false` entries and passes the rest through `redactForTransport`. `probedReadiness(engine, {cache})` never calls `getStats`/`getHealth`; 60 s cache (`createReadinessCache()` per ServeHttpContext, process-wide otherwise), single-flight, 2 s per-probe bound, stale-while-revalidate; `readinessTail` is MCP initialize's best-effort 250 ms tail. `embeddingEnablement(cfg)` is the one "turn on embeddings" fix: resolves the datastore (PGLite path, Postgres, a mount from `--brain`/`GBRAIN_BRAIN_ID`) and the column width, picks a keyed provider that fits (or asks for a key with `inputs`), and emits in-place `init --force --embedding-model … --embedding-dimensions … [--path …]` or, for a mount, `embeddings enable --brain …`; it never rebuilds a column. `exclusiveFix` turns an exclusive fix into a two-step plan (actor `user` stops the owning serve named by `lock_owner`, `then` the command) unless the command delegates to the owner. A live status-only `serve --http` marker (`liveStatusMarkers`, config plane) makes CLI `harness_wiring` `serve_status_only` with `transport: 'http'` and the status reason's fix (`httpStatusServerEntry`, shared with doctor), never "start `gbrain serve --http`" on the port it holds. `harnessWiringEntry` builds harness-native stdio registration (absolute binary, `stdioServeArgv` with `REGISTRATION_SURFACE` = `starter`, or `input.surface` from `gbrain init --surface`; `configReadiness(cfg, {transport, surface})` skips the memo when a surface is passed), shared-HTTP `bootstrap harness`, or the MEMORY_VERBS install anchor, with effects and destinations disclosed. Consumers never coach on `disabled_by_choice`. Tests: `test/readiness.test.ts`, `test/readiness-http-cost.test.ts`, `test/readiness-advice-lint.test.ts` (no hand-written enablement advice outside this module; shrink-only baseline), `test/readiness-embedding-enablement.serial.test.ts` (the E2E matrix).
-- `src/core/secret-scan.ts` — pattern-based secret detection shared by `sources push`, bootstrap verify, the compiled-context sensitivity scan and the transcripts redactor. Detection is FORMAT-based, not prefix-only: vendor shapes (anthropic, openai, voyage, github, gitlab, slack, aws AKIA/ASIA, google, stripe, sendgrid, twilio, supabase sb_secret_/sbp_, npm, huggingface, `digitalocean` `do[opr]_v1_` + 64 hex, gbrain), JWTs, private keys (whole-text claims, below), plus four catch-alls appended LAST (`bearer` — prebuilt two-group layout so only the token is the value; `db_url_credentials` — the `scheme://user:pass@` span of database URLs, host/db kept; `url_credentials` — the same span for `http(s)` (scheme case-insensitive, `gi`), user 0–128 stopping at `:`/`/`, password 1–256 excluding whitespace, `@`, `"`, `'`, `/`, `?`, `#`, with a `validate` hook that rejects placeholder passwords (`<...>`, `${...}`, `$VAR`, all `*`, all `x`); `basic_auth` — two prebuilt case-insensitive forms, `Authorization: Basic` with a 4–2048 char value and bare `Basic` with 16–2048, both with a hard right edge and a `validate` that requires the value to base64-decode to printable ASCII containing `:`; it is NOT in the bearer family, so it joins neither the echo dictionary nor `secret:bearer`). The pattern contract: `CorePattern` carries optional `flags` (default `'g'`), `precheck`, `validate(value)` (O(value), run on the whole match before the claim and the union split; a rejected match is not re-tried from inside) and `since` (the gbrain version that added or last changed the rule; `SECURITY_WAVE_SINCE` = `0.60.31.0` on `digitalocean`, `url_credentials`, `basic_auth` and `private_key_pem`, kept in step with the release that ships a rule change). Compiled patterns keep group 1 = anchor, group 2 = value. `patternSince(pattern)` reads the map; every finding of such a pattern carries `SecretFinding.since`, which the push and bootstrap refusals render. Fixed-length shapes carry a trailing negative lookahead. Per-line claimed-span dedupe is first-wins for ATTRIBUTION (order matters: `Bearer <vendor key>` keeps the vendor name, a fully covered later span is skipped) but coverage is the UNION: every unclaimed slice of a later overlapping span is claimed as a hit of the later pattern (own value, own fingerprint), so a database URL whose username is a vendor-shaped id still loses its password. The transcript-only `labeled_credential` rule (`ScanOpts.labeledCredentials`) lives in `secret-scan-labeled.ts` (Security). The opt-in `high_entropy_assignment` rule (`ScanOpts.highEntropy`) requires a 12+ char value that contains a digit and a non-digit AND clears 3.5 bits/char on the bias-corrected (Miller-Madow) estimate `correctedEntropy`, since raw per-character entropy is capped at log2(n) and rejected most random 12-16 char secrets. It is two compiled patterns sharing the name: QUOTED (after `"` or `'`, any run of non-quote, non-whitespace characters) and UNQUOTED (the legacy `[A-Za-z0-9+/_=-]` class plus `!#$%*@^~.?<>`; never `&`, `()[]{}`, `:`, `,` or `;`, so query strings, calls and SQL `SET` lists stay intact, and a password carrying `,`/`;` matches only quoted; the last character excludes `.?!`, so a sentence's full stop is not claimed). Its `validate` rejects values that start with `scheme://`, `./`, `~/`, `${`, `$(` or `<REDACTED:`, dotted identifier paths (`process.env.X`) and `/`-paths holding a character outside the legacy class. Consumers with it on: retrieval output, transcript ingest, hooks and the hook heartbeat, the atoms drain, `embed-facts.ts` error text and the context-engine relay re-scan. Off: the push gate, bootstrap verify/repo and the compiled-context sensitivity scan. Own minimal allowlist + `<ws>/.gbrain-scan-allow` per-finding overrides — deliberately NOT the repo's `.gitleaks.toml` (a public-repo CI fixture policy). Deliberately NOT patterns: `sb_publishable_`, Supabase project refs (identifiers, not credentials). Never spell a literal database or `http(s)` URL with userinfo, or any credential, in this file's comments or in fixtures (assemble test values at runtime; `scripts/check-pg-url-redaction.sh` greps `src/` for every `db_url_credentials` scheme). Long lines are scanned in full (no length cap — a secret on a 1 MB minified line must still redact); what keeps that linear is bounded quantifiers on every shape whose value class could otherwise run to end-of-line — `db_url_credentials` (user ≤128 stopping at `:`/`/`; password 1–256 stopping only at whitespace, `@` and the string delimiters `"`/`'`, so unescaped `/ { } < > | ^ \` and backtick passwords redact), `jwt` (prebuilt so its boundary excludes `-` as well as `_`; segments ≤4096), `high_entropy_assignment` (≤64 identifier chars after the keyword, value ≤4096), `url_credentials` (user ≤128, password ≤256), `basic_auth` (value ≤2048, so its decode is constant work) and the private-key walks (below) — plus a per-pattern `precheck` substring gate on the catch-alls (`@` for both URL patterns; `earer`/`EARER`, since an all-caps `BEARER` scheme is accepted; a case-insensitive `basic`), a carried next-newline position in `scanPemBlocks` (sticky -1, so the header-line count is O(text) even when thousands of hits sit ahead of a newline-free multi-megabyte tail), a lazily-allocated per-line claimed-char bitmap behind the first-wins dedupe (O(value) per hit), and a windowed `buildPreview` (whole line ≤160 chars; otherwise hit−40…+80, edges snapped outward to whole spans, every claimed span in the window spliced by position, so a preview never carries a sibling secret or a fragment). `redactFindings` (= `planRedaction` + `applyRedaction`) rebuilds the text by SPAN-SPLICE in one O(text + hits) pass over the claimed spans, and fills the UNCLAIMED gaps with a bounded echo pass: the values claimed by `bearer` and `high_entropy_assignment` form an echo dictionary (value → pattern; floors `ECHO_MIN_CHARS_BEARER` = 20 / `ECHO_MIN_CHARS_ENTROPY` = 12, values ≤ `ECHO_MAX_VALUE_CHARS` = 512, the first `ECHO_MAX_UNIQUE` = 64 unique values in claim order across BOTH patterns — a value past either cap is redacted at its claim, its echoes are the accepted miss), matched by a streaming merge over the ORIGINAL text — per value, the next occurrence at or beyond the emit cursor (`indexOf` resuming at the cursor, re-sought only once the cursor passes it), leftmost-longest at each step, emitted incrementally into the unclaimed gaps — so retained state is O(values) however long the text is (occurrences are never collected into a list) (never an alternation RegExp, never over emitted tokens). Echoes add no findings. `planRedaction` feeds a caller-supplied shared map (`RedactOpts.echoValues`) and `applyRedaction` reads it at apply time, so a multi-field document scrubs an echo in one field of a value claimed in another. Every other pattern redacts exactly what `scanText` reports (a value embedded past its boundary is left as-is; vendor shapes re-match on their own). PRIVATE KEYS: `pemClaims` finds `BEGIN`/`END … PRIVATE KEY` fences in two global passes and merges them in text order. BLOCK: a BEGIN whose next fence is an END within `PEM_BODY_MAX_CHARS` (16384) is claimed header through END; a block never swallows a later BEGIN. FORWARD (BEGIN with no END in view): the header plus the body lines that follow; a header followed by no body line (a marker quoted in prose) is claimed alone. BACKWARD (END with no BEGIN in view): the body lines before the fence plus the fence; an END with no body line before it is no claim. A body line is a whole-line base64 run (`A-Za-z0-9+/=`) indented by up to 16 spaces/tabs; line ends are `\n`, `\r\n` or the literal JSON escapes; interior lines are 16–128 chars, the line next to a fence and a partial line at a cut 1–128; optional RFC 1421 `Proc-Type:`/`DEK-Info:` lines and one blank line may follow BEGIN; a line with anything else, or a run over 128 chars, ends the body. Total claimed body stays within `PEM_BODY_MAX_CHARS`. Each walk stops at the neighbouring fence or the previous claim, so the pass is linear (20k unterminated BEGINs, 20k END-only fences and 1 MB of base64 lines are perf-pinned). Per-line hits that fall wholly inside a key claim are dropped (one key, one finding). A FORWARD claim's finding also carries `legacyFingerprint`, the header-only fingerprint earlier releases reported, so `workspace-push.ts` can name a stale allowlist entry; a truncated key's fingerprint covers its body and therefore depends on where the text was cut, so it is not a stable allowlist key. `privateKeySpans(text)` exports the same claims as sorted, disjoint `{start, end}` spans. Accepted misses: body on the header's own line, space-joined single-line keys, blockquoted (`> `) keys, base64 runs over 128 chars, body past 16384 chars, `http(s)` passwords containing a literal `/`, `?` or `#`, Basic values over 2048 chars, digitless assignment values, dotted passwords whose every segment starts with a letter, and unquoted passwords containing `,` or `;`. False-positive budget: `scripts/secret-scan-fp-budget.ts` diffs findings against a base ref's scanner (`--base`, default `origin/master`) (`--dir <brain>` reports per-pattern counts only, never content) and `test/secret-scan-fp-budget.test.ts` pins a synthetic brain-like fixture (zero findings on its non-secret part in both modes, every planted secret redacted). Shape tests: `test/secret-scan-credential-shapes.test.ts`, `test/secret-scan-private-key-spans.test.ts`. Perf pins: `test/secret-scan-perf.test.ts`. Retrieval output is another consumer of its canonical scanner; that output boundary does not sanitize internal evaluation/provider inputs.
+- `src/core/secret-scan.ts` — pattern-based secret detection shared by `sources push`, bootstrap verify, the compiled-context sensitivity scan and the transcripts redactor. Detection is FORMAT-based, not prefix-only: vendor shapes (anthropic, openai, voyage, github, gitlab, slack, aws AKIA/ASIA, google, stripe, sendgrid, twilio, supabase sb_secret_/sbp_, npm, huggingface, `digitalocean` `do[opr]_v1_` + 64 hex, gbrain), JWTs, private keys (whole-text claims, below), plus four catch-alls appended LAST (`bearer` — prebuilt two-group layout so only the token is the value; `db_url_credentials` — the `scheme://user:pass@` span of database URLs, host/db kept; `url_credentials` — the same span for `http(s)` (scheme case-insensitive, `gi`), user 0–128 stopping at `:`/`/`, password 1–256 excluding whitespace, `@`, `"`, `'`, `/`, `?`, `#`, with a `validate` hook that rejects placeholder passwords (`<...>`, `${...}`, `$VAR`, all `*`, all `x`); `basic_auth` — two prebuilt case-insensitive forms, `Authorization: Basic` with a 4–2048 char value and bare `Basic` with 16–2048, both with a hard right edge and a `validate` that requires the value to base64-decode to printable ASCII containing `:`; it is NOT in the bearer family, so it joins neither the echo dictionary nor `secret:bearer`). The pattern contract: `CorePattern` carries optional `flags` (default `'g'`), `precheck`, `validate(value)` (O(value), run on the whole match before the claim and the union split; a rejected match is not re-tried from inside) and `since` (the gbrain version that added or last changed the rule; `SECURITY_WAVE_SINCE` = `0.60.31.0` on `digitalocean`, `url_credentials`, `basic_auth` and `private_key_pem`, kept in step with the release that ships a rule change). Compiled patterns keep group 1 = anchor, group 2 = value. `patternSince(pattern)` reads the map; every finding of such a pattern carries `SecretFinding.since`, which the push and bootstrap refusals render. Fixed-length shapes carry a trailing negative lookahead. Per-line claimed-span dedupe is first-wins for ATTRIBUTION (order matters: `Bearer <vendor key>` keeps the vendor name, a fully covered later span is skipped) but coverage is the UNION: every unclaimed slice of a later overlapping span is claimed as a hit of the later pattern (own value, own fingerprint), so a database URL whose username is a vendor-shaped id still loses its password. The transcript-only `labeled_credential` rule (`ScanOpts.labeledCredentials`) lives in `secret-scan-labeled.ts` (Security). The opt-in `high_entropy_assignment` rule (`ScanOpts.highEntropy`) requires a 12+ char value that contains a digit and a non-digit AND clears 3.5 bits/char on the bias-corrected (Miller-Madow) estimate `correctedEntropy`, since raw per-character entropy is capped at log2(n) and rejected most random 12-16 char secrets. It is two compiled patterns sharing the name: QUOTED (after `"` or `'`, any run of non-quote, non-whitespace characters) and UNQUOTED (the legacy `[A-Za-z0-9+/_=-]` class plus `!#$%*@^~.?<>`; never `&`, `()[]{}`, `:`, `,` or `;`, so query strings, calls and SQL `SET` lists stay intact, and a password carrying `,`/`;` matches only quoted; the last character excludes `.?!`, so a sentence's full stop is not claimed). Its `validate` rejects values that start with `scheme://`, `./`, `~/`, `${`, `$(` or `<REDACTED:`, dotted identifier paths (`process.env.X`) and `/`-paths holding a character outside the legacy class. Consumers with it on: retrieval output, transcript ingest, hooks and the hook heartbeat, the atoms drain, `embed-facts.ts` error text and the context-engine relay re-scan. Off: the push gate, bootstrap verify/repo and the compiled-context sensitivity scan. Own minimal allowlist + `<ws>/.gbrain-scan-allow` per-finding overrides — deliberately NOT the repo's `.gitleaks.toml` (a public-repo CI fixture policy); the allowlist block (`loadWorkspaceAllowlist`, the glob dialect `globToRegExp`/`matchesGlob`, `valueAllowlisted`/`pathAllowlisted`, `SCAN_ALLOW_FILENAME`, the 16-hex fingerprint floor) lives in `src/core/secret-scan-allowlist.ts` since wave 16 (G4.1, the 1500-line module cap) and is re-exported here unchanged (`test/secret-scan-allowlist.test.ts`). `correctedEntropy` is one histogram pass (distinct count = histogram size; byte-identical to the former `shannonEntropy + Set` form, `test/secret-scan-entropy-equivalence.test.ts`; ~80 → ~25 ms per 250 × 4096-char segment). `ScanOpts.work` / `RedactOpts.work` takes a `ScanWork` accumulator (`src/core/secret-scan-work.ts`: lines, regex execs, candidates per pattern, chars handed to the entropy gate counted inside `correctedEntropy`, validate calls, claims, union splits, echo sweeps) pinned exactly on the perf fixture by `test/secret-scan-work-counters.test.ts`; the perf file's absolute bounds stay the only guard on per-character cost. Deliberately NOT patterns: `sb_publishable_`, Supabase project refs (identifiers, not credentials). Never spell a literal database or `http(s)` URL with userinfo, or any credential, in this file's comments or in fixtures (assemble test values at runtime; `scripts/check-pg-url-redaction.sh` greps `src/` for every `db_url_credentials` scheme). Long lines are scanned in full (no length cap — a secret on a 1 MB minified line must still redact); what keeps that linear is bounded quantifiers on every shape whose value class could otherwise run to end-of-line — `db_url_credentials` (user ≤128 stopping at `:`/`/`; password 1–256 stopping only at whitespace, `@` and the string delimiters `"`/`'`, so unescaped `/ { } < > | ^ \` and backtick passwords redact), `jwt` (prebuilt so its boundary excludes `-` as well as `_`; segments ≤4096), `high_entropy_assignment` (≤64 identifier chars after the keyword, value ≤4096), `url_credentials` (user ≤128, password ≤256), `basic_auth` (value ≤2048, so its decode is constant work) and the private-key walks (below) — plus a per-pattern `precheck` substring gate on the catch-alls (`@` for both URL patterns; `earer`/`EARER`, since an all-caps `BEARER` scheme is accepted; a case-insensitive `basic`), a carried next-newline position in `scanPemBlocks` (sticky -1, so the header-line count is O(text) even when thousands of hits sit ahead of a newline-free multi-megabyte tail), a lazily-allocated per-line claimed-char bitmap behind the first-wins dedupe (O(value) per hit), and a windowed `buildPreview` (whole line ≤160 chars; otherwise hit−40…+80, edges snapped outward to whole spans, every claimed span in the window spliced by position, so a preview never carries a sibling secret or a fragment). `redactFindings` (= `planRedaction` + `applyRedaction`) rebuilds the text by SPAN-SPLICE in one O(text + hits) pass over the claimed spans, and fills the UNCLAIMED gaps with a bounded echo pass: the values claimed by `bearer` and `high_entropy_assignment` form an echo dictionary (value → pattern; floors `ECHO_MIN_CHARS_BEARER` = 20 / `ECHO_MIN_CHARS_ENTROPY` = 12, values ≤ `ECHO_MAX_VALUE_CHARS` = 512, the first `ECHO_MAX_UNIQUE` = 64 unique values in claim order across BOTH patterns — a value past either cap is redacted at its claim, its echoes are the accepted miss), matched by a streaming merge over the ORIGINAL text — per value, the next occurrence at or beyond the emit cursor (`indexOf` resuming at the cursor, re-sought only once the cursor passes it), leftmost-longest at each step, emitted incrementally into the unclaimed gaps — so retained state is O(values) however long the text is (occurrences are never collected into a list) (never an alternation RegExp, never over emitted tokens). Echoes add no findings. `planRedaction` feeds a caller-supplied shared map (`RedactOpts.echoValues`) and `applyRedaction` reads it at apply time, so a multi-field document scrubs an echo in one field of a value claimed in another. Every other pattern redacts exactly what `scanText` reports (a value embedded past its boundary is left as-is; vendor shapes re-match on their own). PRIVATE KEYS: `pemClaims` finds `BEGIN`/`END … PRIVATE KEY` fences in two global passes and merges them in text order. BLOCK: a BEGIN whose next fence is an END within `PEM_BODY_MAX_CHARS` (16384) is claimed header through END; a block never swallows a later BEGIN. FORWARD (BEGIN with no END in view): the header plus the body lines that follow; a header followed by no body line (a marker quoted in prose) is claimed alone. BACKWARD (END with no BEGIN in view): the body lines before the fence plus the fence; an END with no body line before it is no claim. A body line is a whole-line base64 run (`A-Za-z0-9+/=`) indented by up to 16 spaces/tabs; line ends are `\n`, `\r\n` or the literal JSON escapes; interior lines are 16–128 chars, the line next to a fence and a partial line at a cut 1–128; optional RFC 1421 `Proc-Type:`/`DEK-Info:` lines and one blank line may follow BEGIN; a line with anything else, or a run over 128 chars, ends the body. Total claimed body stays within `PEM_BODY_MAX_CHARS`. Each walk stops at the neighbouring fence or the previous claim, so the pass is linear (20k unterminated BEGINs, 20k END-only fences and 1 MB of base64 lines are perf-pinned). Per-line hits that fall wholly inside a key claim are dropped (one key, one finding). A FORWARD claim's finding also carries `legacyFingerprint`, the header-only fingerprint earlier releases reported, so `workspace-push.ts` can name a stale allowlist entry; a truncated key's fingerprint covers its body and therefore depends on where the text was cut, so it is not a stable allowlist key. `privateKeySpans(text)` exports the same claims as sorted, disjoint `{start, end}` spans. Accepted misses: body on the header's own line, space-joined single-line keys, blockquoted (`> `) keys, base64 runs over 128 chars, body past 16384 chars, `http(s)` passwords containing a literal `/`, `?` or `#`, Basic values over 2048 chars, digitless assignment values, dotted passwords whose every segment starts with a letter, and unquoted passwords containing `,` or `;`. False-positive budget: `scripts/secret-scan-fp-budget.ts` diffs findings against a base ref's scanner (`--base`, default `origin/master`) (`--dir <brain>` reports per-pattern counts only, never content) and `test/secret-scan-fp-budget.test.ts` pins a synthetic brain-like fixture (zero findings on its non-secret part in both modes, every planted secret redacted). Shape tests: `test/secret-scan-credential-shapes.test.ts`, `test/secret-scan-private-key-spans.test.ts`. Perf pins: `test/secret-scan-perf.test.ts`. Retrieval output is another consumer of its canonical scanner; that output boundary does not sanitize internal evaluation/provider inputs.
- `src/core/transcripts/render.ts` — session → conversation page(s) for `gbrain transcripts ingest`. `redactSession` is two-phase over message text, speaker labels, title and every raw-meta string, BEFORE any engine write: `planRedaction(…, { highEntropy: true, echoValues })` on every field into ONE session-wide echo dictionary, then `applyRedaction` per field, so a bearer or high-entropy value claimed in one message is scrubbed where it recurs bare in any other field, in either order; echoes add nothing to `redactionCount` (fail-closed: a scanner/pattern throw aborts the session), then the operator pattern file; nested raw-meta values are dropped. This is the only lane that opts into the entropy heuristic (pasted `.env` lines are most likely here). Rendering shares the imessage-slack anchor regex with the parser and escapes body lines that would forge it; long sessions split into `-pN` parts at message boundaries once a part would pass `PART_TARGET_BYTES` (45,000 bytes, 0.9 × the content-sanity warn line `DEFAULT_BYTES_WARN`; `renderSessionParts(…, { partTargetBytes })` overrides it for measurement and refuses a non-positive or non-integer target). No message is truncated (#6388; the former 4,000-character `MESSAGE_CHAR_CAP` is gone): a message whose block would not fit a part becomes continuation blocks that repeat its speaker and timestamp anchor, cut at line breaks or, inside an over-long line, at a code-point boundary (a cut piece always lands on the generated anchor line, so every body line was escaped whole); overlap repeats only whole messages, never continuation blocks, and is trimmed so no part body passes the target (`test/transcript-long-message-render.test.ts`). `scripts/measure-transcript-split-cost.ts` imports one deterministic synthetic 1 MB session through the real redact → render → `importFromContent` path into in-memory PGLite with a token-counting stub embedder at the former 300,000-byte target and the current one: 4 → 27 pages (×6.75), 380 → 424 chunks (×1.116), 199,614 → 217,057 embed input tokens (×1.087); the extra tokens are the part headers and the two overlap messages repeated at each boundary. Each `RenderedPart` carries the `frontmatter` it owns and its `body`; on re-ingest `runTranscriptsIngest` carries any other key already on the page (a review flag another tool added) onto the re-rendered part, except the re-derived safety and atom-scan markers (#5431, `test/transcripts-retitle.test.ts`). `redactSession` plans every field with `highEntropy` and `labeledCredentials` on.
- `src/core/context/sensitivity-scan.ts` — composed detector for compiled-context entries (secret-scan → PII → path shapes → operator blocklist → operator pattern file). secret-scan OWNS credential-shaped families it also matches: a PII finding whose value (raw, or with the `Bearer ` keyword stripped) matches a secret finding's fingerprint is not reported twice; short bearer tokens under secret-scan's floor still surface as `pii:bearer`. Every family honors the same `.gbrain-scan-allow` fingerprint escape hatch. `formatSensitivityDrop(drop, workspaceRoot)` renders the one content-free stderr line `gbrain compile-context` prints per dropped entry: reason `sensitivity_scan`, the pattern family, the fingerprint and the absolute `.gbrain-scan-allow` path, never the value (`test/sensitivity-scan.test.ts`).
- `src/core/backup/status-file.ts` — ENGINE-FREE core of the monthly backup-coverage check: the cached verdict (`~/.gbrain/backup-status.json`, schema `gbrain-backup-status-v2`, which includes the `connector` asset kind; a cache with any other schema reads as absent and is recomputed; fail-open load, atomic tmp+rename write, `invalidateBackupStatus()` fired by the fix paths — `bootstrap repo` receipt write, `sources harden`, `workspacePush` finish on ok when the cache carried a warn or failing/unpushed totals (a routine healthy push leaves an ok cache alone, preserving the monthly throttle)), the notice renderer (`backupNoticeText(s, 'human'|'aggregate')` — human ≤300 chars names assets, aggregate is counts-only for remote surfaces; the remote-privacy pin), and the bounded nag gate shared by every render channel (`backupNagGate(channel, s)` on `backup-nag-state.json`, OWN schema `gbrain-backup-nag-v1` — skillpack `loadNagState` would drop the extra fields on round-trip, so only the pure policy fns `decideNagAction`/`recordNagDisplay` are reused). Budget = AND of: 24h cross-channel dampener (`last_shown_at`), per-channel ceiling 3 per pseudo-version (`YYYY-MM(checked_at)` + no-remote fingerprint — month rollover or a changed verdict re-surfaces; a same-month recompute with an unchanged verdict stays quiet), and a global cap of 3 recorded impressions per month (`global_shown_count`/`global_month`). `backupNagReadOnlyConsult` is the OpenClaw context-engine's never-writes variant; `backupSpawnDue`/`recordBackupSpawn` debounce the session-end detached spawn (no sidecar file); `maybeEmitBackupNag` is the cli.ts startup rail body (skip set incl. serve/call/jobs; `BACKUP_LOCAL_ONLY <n>` machine marker + human line). Off switches: `GBRAIN_BACKUP_CHECK=0`, config `backup.check_enabled`; interval env `GBRAIN_BACKUP_CHECK_DAYS` > config `backup.check_interval_days` > 30; values <1 or non-numeric fall back to the 30-day default (`DAYS=0` never means "always stale"; `config set` rejects <1 outright). Tests: `test/backup-status-file.serial.test.ts`. Remote evidence is identity-bound and one-hour-limited; absent, stale, future-dated or inconsistent evidence cannot produce verified recovery counts, and failed refresh does not overwrite cache.
diff --git a/src/core/secret-scan-allowlist.ts b/src/core/secret-scan-allowlist.ts
new file mode 100644
index 0000000000..5f08c7742e
--- /dev/null
+++ b/src/core/secret-scan-allowlist.ts
@@ -0,0 +1,116 @@
+/**
+ * The secret-scan allowlist (peeled from secret-scan.ts, wave 16 G4.1, so the scanner stays under the module-size
+ * cap): `<workspaceRoot>/.gbrain-scan-allow` entries, the shared glob dialect, and the fingerprint / path checks.
+ * `secret-scan.ts` re-exports every public name, so importers of either module see the same surface.
+ */
+import { existsSync, readFileSync } from 'fs';
+import { join, sep } from 'path';
+
+/** Name of the per-workspace allowlist override file. */
+export const SCAN_ALLOW_FILENAME = '.gbrain-scan-allow';
+
+/**
+ * Load `<workspaceRoot>/.gbrain-scan-allow`: one glob-or-fingerprint per
+ * line, `#` comments and blank lines ignored. Absent/unreadable file → []
+ * (the shipped default allowlist is EMPTY [CX2-15]).
+ */
+export function loadWorkspaceAllowlist(workspaceRoot: string): string[] {
+ try {
+ const p = join(workspaceRoot, SCAN_ALLOW_FILENAME);
+ if (!existsSync(p)) return [];
+ return readFileSync(p, 'utf-8')
+ .split('\n')
+ .map((l) => l.trim())
+ .filter((l) => l.length > 0 && !l.startsWith('#'));
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Minimal anchored glob → RegExp. `**` crosses `/`, `*` stays within a path
+ * segment, `?` is one non-slash char. Shared by the scan allowlist and the
+ * workspace-push deny-glob backstop (one glob dialect everywhere).
+ */
+const GLOB_REGEX_CACHE = new Map<string, RegExp>();
+
+export function globToRegExp(glob: string): RegExp {
+ const cached = GLOB_REGEX_CACHE.get(glob);
+ if (cached) return cached;
+ let g = glob;
+ if (g.endsWith('/')) g += '**'; // `foo/` means everything under foo/
+ let re = '';
+ for (let i = 0; i < g.length; i++) {
+ const c = g[i];
+ if (c === '*') {
+ if (g[i + 1] === '*') {
+ i++;
+ if (g[i + 1] === '/') {
+ re += '(?:.*/)?';
+ i++;
+ } else {
+ re += '.*';
+ }
+ } else {
+ re += '[^/]*';
+ }
+ } else if (c === '?') {
+ re += '[^/]';
+ } else if ('\\^$.|+()[]{}'.includes(c)) {
+ re += '\\' + c;
+ } else {
+ re += c;
+ }
+ }
+ const compiled = new RegExp(`^${re}$`);
+ GLOB_REGEX_CACHE.set(glob, compiled);
+ return compiled;
+}
+
+/**
+ * Gitignore-flavored match: a glob WITHOUT `/` matches the basename at any
+ * depth (`*.pem` catches `sub/dir/key.pem`); a glob WITH `/` is anchored at
+ * the workspace root (`.gbrain/**`). Paths are normalized to `/` separators.
+ */
+export function matchesGlob(glob: string, relPath: string): boolean {
+ const norm = relPath.split(sep).join('/');
+ if (!glob.includes('/')) {
+ const base = norm.slice(norm.lastIndexOf('/') + 1);
+ return globToRegExp(glob).test(base);
+ }
+ return globToRegExp(glob).test(norm);
+}
+
+function isFingerprintEntry(entry: string): boolean {
+ return entry.startsWith('sha256:');
+}
+
+/**
+ * Minimum fingerprint-prefix length (hex chars) an allowlist entry must carry
+ * to suppress a finding. 16 hex = 64 bits: an 8-hex (32-bit) floor was low
+ * enough that a short allowlist entry could collide with an UNRELATED secret's
+ * hash and silently un-report it. The emitted fingerprint is exactly 16 hex,
+ * so a copy-pasted fingerprint still matches at the floor.
+ */
+export const ALLOWLIST_FINGERPRINT_MIN_HEX = 16;
+
+/**
+ * True when the full sha256 hex of a matched value is allowlisted (≥16-hex
+ * prefix). Exported so the sensitivity scan (context/sensitivity-scan.ts)
+ * honors the SAME `.gbrain-scan-allow` fingerprint mechanics for its
+ * non-secret families (PII, blocklist, pattern-file) — one escape hatch,
+ * one dialect.
+ */
+export function valueAllowlisted(fullHex: string, allowlist: string[]): boolean {
+ for (const entry of allowlist) {
+ if (!isFingerprintEntry(entry)) continue;
+ const prefix = entry.slice('sha256:'.length).toLowerCase();
+ if (prefix.length >= ALLOWLIST_FINGERPRINT_MIN_HEX && fullHex.startsWith(prefix)) return true;
+ }
+ return false;
+}
+
+/** True when a file path is allowlisted by any glob entry. */
+export function pathAllowlisted(relPath: string, allowlist: string[]): boolean {
+ return allowlist.some((entry) => !isFingerprintEntry(entry) && matchesGlob(entry, relPath));
+}
diff --git a/src/core/secret-scan-work.ts b/src/core/secret-scan-work.ts
new file mode 100644
index 0000000000..8317af8efb
--- /dev/null
+++ b/src/core/secret-scan-work.ts
@@ -0,0 +1,40 @@
+/**
+ * Deterministic work counters for the secret scanner (wave 16 G4.1; the
+ * write gate's `WriteGateWork` shape, #6490). A caller passes `work` on
+ * `ScanOpts`/`RedactOpts` and reads back what the scan did, counted at the
+ * sites that do the work: each regex `exec`, each candidate a pattern
+ * returned, each character handed to the entropy gate (inside
+ * `correctedEntropy`, so a second entropy call per candidate doubles
+ * `gateChars`), each validate call, each claimed span, each union split and
+ * each echo sweep. The same text gives the same counts on every machine, so
+ * a test can pin them exactly where a wall-clock bound could only flake.
+ * Per-character cost inside one call (the entropy histogram, a regex's
+ * backtracking) is not countable here; the perf file's absolute bounds are
+ * the only guard for that.
+ */
+export interface ScanWork {
+ /** Lines the per-line loop looked at (after the short-line skip). */
+ linesScanned: number;
+ /** Characters of those lines. */
+ lineChars: number;
+ /** Regex `exec` calls over the per-line patterns, matches and the final null alike. */
+ regexExecs: number;
+ /** Matches a pattern returned, per pattern name, before any gate. */
+ candidates: Record<string, number>;
+ /** Characters handed to `correctedEntropy`. */
+ gateChars: number;
+ /** Candidates that passed the entropy gate. */
+ gatePassed: number;
+ /** `validate` calls. */
+ validateCalls: number;
+ /** Spans claimed on a line (reported or not). */
+ claims: number;
+ /** Candidates that overlapped an earlier claim and were split into their unclaimed sub-ranges. */
+ unionSplits: number;
+ /** `applyRedaction` echo sweeps started (one per call with a non-empty dictionary). */
+ echoSweeps: number;
+}
+
+export function createScanWork(): ScanWork {
+ return { linesScanned: 0, lineChars: 0, regexExecs: 0, candidates: {}, gateChars: 0, gatePassed: 0, validateCalls: 0, claims: 0, unionSplits: 0, echoSweeps: 0 };
+}
diff --git a/src/core/secret-scan.ts b/src/core/secret-scan.ts
index 519cf8655f..6e6f6eb215 100644
--- a/src/core/secret-scan.ts
+++ b/src/core/secret-scan.ts
@@ -29,7 +29,7 @@
*/
import { existsSync, readFileSync, statSync } from 'fs';
-import { isAbsolute, join, relative, sep } from 'path';
+import { isAbsolute, join, relative } from 'path';
import { createHash } from 'crypto';
import {
LABELED_CREDENTIAL_PATTERNS,
@@ -87,10 +87,16 @@ export interface ScanOpts {
* transcript audit only. Default false.
*/
labeledCredentials?: boolean;
+ /** Work counters the scan fills in (secret-scan-work.ts); absent means no counting. */
+ work?: ScanWork;
}
-/** Name of the per-workspace allowlist override file. */
-export const SCAN_ALLOW_FILENAME = '.gbrain-scan-allow';
+export {
+ SCAN_ALLOW_FILENAME, ALLOWLIST_FINGERPRINT_MIN_HEX, loadWorkspaceAllowlist, globToRegExp, matchesGlob, valueAllowlisted, pathAllowlisted,
+} from './secret-scan-allowlist.ts';
+import { valueAllowlisted, pathAllowlisted } from './secret-scan-allowlist.ts';
+import type { ScanWork } from './secret-scan-work.ts';
+export { createScanWork, type ScanWork } from './secret-scan-work.ts';
// ── Patterns ────────────────────────────────────────────────────────────────
//
@@ -732,10 +738,27 @@ function compilePatterns(opts: ScanOpts): CompiledPattern[] {
* Bias-corrected (Miller-Madow) Shannon entropy in bits/char: the raw
* estimate plus (distinct - 1) / (2 n ln 2). The entropy gate of
* `high_entropy_assignment` reads this. Exported for tests.
+ *
+ * One histogram pass: the distinct count is the histogram's size, so the
+ * former second pass (`new Set(s).size`, ~80 % of the gate's time on a
+ * 4096-char value) is gone. The arithmetic is unchanged and the result is
+ * byte-identical to `shannonEntropy(s) + (new Set(s).size - 1) / (2 n ln 2)`
+ * (test/secret-scan-entropy-equivalence.test.ts): the same `for…of` code
+ * points, the same insertion-ordered sum, the same `s.length` (UTF-16 units)
+ * denominator. `work` counts the characters handed to the gate here, at the
+ * call, so a second call per candidate doubles `gateChars`.
*/
-export function correctedEntropy(s: string): number {
+export function correctedEntropy(s: string, work?: ScanWork): number {
+ if (work) work.gateChars += s.length;
if (s.length === 0) return 0;
- return shannonEntropy(s) + (new Set(s).size - 1) / (2 * s.length * Math.LN2);
+ const counts = new Map<string, number>();
+ for (const ch of s) counts.set(ch, (counts.get(ch) ?? 0) + 1);
+ let bits = 0;
+ for (const n of counts.values()) {
+ const p = n / s.length;
+ bits -= p * Math.log2(p);
+ }
+ return bits + (counts.size - 1) / (2 * s.length * Math.LN2);
}
/** Shannon entropy in bits/char. Exported for tests. */
@@ -751,114 +774,6 @@ export function shannonEntropy(s: string): number {
return bits;
}
-// ── Allowlist ───────────────────────────────────────────────────────────────
-
-/**
- * Load `<workspaceRoot>/.gbrain-scan-allow`: one glob-or-fingerprint per
- * line, `#` comments and blank lines ignored. Absent/unreadable file → []
- * (the shipped default allowlist is EMPTY [CX2-15]).
- */
-export function loadWorkspaceAllowlist(workspaceRoot: string): string[] {
- try {
- const p = join(workspaceRoot, SCAN_ALLOW_FILENAME);
- if (!existsSync(p)) return [];
- return readFileSync(p, 'utf-8')
- .split('\n')
- .map((l) => l.trim())
- .filter((l) => l.length > 0 && !l.startsWith('#'));
- } catch {
- return [];
- }
-}
-
-/**
- * Minimal anchored glob → RegExp. `**` crosses `/`, `*` stays within a path
- * segment, `?` is one non-slash char. Shared by the scan allowlist and the
- * workspace-push deny-glob backstop (one glob dialect everywhere).
- */
-const GLOB_REGEX_CACHE = new Map<string, RegExp>();
-
-export function globToRegExp(glob: string): RegExp {
- const cached = GLOB_REGEX_CACHE.get(glob);
- if (cached) return cached;
- let g = glob;
- if (g.endsWith('/')) g += '**'; // `foo/` means everything under foo/
- let re = '';
- for (let i = 0; i < g.length; i++) {
- const c = g[i];
- if (c === '*') {
- if (g[i + 1] === '*') {
- i++;
- if (g[i + 1] === '/') {
- re += '(?:.*/)?';
- i++;
- } else {
- re += '.*';
- }
- } else {
- re += '[^/]*';
- }
- } else if (c === '?') {
- re += '[^/]';
- } else if ('\\^$.|+()[]{}'.includes(c)) {
- re += '\\' + c;
- } else {
- re += c;
- }
- }
- const compiled = new RegExp(`^${re}$`);
- GLOB_REGEX_CACHE.set(glob, compiled);
- return compiled;
-}
-
-/**
- * Gitignore-flavored match: a glob WITHOUT `/` matches the basename at any
- * depth (`*.pem` catches `sub/dir/key.pem`); a glob WITH `/` is anchored at
- * the workspace root (`.gbrain/**`). Paths are normalized to `/` separators.
- */
-export function matchesGlob(glob: string, relPath: string): boolean {
- const norm = relPath.split(sep).join('/');
- if (!glob.includes('/')) {
- const base = norm.slice(norm.lastIndexOf('/') + 1);
- return globToRegExp(glob).test(base);
- }
- return globToRegExp(glob).test(norm);
-}
-
-function isFingerprintEntry(entry: string): boolean {
- return entry.startsWith('sha256:');
-}
-
-/**
- * Minimum fingerprint-prefix length (hex chars) an allowlist entry must carry
- * to suppress a finding. 16 hex = 64 bits: an 8-hex (32-bit) floor was low
- * enough that a short allowlist entry could collide with an UNRELATED secret's
- * hash and silently un-report it. The emitted fingerprint is exactly 16 hex,
- * so a copy-pasted fingerprint still matches at the floor.
- */
-export const ALLOWLIST_FINGERPRINT_MIN_HEX = 16;
-
-/**
- * True when the full sha256 hex of a matched value is allowlisted (≥16-hex
- * prefix). Exported so the sensitivity scan (context/sensitivity-scan.ts)
- * honors the SAME `.gbrain-scan-allow` fingerprint mechanics for its
- * non-secret families (PII, blocklist, pattern-file) — one escape hatch,
- * one dialect.
- */
-export function valueAllowlisted(fullHex: string, allowlist: string[]): boolean {
- for (const entry of allowlist) {
- if (!isFingerprintEntry(entry)) continue;
- const prefix = entry.slice('sha256:'.length).toLowerCase();
- if (prefix.length >= ALLOWLIST_FINGERPRINT_MIN_HEX && fullHex.startsWith(prefix)) return true;
- }
- return false;
-}
-
-/** True when a file path is allowlisted by any glob entry. */
-export function pathAllowlisted(relPath: string, allowlist: string[]): boolean {
- return allowlist.some((entry) => !isFingerprintEntry(entry) && matchesGlob(entry, relPath));
-}
-
// ── Scanning ────────────────────────────────────────────────────────────────
/** One claimed span on a line: where `value` starts within the line text. */
@@ -948,6 +863,7 @@ function insideClaim(claims: PemClaim[], start: number, end: number): boolean {
function scanInternal(text: string, opts: ScanOpts): RawHit[] {
const patterns = compilePatterns(opts);
+ const work = opts.work;
// PEM blocks first: their full-span value must be redacted before any
// per-line replacement can touch the region (base64 bodies never match the
// named patterns, so order is a belt-and-suspenders guarantee).
@@ -986,12 +902,14 @@ function scanInternal(text: string, opts: ScanOpts): RawHit[] {
// ENG-12: a line wholly inside a private-key claim is already redacted by
// it; hits on it would only double-report (one key, one finding).
if (pem.length > 0 && insideClaim(pem, lineStart, lineStart + line.length)) continue;
+ if (work) { work.linesScanned++; work.lineChars += line.length; }
const spans: LineSpans = { all: [] };
// Claimed-character bitmap behind the first-wins dedupe: allocated on the
// line's FIRST hit only (most lines have none), then O(value) to test and
// to mark. Same answer as scanning every prior span for an intersection.
let taken: Uint8Array | null = null;
const claim = (pattern: string, value: string, start: number): void => {
+ if (work) work.claims++;
taken!.fill(1, start, start + value.length);
// A hit entirely inside a private-key claim (a vendor-shaped run in a
// key body on a line the claim only partly covers) still takes its
@@ -1005,7 +923,11 @@ function scanInternal(text: string, opts: ScanOpts): RawHit[] {
if (p.precheck && !p.precheck(line)) continue;
p.re.lastIndex = 0;
let m: RegExpExecArray | null;
- while ((m = p.re.exec(line)) !== null) {
+ for (;;) {
+ if (work) work.regexExecs++;
+ m = p.re.exec(line);
+ if (m === null) break;
+ if (work) work.candidates[p.name] = (work.candidates[p.name] ?? 0) + 1;
const value = m[2];
const start = m.index + m[1].length;
const end = start + value.length;
@@ -1014,11 +936,18 @@ function scanInternal(text: string, opts: ScanOpts): RawHit[] {
// The entropy gate judges the WHOLE matched value (the rule fired on
// the assignment's value), before any overlap split.
if (p.entropyGated && (!HIGH_ENTROPY_REQUIRES_DIGIT_RE.test(value) || !HIGH_ENTROPY_REQUIRES_NON_DIGIT_RE.test(value))) continue;
- if (p.entropyGated && correctedEntropy(value) < HIGH_ENTROPY_MIN_BITS_PER_CHAR) continue;
- if (p.validate && !p.validate(value, m[1])) continue;
+ if (p.entropyGated) {
+ if (correctedEntropy(value, work) < HIGH_ENTROPY_MIN_BITS_PER_CHAR) continue;
+ if (work) work.gatePassed++;
+ }
+ if (p.validate) {
+ if (work) work.validateCalls++;
+ if (!p.validate(value, m[1])) continue;
+ }
if (!taken) {
taken = new Uint8Array(line.length);
} else if (anyTaken(taken, start, end)) {
+ if (work) work.unionSplits++;
// UNION COVERAGE. An earlier pattern already claimed part of this
// span. Attribution stays first-wins — a FULLY covered span is
// skipped, so `Bearer <vendor key>` reports the vendor only — but
@@ -1355,6 +1284,8 @@ export interface RedactionPlan {
text: string;
/** Claimed spans, sorted by absolute offset. */
claimed: Array<{ abs: number; end: number; pattern: string }>;
+ /** The caller's work counters, carried to `applyRedaction` (echo sweeps are counted there). */
+ work?: ScanWork;
}
function addEchoValue(into: EchoDictionary, pattern: string, value: string): void {
@@ -1391,7 +1322,7 @@ export function planRedaction(text: string, opts: RedactOpts = {}): RedactionPla
addEchoValue(echoValues, hit.pattern, hit.value);
}
claimed.sort((a, b) => a.abs - b.abs);
- return { redactions, echoValues, text, claimed };
+ return { redactions, echoValues, text, claimed, ...(opts.work ? { work: opts.work } : {}) };
}
/**
@@ -1435,6 +1366,7 @@ export function applyRedaction(plan: RedactionPlan): string {
const { text, claimed, echoValues } = plan;
if (claimed.length === 0 && echoValues.size === 0) return text;
const sweep = echoValues.size > 0 ? startEchoSweep(text, echoValues) : null;
+ if (sweep && plan.work) plan.work.echoSweeps++;
const parts: string[] = [];
// Copy text[from, to) through, splicing the echo occurrences inside it. At
// each step the leftmost (then longest) occurrence at or beyond the cursor
diff --git a/test/secret-scan-allowlist.test.ts b/test/secret-scan-allowlist.test.ts
new file mode 100644
index 0000000000..48d78d7212
--- /dev/null
+++ b/test/secret-scan-allowlist.test.ts
@@ -0,0 +1,85 @@
+/**
+ * G4.1 (wave 16): the allowlist block moved from secret-scan.ts to src/core/secret-scan-allowlist.ts so the scanner
+ * stays under the 1500-line module cap. This file tests the path / fingerprint / glob behaviour THROUGH the new module
+ * and pins the import surface: every name is still exported from secret-scan.ts and is the same function.
+ * (test/secret-scan.test.ts keeps its own allowlist cases through the old import path.)
+ */
+import { describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import * as allowlist from '../src/core/secret-scan-allowlist.ts';
+import * as scanner from '../src/core/secret-scan.ts';
+
+const { ALLOWLIST_FINGERPRINT_MIN_HEX, SCAN_ALLOW_FILENAME, globToRegExp, loadWorkspaceAllowlist, matchesGlob, pathAllowlisted, valueAllowlisted } = allowlist;
+
+describe('import surface', () => {
+ test('secret-scan.ts re-exports every allowlist name as the same function or value', () => {
+ for (const name of ['ALLOWLIST_FINGERPRINT_MIN_HEX', 'SCAN_ALLOW_FILENAME', 'globToRegExp', 'loadWorkspaceAllowlist', 'matchesGlob', 'pathAllowlisted', 'valueAllowlisted'] as const) {
+ expect((scanner as Record<string, unknown>)[name], name).toBe((allowlist as Record<string, unknown>)[name]);
+ }
+ expect(SCAN_ALLOW_FILENAME).toBe('.gbrain-scan-allow');
+ expect(ALLOWLIST_FINGERPRINT_MIN_HEX).toBe(16);
+ });
+});
+
+describe('workspace allowlist file', () => {
+ test('absent file is the empty default; entries parse with comments and blanks dropped; an unreadable root is empty', () => {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-scan-allow-'));
+ try {
+ expect(loadWorkspaceAllowlist(root)).toEqual([]);
+ writeFileSync(join(root, SCAN_ALLOW_FILENAME), '# comment\n\nfixtures/**\n sha256:0123456789abcdef \n\n*.pem\n');
+ expect(loadWorkspaceAllowlist(root)).toEqual(['fixtures/**', 'sha256:0123456789abcdef', '*.pem']);
+ expect(loadWorkspaceAllowlist(join(root, 'nope', 'deeper'))).toEqual([]);
+ } finally { rmSync(root, { recursive: true, force: true }); }
+ });
+});
+
+describe('glob dialect', () => {
+ test('`**` crosses `/`, `*` stays in a segment, `?` is one non-slash char, a trailing `/` means everything under', () => {
+ expect(globToRegExp('a/**/b.md').test('a/b.md')).toBe(true);
+ expect(globToRegExp('a/**/b.md').test('a/x/y/b.md')).toBe(true);
+ expect(globToRegExp('a/*/b.md').test('a/x/b.md')).toBe(true);
+ expect(globToRegExp('a/*/b.md').test('a/x/y/b.md')).toBe(false);
+ expect(globToRegExp('a/?.md').test('a/x.md')).toBe(true);
+ expect(globToRegExp('a/?.md').test('a/xy.md')).toBe(false);
+ expect(globToRegExp('a/?.md').test('a//.md')).toBe(false);
+ expect(globToRegExp('fixtures/').test('fixtures/deep/file.txt')).toBe(true);
+ });
+
+ test('regex metacharacters in a glob are literal, and the compiled regex is cached per glob', () => {
+ expect(globToRegExp('a.b').test('a.b')).toBe(true);
+ expect(globToRegExp('a.b').test('aXb')).toBe(false);
+ expect(globToRegExp('x(1)[2]{3}+$^|.md').test('x(1)[2]{3}+$^|.md')).toBe(true);
+ expect(globToRegExp('**/*.pem')).toBe(globToRegExp('**/*.pem'));
+ });
+
+ test('gitignore flavour: a glob without `/` matches the basename at any depth; one with `/` is root-anchored', () => {
+ expect(matchesGlob('*.pem', 'key.pem')).toBe(true);
+ expect(matchesGlob('*.pem', 'sub/dir/key.pem')).toBe(true);
+ expect(matchesGlob('.gbrain/**', '.gbrain/config.json')).toBe(true);
+ expect(matchesGlob('.gbrain/**', 'nested/.gbrain/config.json')).toBe(false);
+ expect(matchesGlob('sub/*.pem', ['sub', 'key.pem'].join('/'))).toBe(true);
+ });
+});
+
+describe('fingerprint and path checks', () => {
+ const full = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
+
+ test('a fingerprint entry suppresses a value only at or past the 16-hex floor, case-insensitively', () => {
+ expect(valueAllowlisted(full, ['sha256:0123456789abcdef'])).toBe(true);
+ expect(valueAllowlisted(full, ['sha256:0123456789ABCDEF'])).toBe(true);
+ expect(valueAllowlisted(full, [`sha256:${full}`])).toBe(true);
+ expect(valueAllowlisted(full, ['sha256:0123456789abcde'])).toBe(false); // 15 hex: below the floor
+ expect(valueAllowlisted(full, ['sha256:fedcba9876543210'])).toBe(false);
+ expect(valueAllowlisted(full, ['*.pem', 'fixtures/**'])).toBe(false); // globs never match a value
+ expect(valueAllowlisted(full, [])).toBe(false);
+ });
+
+ test('a path is allowlisted by any glob entry and never by a fingerprint entry', () => {
+ expect(pathAllowlisted('sub/key.pem', ['*.pem'])).toBe(true);
+ expect(pathAllowlisted('fixtures/x/y.txt', ['sha256:0123456789abcdef', 'fixtures/**'])).toBe(true);
+ expect(pathAllowlisted('src/index.ts', ['*.pem', 'fixtures/**'])).toBe(false);
+ expect(pathAllowlisted('sha256:0123456789abcdef', ['sha256:0123456789abcdef'])).toBe(false);
+ });
+});
diff --git a/test/secret-scan-entropy-equivalence.test.ts b/test/secret-scan-entropy-equivalence.test.ts
new file mode 100644
index 0000000000..a6f31824c6
--- /dev/null
+++ b/test/secret-scan-entropy-equivalence.test.ts
@@ -0,0 +1,97 @@
+/**
+ * G4.1 (wave 16): `correctedEntropy` computes bits and the distinct count in ONE histogram pass. The former
+ * implementation (kept below as the reference, verbatim from master) ran `shannonEntropy` and then `new Set(s).size`,
+ * a second full pass that was ~80 % of the entropy gate's time on a 4096-char value and the reason
+ * test/secret-scan-perf.test.ts's `high_entropy_assignment` segment drifted toward its 300 ms bound under shard load.
+ *
+ * The optimisation must be an exact equivalence, not a Unicode "fix": the same `for…of` code-point iteration, the
+ * same insertion-ordered sum, the same UTF-16 `s.length` denominator. `Object.is` on every sample, including the
+ * empty string, one character, astral characters, an unpaired surrogate, and 4096-char high-entropy values.
+ * Deterministic: the same strings on every machine.
+ */
+import { describe, expect, test } from 'bun:test';
+import { correctedEntropy, shannonEntropy } from '../src/core/secret-scan.ts';
+
+/** Master's `correctedEntropy`, unchanged. */
+function referenceCorrectedEntropy(s: string): number {
+ if (s.length === 0) return 0;
+ return referenceShannon(s) + (new Set(s).size - 1) / (2 * s.length * Math.LN2);
+}
+/** Master's `shannonEntropy`, unchanged. */
+function referenceShannon(s: string): number {
+ if (s.length === 0) return 0;
+ const counts = new Map<string, number>();
+ for (const ch of s) counts.set(ch, (counts.get(ch) ?? 0) + 1);
+ let bits = 0;
+ for (const n of counts.values()) {
+ const p = n / s.length;
+ bits -= p * Math.log2(p);
+ }
+ return bits;
+}
+
+/** Deterministic LCG so the corpus is the same everywhere. */
+function lcg(seed: number): () => number {
+ let x = seed >>> 0;
+ return () => { x = (Math.imul(x, 1664525) + 1013904223) >>> 0; return x / 0x1_0000_0000; };
+}
+
+const ALPHABETS = [
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#%<>',
+ 'abcdefghijklmnopqrstuvwxyz0123456789+/=',
+ '0123456789',
+ 'aé€𝄞😀\u00e9e\u0301', // Latin, BMP non-ASCII, astral (surrogate pairs), composed and decomposed é
+ '\ud800\udc00\ud83d\ude00\ud800', // valid pairs plus a lone high surrogate inside the alphabet
+];
+
+function corpus(): string[] {
+ const out: string[] = ['', 'a', '0', '€', '😀', '\ud800', '\udc00', 'a\ud800b', '😀😀😀', 'aaaaaaaaaaaa', 'ab'.repeat(2048)];
+ const rnd = lcg(0x5eed);
+ for (let i = 0; i < 300; i++) {
+ const alphabet = [...ALPHABETS[i % ALPHABETS.length]!];
+ const length = [1, 2, 3, 7, 12, 31, 64, 255, 1024, 4096][i % 10]!;
+ let s = '';
+ for (let k = 0; k < length; k++) s += alphabet[Math.floor(rnd() * alphabet.length)];
+ out.push(s);
+ }
+ // The perf fixture's exact values: 4096-char entropic strings for 250 salts.
+ const PERF_ALPHABET = ALPHABETS[0]!;
+ for (let salt = 0; salt < 250; salt++) out.push(Array.from({ length: 4096 }, (_, k) => PERF_ALPHABET[(k * 7 + salt) % PERF_ALPHABET.length]).join(''));
+ return out;
+}
+
+describe('correctedEntropy one-pass equivalence', () => {
+ const samples = corpus();
+
+ test('the corpus is at least 300 samples and covers the edge shapes', () => {
+ expect(samples.length).toBeGreaterThanOrEqual(300);
+ expect(samples).toContain('');
+ expect(samples).toContain('\ud800');
+ expect(samples.some(s => /[\u{10000}-\u{10FFFF}]/u.test(s))).toBe(true);
+ expect(samples.filter(s => s.length === 4096).length).toBeGreaterThanOrEqual(250);
+ });
+
+ test('byte-identical to the master implementation on every sample (Object.is)', () => {
+ for (const s of samples) {
+ const got = correctedEntropy(s);
+ const want = referenceCorrectedEntropy(s);
+ expect(Object.is(got, want), JSON.stringify(s.slice(0, 24))).toBe(true);
+ }
+ });
+
+ test('shannonEntropy is unchanged and the correction term still uses the UTF-16 length denominator', () => {
+ for (const s of samples) {
+ expect(Object.is(shannonEntropy(s), referenceShannon(s))).toBe(true);
+ if (s.length) expect(Object.is(correctedEntropy(s), shannonEntropy(s) + (new Set(s).size - 1) / (2 * s.length * Math.LN2))).toBe(true);
+ }
+ });
+
+ test('a lone surrogate counts as one symbol over a UTF-16 length of one, exactly as before', () => {
+ expect(correctedEntropy('\ud800')).toBe(referenceCorrectedEntropy('\ud800'));
+ expect(correctedEntropy('a\ud800b')).toBe(referenceCorrectedEntropy('a\ud800b'));
+ // An astral pair is one symbol but two UTF-16 units, so p = 1/2 and the "entropy" of one symbol reads 0.5 bits:
+ // the master quirk, preserved on purpose (a Unicode fix would be a separate behaviour change).
+ expect(correctedEntropy('😀')).toBe(0.5);
+ expect(correctedEntropy('😀')).toBe(referenceCorrectedEntropy('😀'));
+ });
+});
diff --git a/test/secret-scan-perf.test.ts b/test/secret-scan-perf.test.ts
index 632398fa11..670368cdd7 100644
--- a/test/secret-scan-perf.test.ts
+++ b/test/secret-scan-perf.test.ts
@@ -17,6 +17,15 @@
*
* Every credential-shaped value is synthetic and runtime-joined from >= 2
* fragments; constant names keep scanner keywords away from the `=`.
+ *
+ * The `high_entropy_assignment` bounds are the backtracking guard, and the
+ * absolute bound is the ONLY guard on per-character cost: the entropy gate's
+ * histogram and a regex's inner loop are not countable by the ScanWork
+ * counters (test/secret-scan-work-counters.test.ts pins the counts of execs,
+ * candidates, gated chars and claims instead). Measured on a 4-core cloud box
+ * (wave 16 G4.1): the 250 × 4096 segments cost ~80 ms each with the former
+ * two-pass `correctedEntropy` (Set pass ~65 ms of it) and ~25 ms with the
+ * one-pass histogram, so a loaded shard VM at 3-4× no longer reaches 300 ms.
*/
import { describe, expect, test } from 'bun:test';
import { createHash } from 'crypto';
diff --git a/test/secret-scan-work-counters.test.ts b/test/secret-scan-work-counters.test.ts
new file mode 100644
index 0000000000..944cf2247d
--- /dev/null
+++ b/test/secret-scan-work-counters.test.ts
@@ -0,0 +1,114 @@
+/**
+ * G4.1 (wave 16): the secret scanner's cost on the high-entropy perf fixture is pinned by deterministic work
+ * counters (`ScanWork`, src/core/secret-scan-work.ts; the write gate's #6490 shape), counted at the sites that do
+ * the work: each regex `exec`, each candidate a pattern returns, each character handed to `correctedEntropy`
+ * (inside the call, so a second entropy call per candidate doubles `gateChars`), each validate, each claim, each
+ * union split, each echo sweep. The same text gives the same counts on every machine.
+ *
+ * Forced probes (each applied alone to src/core/secret-scan.ts, this file rerun):
+ * 1. quoted pattern's trailing quote made optional (`["']?` in ASSIGNMENT_QUOTED_SOURCE's group 1) → both
+ * high-entropy patterns match the unquoted line: candidates 500, gateChars doubles (2,047,976).
+ * 2. a second `correctedEntropy(value, work)` call per candidate → gateChars doubles, candidates unchanged.
+ * What the counters cannot see: per-character cost inside one entropy call (the one-pass histogram vs the former
+ * Set pass) or inside one regex exec; test/secret-scan-perf.test.ts's absolute bounds are the only guard for that.
+ */
+import { describe, expect, test } from 'bun:test';
+import { createScanWork, redactFindings, scanText, type ScanWork } from '../src/core/secret-scan.ts';
+
+const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#%<>';
+const entropic = (n: number, salt: number) => Array.from({ length: n }, (_, k) => ALPHABET[(k * 7 + salt) % ALPHABET.length]).join('');
+/** The three inputs of the perf file's `high_entropy_assignment` test, byte for byte. */
+const QUOTED = Array.from({ length: 250 }, (_, i) => `password="${entropic(4096, i)}"`).join(' ');
+const UNQUOTED = Array.from({ length: 250 }, (_, i) => `token=${entropic(4096, i).replace(/[<>]/g, '.')}`).join(' ');
+const TRAILING = `token=${'.'.repeat(4100)} `.repeat(250);
+
+/** The unquoted class excludes `.?!` as the LAST character, so a value ending on a replaced `<`/`>` or on `!` is matched without that run. */
+const UNQUOTED_VALUE_CHARS = Array.from({ length: 250 }, (_, i) => entropic(4096, i).replace(/[<>]/g, '.').replace(/[.?!]+$/, '').length).reduce((a, b) => a + b, 0);
+
+function scanWork(text: string): { work: ScanWork; findings: number } {
+ const work = createScanWork();
+ const { redactions } = redactFindings(text, { highEntropy: true, work });
+ return { work, findings: redactions.length };
+}
+
+describe('ScanWork on the high-entropy perf fixture', () => {
+ test('250 quoted 4096-char values: 250 candidates, 1,024,000 gate chars, 250 claims', () => {
+ const { work, findings } = scanWork(QUOTED);
+ expect(findings).toBe(250);
+ expect(work.linesScanned).toBe(1);
+ expect(work.lineChars).toBe(QUOTED.length);
+ expect(work.candidates).toEqual({ high_entropy_assignment: 250 });
+ expect(work.gateChars).toBe(250 * 4096);
+ expect(work.gatePassed).toBe(250);
+ expect(work.validateCalls).toBe(250);
+ expect(work.claims).toBe(250);
+ expect(work.unionSplits).toBe(0);
+ // 4096-char values exceed ECHO_MAX_VALUE_CHARS, so the echo dictionary stays empty and no sweep runs.
+ expect(work.echoSweeps).toBe(0);
+ });
+
+ test('250 unquoted values: 250 candidates, every value character gated once, 250 claims', () => {
+ const { work, findings } = scanWork(UNQUOTED);
+ expect(findings).toBe(250);
+ expect(UNQUOTED_VALUE_CHARS).toBe(1_023_988);
+ expect(work.candidates).toEqual({ high_entropy_assignment: 250 });
+ expect(work.gateChars).toBe(UNQUOTED_VALUE_CHARS);
+ expect(work.gatePassed).toBe(250);
+ expect(work.validateCalls).toBe(250);
+ expect(work.claims).toBe(250);
+ expect(work.unionSplits).toBe(0);
+ });
+
+ test('the two high-entropy patterns run 251 + 1 execs on the unquoted line (250 matches + the final null; the quoted pattern finds nothing)', () => {
+ const withGate = createScanWork();
+ scanText(UNQUOTED, { highEntropy: true, work: withGate });
+ const coreOnly = createScanWork();
+ scanText(UNQUOTED, { highEntropy: false, work: coreOnly });
+ expect(coreOnly.candidates).toEqual({});
+ expect(withGate.regexExecs - coreOnly.regexExecs).toBe(251 + 1);
+ });
+
+ test('4100-char runs of trailing punctuation: no candidate, nothing gated, nothing claimed', () => {
+ const work = createScanWork();
+ expect(scanText(TRAILING, { highEntropy: true, work })).toEqual([]);
+ expect(work.linesScanned).toBe(1);
+ expect(work.candidates).toEqual({});
+ expect(work.gateChars).toBe(0);
+ expect(work.gatePassed).toBe(0);
+ expect(work.validateCalls).toBe(0);
+ expect(work.claims).toBe(0);
+ });
+
+ test('the counters change nothing: findings and redacted text are identical with and without the accumulator', () => {
+ for (const text of [QUOTED, UNQUOTED, TRAILING]) {
+ const plain = redactFindings(text, { highEntropy: true });
+ const counted = redactFindings(text, { highEntropy: true, work: createScanWork() });
+ expect(counted.text).toBe(plain.text);
+ expect(counted.redactions).toEqual(plain.redactions);
+ }
+ });
+});
+
+describe('ScanWork on the overlap and echo paths', () => {
+ const TWILIO_SID = ['AC', '0123456789abcdef0123456789abcdef'].join('');
+ const PW = ['s3cr3t', 'P4ssw0rdXyz'].join('');
+
+ test('a database URL whose username is a vendor-shaped id is one union split: three claims from two candidates', () => {
+ const work = createScanWork();
+ const findings = scanText(['postgres://', TWILIO_SID, ':', PW, '@db.internal/app'].join(''), { work });
+ expect(findings.map(f => f.pattern)).toEqual(['twilio', 'db_url_credentials', 'db_url_credentials']);
+ expect(work.unionSplits).toBe(1);
+ expect(work.claims).toBe(3);
+ expect(work.candidates).toEqual({ twilio: 1, db_url_credentials: 1 });
+ });
+
+ test('a bearer value echoed bare later in the text: one claim, one echo sweep', () => {
+ const work = createScanWork();
+ const value = ['opaque', 'Token0123456789abcdefXYZ'].join('');
+ const { text, redactions } = redactFindings(`tool: curl -H "Authorization: Bearer ${value}" https://api.example/v1\nassistant: the token ${value} expired\n`, { work });
+ expect(redactions.length).toBe(1);
+ expect(text).toBe('tool: curl -H "Authorization: Bearer <REDACTED:bearer>" https://api.example/v1\nassistant: the token <REDACTED:bearer> expired\n');
+ expect(work.claims).toBe(1);
+ expect(work.echoSweeps).toBe(1);
+ });
+});