Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(transcripts): redact labeled credentials and audit imported pages (#6147)
garrytanbfc68e989003
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.mdindex 5ed19b80b1..2bacba68fc 100644--- a/docs/architecture/key-files/agent-bootstrap-continued.md+++ b/docs/architecture/key-files/agent-bootstrap-continued.md@@ -25,8 +25,8 @@- `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 and non-PGLite configs never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, and `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step).- `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 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: a repetitive tail against 64 short claimed values meant millions of candidate objects and hundreds of MB of RSS for 64 findings, ahead of message truncation) (never an alternation RegExp — O(text × Σ|values|) on prefix-sharing values; never over emitted tokens, so a value spelling a pattern name cannot nest). 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). `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`).+- `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/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). `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.- `src/core/backup/coverage.ts` + `src/core/backup/repository.ts` — local Git discovery and bounded remote readback. Trusted non-quiet local backup CLI/doctor may read at most eight refs per sweep with a shared eight-second budget, two-second subprocess timeout and no prompts, pushes or fetches; pending/oldest evidence rotates first. Both git calls run with `backupGitEnv()`, an allowlist (`HOME`, `PATH`, `XDG_CONFIG_HOME`, `SSH_AUTH_SOCK`, `GIT_CONFIG_GLOBAL`, proxy variables, and Windows profile variables) under the no-prompt overrides, so user Git config and credential helpers apply but `GIT_DIR`/`GIT_WORK_TREE` never do (#5794). `currentBackupEvidence` retains one-hour readback only while source kind/id, physical Git directory, HEAD, branch, origin, push-status identity and clean tree match. `recoverable_repos` counts clean matching remote HEADs, while `configured_repos` counts configuration; expired, failed, mismatched, dirty or budget-exhausted observations cannot turn coverage green. New matching readback can supersede historical push failure without erasing it. Background/stdio are local-only; remote MCP doctor uses aggregate cache only. A failed refresh is degraded and does not overwrite a valid cache. Git covers committed files, not DB-only facts/config/credentials. API connector sources are not repositories: a `connector_database` source (managed, unbound) and an unmanaged connector whose directory is not a Git repo each become a `connector` info asset with the `gbrain sync --source <id> --full` fix (not `gbrain export`: the connector sync rebuilds pages from the provider and never reads a Markdown dump, so an export is an archive, not a restore path), while a bound connector keeps the repository verdict. The doctor `backup_coverage` message and the advisor collector list each asset that keeps the verdict in warn with its reason (`blockingAssetReasons` in status-file.ts: `no git remote`, `remote configured, nothing pushed`, `dirty`, a fixed `unknown` code, unverified remote) locally, and reason counts only on the remote surface; a warn with no blocking asset leads with the stale or degraded cause. `gbrain backup status` names a fix for dirty and unverified rows too. Tests: `test/backup-verification.serial.test.ts`, `test/backup-git-env.test.ts`, `test/backup-coverage.serial.test.ts`, `test/doctor-backup-coverage.serial.test.ts`, `test/e2e/backup-coverage-parity.test.ts`.diff --git a/docs/architecture/key-files/commands-6.md b/docs/architecture/key-files/commands-6.mdindex c312aa3d90..f286a2b9b3 100644--- a/docs/architecture/key-files/commands-6.md+++ b/docs/architecture/key-files/commands-6.md@@ -10,7 +10,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/takes-mutation.ts` — one parser and operation adapter for local, resident PGLite, and HTTP take mutations. Allocates a request UUID before delivery; retries retain that UUID and caller intent. `--source` remains claim provenance, `--source-id` selects the logical source, and `--dir` becomes a trusted local canonical-root assertion. Default owner/resolver choices remain unset until admission freezes them. The CLI and thin-client router share this parser for all four mutations before connecting; queued/error responses never print completed-mutation text. Remote failures use the shared typed reporter directly, retaining UUIDs, unknown delivery status and original receipt fields in JSON. `test/persistence-cli-delegation.test.ts` drives the real CLI through a held PGLite owner's socket, checks all four parameter mappings and pending receipts, and rejects malformed numeric/precondition input.-- `src/commands/transcripts.ts` — the transcripts command family, all local-only (`ctx.remote=false` by construction). `recent`: raw `.txt` corpus reads via `listRecentTranscripts` (same library as the gated `get_recent_transcripts` op). `ingest <path-or-glob>`: the cross-harness session importer — resolves ONE source id (6-tier chain), threads activePack once, streams progress (phase `transcripts.ingest`), and calls `runTranscriptsIngest` with the CLI's `makeContext` context, so on a writer-claimed brain each rendered part is submitted as a `put_page` write request naming the page's current revision (unmanaged brains and dry runs keep the direct importer; `recover codex --apply` passes the same context; pinned by `test/transcripts-managed-ingest.test.ts`); embedding is OFF by default (embed backfill is the catch-up lane; the embed flag opts in); the max-bytes flag (validated size string, e.g. `4gb`) overrides the per-format file/store byte caps for oversized stores while omission preserves each adapter's native default; the since-last watermark is an op-checkpoint (op `transcripts-ingest`, fingerprint = source + pathspec + format + adapter version + any explicit byte cap via `ingestCheckpointFingerprintInput` — a checkpoint written under one cap is never silently reused under another, so a capped run's skipped tail can't read as scanned; the pathspec binds the user-stated paths resolved + sorted, and the no-arg/all lane substitutes hostname + sorted harness roots so DB-backed checkpoints shared across a brain's machines never let one machine inherit another's watermark and skip sessions it never scanned) advanced ONLY after a clean, untruncated, non-dry scan; no-arg = confined discovery table, the all flag imports the discovered set. `status`: found-vs-imported gap table (disk scan vs ONE conversation-pages frontmatter query — `executeRaw`, both engines — in `src/core/transcripts/discover.ts`) — the correctness surface that catches late-arriving sessions no watermark can. The facts flag hands EVERY touched slug (including hash-skipped) to `src/core/transcripts/ingest-facts.ts`; a page that fails extraction counts in `facts.pagesFailed`, stays unfinished, and makes the command exit 1. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + SELF_HELP_WITHOUT_ENGINE (engine-free help). `expandTilde(raw)` (bare `~`, leading `~/` or `~\\` → home dir; `~user` forms and a mid-string `~` stay literal) is the one tilde expansion `expandPaths` applies to every path spec. `recover codex` (`src/commands/transcripts-recover.ts`, logic `src/core/transcripts/recover.ts`; D15 for #5163): finds codex conversation pages in one source with no `**User**` anchor, re-parses the retained rollouts (discovery root + archived store, or given paths) and classifies each session recoverable / still userless / unrecoverable (rollout gone); preview by default, `--apply` re-imports only the recoverable rollouts through `runTranscriptsIngest` (content-hash dedup, no facts, no watermark write). Pinned by `test/transcripts-recover-codex.test.ts`.+- `src/commands/transcripts.ts` — the transcripts command family, all local-only (`ctx.remote=false` by construction). `recent`: raw `.txt` corpus reads via `listRecentTranscripts` (same library as the gated `get_recent_transcripts` op). `ingest <path-or-glob>`: the cross-harness session importer — resolves ONE source id (6-tier chain), threads activePack once, streams progress (phase `transcripts.ingest`), and calls `runTranscriptsIngest` with the CLI's `makeContext` context, so on a writer-claimed brain each rendered part is submitted as a `put_page` write request naming the page's current revision (unmanaged brains and dry runs keep the direct importer; `recover codex --apply` passes the same context; pinned by `test/transcripts-managed-ingest.test.ts`); embedding is OFF by default (embed backfill is the catch-up lane; the embed flag opts in); the max-bytes flag (validated size string, e.g. `4gb`) overrides the per-format file/store byte caps for oversized stores while omission preserves each adapter's native default; the since-last watermark is an op-checkpoint (op `transcripts-ingest`, fingerprint = source + pathspec + format + adapter version + any explicit byte cap via `ingestCheckpointFingerprintInput` — a checkpoint written under one cap is never silently reused under another, so a capped run's skipped tail can't read as scanned; the pathspec binds the user-stated paths resolved + sorted, and the no-arg/all lane substitutes hostname + sorted harness roots so DB-backed checkpoints shared across a brain's machines never let one machine inherit another's watermark and skip sessions it never scanned) advanced ONLY after a clean, untruncated, non-dry scan; no-arg = confined discovery table, the all flag imports the discovered set. `status`: found-vs-imported gap table (disk scan vs ONE conversation-pages frontmatter query — `executeRaw`, both engines — in `src/core/transcripts/discover.ts`) — the correctness surface that catches late-arriving sessions no watermark can. The facts flag hands EVERY touched slug (including hash-skipped) to `src/core/transcripts/ingest-facts.ts`; a page that fails extraction counts in `facts.pagesFailed`, stays unfinished, and makes the command exit 1. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + SELF_HELP_WITHOUT_ENGINE (engine-free help). `expandTilde(raw)` (bare `~`, leading `~/` or `~\\` → home dir; `~user` forms and a mid-string `~` stay literal) is the one tilde expansion `expandPaths` applies to every path spec. `recover codex` (`src/commands/transcripts-recover.ts`, logic `src/core/transcripts/recover.ts`; D15 for #5163): finds codex conversation pages in one source with no `**User**` anchor, re-parses the retained rollouts (discovery root + archived store, or given paths) and classifies each session recoverable / still userless / unrecoverable (rollout gone); preview by default, `--apply` re-imports only the recoverable rollouts through `runTranscriptsIngest` (content-hash dedup, no facts, no watermark write). Pinned by `test/transcripts-recover-codex.test.ts`. `audit-secrets [--source-id S] [--json]` (`src/commands/transcripts-audit.ts`, logic `src/core/transcripts/secret-audit.ts`): the read-only installed-base audit that streams imported conversation pages (`type = 'conversation'` with `transcript_import` frontmatter) in id-keyset batches of 25, scans title and body with the transcript-lane detectors, lists slug, source, hit counts per pattern and up to 20 line numbers (never values or previews), and caches the summary without slugs in config row `transcripts.secret_audit` for the doctor check `transcript_secret_exposure` (`src/commands/doctor/checks/transcript-secrets.ts`, brain category), which counts imported conversation pages and reads that summary (never scans): no audit, an older `TRANSCRIPT_SECRET_AUDIT_VERSION` or a source-scoped audit warns with the audit as fix; hits warn with the audit's age; a clean full audit is ok. Pinned by `test/transcripts-secret-audit.test.ts`.- `src/commands/upgrade.ts` — self-update CLI. It sets `GBRAIN_UPGRADE_OWNS_MIGRATIONS=1` for the install step, so package postinstall (`scripts/postinstall.ts`) skips `apply-migrations`; post-upgrade owns them. An install step that fails or times out after `gbrain --version` already reports a newer version counts as installed. The run ends with a `Binary:` line (installed version, or upgrade failed) and a `Migrations:` line: complete; running, with the lock holder's host and pid when post-upgrade exits 75; or failed, with the recovery command (`--force-retry <v>` for wedged versions). `runPostUpgrade()` enumerates migrations from the TS registry (`src/commands/migrations/index.ts`) and tail-calls `runApplyMigrations(['--yes', '--non-interactive'])` so the mechanical side of every outstanding migration runs unconditionally. After schema apply it prints the one-shot auto_chronicle default-on `[AGENT]` notice (`core/chronicle/upgrade-notice.ts`). Before the swap of a bun-link, package or ClawHub install it refuses (exit 78, nothing changed) a target whose Bun floor is above the host's Bun or unreadable (`--no-bun-floor-check` overrides, manual only; `src/core/bun-floor.ts`); after the swap it runs `gbrain --help` as a smoke that passes the startup Bun check and, on failure, exits 1 with per-method recovery (#5855). Tests: `upgrade-migration-outcome.test.ts`, `upgrade-no-autopilot.serial.test.ts`, `upgrade-bun-link-arc.serial.test.ts`. `post-upgrade --json` (D2, `json: 'document'`): human lines go to stderr and stdout is one report `{status, apply_migrations:{exit_code}, schema, warnings[]}`; it calls `applyMigrations()` and still ends on any status apply-migrations returns (a failure is one envelope leading with the report).diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.mdindex a3f7d25093..c65836e8cf 100644--- a/docs/architecture/key-files/security.md+++ b/docs/architecture/key-files/security.md@@ -24,4 +24,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/scope.ts` — OAuth scope hierarchy + allowlist (the 6 scope strings, `hasScope`, `assertAllowedScopes`, `filterAllowedScopes`, `parseScopeString`, `normalizeScopesInput`) AND the anonymous-registration policy: `DCR_REGISTRABLE_SCOPES` (`read`, `write`) and `dcrScopeViolation(requested, grantTypes)` — returns `null` when the requested scopes fit the Dynamic Client Registration ceiling, otherwise the `invalid_client_metadata` message naming the offending scopes and the operator remedy (`gbrain auth register-client` / admin API / `gbrain auth rescope-client <client_id> --scopes ...`). `agent` keeps its own "operator-approved grant with explicit delegation bindings" wording; when `grantTypes` includes `client_credentials` (only reachable under `--enable-dcr-insecure`) the ceiling is `read` alone; unknown scope strings are ignored here (the unknown-filter drops them). `scopesSupportedForDiscovery({ enableDcr })` is the `scopes_supported` list for OAuth discovery (consumed by `serve-http.ts`'s `authRouterOptions`): the DCR-registrable subset (`read write`, canonical order) while DCR is enabled — so a client that copies discovery into its registration passes `dcrScopeViolation` — and every scope except `agent` otherwise; it never narrows an operator-registered client, because a client that omits `scope` at `/authorize` receives its full registered set via `grantScopes` (`oauth-grants.ts`) and an explicit request is intersected with the registration. The DCR constants and the helper sit BELOW `ALLOWED_SCOPES_LIST`, and no comment line pairs that identifier with `[`, because `scripts/check-admin-scope-drift.sh` extracts the allowlist block with an awk match on exactly that pair. Pinned by `test/scope.test.ts` + `test/oauth-dcr-scope-ceiling.test.ts` + the discovery test in `test/e2e/serve-http-consent.test.ts`.+- `src/core/secret-scan-labeled.ts` — the transcript-lane `labeled_credential` detector (#6147 idea, widened), compiled by `secret-scan.ts` only under `ScanOpts.labeledCredentials` (transcript pages, the recent-transcripts read and `transcripts audit-secrets`), after every other rule so a vendor or entropy claim keeps attribution. SINGLE labels (`password|passwd|passcode|passphrase|pwd`, optional identifier prefix, JSON-key quote, markdown bold) before `:`/`=`/`:`, and PAIR labels (`login|log-in|credentials|creds|user/pass|username/password|…`) before `:`/`=`/`:`/` - `/nothing then `user / pass` or `user:pass`, each in a bare and a quoted/backticked form; only the password half is claimed. `labeledValueIsCredential(value, form, head)` (the scanner passes the match head to `validate`) rejects placeholders, masks, templating, URLs, paths, calls, dotted references, digitless code identifiers, a backtick that closes a code span holding the label, a meeting link's `?pwd=`, and `LABELED_STOPLIST` words; a pair's password also needs 4+ chars with a letter and a digit or symbol, and its user half must not be a stopword. `endsWithDanglingPair` gates the next-line continuation pattern (such a line is scanned even when shorter than 8 chars). Claimed values join the echo dictionary at `ECHO_MIN_CHARS_LABELED` = 8 when `labeledEchoEligible`. Every quantifier is bounded (perf-pinned in `test/secret-scan-perf.test.ts`); acceptance table in `test/transcript-labeled-credential.test.ts`; user doc `docs/guides/data-ingestion.md#credential-redaction`.+- `src/core/ssrf-validate.ts` — DNS-rebinding-defended URL validation. `validateAndResolveUrl(url)` resolves the hostname via `dns.lookup({all: true, family: 0})`, checks EVERY A and AAAA record against the internal-IP deny list, and returns the resolved IP so callers fetch by IP (validation IP === fetch IP defeats DNS rebinding). `fetchWithSSRFGuard(url, opts)` does redirect-aware fetching with per-hop re-validation (max 3 hops by default). Reusable across all URL-fetching features. Test seam `__setDnsLookupForTests` for hermetic tests.diff --git a/docs/guides/data-ingestion.md b/docs/guides/data-ingestion.mdindex 3897794775..aaf2fd214d 100644--- a/docs/guides/data-ingestion.md+++ b/docs/guides/data-ingestion.md@@ -65,8 +65,9 @@ conversation pages with provenance back to the exact session file. Pattern-basedmetadata before anything is written — vendor key prefixes, JWTs, cloud/API keyshapes, `Bearer` and `Authorization: Basic` headers, database and `http(s)`URLs carrying a password, private keys (also when an excerpt cut off the-`BEGIN` or `END` line), and high-entropy `KEY=`/`TOKEN=`/`password=`-assignments (quoted values may contain punctuation) become `<REDACTED:…>` placeholders (preview with+`BEGIN` or `END` line), high-entropy `KEY=`/`TOKEN=`/`password=`+assignments (quoted values may contain punctuation), and typed passwords+after a credential label (see [Credential redaction](#credential-redaction)) become `<REDACTED:…>` placeholders (preview with`--dry-run`; no pattern set is complete, so if a secret still lands see["If a secret reached the brain"](../../SECURITY.md#if-a-secret-reached-the-brain):rotate it, then `gbrain delete <slug> --purge`). Embedding is off by default@@ -94,6 +95,50 @@ watermark alone; for facts from a restored session, run**Say to your agent:** *"Restore the codex sessions that lost my side of the conversation"* (your agent runs the preview, shows you the counts, and applies after you agree).+### Credential redaction++Transcript pages also redact a password typed after a credential label,+even when it is short and low-entropy (`labeled_credential`). Two label+forms are recognized, with bare, quoted or backticked values:++- a single label, `password`, `passwd`, `passcode`, `passphrase` or `pwd`+ (also behind a prefix such as `DB_` and as a JSON key), followed by `:`,+ `=` or the full-width `:` — `password: hunter2`, `**Password:** …`,+ `{"password": "…"}`;+- a pair label, `login`, `log-in`, `credentials`, `creds`, `user/pass` or+ `username/password`, followed by `:`, `=`, `:`, ` - ` or nothing, then+ `user / pass` or `user:pass` — `login alice / hunter2`,+ `creds: alice:hunter2`. Only the password half is redacted. A pair whose+ password starts the next line is redacted too.++To keep prose and code intact, a value is never redacted when it is a+placeholder (`<…>`, `${…}`, `$VAR`), a mask (`****`), a URL, a path, a+function call, a dotted reference (`req.body.password`), a code identifier+(`hashedPassword`), or one of the stoplisted words (`n/a`, `none`, `string`,+`required`, `changed`, `reset`, `flow`, `email`, `await` and similar; the+list is `LABELED_STOPLIST` in `src/core/secret-scan-labeled.ts`). A pair's+password must also be 4+ characters with a letter and a digit or symbol, so+`login: Google/GitHub SSO` and `credentials: docs/auth.md` stay. Known+misses: an unquoted multi-word passphrase, a label with no delimiter+(`the password is …`), and a meeting link's `?pwd=` passcode. A redacted+value of 8+ characters that is not a stoplisted word is also scrubbed where+the session repeats it bare.++Pages imported before this detector shipped are not rewritten+automatically. `gbrain transcripts audit-secrets --json` (read-only; all+sources, or one with `--source-id`) lists the conversation pages that still+carry a credential: slug, source, hit count per pattern and line numbers,+never the text. The doctor check `transcript_secret_exposure` reads the+audit's cached summary (it never scans pages itself) and says when no audit+has run or what the last one found and how long ago. Review, edit and+removal are separate steps: `gbrain get <slug>`, then `gbrain put <slug> <+edited.md` to remove the credential, or `gbrain delete <slug> --purge` after+asking the user. Rotate any real credential that reached a page (see+["If a secret reached the brain"](../../SECURITY.md#if-a-secret-reached-the-brain)),+then re-run the audit.++**Say to your agent:** *"Check my imported transcripts for passwords"* (your agent runs the audit, lists the pages by slug and asks before changing any).+Or connect the account and skip the manual export entirely. `gbrain connectors`syncs your ChatGPT and Claude conversation history live, using your own browsersession cookie — incrementally (a durable per-provider watermark, plus adiff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 4643e946af..b6d2a9f1f5 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2350,6 +2350,16 @@ Reasons: `content_directory`.|---|---|---|---|---|---|---|| Adding this source would replace or overlap another owner root. | Only the operator of the brain host can change what blocks this. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |+### transcript_secret_exposure++<a id="transcript_secret_exposure"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| Imported conversation pages may still carry a typed credential from before the labeled-credential detector, or the last audit found some; pages are never rewritten automatically. | Re-ingest skips unchanged sessions, so pages imported before the detector keep any password typed in prose until someone reviews them. | Run the read-only audit to list affected slugs (never values), then review, edit or (after asking the user) remove each page, and ask the user to rotate any real credential. Run: gbrain transcripts audit-secrets --json | agent | `gbrain doctor --only transcript_secret_exposure --json` | 1 | no |++More: [docs/guides/data-ingestion.md#credential-redaction](../../docs/guides/data-ingestion.md#credential-redaction)+### trusted_local_only<a id="trusted_local_only"></a>diff --git a/src/commands/doctor/checks/transcript-secrets.ts b/src/commands/doctor/checks/transcript-secrets.tsnew file mode 100644index 0000000000..ac1247e85e--- /dev/null+++ b/src/commands/doctor/checks/transcript-secrets.ts@@ -0,0 +1,79 @@+/**+ * transcript_secret_exposure: conversation pages imported before the+ * transcript lane's `labeled_credential` detector may still carry a typed+ * password (`password: …`, `login user / pass`); nothing rewrites them on+ * upgrade. The check never scans pages itself: it counts imported+ * conversation pages (one indexed aggregate) and reads the summary the+ * read-only `gbrain transcripts audit-secrets` caches, reporting its age.+ */+import type { Check } from '../../doctor.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { agentFix } from '../check-fix.ts';+import {+ TRANSCRIPT_PAGE_PREDICATE,+ TRANSCRIPT_SECRET_AUDIT_VERSION,+ loadTranscriptSecretAudit,+} from '../../../core/transcripts/secret-audit.ts';++const NAME = 'transcript_secret_exposure';+const DOCS = 'docs/guides/data-ingestion.md#credential-redaction';+const AUDIT_ARGV = ['gbrain', 'transcripts', 'audit-secrets', '--json'];++function ageText(scannedAt: string, now: number): string {+ const hours = Math.max(0, Math.round((now - Date.parse(scannedAt)) / 3_600_000));+ return hours < 48 ? `${hours}h ago` : `${Math.round(hours / 24)}d ago`;+}++export async function transcriptSecretExposureCheck(ctx: DoctorContext, now = Date.now()): Promise<Check | null> {+ const engine = connectedEngine(ctx);+ try {+ const [row] = await engine.executeRaw<{ n: number | string }>(`SELECT count(*) AS n FROM pages WHERE ${TRANSCRIPT_PAGE_PREDICATE}`);+ const pages = Number(row?.n ?? 0);+ if (pages === 0) return null;+ const audit = await loadTranscriptSecretAudit(engine);+ if (audit === null || audit.detector_version < TRANSCRIPT_SECRET_AUDIT_VERSION || audit.source_id !== null) {+ const why = audit === null+ ? 'it has never been audited'+ : audit.source_id !== null ? `the last audit covered only source ${audit.source_id}` : 'the last audit used older detectors';+ return {+ name: 'transcript_secret_exposure', status: 'warn', details: { transcript_pages: pages, audited: audit !== null, docs: DOCS },+ message: `${pages} imported conversation page(s) may carry a typed credential from before the labeled-credential detector, and ${why}. ` ++ 'Pages are not rewritten automatically. Run the read-only audit to list affected slugs (never values).',+ fix: agentFix(AUDIT_ARGV, 'Lists conversation pages that still carry a credential with hit counts per pattern; changes no page.', NAME, { docs: DOCS }),+ };+ }+ const details = { transcript_pages: pages, ...audit, docs: DOCS };+ const age = ageText(audit.scanned_at, now);+ if (audit.hits_total > 0) {+ return {+ name: 'transcript_secret_exposure', status: 'warn', details,+ message: `The transcript secret audit (${age}) found ${audit.hits_total} credential hit(s) on ${audit.pages_affected} conversation page(s). ` ++ 'List them with the audit, then review (`gbrain get <slug>`), edit (`gbrain put <slug>`) or, after asking the user, remove (`gbrain delete <slug> --purge`) each one, and ask the user to rotate any real credential. Re-run the audit afterwards.',+ fix: agentFix(AUDIT_ARGV, 'Lists the affected slugs and line numbers (never values) so each page can be reviewed; read-only.', NAME, { docs: DOCS }),+ };+ }+ return {+ name: 'transcript_secret_exposure', status: 'ok', details,+ message: `The transcript secret audit (${age}) found no credential in ${audit.pages_scanned} conversation page(s).`,+ };+ } catch (err) {+ return {+ name: 'transcript_secret_exposure', status: 'warn', fix_unavailable_reason: 'check_errored',+ message: `Transcript secret exposure could not be checked: ${err instanceof Error ? err.message : String(err)}. Health is unknown.`,+ };+ }+}++async function runTranscriptSecretExposure(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ ctx.progress.heartbeat('transcript_secret_exposure');+ const check = await transcriptSecretExposureCheck(ctx);+ if (check) checks.push(check);+ return checks;+}++export const transcriptSecretExposureEntry: DoctorEntry = {+ name: 'transcript_secret_exposure',+ emits: ['transcript_secret_exposure'],+ run: runTranscriptSecretExposure,+};diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 466e154057..b97fb34122 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -85,6 +85,7 @@ import { legacyTokenGrantsEntry } from './checks/legacy-token-grants.ts';import { syncFreshnessEntry, searchModeEntry } from './checks/sync-search.ts';import { gitConvergenceEntry } from './checks/git-convergence.ts';import { retrievalFeedbackEntry } from './checks/retrieval-feedback.ts';+import { transcriptSecretExposureEntry } from './checks/transcript-secrets.ts';import { autoChronicleEntry } from './checks/auto-chronicle.ts';import { factsDrainEntry } from './checks/facts-drain.ts';import { factTakeVectorsEntry } from './checks/vector-coverage.ts';@@ -170,6 +171,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [factTakeVectorsEntry,plannerStatsEntry,retrievalFeedbackEntry,+ transcriptSecretExposureEntry,revisionBackfillEntry,coreMemoryEntry,searchModeEntry,diff --git a/src/commands/transcripts-audit.ts b/src/commands/transcripts-audit.tsnew file mode 100644index 0000000000..4ceb327ef9--- /dev/null+++ b/src/commands/transcripts-audit.ts@@ -0,0 +1,73 @@+/**+ * `gbrain transcripts audit-secrets` — the read-only installed-base audit for+ * credentials in conversation pages imported before the transcript lane's+ * `labeled_credential` detector (logic in core/transcripts/secret-audit.ts).+ * Lists affected page slugs and hit counts per pattern, never a value; caches+ * the summary for the `transcript_secret_exposure` doctor check.+ */++import type { BrainEngine } from '../core/engine.ts';++export const TRANSCRIPTS_AUDIT_HELP = `Usage:+ gbrain transcripts audit-secrets [--source-id S] [--json]++Scans every imported conversation page (all sources, or one with+--source-id) with the transcript import's secret detectors and lists the+pages that still carry a credential: slug, source and hit count per+pattern, never the matched text. Pages imported before the+labeled-credential detector (password: …, login user / pass) are not+rewritten automatically; this finds them. Read-only: no page changes. The+summary is cached for \`gbrain doctor --only transcript_secret_exposure\`.++Next actions are separate and each is yours to choose:+ review gbrain get <slug>+ edit gbrain put <slug> < edited.md (remove the credential, keep the page)+ remove gbrain delete <slug> --purge (ask the user first; no recovery window)+A credential that reached a page should also be rotated (SECURITY.md,+"If a secret reached the brain"): edits and deletes do not reach git history,+synced copies or exports.++ --source-id S Audit one source (default: every source)+ --json Machine-readable result+`;++export async function runTranscriptsAuditSecrets(engine: BrainEngine, args: string[]): Promise<void> {+ if (args.includes('--help') || args.includes('-h')) {+ console.log(TRANSCRIPTS_AUDIT_HELP);+ return;+ }+ let json = false;+ let sourceId: string | undefined;+ for (let i = 0; i < args.length; i++) {+ const a = args[i]!;+ if (a === '--json') { json = true; continue; }+ if (a === '--source-id' && args[i + 1] && !args[i + 1]!.startsWith('-')) { sourceId = args[++i]; continue; }+ const { exitCliError, usageError } = await import('../cli/cli-error.ts');+ exitCliError(usageError(`gbrain transcripts audit-secrets does not accept ${a}; nothing was scanned.`,+ 'Run `gbrain transcripts audit-secrets --json` (every source) or add `--source-id <id>`.'), 'transcripts', { json: args.includes('--json') });+ }+ const { auditTranscriptSecrets, saveTranscriptSecretAudit } = await import('../core/transcripts/secret-audit.ts');+ const result = await auditTranscriptSecrets(engine, { sourceId });+ const cached = await saveTranscriptSecretAudit(engine, result);+ const nextActions = result.pages_affected === 0 ? [] : [+ { action: 'review', argv: ['gbrain', 'get', '<slug>'], why: 'Read the page at the listed lines to confirm each hit is a real credential.' },+ { action: 'edit', argv: ['gbrain', 'put', '<slug>'], why: 'Rewrite the page with the credential removed (page content on stdin); the rest of the conversation stays searchable.' },+ { action: 'remove', next: 'ask_user', argv: ['gbrain', 'delete', '<slug>', '--purge'], why: 'Purging a conversation page loses the whole session with no recovery window; ask the user before running it.' },+ { action: 'rotate', next: 'ask_user', why: 'A credential that reached a page may also sit in git history, synced copies or exports; ask the user to rotate it (SECURITY.md, "If a secret reached the brain").' },+ ];+ if (json) {+ console.log(JSON.stringify({ ...result, cached, next_actions: nextActions }, null, 2));+ return;+ }+ console.log(`transcript secret audit (${result.source_id ? `source: ${result.source_id}` : 'every source'}): ${result.pages_scanned} conversation page(s) scanned, ${result.pages_affected} carry ${result.hits_total} credential hit(s)`);+ for (const p of result.pages) {+ const counts = Object.entries(p.hits).map(([k, v]) => `${k}=${v}`).join(', ');+ console.log(` ${p.source_id}:${p.slug} ${counts}${p.lines.length ? ` (lines ${p.lines.join(', ')})` : ''}`);+ }+ if (result.pages_affected > 0) {+ console.log('Next (separately): review with `gbrain get <slug>`, edit with `gbrain put <slug> < edited.md`, or remove with `gbrain delete <slug> --purge` after asking the user; ask the user to rotate any real credential.');+ }+ if (!cached) {+ console.error('[transcripts] the audit summary could not be cached; `gbrain doctor` will keep asking for an audit.');+ }+}diff --git a/src/commands/transcripts.ts b/src/commands/transcripts.tsindex b6afd3edc4..5d94284e14 100644--- a/src/commands/transcripts.ts+++ b/src/commands/transcripts.ts@@ -195,6 +195,7 @@ const HELP = `Usage:gbrain transcripts ingest --all # import everything discoveredgbrain transcripts status # found vs imported gap tablegbrain transcripts recover codex # restore user turns lost to #5163 (preview; --apply)+ gbrain transcripts audit-secrets # list imported pages that still carry a credential (read-only)gbrain transcripts recent [options]ingest — import dead session logs and chat exports as conversation pages@@ -607,6 +608,11 @@ export async function runTranscripts(engine: BrainEngine, args: string[], dispatawait runStatus(engine, args.slice(1));return;}+ if (sub === 'audit-secrets') {+ const { runTranscriptsAuditSecrets } = await import('./transcripts-audit.ts');+ await runTranscriptsAuditSecrets(engine, args.slice(1));+ return;+ }if (sub === 'recover') {const { runTranscriptsRecover } = await import('./transcripts-recover.ts');await runTranscriptsRecover(engine, args.slice(1), dispatch);@@ -615,7 +621,7 @@ export async function runTranscripts(engine: BrainEngine, args: string[], dispatif (sub !== 'recent') {if (sub !== '--help' && sub !== '-h' && args.includes('--json')) {const { exitCliError, usageError } = await import('../cli/cli-error.ts');- exitCliError(usageError(sub && !sub.startsWith('-') ? `Unknown transcripts subcommand: ${sub}` : 'gbrain transcripts needs a subcommand: ingest, status, recover or recent.',+ exitCliError(usageError(sub && !sub.startsWith('-') ? `Unknown transcripts subcommand: ${sub}` : 'gbrain transcripts needs a subcommand: ingest, status, recover, audit-secrets or recent.','Run `gbrain transcripts recent --json` to list recent transcripts, or `gbrain transcripts --help`.'), 'transcripts', { json: true });}console.log(HELP);diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 449dee9b44..93f298b1f8 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -257,6 +257,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.97.0', text: 'Google Calendar sync writes only events between `historyDays` back and 60 days ahead; `gbrain sync --full` removes pages for in-window events the calendar no longer lists (more than 200 is refused and reported partial).' },{ since: '0.60.98.0', text: 'Managed sync now holds a file whose facts or takes fence cannot be imported (code `invalid_fence`; `gbrain sources status <id>` names the fence, section and rows) instead of blocking the whole source, and a source such a fence blocked before recovers on its next sync. Coordinated writes refuse such a fence with `invalid_fence` (wire `error` stays `invalid_params`, or `take_row_collision`). `gbrain config set sync.holds fail` keeps fail-closed blocking.' },{ since: '0.60.99.0', text: 'Fixable facts and takes fences are now rewritten instead of held or refused: managed sync, put_page and the fact and take writers normalize a fence whose meaning is unambiguous (a missing end marker after the table, two-dash takes markers, zero or duplicate row numbers, header aliases, invented kinds and enum synonyms, assistant holders, percent confidences) without changing a claim or an existing row number, and managed sync commits the rewritten file. Results report `fences_normalized`; `gbrain sync --dry-run` lists `would_normalize`. `gbrain config set fences.normalize false` turns it off (such fences are then held or refused).' },+ { since: '0.0.0-wave11', text: 'Imported transcript pages now also redact a password typed after a credential label (`password: …`, `login alice / …`) as `<REDACTED:labeled_credential>`; pages imported earlier are not rewritten, so run `gbrain transcripts audit-secrets --json` to list them (doctor `transcript_secret_exposure`).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex ab833507bb..38d058c7e7 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -162,6 +162,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['timeline_coverage','timeline_orphans','timeline_history',+ // #6147: imported conversation pages that may still carry a typed credential (cached audit).+ 'transcript_secret_exposure',// #5254 — pages written database-only to a source with no canonical owner.'unbound_source','undeclared_db_only_pages',diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex c035264c34..082d26af31 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -318,6 +318,7 @@ export const CODES = {target_escape: { class: 'caller', summary: "The skill target must remain within its selected root." },timeout: { class: 'retryable', summary: "The operation did not finish within its time bound.", exit: 124 },topology_change_required: { class: 'host_only', summary: "Adding this source would replace or overlap another owner root." },+ transcript_secret_exposure: { class: 'unavailable', summary: "Imported conversation pages may still carry a typed credential from before the labeled-credential detector, or the last audit found some; pages are never rewritten automatically.", why: 'Re-ingest skips unchanged sessions, so pages imported before the detector keep any password typed in prose until someone reviews them.', docs: 'docs/guides/data-ingestion.md#credential-redaction', suggestion: 'Run the read-only audit to list affected slugs (never values), then review, edit or (after asking the user) remove each page, and ask the user to rotate any real credential.', fix: { argv: ['gbrain', 'transcripts', 'audit-secrets', '--json'], consent: [], actor: 'agent', why: 'Lists conversation pages that still carry a credential with hit counts per pattern; changes no page.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'transcript_secret_exposure', '--json'] } } },trusted_local_only: { class: 'host_only', summary: 'The operation runs only from the trusted local CLI on the brain host; no MCP connection can call it.', legacy_error: 'permission_denied', suggestion: 'Ask the user to run the named gbrain command on the brain host.' },unavailable: { class: 'unavailable', summary: "A required dependency or capability cannot serve this request." },unexpected_file_bytes: { class: 'server', summary: "A canonical skill file mode changed outside publication." },diff --git a/src/core/secret-scan-labeled.ts b/src/core/secret-scan-labeled.tsnew file mode 100644index 0000000000..86c0d13111--- /dev/null+++ b/src/core/secret-scan-labeled.ts@@ -0,0 +1,169 @@+/**+ * secret-scan-labeled.ts: the transcript-lane `labeled_credential` detector+ * (#6147 idea, widened). A low-entropy password typed into a conversation+ * (`password: hunter2`, `login alice / hunter2`) clears neither the vendor+ * shapes nor the entropy-gated assignment heuristic, so it reached the+ * searchable conversation page verbatim.+ *+ * OPT-IN (`ScanOpts.labeledCredentials`): only the transcript page lane and+ * the read-only `gbrain transcripts audit-secrets` audit turn it on. The push+ * gate and every other surface keep it off, because a label is a much weaker+ * signal than a credential's wire shape.+ *+ * Two label classes, each with a bare and a quoted value form:+ * - SINGLE: `password|passwd|passcode|passphrase|pwd` (optionally behind an+ * identifier prefix such as `DB_` and inside a quoted JSON key) followed+ * by `:`, `=` or the full-width `:`. The value after the label is the+ * secret.+ * - PAIR: `login|log-in|credentials|creds|user/pass|username/password|…`+ * followed by `:`, `=`, `:`, ` - ` or nothing, then `<user> / <pass>` or+ * `<user>:<pass>`. Only the password half is claimed, so the user name+ * stays readable. A pair whose password starts the next line+ * (`login: alice /` then `hunter2`) is claimed through the continuation+ * pattern, which runs only on the line after a dangling pair.+ *+ * False positives are cut by `labeledValueIsCredential`: placeholders,+ * masks, templating, paths, URLs, code references and type names, and a+ * documented stoplist of prose and code words never redact. A pair's password+ * must also carry a letter plus a digit or a symbol, so prose such as+ * `login: Google/GitHub SSO` or `credentials: docs/auth.md` stays intact.+ * Accepted misses: an unquoted multi-word passphrase (`login: alice / pass+ * word`), a delimiter-free single label (`the password is hunter2`), a pair+ * split by anything but one line break, and a meeting link's `?pwd=`+ * passcode (part of a shareable invite URL).+ *+ * Every quantifier is bounded so each candidate start does constant work+ * (pinned in test/secret-scan-perf.test.ts).+ */++const LEFT = '(?:^|[^A-Za-z0-9])';+const LABEL_END = '(?![A-Za-z0-9_-])';+const SINGLE_LABEL = '(?:pass(?:word|wd|code|phrase)|pwd)';+const PAIR_LABEL = '(?:(?:user(?:name)?|login|email)\\s{0,2}/\\s{0,2}pass(?:word|wd)?|log-?in|credentials?|creds)';+const DELIM = '(?:[:=]|\\uFF1A)(?![=>])';+const QUOTE = '["\'`]';+const BARE_VALUE = '[^\\s"\'`]{0,255}[^\\s"\'`.,;:!?)\\]}]';+const BARE_PASS = '[^\\s"\'`/]{0,255}[^\\s"\'`/.,;:!?)\\]}]';+const BARE_END = '(?=[.,;:!?)\\]}]{0,8}(?:\\s|$))';+const QUOTED_VALUE = '[^"\'`\\n]{1,256}';+const BOLD = '(?:\\*{1,2}|_{2})?';+const PAIR_HEAD = `${LEFT}${PAIR_LABEL}${LABEL_END}${BOLD}${QUOTE}?\\s{0,4}(?:${DELIM}|-(?=\\s))?${BOLD}\\s{0,4}`;+const PAIR_USER = `(?:${QUOTE}[^"'\`\\n/]{1,128}${QUOTE}|[^\\s/:"'\`]{1,128})`;+const PAIR_SEP = '(?:\\s{0,4}/\\s{0,4}|:(?![/\\s]))';+const SINGLE_HEAD = `${LEFT}[A-Za-z0-9_]{0,32}${SINGLE_LABEL}${LABEL_END}${BOLD}${QUOTE}?\\s{0,4}${DELIM}${BOLD}\\s{0,4}`;++export interface LabeledPattern {+ source: string;+ form: 'single' | 'pair';+ /** Runs only on the line after one that ends in a dangling pair. */+ continuation?: true;+}++/** Group 1 = everything before the value, group 2 = the value (the scanner's shape). */+export const LABELED_CREDENTIAL_PATTERNS: readonly LabeledPattern[] = [+ { form: 'single', source: `(${SINGLE_HEAD}${QUOTE})(${QUOTED_VALUE})(?=${QUOTE})` },+ { form: 'single', source: `(${SINGLE_HEAD})(${BARE_VALUE})${BARE_END}` },+ { form: 'pair', source: `(${PAIR_HEAD}${PAIR_USER}${PAIR_SEP}${QUOTE})(${QUOTED_VALUE})(?=${QUOTE})` },+ { form: 'pair', source: `(${PAIR_HEAD}${PAIR_USER}${PAIR_SEP})(${BARE_PASS})${BARE_END}` },+ { form: 'pair', continuation: true, source: `(^\\s{0,8}${QUOTE}?)(${BARE_PASS})${BARE_END}` },+];++/** Cheap gate before the label regexes run on a line. */+export const LABELED_PRECHECK_RE = /pass|pwd|log-?in|cred/i;++// nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- compile-time literal; bounded quantifiers+const PAIR_DANGLING_RE = new RegExp(`${PAIR_HEAD}${PAIR_USER}\\s{0,4}/\\s{0,4}$`, 'i');++/** True when `line` ends in a pair label and user name with the password on the next line. */+export function endsWithDanglingPair(line: string): boolean {+ return line.includes('/') && LABELED_PRECHECK_RE.test(line) && PAIR_DANGLING_RE.test(line);+}++/**+ * Words that follow a credential label in prose or code without being the+ * credential. Documented in docs/guides/data-ingestion.md ("Credential+ * redaction"). Matched case-insensitively against the whole value.+ */+export const LABELED_STOPLIST: ReadonlySet<string> = new Set([+ 'a', 'an', 'the', 'and', 'or', 'not', 'no', 'yes', 'ok', 'okay', 'none', 'null', 'nil', 'n/a', 'na', 'tbd', 'todo',+ 'empty', 'blank', 'unknown', 'unset', 'set', 'same', 'hidden', 'redacted', 'masked', 'secret', 'private',+ 'required', 'optional', 'missing', 'invalid', 'incorrect', 'wrong', 'expired', 'changed', 'change', 'reset',+ 'forgot', 'forgotten', 'updated', 'update', 'new', 'old', 'current', 'default', 'see', 'below', 'above',+ 'here', 'there', 'it', 'its', "it's", 'is', 'was', 'be', 'this', 'that', 'these', 'those', 'my', 'your',+ 'our', 'their', 'his', 'her', 'any', 'some', 'all', 'one', 'two', 'true', 'false', 'on', 'off', 'enabled',+ 'disabled', 'flow', 'page', 'form', 'field', 'screen', 'prompt', 'dialog', 'modal', 'button', 'link', 'email',+ 'password', 'passwd', 'passcode', 'passphrase', 'pwd', 'login', 'username', 'user', 'users', 'credentials',+ 'creds', 'manager', 'policy', 'rules', 'strength', 'length', 'hint', 'protected', 'protection', 'auth',+ 'oauth', 'sso', 'saml', 'ldap', 'mfa', '2fa', 'otp', 'token', 'tokens', 'key', 'keys', 'hash', 'hashed',+ 'salt', 'salted', 'encrypted', 'plaintext', 'string', 'str', 'text', 'number', 'int', 'integer', 'bool',+ 'boolean', 'bytes', 'object', 'undefined', 'varchar', 'char', 'secretstr', 'type', 'value', 'values',+ 'input', 'output', 'example', 'placeholder', 'stdin', 'env', 'environment', 'vault', 'keychain', 'keyring',+ 'please', 'enter', 'provide', 'use', 'via', 'from', 'with', 'without', 'for', 'to', 'in', 'of', 'by', 'as',+ 'at', 'if', 'when', 'then', 'only', 'also', 'just', 'still', 'again', 'later', 'now', 'needed', 'need',+ 'works', 'working', 'failed', 'fails', 'failing', 'error', 'errors', 'broken', 'issue', 'issues', 'support',+ 'supported', 'unsupported', 'configured', 'stored', 'saved', 'sent', 'shared', 'rotated', 'rotate', 'revoked',+ 'style', 'format', 'syntax', 'mode', 'option', 'options', 'parameter', 'param', 'argument', 'arg',+ 'await', 'async', 'function', 'fn', 'lambda', 'return', 'yield', 'typeof', 'const', 'let', 'var', 'def',+ 'self', 'cls', 'getpass', 'require', 'import', 'readline', 'ask', 'read',+]);++const PLACEHOLDER_PREFIX_RE = /^(?:<|\[|\{|\$|%|\\|@\{|#\{|\)|\]|\})/;+const MASK_RE = /^[*xX•·.#_-]+$/;+const URL_RE = /^[A-Za-z][A-Za-z0-9+.-]{0,31}:\/\//;+const PATH_RE = /^(?:\.{1,2}\/|~\/|\/|[A-Za-z]:[\\/])/;+const DOTTED_IDENTIFIER_RE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/;+const IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/;+const COMPOUND_IDENTIFIER_RE = /[a-z][A-Z]|_[A-Za-z]/;+const LABEL_WORD_RE = /pass|pwd/i;+const VERSION_RE = /^v?\d+(?:\.\d+)+$/;+const PAIR_SYMBOL_RE = /[0-9!@#$%^&*+=?~]/;+const LETTER_RE = /[A-Za-z]/;++/** Minimum length before a labeled value joins the session-wide echo list. */+export const ECHO_MIN_CHARS_LABELED = 8;++function isStopword(value: string): boolean {+ return LABELED_STOPLIST.has(value.toLowerCase());+}++/** A meeting link's `?pwd=` passcode is part of a shareable invite URL, not a typed credential. */+const QUERY_PWD_RE = /[?&]pwd=$/i;+const LABEL_START_RE = /pass|pwd|log-?in|cred|user|email/i;++/**+ * True when a backtick-"quoted" value is really the close of a code span+ * that holds the label (`` `password=` `` in prose), not a quoted value.+ */+function closesCodeSpan(head: string): boolean {+ const before = head.slice(0, Math.max(0, head.search(LABEL_START_RE)));+ return (before.split('`').length - 1) % 2 === 1;+}++const PAIR_USER_TAIL_RE = /([^\s/:"'`*]+)["'`]?\s*[/:]\s*["'`]?$/;++/**+ * Validate a labeled match's value (`head` is the match text before it):+ * reject placeholders, masks, templating, URLs, paths, code references, code+ * identifiers, type names and stoplisted words. A pair's password (the+ * weaker label) must also be at least 4 characters with a letter and a digit+ * or symbol, and its user half must not be a stoplisted word+ * (`login page / step2`).+ */+export function labeledValueIsCredential(value: string, form: 'single' | 'pair', head = ''): boolean {+ if (value.length < 3 || isStopword(value)) return false;+ if (head.endsWith('`') && closesCodeSpan(head)) return false;+ if (QUERY_PWD_RE.test(head)) return false;+ if (PLACEHOLDER_PREFIX_RE.test(value) || MASK_RE.test(value) || URL_RE.test(value) || PATH_RE.test(value)) return false;+ if (value.includes('(') || DOTTED_IDENTIFIER_RE.test(value)) return false;+ const digitless = !/[0-9]/.test(value);+ if (IDENTIFIER_RE.test(value) && digitless && (LABEL_WORD_RE.test(value) || COMPOUND_IDENTIFIER_RE.test(value))) return false;+ if (form === 'single') return true;+ const user = PAIR_USER_TAIL_RE.exec(head)?.[1];+ if (user !== undefined && isStopword(user)) return false;+ return value.length >= 4 && LETTER_RE.test(value) && PAIR_SYMBOL_RE.test(value) && !VERSION_RE.test(value);+}++/** Echo floor for labeled values: long enough and not a common word. */+export function labeledEchoEligible(value: string): boolean {+ return value.length >= ECHO_MIN_CHARS_LABELED && !isStopword(value) && !/\s/.test(value);+}diff --git a/src/core/secret-scan.ts b/src/core/secret-scan.tsindex 3d33f40fa4..e6bf00c2e8 100644--- a/src/core/secret-scan.ts+++ b/src/core/secret-scan.ts@@ -31,6 +31,14 @@import { existsSync, readFileSync, statSync } from 'fs';import { isAbsolute, join, relative, sep } from 'path';import { createHash } from 'crypto';+import {+ LABELED_CREDENTIAL_PATTERNS,+ ECHO_MIN_CHARS_LABELED,+ LABELED_PRECHECK_RE,+ endsWithDanglingPair,+ labeledEchoEligible,+ labeledValueIsCredential,+} from './secret-scan-labeled.ts';// ── Types ───────────────────────────────────────────────────────────────────@@ -72,6 +80,12 @@ export interface ScanOpts {workspaceRoot?: string;/** Opt-in generic high-entropy assignment heuristic. Default false. */highEntropy?: boolean;+ /**+ * Opt-in `labeled_credential` detector (secret-scan-labeled.ts): a value+ * after a password / login / credentials label. Transcript pages and the+ * transcript audit only. Default false.+ */+ labeledCredentials?: boolean;}/** Name of the per-workspace allowlist override file. */@@ -104,8 +118,10 @@ interface CompiledPattern {entropyGated?: boolean;/** See CorePattern.precheck. */precheck?: (line: string) => boolean;- /** See CorePattern.validate. */- validate?: (value: string) => boolean;+ /** See CorePattern.validate; `head` is the match text before the value. */+ validate?: (value: string, head: string) => boolean;+ /** Runs only on the line after one that ends in a dangling credential pair. */+ continuation?: boolean;}interface CorePattern {@@ -697,6 +713,17 @@ function compilePatterns(opts: ScanOpts): CompiledPattern[] {});}}+ if (opts.labeledCredentials) {+ for (const p of LABELED_CREDENTIAL_PATTERNS) {+ out.push({+ name: 'labeled_credential',+ // nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- compile-time literal; bounded quantifiers, pinned by test/secret-scan-perf.test.ts+ re: new RegExp(p.source, 'gi'),+ ...(p.continuation ? { continuation: true } : { precheck: (line: string) => LABELED_PRECHECK_RE.test(line) }),+ validate: (value: string, head: string) => labeledValueIsCredential(value, p.form, head),+ });+ }+ }return out;}@@ -950,7 +977,8 @@ function scanInternal(text: string, opts: ScanOpts): RawHit[] {const line = lines[i] ?? '';const lineStart = offset;offset += line.length + 1;- if (line.length < 8) continue;+ const dangling = opts.labeledCredentials === true && i > 0 && endsWithDanglingPair(lines[i - 1] ?? '');+ if (line.length < 8 && !dangling) continue;// 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;@@ -969,6 +997,7 @@ function scanInternal(text: string, opts: ScanOpts): RawHit[] {hits.push({ pattern, value, start, abs: lineStart + start, line: i + 1, lineText: line, spans });};for (const p of patterns) {+ if (p.continuation && !dangling) continue;if (p.precheck && !p.precheck(line)) continue;p.re.lastIndex = 0;let m: RegExpExecArray | null;@@ -982,7 +1011,7 @@ function scanInternal(text: string, opts: ScanOpts): RawHit[] {// 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)) continue;+ if (p.validate && !p.validate(value, m[1])) continue;if (!taken) {taken = new Uint8Array(line.length);} else if (anyTaken(taken, start, end)) {@@ -1232,7 +1261,10 @@ export function scanFiles(paths: string[], opts: ScanOpts = {}): SecretFinding[]// collision-safe: a value must clear its pattern's floor// (ECHO_MIN_CHARS_BEARER = 20, ECHO_MIN_CHARS_ENTROPY = 12 — the rules' own// floors, restated so a pattern edit alone can never widen the pass to-// short, collision-prone values), must be at most ECHO_MAX_VALUE_CHARS long,+// short, collision-prone values; an opted-in `labeled_credential` value+// needs ECHO_MIN_CHARS_LABELED = 8 and must not be a stoplisted word, so+// `pwd: 1234` never scrubs every later "1234"), must be at most+// ECHO_MAX_VALUE_CHARS long,// and only the first ECHO_MAX_UNIQUE unique values in claim order — ONE cap// across both patterns — join. A value past either cap is still redacted at// its claimed span; only its echoes are the accepted miss.@@ -1321,12 +1353,15 @@ export interface RedactionPlan {}function addEchoValue(into: EchoDictionary, pattern: string, value: string): void {+ if (pattern === 'labeled_credential' && !labeledEchoEligible(value)) return;const floor =pattern === 'bearer'? ECHO_MIN_CHARS_BEARER: pattern === 'high_entropy_assignment'? ECHO_MIN_CHARS_ENTROPY- : Infinity;+ : pattern === 'labeled_credential'+ ? ECHO_MIN_CHARS_LABELED+ : Infinity;if (value.length < floor || value.length > ECHO_MAX_VALUE_CHARS) return;if (into.has(value) || into.size >= ECHO_MAX_UNIQUE) return;into.set(value, pattern);diff --git a/src/core/transcripts.ts b/src/core/transcripts.tsindex d9bb5dc432..49eb6a53c3 100644--- a/src/core/transcripts.ts+++ b/src/core/transcripts.ts@@ -85,7 +85,7 @@ export async function listRecentTranscripts(const name = basename(c.path);const dateMatch = DATE_RE.exec(name);// Redact the whole file before the summary/full-read cap cuts it.- const text = redactFindings(raw, { highEntropy: true }).text;+ const text = redactFindings(raw, { highEntropy: true, labeledCredentials: true }).text;out.push({path: name,date: dateMatch ? dateMatch[1] : null,diff --git a/src/core/transcripts/render.ts b/src/core/transcripts/render.tsindex a0637377e3..2957368103 100644--- a/src/core/transcripts/render.ts+++ b/src/core/transcripts/render.ts@@ -133,6 +133,11 @@ export function loadImportRedactionPatterns(userPatternsPath?: string): ImportRe* carry a digit and clear the entropy gate). Transcripts are the corpus where* a pasted `.env` line is most likely, so recall wins over the false-positive* cost here; the push gate and compiled-context scan keep the heuristic off.+ * Also opted in for this lane only: the `labeled_credential` detector+ * (`secret-scan-labeled.ts`), which claims a low-entropy value typed after a+ * password / login / credentials label (`password: hunter2`, `login alice /+ * hunter2`); a claimed value of 8+ characters that is not a stoplisted word+ * joins the echo dictionary below.* Every match becomes `<REDACTED:pattern>`; user patterns become* `<REDACTED:user-pattern>`.*@@ -161,9 +166,10 @@ export function redactSession(// sanitizeForJsonb (NUL-strip + well-form): transcripts capture raw tool// output that legitimately carries U+0000, which Postgres text/jsonb// reject at the write boundary (#4392).- // highEntropy: transcripts opt into the assignment heuristic (see doc- // comment above) — the shared scanner keeps it off by default.- planRedaction(sanitizeForJsonb(text), { highEntropy: true, echoValues });+ // highEntropy + labeledCredentials: transcripts opt into the assignment+ // heuristic and the labeled-credential detector (see doc comment above);+ // the shared scanner keeps both off by default.+ planRedaction(sanitizeForJsonb(text), { highEntropy: true, labeledCredentials: true, echoValues });const apply = (p: RedactionPlan): string => {redactionCount += p.redactions.length;diff --git a/src/core/transcripts/secret-audit.ts b/src/core/transcripts/secret-audit.tsnew file mode 100644index 0000000000..cb98586271--- /dev/null+++ b/src/core/transcripts/secret-audit.ts@@ -0,0 +1,118 @@+/**+ * The installed-base transcript secret audit (#6147 follow-through).+ * Conversation pages imported before the `labeled_credential` detector+ * shipped keep any prose credential they carried: re-ingest skips them+ * (content hash and `--since last`), and nothing rewrites a page on its own.+ * `gbrain transcripts audit-secrets` scans those pages with the same+ * transcript-lane detectors the importer uses now and lists the affected+ * page slugs with hit counts per pattern. It never prints, returns or stores+ * a matched value or a preview, and it changes no page. Its summary is+ * cached in the config row `transcripts.secret_audit` so the+ * `transcript_secret_exposure` doctor check reads it instead of scanning.+ *+ * Bounded memory: conversation parts run to ~300 KB, so pages stream in id+ * order in small keyset batches.+ */+import type { BrainEngine } from '../engine.ts';+import { scanText } from '../secret-scan.ts';++/** Bump when the transcript-lane detectors change, so doctor asks for a fresh audit. */+export const TRANSCRIPT_SECRET_AUDIT_VERSION = 1;+export const TRANSCRIPT_SECRET_AUDIT_KEY = 'transcripts.secret_audit';+const BATCH = 25;+const LINES_PER_PAGE = 20;++/** The page set the importer writes: conversation pages stamped with `transcript_import`. */+export const TRANSCRIPT_PAGE_PREDICATE = `type = 'conversation' AND deleted_at IS NULL AND frontmatter ? 'transcript_import'`;++export interface TranscriptSecretAuditPage {+ slug: string;+ source_id: string;+ hits: Record<string, number>;+ /** 1-based body line numbers of the hits (first 20), so a reviewer can find them; never the text. */+ lines: number[];+}++export interface TranscriptSecretAuditSummary {+ detector_version: number;+ scanned_at: string;+ source_id: string | null;+ pages_scanned: number;+ pages_affected: number;+ hits_total: number;+ by_pattern: Record<string, number>;+}++export interface TranscriptSecretAuditResult extends TranscriptSecretAuditSummary {+ pages: TranscriptSecretAuditPage[];+}++export async function auditTranscriptSecrets(+ engine: BrainEngine,+ opts: { sourceId?: string; now?: () => Date } = {},+): Promise<TranscriptSecretAuditResult> {+ const pages: TranscriptSecretAuditPage[] = [];+ const byPattern: Record<string, number> = {};+ let pagesScanned = 0;+ let cursor = 0;+ for (;;) {+ const params: unknown[] = [cursor, BATCH];+ if (opts.sourceId) params.push(opts.sourceId);+ const rows = await engine.executeRaw<{ id: number | string; slug: string; source_id: string; title: string; compiled_truth: string }>(+ `SELECT id, slug, source_id, title, compiled_truth FROM pages+ WHERE ${TRANSCRIPT_PAGE_PREDICATE} AND id > $1${opts.sourceId ? ' AND source_id = $3' : ''}+ ORDER BY id LIMIT $2`,+ params,+ );+ if (rows.length === 0) break;+ for (const row of rows) {+ cursor = Number(row.id);+ pagesScanned++;+ const findings = [+ ...scanText(row.title ?? '', { highEntropy: true, labeledCredentials: true }).map((f) => ({ ...f, line: 0 })),+ ...scanText(row.compiled_truth ?? '', { highEntropy: true, labeledCredentials: true }),+ ];+ if (findings.length === 0) continue;+ const hits: Record<string, number> = {};+ for (const f of findings) {+ hits[f.pattern] = (hits[f.pattern] ?? 0) + 1;+ byPattern[f.pattern] = (byPattern[f.pattern] ?? 0) + 1;+ }+ const lines = [...new Set(findings.map((f) => f.line).filter((l) => l > 0))].slice(0, LINES_PER_PAGE);+ pages.push({ slug: row.slug, source_id: row.source_id, hits, lines });+ }+ if (rows.length < BATCH) break;+ }+ return {+ detector_version: TRANSCRIPT_SECRET_AUDIT_VERSION,+ scanned_at: (opts.now?.() ?? new Date()).toISOString(),+ source_id: opts.sourceId ?? null,+ pages_scanned: pagesScanned,+ pages_affected: pages.length,+ hits_total: Object.values(byPattern).reduce((n, v) => n + v, 0),+ by_pattern: byPattern,+ pages,+ };+}++/** Cache the summary (no slugs, no values) for the doctor check. Best effort. */+export async function saveTranscriptSecretAudit(engine: BrainEngine, result: TranscriptSecretAuditResult): Promise<boolean> {+ const { pages: _pages, ...summary } = result;+ try {+ await engine.setConfig(TRANSCRIPT_SECRET_AUDIT_KEY, JSON.stringify(summary));+ return true;+ } catch {+ return false;+ }+}++export async function loadTranscriptSecretAudit(engine: BrainEngine): Promise<TranscriptSecretAuditSummary | null> {+ try {+ const raw = await engine.getConfig(TRANSCRIPT_SECRET_AUDIT_KEY);+ if (!raw) return null;+ const parsed = JSON.parse(raw) as TranscriptSecretAuditSummary;+ return typeof parsed.scanned_at === 'string' && typeof parsed.hits_total === 'number' ? parsed : null;+ } catch {+ return null;+ }+}diff --git a/test/e2e/transcripts-secret-audit-postgres.test.ts b/test/e2e/transcripts-secret-audit-postgres.test.tsnew file mode 100644index 0000000000..b821d17dd7--- /dev/null+++ b/test/e2e/transcripts-secret-audit-postgres.test.ts@@ -0,0 +1,39 @@+/**+ * Postgres parity for the installed-base transcript secret audit (#6147):+ * the `frontmatter ? 'transcript_import'` page set, keyset batching past one+ * batch, and the doctor check reading the cached summary.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';+import { auditTranscriptSecrets, saveTranscriptSecretAudit } from '../../src/core/transcripts/secret-audit.ts';+import { transcriptSecretExposureCheck } from '../../src/commands/doctor/checks/transcript-secrets.ts';+import type { DoctorContext } from '../../src/commands/doctor/context.ts';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';++const PW = ['hunter', '2'].join('');+const RUN = hasDatabase();+let engine: PostgresEngine;++describe.skipIf(!RUN)('transcripts audit-secrets (Postgres)', () => {+ beforeAll(async () => { engine = await setupDB(); });+ afterAll(async () => { await teardownDB(); });++ test('streams every imported conversation page across batches and reports counts, never values', async () => {+ for (let i = 0; i < 30; i++) {+ await engine.putPage(`conversations/sessions/2026-01-02-codex-${String(i).padStart(12, '0')}`, {+ type: 'conversation', title: 'session', compiled_truth: i % 10 === 0 ? `ok\npassword: ${PW}` : 'clean',+ frontmatter: { transcript_import: { harness: 'codex', session_id: `s${i}` } },+ });+ }+ await engine.putPage('notes/ops', { type: 'note', title: 'ops', compiled_truth: `password: ${PW}` });+ const result = await auditTranscriptSecrets(engine);+ expect(result.pages_scanned).toBe(30);+ expect(result.pages_affected).toBe(3);+ expect(result.pages.every((p) => p.lines[0] === 2)).toBe(true);+ expect(JSON.stringify(result)).not.toContain(PW);+ const ctx = { engine, progress: { heartbeat() {} } } as unknown as DoctorContext;+ expect((await transcriptSecretExposureCheck(ctx))?.message).toContain('never been audited');+ await saveTranscriptSecretAudit(engine, result);+ expect((await transcriptSecretExposureCheck(ctx))?.message).toContain('found 3 credential hit(s) on 3 conversation page(s)');+ });+});diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex e3dc166564..6bdc1b8b2b 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -669,6 +669,10 @@"category": "meta","name": "retrieval_feedback_health"},+ {+ "category": "brain",+ "name": "transcript_secret_exposure"+ },{"category": "meta","name": "revision_backfill"diff --git a/test/secret-scan-perf.test.ts b/test/secret-scan-perf.test.tsindex cd10898921..c910d09958 100644--- a/test/secret-scan-perf.test.ts+++ b/test/secret-scan-perf.test.ts@@ -495,3 +495,21 @@ describe('security fix wave shapes are linear (A1 walks, A2, A3, A5; ENG-15, ENGexpect(ms).toBeLessThan(300);});});++describe('labeled_credential (transcript lane): every candidate start does constant work', () => {+ const LABELED = { highEntropy: true, labeledCredentials: true } as const;+ const adversaries: Array<[string, string]> = [+ ['240 KB of `login `', 'login '.repeat(40_000)],+ ['220 KB of `login: a / `', 'login: a / '.repeat(20_000)],+ ['200 KB of `password: `', 'password: '.repeat(20_000)],+ ['a label, 200k spaces, then a value', 'password:' + ' '.repeat(200_000) + 'x'],+ ['200 KB of `a/` after a login label', 'login: ' + 'a/'.repeat(100_000)],+ ['20000 dangling pair lines', Array.from({ length: 20_000 }, () => 'login: alice-example /').join('\n')],+ ];+ for (const [name, text] of adversaries) {+ test(`${name}: redact < 400ms`, () => {+ const ms = elapsedMs(() => { redactFindings(text, LABELED); });+ expect(ms).toBeLessThan(400);+ });+ }+});diff --git a/test/transcript-labeled-credential.test.ts b/test/transcript-labeled-credential.test.tsnew file mode 100644index 0000000000..713bd4c868--- /dev/null+++ b/test/transcript-labeled-credential.test.ts@@ -0,0 +1,144 @@+/**+ * The transcript lane's `labeled_credential` detector (#6147 idea, widened).+ * A low-entropy password typed into a conversation (`password: hunter2`,+ * `login alice / hunter2`) cleared both the vendor shapes and the+ * entropy-gated assignment heuristic, so it reached the searchable+ * conversation page verbatim.+ *+ * MUST_REDACT holds every leak form from the investigation lane's bypass+ * probe; MUST_KEEP holds its over-redaction cases plus code and prose a+ * coding transcript is full of. Credential values are synthetic.+ */+import { describe, expect, test } from 'bun:test';+import { buildSyntheticBrainCorpus } from '../scripts/secret-scan-fp-budget.ts';+import { redactFindings, scanText } from '../src/core/secret-scan.ts';+import { LABELED_STOPLIST, labeledEchoEligible } from '../src/core/secret-scan-labeled.ts';+import { redactSession, renderSessionParts } from '../src/core/transcripts/render.ts';+import type { ParsedSession } from '../src/core/transcripts/types.ts';++const PW = ['hunter', '2'].join('');+const LONG_PW = ['Tr0ub4', 'dor&3x'].join('');++function session(texts: string[], meta: Partial<ParsedSession['meta']> = {}): ParsedSession {+ return {+ meta: { harness: 'claude-code', sessionId: 'labeled-cred-0001', startedAt: '2026-10-06T09:00:00.000Z', ...meta },+ messages: texts.map((text, i) => ({ role: i % 2 === 0 ? 'user' : 'assistant', timestamp: `2026-10-06T09:00:0${i}.000Z`, text })),+ };+}++function pageText(texts: string[]): string {+ return redactSession(session(texts), { userPatternsPath: '/nonexistent' }).session.messages.map((m) => m.text).join('\n');+}++const MUST_REDACT: Array<[string, string]> = [+ ['bare password label', `password: ${PW}`],+ ['username then password on one line', `username: alice-example password: ${PW}`],+ ['delimiter-free login pair', `login alice-example / ${PW}`],+ ['dash-delimited login pair', `Login - alice-example / ${PW}`],+ ['single-quoted pair', `login: 'alice-example' / '${PW}'`],+ ['backticked pair', `login: \`alice-example\` / \`${PW}\``],+ ['full-width colon', `login:alice-example / ${PW}`],+ ['creds label', `creds: alice-example / ${PW}`],+ ['user/pass label', `user/pass: alice-example / ${PW}`],+ ['colon-joined pair', `login: alice-example:${PW}`],+ ['equals and slash without spaces', `login=alice-example/${PW}`],+ ['pair split across a newline', `login: alice-example /\n${PW}`],+ ['credentials pair', `credentials: alice-example / ${PW}`],+ ['plain login pair', `login: alice-example / ${PW}`],+ ['markdown bold label', `**Password:** ${PW}`],+ ['JSON key', `{"password": "${PW}"}`],+ ['prefixed env name', `DB_PASSWORD=${PW}`],+ ['full-width colon after password', `password:${PW}`],+ ['pwd label', `pwd=${PW}`],+ ['passcode label', `passcode: ${PW}`],+ ['trailing sentence punctuation', `The password: ${PW}.`],+];++const MUST_KEEP: Array<[string, string]> = [+ ['login flow prose', 'Login: email/password flow is broken'],+ ['SSO provider pair', 'login: Google/GitHub SSO'],+ ['doc path', 'credentials: docs/auth.md'],+ ['host and path', 'login: example.test/path'],+ ['n/a', 'login: n/a'],+ ['type annotation', 'password: string'],+ ['validator chain', 'password: z.string().min(8)'],+ ['request field', 'password = req.body.password'],+ ['shell pwd output', 'pwd: /home/alice-example'],+ ['PWD env', 'PWD=/home/alice-example'],+ ['mask', 'password: ********'],+ ['prose after the label', 'Password: changed yesterday'],+ ['yes', 'password: yes'],+ ['login page path', 'login page / step2'],+ ['env reference', 'password=$DB_PASS'],+ ['template reference', 'password: ${DB_PASSWORD}'],+ ['identifier declaration', 'const hashedPassword: string'],+ ['identifier value', 'password: hashedPassword'],+ ['delimiter-free prose', 'password reset flow'],+ ['URL after login', 'login: https://example.test/v2'],+ ['placeholder', 'password: <your password>'],+ ['function call', 'pwd = os.getcwd()'],+ ['versions', 'login: v1.2/v1.3'],+ ['type name', 'password: SecretStr = Field()'],+ ['await', 'const passphrase = await passphraseFrom(args);'],+ ['code span label', 'the libpq form (`password=`, `sslpassword=`) is scrubbed'],+ ['already redacted', 'password: <REDACTED:high_entropy_assignment>'],+];++describe('labeled_credential on the transcript page lane', () => {+ for (const [name, text] of MUST_REDACT) {+ test(`redacts: ${name}`, () => {+ const out = pageText([text]);+ expect(out).not.toContain(PW);+ expect(out).toContain('<REDACTED:labeled_credential>');+ });+ }+ for (const [name, text] of MUST_KEEP) {+ test(`keeps: ${name}`, () => {+ expect(pageText([text])).toBe(text);+ });+ }++ test('only the password half of a pair is claimed; the user name stays readable', () => {+ expect(pageText([`login: alice-example / ${PW}`])).toBe('login: alice-example / <REDACTED:labeled_credential>');+ });++ test('the receipt counts a typed labeled_credential finding', () => {+ const red = redactSession(session([`password: ${PW}`]), { userPatternsPath: '/nonexistent' });+ expect(red.redactionCount).toBe(1);+ expect(scanText(`password: ${PW}`, { labeledCredentials: true }).map((f) => f.pattern)).toEqual(['labeled_credential']);+ });++ test('a value of 8+ characters joins the session-wide echo list: a bare repeat in another message and the title is scrubbed', () => {+ const red = redactSession(+ session([`creds for staging: login alice-example / ${LONG_PW}`, `retrying with ${LONG_PW} now`], { title: `staging ${LONG_PW}` }),+ { userPatternsPath: '/nonexistent' },+ );+ expect(JSON.stringify(red.session)).not.toContain(LONG_PW);+ expect(red.session.messages[1].text).toBe('retrying with <REDACTED:labeled_credential> now');+ const content = renderSessionParts(red).parts[0].content;+ expect(content).not.toContain(LONG_PW);+ });++ test('echo floor: a short or common value is redacted at its label but never scrubbed elsewhere', () => {+ const out = pageText(['pwd: 1234', 'the room is 1234 and the code reviewer said 1234']);+ expect(out).toBe('pwd: <REDACTED:labeled_credential>\nthe room is 1234 and the code reviewer said 1234');+ expect(labeledEchoEligible('1234')).toBe(false);+ expect(labeledEchoEligible('passwords')).toBe(true);+ expect(labeledEchoEligible('required')).toBe(false);+ expect(LABELED_STOPLIST.has('required')).toBe(true);+ });+});++describe('labeled_credential is opt-in', () => {+ test('off by default, and off with only highEntropy (the push gate and every other lane)', () => {+ expect(scanText(`password: ${PW}`)).toEqual([]);+ expect(scanText(`password: ${PW}`, { highEntropy: true })).toEqual([]);+ expect(redactFindings(`login alice-example / ${PW}`, { highEntropy: true }).text).toBe(`login alice-example / ${PW}`);+ });++ test('the synthetic brain-like clean corpus gains no labeled_credential finding', () => {+ for (const doc of buildSyntheticBrainCorpus().filter((d) => d.kind === 'clean')) {+ expect(scanText(doc.text, { highEntropy: true, labeledCredentials: true }).filter((f) => f.pattern === 'labeled_credential')).toEqual([]);+ }+ });+});diff --git a/test/transcripts-secret-audit.test.ts b/test/transcripts-secret-audit.test.tsnew file mode 100644index 0000000000..9ae4a5a024--- /dev/null+++ b/test/transcripts-secret-audit.test.ts@@ -0,0 +1,111 @@+/**+ * The installed-base transcript secret audit (#6147) and its doctor check.+ * Pages imported before the labeled-credential detector keep a typed+ * password; `gbrain transcripts audit-secrets` lists them by slug and count+ * (never a value) and `transcript_secret_exposure` reads its cached summary.+ *+ * R3/R4: engine in beforeAll, disconnect in afterAll; state reset per test.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import {+ TRANSCRIPT_SECRET_AUDIT_KEY,+ auditTranscriptSecrets,+ loadTranscriptSecretAudit,+ saveTranscriptSecretAudit,+} from '../src/core/transcripts/secret-audit.ts';+import { transcriptSecretExposureCheck } from '../src/commands/doctor/checks/transcript-secrets.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';++const PW = ['hunter', '2'].join('');+let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+});++async function conversation(slug: string, body: string): Promise<void> {+ await engine.putPage(slug, {+ type: 'conversation', title: 'session', compiled_truth: body,+ frontmatter: { transcript_import: { harness: 'codex', session_id: slug } },+ });+}++const ctx = () => ({ engine, progress: { heartbeat() {} } }) as unknown as DoctorContext;++describe('transcripts audit-secrets', () => {+ test('lists affected conversation pages with counts and lines, never values; other pages are not scanned', async () => {+ await conversation('conversations/sessions/2026-01-02-codex-aaaaaaaaaaaa', `intro\nuser: password: ${PW}\nok\nlogin alice-example / ${PW}`);+ await conversation('conversations/sessions/2026-01-03-codex-bbbbbbbbbbbb', 'nothing secret here');+ await engine.putPage('notes/ops', { type: 'note', title: 'ops', compiled_truth: `password: ${PW}` });+ const result = await auditTranscriptSecrets(engine);+ expect(result.pages_scanned).toBe(2);+ expect(result.pages_affected).toBe(1);+ expect(result.hits_total).toBe(2);+ expect(result.by_pattern).toEqual({ labeled_credential: 2 });+ expect(result.pages).toEqual([+ { slug: 'conversations/sessions/2026-01-02-codex-aaaaaaaaaaaa', source_id: 'default', hits: { labeled_credential: 2 }, lines: [2, 4] },+ ]);+ expect(JSON.stringify(result)).not.toContain(PW);+ });++ test('the cached summary carries no slugs and no values', async () => {+ await conversation('conversations/sessions/2026-01-02-codex-aaaaaaaaaaaa', `password: ${PW}`);+ expect(await saveTranscriptSecretAudit(engine, await auditTranscriptSecrets(engine))).toBe(true);+ const raw = (await engine.getConfig(TRANSCRIPT_SECRET_AUDIT_KEY)) ?? '';+ expect(raw).not.toContain(PW);+ expect(raw).not.toContain('conversations/');+ expect((await loadTranscriptSecretAudit(engine))?.hits_total).toBe(1);+ });+});++describe('transcript_secret_exposure doctor check', () => {+ test('no imported conversation pages: no check emitted', async () => {+ expect(await transcriptSecretExposureCheck(ctx())).toBeNull();+ });++ test('never audited: warn with the read-only audit as fix', async () => {+ await conversation('conversations/sessions/2026-01-02-codex-aaaaaaaaaaaa', `password: ${PW}`);+ const check = await transcriptSecretExposureCheck(ctx());+ expect(check?.status).toBe('warn');+ expect((check?.fix as { argv: string[] }).argv).toEqual(['gbrain', 'transcripts', 'audit-secrets', '--json']);+ expect(check?.message).toContain('never been audited');+ });++ test('a cached audit with hits warns with its age; a clean audit is ok; the check never scans pages', async () => {+ await conversation('conversations/sessions/2026-01-02-codex-aaaaaaaaaaaa', `password: ${PW}`);+ const now = Date.parse('2026-10-06T12:00:00.000Z');+ await saveTranscriptSecretAudit(engine, await auditTranscriptSecrets(engine, { now: () => new Date(now - 3 * 3_600_000) }));+ const warn = await transcriptSecretExposureCheck(ctx(), now);+ expect(warn?.status).toBe('warn');+ expect(warn?.message).toContain('(3h ago) found 1 credential hit(s) on 1 conversation page(s)');+ expect(JSON.stringify(warn)).not.toContain(PW);++ await conversation('conversations/sessions/2026-01-02-codex-aaaaaaaaaaaa', 'password: <REDACTED:labeled_credential>');+ const stale = await transcriptSecretExposureCheck(ctx(), now);+ expect(stale?.status).toBe('warn');++ await saveTranscriptSecretAudit(engine, await auditTranscriptSecrets(engine, { now: () => new Date(now) }));+ const ok = await transcriptSecretExposureCheck(ctx(), now);+ expect(ok?.status).toBe('ok');+ });++ test('a source-scoped audit does not clear the brain-wide warning', async () => {+ await conversation('conversations/sessions/2026-01-02-codex-aaaaaaaaaaaa', 'clean');+ await saveTranscriptSecretAudit(engine, await auditTranscriptSecrets(engine, { sourceId: 'default' }));+ const check = await transcriptSecretExposureCheck(ctx());+ expect(check?.status).toBe('warn');+ expect(check?.message).toContain('covered only source default');+ });+});