Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Pre-push secret scan: stream staged blobs over 25 MiB in bounded windows

garrytan99be598cabab
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.md
index c26f12505a..3e6de0da58 100644
--- a/docs/architecture/key-files/agent-bootstrap-continued.md
+++ b/docs/architecture/key-files/agent-bootstrap-continued.md
@@ -27,7 +27,7 @@
- `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: the `DELEGATED_SYNC_OPTION_FIELDS` table is the single source of truth for the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). #6317 (D1 a′), managed Postgres brains: `maybeDelegateManagedSyncToServe(engine, args, opts)` runs post-connect from `runSingleSourceSync` right before `performSync`; it probes the host's live full `serve` consumer through `persistence_consumers` (`consumer-heartbeat.ts`, the database, never a socket), admits the catch-up's flags (`--no-bulk`, `--lanes`/`--no-lanes`, `--json`, the processing flags), sends the CLI's durable `cli` registration in `sync_start`, prints the drain's own numbered lines from `sync_status` (`managed`, `lines`, `drain`, `next`) and returns the SyncResult to the in-process printers, so exit codes and the JSON envelope do not change. The serve verifies the registration (`withVerifiedLocalRegistration`) and runs `performSync({ drain: true })` as that writer under `withHumanLineSink`; the shared-secret lane stays under `withLegacySyncDelegation` and is still refused on a managed brain; a denied, revoked or stdio registration answers `sync_start` with `permission_denied` and the envelope (`refusal`), which the CLI rethrows. Every other rung (no owner, a non-serve owner, an unsupported flag, no socket, the kill switch, `stale_serve` / `unsupported_kind` from an older serve, `source_mismatch`, a serve lost mid-drain) runs without the serve with one actionable line; only the opt-out, a serve not answering its socket and a `stale_serve` serve call `forceOwnConsumer` (#6543), the rest admit writes the serve consumes under `persistence.single_consumer`. #6696: both builders send `explicitProcessing` as computed, so a flagless run sends `[]` and adopts an unfinished cursor's stored options exactly as in-process; the serve reads a payload without the list (an older CLI) as explicit for each processing boolean it sends `true`, a flagless payload as `[]`, and keeps a supplied list as sent. Wire `embedDeferred` (sent only when true) carries the cost gate's runtime deferral, so adopting a cursor that stores `noEmbed=false` never embeds in that run. `maybeDelegateManagedSyncToServe` refuses `--skip-failed` / `--include-gitignored` on a managed source with `managed_sync_flag_refused` before any probe or socket call (`test/sync-delegated-options-6696.serial.test.ts`, `test/sync-managed-forbidden-flags-6696.test.ts`). Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/serve-sync-handoff.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step) and `test/e2e/serve-delegated-managed-sync.serial.test.ts` (Postgres, spawned serve, MCP latency printed).
- `src/core/capability.ts` — config-plane keyless/keyed detection + the honest capability report (per-provider keyless banner: OpenAI = semantic search + auto-extraction, Voyage = semantic search, Anthropic = auto-extraction) rendered by verify and the runbook. The extraction probe resolves through the SAME shared `resolveEffectiveChatModel` the gateway's reconfigure fallback uses (`GBRAIN_MODEL` > servable file pin > key-aware tier default), so a stale unservable pin degrades identically in the report and at runtime. Key/env fold comes from `mergedProviderEnv` (`src/core/ai/provider-env.ts`). Accepted limitation (documented in the module): DB-plane overrides (`models.default`, `facts.extraction_model`) are invisible to this engine-less probe; the runtime gate in `facts/extract.ts` and the engine-aware pre-enqueue gate in `facts/backstop.ts` are the backstops.
- `src/core/readiness.ts` — capability readiness (agent operator contract A7): `ReadinessEntry {capability, state, reason, why, fix, tier, asset?, http_visible}` for embeddings, chat_llm, writeback, tool_surface, sync, harness_wiring (config tier) and worker, backup per asset, migrations, sync (probed tier); each capability's reasons are a closed exported const (`EMBEDDINGS_REASONS`, …). `configReadiness(cfg, {transport})` is synchronous and memoized per (config object, transport); its only file read is one memoized `peekLock()` (none when this process holds the lock, via `heldLockFor`), plus one process-wide gbrain-binary PATH lookup on the CLI transport only. The HTTP view drops `http_visible:false` entries and passes the rest through `redactForTransport`. `probedReadiness(engine, {cache})` never calls `getStats`/`getHealth`; 60 s cache (`createReadinessCache()` per ServeHttpContext, process-wide otherwise), single-flight, 2 s per-probe bound, stale-while-revalidate; `readinessTail` is MCP initialize's best-effort 250 ms tail. `embeddingEnablement(cfg)` is the one "turn on embeddings" fix: resolves the datastore (PGLite path, Postgres, a mount from `--brain`/`GBRAIN_BRAIN_ID`) and the column width, picks a keyed provider that fits (or asks for a key with `inputs`), and emits in-place `init --force --embedding-model … --embedding-dimensions … [--path …]` or, for a mount, `embeddings enable --brain …`; it never rebuilds a column. `exclusiveFix` turns an exclusive fix into a two-step plan (actor `user` stops the owning serve named by `lock_owner`, `then` the command) unless the command delegates to the owner. A live status-only `serve --http` marker (`liveStatusMarkers`, config plane) makes CLI `harness_wiring` `serve_status_only` with `transport: 'http'` and the status reason's fix (`httpStatusServerEntry`, shared with doctor), never "start `gbrain serve --http`" on the port it holds. `harnessWiringEntry` builds harness-native stdio registration (absolute binary, `stdioServeArgv` with `REGISTRATION_SURFACE` = `starter`, or `input.surface` from `gbrain init --surface`; `configReadiness(cfg, {transport, surface})` skips the memo when a surface is passed), shared-HTTP `bootstrap harness`, or the MEMORY_VERBS install anchor, with effects and destinations disclosed. Consumers never coach on `disabled_by_choice`. Tests: `test/readiness.test.ts`, `test/readiness-http-cost.test.ts`, `test/readiness-advice-lint.test.ts` (no hand-written enablement advice outside this module; shrink-only baseline), `test/readiness-embedding-enablement.serial.test.ts` (the E2E matrix).
-- Secret and sensitivity scanning (`src/core/secret-scan.ts`, `src/core/secret-scan-allowlist.ts`, `src/core/secret-scan-work.ts`, `src/core/context/sensitivity-scan.ts`): see [secret-scan.md](secret-scan.md).
+- Secret and sensitivity scanning (`src/core/secret-scan.ts`, `src/core/secret-scan-allowlist.ts`, `src/core/secret-scan-stream.ts`, `src/core/secret-scan-work.ts`, `src/core/context/sensitivity-scan.ts`): see [secret-scan.md](secret-scan.md).
- `src/core/transcripts/render.ts` — session → conversation page(s) for `gbrain transcripts ingest`. `redactSession` is two-phase over message text, speaker labels, title and every raw-meta string, BEFORE any engine write: `planRedaction(…, { highEntropy: true, echoValues })` on every field into ONE session-wide echo dictionary, then `applyRedaction` per field, so a bearer or high-entropy value claimed in one message is scrubbed where it recurs bare in any other field, in either order; echoes add nothing to `redactionCount` (fail-closed: a scanner/pattern throw aborts the session), then the operator pattern file; nested raw-meta values are dropped. This is the only lane that opts into the entropy heuristic (pasted `.env` lines are most likely here). Rendering shares the imessage-slack anchor regex with the parser and escapes body lines that would forge it; long sessions split into `-pN` parts at message boundaries once a part would pass `PART_TARGET_BYTES` (45,000 bytes, 0.9 × the content-sanity warn line `DEFAULT_BYTES_WARN`; `renderSessionParts(…, { partTargetBytes })` overrides it for measurement and refuses a non-positive or non-integer target). No message is truncated (#6388; the former 4,000-character `MESSAGE_CHAR_CAP` is gone): a message whose block would not fit a part becomes continuation blocks that repeat its speaker and timestamp anchor, cut at line breaks or, inside an over-long line, at a code-point boundary (a cut piece always lands on the generated anchor line, so every body line was escaped whole); overlap repeats only whole messages, never continuation blocks, and is trimmed so no part body passes the target (`test/transcript-long-message-render.test.ts`). `scripts/measure-transcript-split-cost.ts` imports one deterministic synthetic 1 MB session through the real redact → render → `importFromContent` path into in-memory PGLite with a token-counting stub embedder at the former 300,000-byte target and the current one: 4 → 27 pages (×6.75), 380 → 424 chunks (×1.116), 199,614 → 217,057 embed input tokens (×1.087); the extra tokens are the part headers and the two overlap messages repeated at each boundary. Each `RenderedPart` carries the `frontmatter` it owns and its `body`; on re-ingest `runTranscriptsIngest` carries any other key already on the page (a review flag another tool added) onto the re-rendered part, except the re-derived safety and atom-scan markers (#5431, `test/transcripts-retitle.test.ts`). `redactSession` plans every field with `highEntropy` and `labeledCredentials` on.
- `src/core/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.
- Workspace push and backup coverage (`src/core/workspace-push.ts`, `src/core/backup/{coverage,repository}.ts`): see [workspace-push-and-backup.md](workspace-push-and-backup.md).
diff --git a/docs/architecture/key-files/secret-scan.md b/docs/architecture/key-files/secret-scan.md
index 921bca7fcb..4eb3ceb57d 100644
--- a/docs/architecture/key-files/secret-scan.md
+++ b/docs/architecture/key-files/secret-scan.md
@@ -7,4 +7,5 @@ compiled-context sensitivity scan and the transcripts redactor, and the composed
sensitivity detector built on it.
- `src/core/secret-scan.ts` — pattern-based secret detection shared by `sources push`, bootstrap verify, the compiled-context sensitivity scan and the transcripts redactor. Detection is FORMAT-based, not prefix-only: vendor shapes (anthropic, openai, voyage, github, gitlab, slack, aws AKIA/ASIA, google, stripe, sendgrid, twilio, supabase sb_secret_/sbp_, npm, huggingface, `digitalocean` `do[opr]_v1_` + 64 hex, gbrain), JWTs, private keys (whole-text claims, below), plus four catch-alls appended LAST (`bearer` — prebuilt two-group layout so only the token is the value; `db_url_credentials` — the `scheme://user:pass@` span of database URLs, host/db kept; `url_credentials` — the same span for `http(s)` (scheme case-insensitive, `gi`), user 0–128 stopping at `:`/`/`, password 1–256 excluding whitespace, `@`, `"`, `'`, `/`, `?`, `#`, with a `validate` hook that rejects placeholder passwords (`<...>`, `${...}`, `$VAR`, all `*`, all `x`); `basic_auth` — two prebuilt case-insensitive forms, `Authorization: Basic` with a 4–2048 char value and bare `Basic` with 16–2048, both with a hard right edge and a `validate` that requires the value to base64-decode to printable ASCII containing `:`; it is NOT in the bearer family, so it joins neither the echo dictionary nor `secret:bearer`). The pattern contract: `CorePattern` carries optional `flags` (default `'g'`), `precheck`, `validate(value)` (O(value), run on the whole match before the claim and the union split; a rejected match is not re-tried from inside) and `since` (the gbrain version that added or last changed the rule; `SECURITY_WAVE_SINCE` = `0.60.31.0` on `digitalocean`, `url_credentials`, `basic_auth` and `private_key_pem`, kept in step with the release that ships a rule change). Compiled patterns keep group 1 = anchor, group 2 = value. `patternSince(pattern)` reads the map; every finding of such a pattern carries `SecretFinding.since`, which the push and bootstrap refusals render. Fixed-length shapes carry a trailing negative lookahead. Per-line claimed-span dedupe is first-wins for ATTRIBUTION (order matters: `Bearer <vendor key>` keeps the vendor name, a fully covered later span is skipped) but coverage is the UNION: every unclaimed slice of a later overlapping span is claimed as a hit of the later pattern (own value, own fingerprint), so a database URL whose username is a vendor-shaped id still loses its password. The transcript-only `labeled_credential` rule (`ScanOpts.labeledCredentials`) lives in `secret-scan-labeled.ts` (Security). The opt-in `high_entropy_assignment` rule (`ScanOpts.highEntropy`) requires a 12+ char value that contains a digit and a non-digit AND clears 3.5 bits/char on the bias-corrected (Miller-Madow) estimate `correctedEntropy`, since raw per-character entropy is capped at log2(n) and rejected most random 12-16 char secrets. It is two compiled patterns sharing the name: QUOTED (after `"` or `'`, any run of non-quote, non-whitespace characters) and UNQUOTED (the legacy `[A-Za-z0-9+/_=-]` class plus `!#$%*@^~.?<>`; never `&`, `()[]{}`, `:`, `,` or `;`, so query strings, calls and SQL `SET` lists stay intact, and a password carrying `,`/`;` matches only quoted; the last character excludes `.?!`, so a sentence's full stop is not claimed). Its `validate` rejects values that start with `scheme://`, `./`, `~/`, `${`, `$(` or `<REDACTED:`, dotted identifier paths (`process.env.X`) and `/`-paths holding a character outside the legacy class. Consumers with it on: retrieval output, transcript ingest, hooks and the hook heartbeat, the atoms drain, `embed-facts.ts` error text and the context-engine relay re-scan. Off: the push gate, bootstrap verify/repo and the compiled-context sensitivity scan. Own minimal allowlist + `<ws>/.gbrain-scan-allow` per-finding overrides — deliberately NOT the repo's `.gitleaks.toml` (a public-repo CI fixture policy); the allowlist block (`loadWorkspaceAllowlist`, the glob dialect `globToRegExp`/`matchesGlob`, `valueAllowlisted`/`pathAllowlisted`, `SCAN_ALLOW_FILENAME`, the 16-hex fingerprint floor) lives in `src/core/secret-scan-allowlist.ts` since wave 16 (G4.1, the 1500-line module cap) and is re-exported here unchanged (`test/secret-scan-allowlist.test.ts`). `correctedEntropy` is one histogram pass (distinct count = histogram size; byte-identical to the former `shannonEntropy + Set` form, `test/secret-scan-entropy-equivalence.test.ts`; ~80 → ~25 ms per 250 × 4096-char segment). `ScanOpts.work` / `RedactOpts.work` takes a `ScanWork` accumulator (`src/core/secret-scan-work.ts`: lines, regex execs, candidates per pattern, chars handed to the entropy gate counted inside `correctedEntropy`, validate calls, claims, union splits, echo sweeps) pinned exactly on the perf fixture by `test/secret-scan-work-counters.test.ts`; the perf file's absolute bounds stay the only guard on per-character cost. Deliberately NOT patterns: `sb_publishable_`, Supabase project refs (identifiers, not credentials). Never spell a literal database or `http(s)` URL with userinfo, or any credential, in this file's comments or in fixtures (assemble test values at runtime; `scripts/check-pg-url-redaction.sh` greps `src/` for every `db_url_credentials` scheme). Long lines are scanned in full (no length cap — a secret on a 1 MB minified line must still redact); what keeps that linear is bounded quantifiers on every shape whose value class could otherwise run to end-of-line — `db_url_credentials` (user ≤128 stopping at `:`/`/`; password 1–256 stopping only at whitespace, `@` and the string delimiters `"`/`'`, so unescaped `/ { } < > | ^ \` and backtick passwords redact), `jwt` (prebuilt so its boundary excludes `-` as well as `_`; segments ≤4096), `high_entropy_assignment` (≤64 identifier chars after the keyword, value ≤4096), `url_credentials` (user ≤128, password ≤256), `basic_auth` (value ≤2048, so its decode is constant work) and the private-key walks (below) — plus a per-pattern `precheck` substring gate on the catch-alls (`@` for both URL patterns; `earer`/`EARER`, since an all-caps `BEARER` scheme is accepted; a case-insensitive `basic`), a carried next-newline position in `scanPemBlocks` (sticky -1, so the header-line count is O(text) even when thousands of hits sit ahead of a newline-free multi-megabyte tail), a lazily-allocated per-line claimed-char bitmap behind the first-wins dedupe (O(value) per hit), and a windowed `buildPreview` (whole line ≤160 chars; otherwise hit−40…+80, edges snapped outward to whole spans, every claimed span in the window spliced by position, so a preview never carries a sibling secret or a fragment). `redactFindings` (= `planRedaction` + `applyRedaction`) rebuilds the text by SPAN-SPLICE in one O(text + hits) pass over the claimed spans, and fills the UNCLAIMED gaps with a bounded echo pass: the values claimed by `bearer` and `high_entropy_assignment` form an echo dictionary (value → pattern; floors `ECHO_MIN_CHARS_BEARER` = 20 / `ECHO_MIN_CHARS_ENTROPY` = 12, values ≤ `ECHO_MAX_VALUE_CHARS` = 512, the first `ECHO_MAX_UNIQUE` = 64 unique values in claim order across BOTH patterns — a value past either cap is redacted at its claim, its echoes are the accepted miss), matched by a streaming merge over the ORIGINAL text — per value, the next occurrence at or beyond the emit cursor (`indexOf` resuming at the cursor, re-sought only once the cursor passes it), leftmost-longest at each step, emitted incrementally into the unclaimed gaps — so retained state is O(values) however long the text is (occurrences are never collected into a list) (never an alternation RegExp, never over emitted tokens). Echoes add no findings. `planRedaction` feeds a caller-supplied shared map (`RedactOpts.echoValues`) and `applyRedaction` reads it at apply time, so a multi-field document scrubs an echo in one field of a value claimed in another. Every other pattern redacts exactly what `scanText` reports (a value embedded past its boundary is left as-is; vendor shapes re-match on their own). PRIVATE KEYS: `pemClaims` finds `BEGIN`/`END … PRIVATE KEY` fences in two global passes and merges them in text order. BLOCK: a BEGIN whose next fence is an END within `PEM_BODY_MAX_CHARS` (16384) is claimed header through END; a block never swallows a later BEGIN. FORWARD (BEGIN with no END in view): the header plus the body lines that follow; a header followed by no body line (a marker quoted in prose) is claimed alone. BACKWARD (END with no BEGIN in view): the body lines before the fence plus the fence; an END with no body line before it is no claim. A body line is a whole-line base64 run (`A-Za-z0-9+/=`) indented by up to 16 spaces/tabs; line ends are `\n`, `\r\n` or the literal JSON escapes; interior lines are 16–128 chars, the line next to a fence and a partial line at a cut 1–128; optional RFC 1421 `Proc-Type:`/`DEK-Info:` lines and one blank line may follow BEGIN; a line with anything else, or a run over 128 chars, ends the body. Total claimed body stays within `PEM_BODY_MAX_CHARS`. Each walk stops at the neighbouring fence or the previous claim, so the pass is linear (20k unterminated BEGINs, 20k END-only fences and 1 MB of base64 lines are perf-pinned). Per-line hits that fall wholly inside a key claim are dropped (one key, one finding). A FORWARD claim's finding also carries `legacyFingerprint`, the header-only fingerprint earlier releases reported, so `workspace-push.ts` can name a stale allowlist entry; a truncated key's fingerprint covers its body and therefore depends on where the text was cut, so it is not a stable allowlist key. `privateKeySpans(text)` exports the same claims as sorted, disjoint `{start, end}` spans. Accepted misses: body on the header's own line, space-joined single-line keys, blockquoted (`> `) keys, base64 runs over 128 chars, body past 16384 chars, `http(s)` passwords containing a literal `/`, `?` or `#`, Basic values over 2048 chars, digitless assignment values, dotted passwords whose every segment starts with a letter, and unquoted passwords containing `,` or `;`. False-positive budget: `scripts/secret-scan-fp-budget.ts` diffs findings against a base ref's scanner (`--base`, default `origin/master`) (`--dir <brain>` reports per-pattern counts only, never content) and `test/secret-scan-fp-budget.test.ts` pins a synthetic brain-like fixture (zero findings on its non-secret part in both modes, every planted secret redacted). Shape tests: `test/secret-scan-credential-shapes.test.ts`, `test/secret-scan-private-key-spans.test.ts`. Perf pins: `test/secret-scan-perf.test.ts`. Retrieval output is another consumer of its canonical scanner; that output boundary does not sanitize internal evaluation/provider inputs.
+- `src/core/secret-scan-stream.ts` — `scanTextStream(chunks, opts)`, the windowed scan of a byte stream too large to hold as one string (the push gate's staged blobs over 25 MiB). Bytes are decoded by a streaming `TextDecoder` (`ignoreBOM`, so a split multi-byte character joins and invalid bytes become U+FFFD as `Buffer.toString` makes them) and handed to `scanTextSpans` (`secret-scan.ts`: `scanText` plus each claim's absolute span, allowlisted claims kept with `finding: null`) in windows of at most `STREAM_SCAN_WINDOW_CHARS` (8 Mi UTF-16 units). Each next window starts at a line start at least `STREAM_SCAN_OVERLAP_CHARS` (64 Ki, above the longest claim: a private key's 16384-char body plus fences, a jwt's 3 × 4096) before the previous end, or mid-line at exactly the overlap (never inside a surrogate pair) when the line is too long. A window keeps the claims that start before the next window's start, the last window keeps the rest, and a claim wholly inside a span an earlier window kept (a seam's partial view, or an exact duplicate) is dropped; lines are 1-based over the whole stream. `streamScanWork` (@internal) counts windows, bytes, scanned chars and the largest window. `test/secret-scan-stream.test.ts` pins equality with `scanText` across both seams of a window, mid-line splits, split multi-byte characters, invalid UTF-8 and a BOM.
- `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`).
diff --git a/docs/architecture/key-files/workspace-push-and-backup.md b/docs/architecture/key-files/workspace-push-and-backup.md
index 2e4cf56d30..bc7f4394d2 100644
--- a/docs/architecture/key-files/workspace-push-and-backup.md
+++ b/docs/architecture/key-files/workspace-push-and-backup.md
@@ -8,4 +8,4 @@ guide: [backup check](../../operations/backup-check.md).
Key files:
- `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. An ordinary (non-forced) `getBackupStatus` re-probes before the one-hour sweep clock expires when the cached verdict still has pending repository evidence (a configured remote left `budget_exhausted`, relabelled `stale`, or `verified` older than the evidence window), at most once per `BACKUP_CONTINUATION_THROTTLE_MS` (60 s); real failures (`unavailable`, `mismatch`, `missing_ref`) are not retried per check (#6614, #6687; `test/backup-pending-continuation.serial.test.ts`). `budgetAllowsProbe` starts a probe only with its full two-second slot inside the deadline (a sub-slot leftover defers the root as `budget_exhausted` and the sweep keeps that root's first-pass `verified` evidence); an `unavailable` verification carries `cause: 'timeout' | 'exit'` (#6499). 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`. #6083: `assessBackupRepository` drops physical-root metadata (`withoutPhysicalRootMetadata`) from both porcelain probes, classifies a root with no origin remote as `no_remote` even after a recorded push failure, and gives a managed canonical worktree (`managedFilesystemRootFor`) the read-only `gbrain sources writer status [<source>] --probe --json` fix instead of the refused `sources push` (`backup-coverage.ts` explains that fix with the retry-effects step).
-- `src/core/workspace-push.ts` — `gbrain sources push`: deny-glob backstop (tracked `*.pglite`/`.env*`, and since #5186 the ownership markers `.gbrain-owner.json` / `.gbrain-owner-*.json` / `.gbrain-owner.json.*.tmp` plus `.gbrain-bootstrap.lock/**`, refused regardless of .gitignore state; untracked matches are excluded from the commit and named in `excludedUntracked`) → stage FIRST → secret-scan the STAGED index blobs via `git cat-file` (closes the scan-then-stage TOCTOU — scanned bytes == committed bytes) → commit FIRST → divergence-safe pull → push, under one cross-platform lock (mkdir-atomic; flock is not a dependency — macOS) keyed on the repo's realpath, so a symlinked spelling and git's physical toplevel share it (an absent path hashes its raw string). The pre-push secret gate FAILS CLOSED: an unreadable, oversized (> `PUSH_MAX_SCAN_BYTES`), or otherwise unscannable staged blob returns `blocked_unscannable` (nothing committed) instead of sailing through — only a confirmed staged deletion is skipped, and binary/NUL-sniffed blobs are scanned anyway. Statuses map to exit codes in `src/commands/sources.ts`: `pushed`/`skipped_in_flight` → 0; `blocked_secrets`/`blocked_tracked_deny`/`blocked_unscannable`/`refused_visibility` → 5; `pull_conflict`/`push_failed`/other → 1. Refuses public AND unverifiable remotes (never fail-open); pushes even on clean trees; writes `<home>/bootstrap/push-status.json`. Parent-repo-aware (a source may be a subdirectory of the workspace repo). A `blocked_secrets` result carries `PushSecretFinding[]`: each finding adds `file`, `since`, the absolute `allowlistPath` of the root `.gbrain-scan-allow`, a shell-quoted `allowCommand` (`printf` append, runnable from any cwd), `retryCommand` (`gbrain sources push --path <abs>` plus the run's `--branch`/`--allow-unverified-remote`), `docs` (`SECRET_SCAN_REFUSAL_DOCS`, the `write-refusals.md#secret-scan-refusals-and-redaction` anchor; keep that heading) and, when the scanner's `legacyFingerprint` matches an allowlist entry, `staleAllowlistEntry { entry, replacement }`. `formatBlockedSecrets` renders the CLI text from the same objects, so human and `--json` output carry the same commands, and no field holds a value. `blockedSecretsReason` keeps `reason` a one-line summary (count, first location, pattern) within the 140 chars `sanitizePushReason` passes. `bootstrap/verify.ts` and `bootstrap/repo.ts` refusals reuse the docs anchor and print fingerprint, `since` and the absolute allowlist path. `pushStatusForWorkspace(entries, ws)` picks the record whose `repoRoot` resolves to `ws` (a single legacy record without `repoRoot` is attributed to it); `bootstrap status` `support.last_push` and doctor `bootstrap_push_health`'s dirty-tree FAIL use only that record (`test/doctor-not-verified-5432.test.ts`). Tests: `test/workspace-push-guidance.test.ts`, `test/sources-push-cli.serial.test.ts`. #6083: the managed-guard refusal record carries `code: writer_coordinator_required` (`PushStatusEntry.code`); the hook push call sites (`dirtyTreePush`, `stopPushIfDue`, SessionEnd) skip a managed root with heartbeat reason `push_managed_coordinator`; doctor `bootstrap_push_health` (`src/commands/doctor/bootstrap-checks.ts` `recordedPushFailureCheck`) reports ok when every recorded failure's tree now matches its configured origin with nothing uncommitted. #5799: `isSupersededPushStatus(entry)` / `livePushStatuses(entries)` drop a record the managed topology has superseded (code or reason prefix `writer_coordinator_required`, or a `repoRoot` that is a managed worktree now; an unreadable marker is not assumed managed), because the coordinator's git effect never writes push-status and the refusal would otherwise feed the hook's FAILING banner and staleness note forever (`test/workspace-push-superseded-status.test.ts`); the hook call sites read `livePushStatuses(readPushStatuses())`.
+- `src/core/workspace-push.ts` — `gbrain sources push`: deny-glob backstop (tracked `*.pglite`/`.env*`, and since #5186 the ownership markers `.gbrain-owner.json` / `.gbrain-owner-*.json` / `.gbrain-owner.json.*.tmp` plus `.gbrain-bootstrap.lock/**`, refused regardless of .gitignore state; untracked matches are excluded from the commit and named in `excludedUntracked`) → stage FIRST → secret-scan the STAGED index blobs via `git cat-file` (closes the scan-then-stage TOCTOU — scanned bytes == committed bytes) → commit FIRST → divergence-safe pull → push, under one cross-platform lock (mkdir-atomic; flock is not a dependency — macOS) keyed on the repo's realpath, so a symlinked spelling and git's physical toplevel share it (an absent path hashes its raw string). The pre-push secret gate FAILS CLOSED: an unreadable, oversized (> `PUSH_STREAM_SCAN_MAX_BYTES`, 512 MiB), or otherwise unscannable staged blob returns `blocked_unscannable` (nothing committed) instead of sailing through. A blob up to `PUSH_MAX_SCAN_BYTES` (25 MiB) is read whole and scanned by `scanText` as before; a larger one is found by its index size (one `ls-files -s` plus one `cat-file --batch-check`, `stagedBlobSizes`), streamed by oid through `git cat-file blob` into `scanTextStream` (`secret-scan-stream.ts`) and fails closed when git errors, runs past 10 minutes or delivers a byte count other than the recorded size (`test/workspace-push-large-blob.serial.test.ts`: a clean 30 MiB file pushes, secrets across window seams block once each with their line, the ceiling still blocks) — only a confirmed staged deletion is skipped, and binary/NUL-sniffed blobs are scanned anyway. Statuses map to exit codes in `src/commands/sources.ts`: `pushed`/`skipped_in_flight` → 0; `blocked_secrets`/`blocked_tracked_deny`/`blocked_unscannable`/`refused_visibility` → 5; `pull_conflict`/`push_failed`/other → 1. Refuses public AND unverifiable remotes (never fail-open); pushes even on clean trees; writes `<home>/bootstrap/push-status.json`. Parent-repo-aware (a source may be a subdirectory of the workspace repo). A `blocked_secrets` result carries `PushSecretFinding[]`: each finding adds `file`, `since`, the absolute `allowlistPath` of the root `.gbrain-scan-allow`, a shell-quoted `allowCommand` (`printf` append, runnable from any cwd), `retryCommand` (`gbrain sources push --path <abs>` plus the run's `--branch`/`--allow-unverified-remote`), `docs` (`SECRET_SCAN_REFUSAL_DOCS`, the `write-refusals.md#secret-scan-refusals-and-redaction` anchor; keep that heading) and, when the scanner's `legacyFingerprint` matches an allowlist entry, `staleAllowlistEntry { entry, replacement }`. `formatBlockedSecrets` renders the CLI text from the same objects, so human and `--json` output carry the same commands, and no field holds a value. `blockedSecretsReason` keeps `reason` a one-line summary (count, first location, pattern) within the 140 chars `sanitizePushReason` passes. `bootstrap/verify.ts` and `bootstrap/repo.ts` refusals reuse the docs anchor and print fingerprint, `since` and the absolute allowlist path. `pushStatusForWorkspace(entries, ws)` picks the record whose `repoRoot` resolves to `ws` (a single legacy record without `repoRoot` is attributed to it); `bootstrap status` `support.last_push` and doctor `bootstrap_push_health`'s dirty-tree FAIL use only that record (`test/doctor-not-verified-5432.test.ts`). Tests: `test/workspace-push-guidance.test.ts`, `test/sources-push-cli.serial.test.ts`. #6083: the managed-guard refusal record carries `code: writer_coordinator_required` (`PushStatusEntry.code`); the hook push call sites (`dirtyTreePush`, `stopPushIfDue`, SessionEnd) skip a managed root with heartbeat reason `push_managed_coordinator`; doctor `bootstrap_push_health` (`src/commands/doctor/bootstrap-checks.ts` `recordedPushFailureCheck`) reports ok when every recorded failure's tree now matches its configured origin with nothing uncommitted. #5799: `isSupersededPushStatus(entry)` / `livePushStatuses(entries)` drop a record the managed topology has superseded (code or reason prefix `writer_coordinator_required`, or a `repoRoot` that is a managed worktree now; an unreadable marker is not assumed managed), because the coordinator's git effect never writes push-status and the refusal would otherwise feed the hook's FAILING banner and staleness note forever (`test/workspace-push-superseded-status.test.ts`); the hook call sites read `livePushStatuses(readPushStatuses())`.
diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.md
index 6478a0879e..e0bf842187 100644
--- a/docs/guides/memory-boundaries.md
+++ b/docs/guides/memory-boundaries.md
@@ -202,7 +202,7 @@ wrong with the page.
| `put_pages` batch | 8 MiB per batch | send large pages one per `put_page`, or by file |
| Persistence journal | 64 MiB of outstanding JSON-escaped write intent per principal (was 32 MiB), 256 MiB per brain | nothing: a second large write waits for the first |
| Local persistence socket (IPC) | 32 MiB per frame, JSON-escaped | nothing for ordinary text; only a pathological page (mostly quotes or backslashes) reaches it below the ceiling |
-| Pre-push secret scan | 25 MiB per file; gbrain never writes a canonical file over it | — |
+| Pre-push secret scan | 512 MiB per staged file: up to 25 MiB a file is scanned whole, above it in bounded windows streamed from git; gbrain still never writes a canonical file over 25 MiB | split the file, or `git rm --cached` it |
| GitHub | warns at 50 MB, rejects at 100 MB | — |
| Export | streams a page stored in segments, up to the page ceiling; aborts on an inline page whose payload is over 32 MiB, which the 24 MiB ceiling makes unreachable | — |
| Company-brain inspection | 5 MB per file | unchanged |
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index 9eb11b70ae..05ec834a92 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -55,5 +55,4 @@ src/core/skillopt/orchestrator.ts runOptimizationLoop 704 seed: W5 baseline, ref
src/core/skillopt/orchestrator.ts runOptimizationLoop>withBudgetTracker(#1) 405 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/sources-ops.ts addSource 317 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/think/index.ts runThink 450 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/core/workspace-push.ts workspacePush 312 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/mcp/http-transport.ts startHttpTransport 409 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): dispatch resultRows from X-Gbrain-Client / mcp.result_rows (logic in mcp/result-rows.ts)
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index 96339ace60..2753b35f60 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -680,7 +680,7 @@ async function runPush(engine: BrainEngine, args: string[]): Promise<void> {
console.error('PUSH BLOCKED — staged file(s) the secret scan could not read (fail-closed):');
for (const p of res.unscannable ?? []) console.error(` ${p}`);
console.error(
- 'Remove from the index (git rm --cached <path>), keep it under the scan cap, ' +
+ 'Remove from the index (git rm --cached <path>), keep it under the scan ceiling, ' +
`or allowlist it in ${SCAN_ALLOW_FILENAME}.`,
);
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 70d950fec5..f5ec4767c5 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -662,6 +662,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: 'TBD', text: '`gbrain projections drain` now builds pages stored in segments whose post-commit build never ran or died, skipping one another process is still building (claim renewed within 60 s), so a brain with no resident writer can make a large new page searchable. A pending receipt\'s `searchable_fix` names it as the fallback after the re-read wait, and doctor `text_projection_readiness` counts such pages (`segmented_pending`) and points to it.' },
{ since: 'TBD', text: 'Deleting and restoring a page over 24 MiB on a source backed by files is now lossless up to the page ceiling (`pages.max_bytes`). `restore_page` and `gbrain restore` write the file back byte for byte by streaming it from the stored segments into its staging file, including a file over the 25 MiB pre-push scan cap (the restore used to refuse with `request_too_large`, so the file a soft delete had removed could not be put back on disk). A delete or restore that replaces or removes a file over 24 MiB keeps the prior file as a staged copy beside it (a hidden `.<sha256>.tmp.before-<uuid>` file) until the write commits, named in its recovery record by path and SHA-256 instead of embedded in it: the record stays a few hundred bytes, the recovery reservation counts the file once (a 90 MiB delete used to need 283 MB against the 256 MiB `persistence.limits.worktree_recovery_bytes` budget and was refused), and a crash between removing the file and committing renames the copy back. A page whose file plus its staging does not fit that budget (a Postgres page near the 256 MiB ceiling) is still refused with `request_too_large` before anything is touched. `gbrain repair stuck-recovery` refuses such a recovery with `recovery_large_file_unsupported` (resolve it by hand; the resident writer finishes it).' },
{ since: 'TBD', text: 'Chunks of a page stored in segments keep a Markdown heading with the text after it, so a section appended after a full last chunk re-embeds only its own chunk (was two). Inline pages chunk as before.' },
+ { since: 'TBD', text: 'The pre-push secret scan (`gbrain sources push` and the automatic pushes) now scans a staged file over 25 MiB in bounded 8 Mi-character windows streamed from git, instead of refusing the push as `blocked_unscannable`: a clean large file pushes, and one holding a secret is refused as `blocked_secrets` naming its file and line. A staged file over 512 MiB still refuses as `blocked_unscannable`.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/page-size-policy.ts b/src/core/page-size-policy.ts
index d4b68e3b3d..cd3672d0bb 100644
--- a/src/core/page-size-policy.ts
+++ b/src/core/page-size-policy.ts
@@ -4,8 +4,8 @@
* large (post-commit embedding, title-tier context, bounded history).
*
* The ceiling is 24 MiB, not 32 MB: the journal and the local persistence IPC
- * count escaped JSON against 32 MiB caps, and the pre-push secret scan skips
- * (and so refuses to push) any file over 25 MiB. A page at the ceiling plus
+ * count escaped JSON against 32 MiB caps, and no canonical file write may
+ * exceed the 25 MiB whole-file secret-scan bound. A page at the ceiling plus
* its frontmatter stays under every one of them. Code files keep their own
* 5 MB bound (they skip content sanity and run tree-sitter plus the edge
* extractor). The per-entry-point table lives in
@@ -16,8 +16,9 @@
export const PAGE_MAX_BYTES = 24 * 1024 ** 2;
/**
- * The pre-push secret scan skips (and so the push gate refuses) any file over
- * this many bytes; no canonical file write may produce one (secret-scan.ts).
+ * Files up to this many bytes are secret-scanned whole: `scanFiles` skips a
+ * larger one, the push gate streams it in windows (workspace-push.ts), and no
+ * canonical file write may produce one (secret-scan.ts).
*/
export const PUSH_SCAN_MAX_FILE_BYTES = 25 * 1024 * 1024;
diff --git a/src/core/secret-scan-stream.ts b/src/core/secret-scan-stream.ts
new file mode 100644
index 0000000000..6cbc4f9445
--- /dev/null
+++ b/src/core/secret-scan-stream.ts
@@ -0,0 +1,99 @@
+/**
+ * Windowed secret scan of a byte stream too large to hold as one string: the
+ * pre-push gate's staged blobs over PUSH_MAX_SCAN_BYTES (workspace-push.ts).
+ *
+ * The bytes are decoded with a streaming UTF-8 decoder (a character split
+ * across chunks is joined, an invalid sequence becomes U+FFFD as
+ * `Buffer.toString('utf-8')` makes it, a BOM is kept) and scanned by
+ * `scanTextSpans` in windows of at most STREAM_SCAN_WINDOW_CHARS UTF-16
+ * units. Each next window starts at a line start at least
+ * STREAM_SCAN_OVERLAP_CHARS before the previous window's end; a line too long
+ * for that is split mid-line at exactly the overlap (never inside a surrogate
+ * pair). The overlap is longer than any claim of the push gate's patterns: a
+ * private key (PEM_BODY_MAX_CHARS 16384 of body plus fences, RFC 1421 header
+ * lines and indentation, under 18 Ki) and the bounded line values (jwt
+ * 3 x 4096 + 2, basic_auth 2048, URL userinfo 384, assignment values 4096).
+ *
+ * OWNERSHIP. A window keeps a claim that starts before the next window's start
+ * (it lies wholly inside this window, since it is shorter than the overlap);
+ * the next window sees every later claim with all of the overlap behind it.
+ * The last window keeps everything. A claim lying wholly inside a span kept by
+ * an earlier window is the seam's partial view of it (the body of a key cut at
+ * the window start, a suffix of a split line) and is dropped, which also drops
+ * an exact duplicate (same offset and pattern). Line numbers are 1-based over
+ * the whole stream. What a seam can add is a finding the whole-text scan would
+ * not make (a cut read as a boundary): that blocks the push, never leaks.
+ * An unbounded vendor value longer than the overlap is still reported, cut
+ * at the window end.
+ */
+import { scanTextSpans, type ScanOpts, type SecretFinding } from './secret-scan.ts';
+
+/** Largest text window one scan holds (UTF-16 units). */
+export const STREAM_SCAN_WINDOW_CHARS = 8 * 1024 ** 2;
+
+/** Text every window repeats from the end of the one before it (see the header). */
+export const STREAM_SCAN_OVERLAP_CHARS = 64 * 1024;
+
+/**
+ * @internal Work counters (test/helpers/work-counts.ts): windows scanned,
+ * bytes read from the stream, text units scanned (overlap included) and the
+ * largest window, so a test pins boundedness without timing.
+ */
+export const streamScanWork = { windows: 0, bytes: 0, chars: 0, largestWindow: 0 };
+
+/**
+ * Scan `chunks` as one UTF-8 text; the findings `scanText` would report on
+ * the whole text, plus any a seam adds (header). `windowChars` is a test
+ * seam; it must be at least twice the overlap.
+ */
+export async function scanTextStream(
+ chunks: AsyncIterable<Uint8Array>, opts: ScanOpts = {}, windowChars = STREAM_SCAN_WINDOW_CHARS,
+): Promise<SecretFinding[]> {
+ if (windowChars < 2 * STREAM_SCAN_OVERLAP_CHARS) throw new RangeError(`a scan window must be at least ${2 * STREAM_SCAN_OVERLAP_CHARS} chars`);
+ const decoder = new TextDecoder('utf-8', { ignoreBOM: true });
+ const findings: SecretFinding[] = [];
+ let carried: Array<{ start: number; end: number }> = [];
+ let pending = '';
+ let base = 0;
+ let baseLine = 1;
+ const drain = (final: boolean): void => {
+ while (pending.length >= windowChars || (final && pending.length > 0)) {
+ const last = final && pending.length <= windowChars;
+ const text = last ? pending : pending.slice(0, windowChars);
+ let next = text.length;
+ if (!last) {
+ const preferred = text.length - STREAM_SCAN_OVERLAP_CHARS;
+ const lineStart = text.lastIndexOf('\n', preferred - 1) + 1;
+ next = lineStart > preferred / 2 ? lineStart : preferred - ((text.charCodeAt(preferred) & 0xfc00) === 0xdc00 ? 1 : 0);
+ }
+ streamScanWork.windows++;
+ streamScanWork.chars += text.length;
+ if (text.length > streamScanWork.largestWindow) streamScanWork.largestWindow = text.length;
+ const kept: Array<{ start: number; end: number }> = [];
+ for (const claim of scanTextSpans(text, opts)) {
+ if (claim.start >= next) continue;
+ const start = base + claim.start;
+ const end = base + claim.end;
+ if (carried.some((c) => c.start <= start && end <= c.end)) continue;
+ kept.push({ start, end });
+ if (claim.finding) findings.push({ ...claim.finding, line: baseLine + claim.finding.line - 1 });
+ }
+ if (last) {
+ pending = '';
+ return;
+ }
+ for (let i = text.indexOf('\n'); i !== -1 && i < next; i = text.indexOf('\n', i + 1)) baseLine++;
+ base += next;
+ carried = [...carried, ...kept].filter((c) => c.end > base);
+ pending = pending.slice(next);
+ }
+ };
+ for await (const chunk of chunks) {
+ streamScanWork.bytes += chunk.length;
+ pending += decoder.decode(chunk, { stream: true });
+ drain(false);
+ }
+ pending += decoder.decode();
+ drain(true);
+ return findings;
+}
diff --git a/src/core/secret-scan.ts b/src/core/secret-scan.ts
index 6fd58c5148..426348a60e 100644
--- a/src/core/secret-scan.ts
+++ b/src/core/secret-scan.ts
@@ -1103,6 +1103,20 @@ export function scanText(text: string, opts: ScanOpts = {}): SecretFinding[] {
return out;
}
+/**
+ * `scanText` with each claim's absolute span [start, end) in `text` (UTF-16
+ * offsets of the claimed value). An allowlisted claim keeps its span with
+ * `finding: null`, so the windowed scan (secret-scan-stream.ts) can still
+ * drop a seam's partial copy of it.
+ */
+export function scanTextSpans(text: string, opts: ScanOpts = {}): Array<{ start: number; end: number; finding: SecretFinding | null }> {
+ const allowlist = opts.allowlist ?? [];
+ return scanInternal(text, opts).map((hit) => {
+ const fullHex = sha256Hex(hit.value);
+ return { start: hit.abs, end: hit.abs + hit.value.length, finding: valueAllowlisted(fullHex, allowlist) ? null : toFinding(hit, fullHex) };
+ });
+}
+
/** Bytes to sniff for NUL when deciding content is binary. */
export const BINARY_SNIFF_BYTES = 8192;
diff --git a/src/core/workspace-push.ts b/src/core/workspace-push.ts
index ed9420f93e..00349bb6d0 100644
--- a/src/core/workspace-push.ts
+++ b/src/core/workspace-push.ts
@@ -58,7 +58,7 @@ import {
} from 'fs';
import { dirname, join, resolve } from 'path';
import { createHash, randomBytes } from 'crypto';
-import { execFileSync } from './spawn.ts';
+import { execFileSync, spawn } from './spawn.ts';
import { GIT_ENV, GIT_ENV_AUTH, GIT_SSRF_SUBCOMMAND_FLAGS, detectDefaultBranch, divergenceSafePull, type PullStrategy } from './git-remote.ts';
import { loadConfigFileOnly } from './config.ts';
import { ensureGbrainHome } from './gbrain-home.ts';
@@ -75,6 +75,7 @@ import {
SCAN_ALLOW_FILENAME, SCAN_MAX_FILE_BYTES,
type SecretFinding,
} from './secret-scan.ts';
+import { scanTextStream } from './secret-scan-stream.ts';
import { shellQuote } from './mcp-registration.ts';
import { gitChildEnv } from './git-env.ts';
@@ -172,9 +173,20 @@ export const PUSH_DENY_GLOBS: readonly string[] = [
'*.pglite', '.env*', '*.pem', '*.key', '.gbrain/**', ...OWNERSHIP_MARKER_GLOBS, '.gbrain-bootstrap.lock/**',
];
-/** Files larger than this are neither scanned nor considered text candidates. */
+/**
+ * Staged blobs up to this size are read whole and scanned in memory; larger
+ * ones are streamed through the windowed scan (secret-scan-stream.ts) up to
+ * PUSH_STREAM_SCAN_MAX_BYTES.
+ */
export const PUSH_MAX_SCAN_BYTES = SCAN_MAX_FILE_BYTES;
+/**
+ * Hard ceiling of the streamed pre-push scan: a staged blob over it blocks the
+ * push as unscannable. Above the largest canonical file (a 256 MiB page plus
+ * its frontmatter).
+ */
+export const PUSH_STREAM_SCAN_MAX_BYTES = 512 * 1024 ** 2;
+
// ── Cross-platform push lock [CX2-6, G14/A5] ────────────────────────────────
/** A holder is stolen only when pid is DEAD **and** the lock is older than this. */
@@ -347,6 +359,117 @@ function listZ(root: string, args: string[]): string[] {
return out.split('\0').filter((s) => s.length > 0);
}
+/**
+ * Index blob id and size of each of `paths` (stage 0 entries only), from one
+ * `ls-files -s` and one `cat-file --batch-check`. Empty on any git error: a
+ * path missing here takes the whole-blob read, which fails closed.
+ */
+function stagedBlobSizes(root: string, paths: readonly string[]): Map<string, { oid: string; size: number }> {
+ const out = new Map<string, { oid: string; size: number }>();
+ try {
+ const wanted = new Set(paths);
+ const entries = listZ(root, ['ls-files', '-s']).flatMap((rec) => {
+ const m = /^(\d{6}) ([0-9a-f]+) 0\t(.*)$/s.exec(rec);
+ return m && m[1] !== '160000' && wanted.has(m[3]!) ? [{ oid: m[2]!, path: m[3]! }] : [];
+ });
+ if (entries.length === 0) return out;
+ const batch = execFileSync('git', ['-C', root, 'cat-file', '--batch-check=%(objectname) %(objecttype) %(objectsize)'], {
+ input: entries.map((e) => e.oid).join('\n') + '\n',
+ stdio: ['pipe', 'pipe', 'pipe'],
+ timeout: 60_000,
+ maxBuffer: 64 * 1024 * 1024,
+ env: gitChildEnv({ ...GIT_ENV }),
+ }).toString();
+ const sizes = new Map<string, number>();
+ for (const line of batch.split('\n')) {
+ const [oid, type, size] = line.split(' ');
+ if (type === 'blob') sizes.set(oid!, Number(size));
+ }
+ for (const e of entries) {
+ const size = sizes.get(e.oid);
+ if (size !== undefined) out.set(e.path, { oid: e.oid, size });
+ }
+ } catch {
+ out.clear();
+ }
+ return out;
+}
+
+/**
+ * Stream one staged blob (`git cat-file blob <oid>`) through the windowed
+ * scan, never holding it whole. Throws when git fails, exceeds 10 minutes, or
+ * delivers a byte count other than the index recorded.
+ */
+async function scanStagedBlobStreamed(root: string, blob: { oid: string; size: number }, allowlist: string[]): Promise<SecretFinding[]> {
+ const child = spawn('git', ['-C', root, 'cat-file', 'blob', blob.oid], {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: gitChildEnv({ ...GIT_ENV }),
+ });
+ const exited = new Promise<number | null>((resolve, reject) => {
+ child.once('error', reject);
+ child.once('close', resolve);
+ });
+ exited.catch(() => {});
+ let stderr = '';
+ child.stderr.on('data', (d: Buffer) => { stderr = (stderr + d.toString()).slice(0, 200); });
+ let bytes = 0;
+ async function* counted(): AsyncGenerator<Uint8Array> {
+ for await (const chunk of child.stdout) {
+ bytes += (chunk as Buffer).length;
+ yield chunk as Buffer;
+ }
+ }
+ const timer = setTimeout(() => child.kill('SIGKILL'), 600_000);
+ try {
+ const findings = await scanTextStream(counted(), { allowlist });
+ const code = await exited;
+ if (code !== 0) throw new Error(`git cat-file exited ${code}: ${stderr.trim()}`);
+ if (bytes !== blob.size) throw new Error(`read ${bytes} of ${blob.size} bytes`);
+ return findings;
+ } finally {
+ clearTimeout(timer);
+ if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');
+ }
+}
+
+/**
+ * Read and scan one staged, non-deleted blob: its findings, or the
+ * `unscannable` entry naming why it cannot be proven clean (fail closed).
+ * Up to PUSH_MAX_SCAN_BYTES (or when its size is unknown) the blob is read
+ * whole; above it, streamed by oid up to PUSH_STREAM_SCAN_MAX_BYTES.
+ */
+async function scanStagedBlob(
+ root: string, rel: string, staged: { oid: string; size: number } | undefined, allowlist: string[],
+): Promise<SecretFinding[] | string> {
+ if (staged && staged.size > PUSH_MAX_SCAN_BYTES) {
+ if (staged.size > PUSH_STREAM_SCAN_MAX_BYTES) return `${rel} (${staged.size}B exceeds the ${PUSH_STREAM_SCAN_MAX_BYTES}B scan ceiling)`;
+ try {
+ return await scanStagedBlobStreamed(root, staged, allowlist);
+ } catch (e) {
+ return `${rel} (unreadable: ${(e as Error).message.slice(0, 80)})`;
+ }
+ }
+ let blob: Buffer;
+ try {
+ blob = gitBuffer(root, ['cat-file', '-p', `:${rel}`]);
+ } catch (e) {
+ // NOT a deletion (the caller checked) — we cannot prove this file is clean.
+ // A blob we can't read (missing index entry, over maxBuffer, git error)
+ // must never sail through the only pre-push secret gate.
+ return `${rel} (unreadable: ${(e as Error).message.slice(0, 80)})`;
+ }
+ if (blob.length > PUSH_MAX_SCAN_BYTES) {
+ // Its size was not looked up, and it is too big to scan in-memory → block rather than exempt.
+ return `${rel} (${blob.length}B exceeds the ${PUSH_MAX_SCAN_BYTES}B scan cap)`;
+ }
+ // Binary (NUL-sniffed) files are scanned ANYWAY — a NUL byte doesn't mean
+ // the blob is secret-free (an ASCII key can sit inside a "binary" file).
+ // Buffer.toString('utf-8') keeps ASCII runs intact so the named patterns
+ // still fire; invalid byte sequences become U+FFFD and simply don't match.
+ const text = blob.toString('utf-8');
+ return scanText(text, { allowlist });
+}
+
/**
* Ensure SOME git identity exists so the commit can't fail on a fresh
* machine. Never overrides an existing name/email (any config scope).
@@ -856,10 +979,11 @@ export async function workspacePush(opts: WorkspacePushOpts): Promise<WorkspaceP
// 4. secret scan over the STAGED content. This is the SOLE
// block-secrets-before-they-leave control, so it FAILS CLOSED: the only
// benign "no blob" case is a staged DELETION (removes content — nothing to
- // leak); every OTHER unscannable case (cat-file error, oversized blob)
- // BLOCKS the push naming the path, rather than silently exempting it.
- // `git cat-file -p :<path>` reads the index blob verbatim (no filters) —
- // exactly what a commit would record.
+ // leak); every OTHER unscannable case (cat-file error, a blob over
+ // PUSH_STREAM_SCAN_MAX_BYTES) BLOCKS the push naming the path, rather than
+ // silently exempting it. `git cat-file -p :<path>` reads the index blob
+ // verbatim (no filters) — exactly what a commit would record; a blob over
+ // PUSH_MAX_SCAN_BYTES is streamed by its index oid and scanned in windows.
let stagedDeletions: Set<string>;
try {
stagedDeletions = new Set(listZ(root, ['diff', '--cached', '--name-only', '--diff-filter=D']));
@@ -875,30 +999,15 @@ export async function workspacePush(opts: WorkspacePushOpts): Promise<WorkspaceP
const retryCommand = pushRetryCommand(opts);
const findings: PushSecretFinding[] = [];
const unscannable: string[] = [];
+ const stagedBlobs = stagedBlobSizes(root, stagedForScan);
for (const rel of stagedForScan) {
if (pathAllowlisted(rel, allowlist)) continue; // user-declared safe path
if (stagedDeletions.has(rel)) continue; // deletion — no content to scan
- let blob: Buffer;
- try {
- blob = gitBuffer(root, ['cat-file', '-p', `:${rel}`]);
- } catch (e) {
- // NOT a deletion (checked above) — we cannot prove this file is clean.
- // A blob we can't read (missing index entry, over maxBuffer, git error)
- // must never sail through the only pre-push secret gate.
- unscannable.push(`${rel} (unreadable: ${(e as Error).message.slice(0, 80)})`);
- continue;
- }
- if (blob.length > PUSH_MAX_SCAN_BYTES) {
- // Too big to scan in-memory → block rather than exempt.
- unscannable.push(`${rel} (${blob.length}B exceeds the ${PUSH_MAX_SCAN_BYTES}B scan cap)`);
+ const fileFindings = await scanStagedBlob(root, rel, stagedBlobs.get(rel), allowlist);
+ if (typeof fileFindings === 'string') {
+ unscannable.push(fileFindings);
continue;
}
- // Binary (NUL-sniffed) files are scanned ANYWAY — a NUL byte doesn't mean
- // the blob is secret-free (an ASCII key can sit inside a "binary" file).
- // Buffer.toString('utf-8') keeps ASCII runs intact so the named patterns
- // still fire; invalid byte sequences become U+FFFD and simply don't match.
- const text = blob.toString('utf-8');
- const fileFindings = scanText(text, { allowlist });
if (fileFindings.length === 0) continue;
for (const f of buildPushFindings({ file: rel, findings: fileFindings, allowlist, allowlistPath, retryCommand })) {
findings.push(f);
@@ -922,7 +1031,7 @@ export async function workspacePush(opts: WorkspacePushOpts): Promise<WorkspaceP
const reason =
`secret scan could not read ${unscannable.length} staged file(s): ${summary} — nothing committed. ` +
`The pre-push secret gate fails closed: remove the file from the index (git rm --cached <path>), ` +
- `keep it under the scan cap (${PUSH_MAX_SCAN_BYTES}B), or allowlist it in ${SCAN_ALLOW_FILENAME}.`;
+ `keep it under the scan ceiling (${PUSH_STREAM_SCAN_MAX_BYTES}B), or allowlist it in ${SCAN_ALLOW_FILENAME}.`;
log(`PUSH BLOCKED: ${reason}`);
return finish({
ok: false, status: 'blocked_unscannable', repoRoot: root, branch, unscannable, reason,
diff --git a/test/secret-scan-stream.test.ts b/test/secret-scan-stream.test.ts
new file mode 100644
index 0000000000..c554aee93c
--- /dev/null
+++ b/test/secret-scan-stream.test.ts
@@ -0,0 +1,92 @@
+/**
+ * secret-scan-stream.ts: the windowed scan reports exactly what scanText
+ * reports on the whole text (pattern, 1-based line, fingerprint), whatever the
+ * window seams and chunk boundaries cut: single-line values and private keys
+ * swept across both seams of a window, a line longer than a window split
+ * mid-line, multi-byte characters split across chunks, invalid UTF-8 and a
+ * BOM. Windows are shrunk to the smallest the module allows (the windowChars
+ * test seam) so a sweep stays small; the overlap is the production one.
+ * Secrets are assembled at runtime from split literals.
+ */
+import { describe, test, expect } from 'bun:test';
+import { scanText, type SecretFinding } from '../src/core/secret-scan.ts';
+import { scanTextStream, STREAM_SCAN_OVERLAP_CHARS as O, streamScanWork } from '../src/core/secret-scan-stream.ts';
+
+let seed = 7;
+const rnd = (): number => (seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648;
+const ALNUM = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
+const rs = (n: number, cs = ALNUM): string => Array.from({ length: n }, () => cs[Math.floor(rnd() * cs.length)]).join('');
+const BEGIN = ['-----BEGIN', ' RSA PRIVATE KEY', '-----'].join('');
+const END = ['-----END', ' RSA PRIVATE KEY', '-----'].join('');
+const pem = (): string => [BEGIN, ...Array.from({ length: 200 }, () => rs(64, ALNUM + '+/')), END].join('\n');
+const SECRETS: Array<() => string> = [
+ () => '\nkey: ' + 'sk-' + rs(40) + '\n',
+ () => ' Bearer ' + 'eyJ' + rs(4000) + '.' + rs(4000) + '.' + rs(4000) + ' ',
+ () => '\n' + pem() + '\n',
+ () => ' ' + 'sk-ant-' + rs(30) + ' ',
+];
+const W = 3 * O;
+
+async function* chunks(buf: Uint8Array, size: () => number): AsyncGenerator<Uint8Array> {
+ for (let i = 0; i < buf.length; ) {
+ const n = size();
+ yield buf.subarray(i, i + n);
+ i += n;
+ }
+}
+const keys = (fs: SecretFinding[]): string[] => fs.map((f) => `${f.pattern}@${f.line}#${f.fingerprint}`).sort();
+
+async function expectSameAsWhole(buf: Buffer, windowChars = W, size = () => 1 + Math.floor(rnd() * 70_000)): Promise<SecretFinding[]> {
+ const whole = scanText(buf.toString('utf-8'));
+ const streamed = await scanTextStream(chunks(buf, size), {}, windowChars);
+ expect(keys(streamed)).toEqual(keys(whole));
+ return streamed;
+}
+
+describe('scanTextStream', () => {
+ test('values and private keys swept across both seams of a window match the whole-text scan', async () => {
+ const lines = Array.from({ length: 4000 }, () => rs(80, ALNUM + ' ')).join('\n');
+ const long = rs(5 * O, ALNUM + ' ');
+ let found = 0;
+ for (const filler of [lines, long]) {
+ for (const make of SECRETS) {
+ for (let at = W - O - 12_000; at < W + 12_000; at += 3001) {
+ found += (await expectSameAsWhole(Buffer.from(filler.slice(0, at) + make() + filler.slice(at)))).length;
+ }
+ }
+ }
+ expect(found).toBeGreaterThanOrEqual(2 * SECRETS.length * 8);
+ });
+
+ test('a line longer than a window is split mid-line and still yields every value on it', async () => {
+ const parts: string[] = [];
+ for (let i = 0; i < 40; i++) parts.push(rs(9000 + Math.floor(rnd() * 9000), ALNUM + ' '), ' ' + 'gh' + 'p_' + rs(36) + ' ');
+ const found = await expectSameAsWhole(Buffer.from('head\n' + parts.join('') + '\ntail\n'));
+ expect(found).toHaveLength(40);
+ expect(found.every((f) => f.line === 2)).toBe(true);
+ });
+
+ test('multi-byte characters split across chunks, a surrogate pair at a mid-line split, invalid UTF-8 and a BOM', async () => {
+ const emoji = '\u{1F600}'.repeat(2 * O);
+ const text = '\uFEFF' + 'é日本語 ' + 'sk-ant-' + rs(30) + '\n' + emoji + ' ' + 'sk-' + rs(40) + ' ' + emoji + '\n' + 'é'.repeat(O) + ' ' + 'sk-' + rs(40) + '\n';
+ expect(text.charCodeAt(O + 1) & 0xfc00).toBe(0xdc00); // the first mid-line split point is a low surrogate
+ expect(await expectSameAsWhole(Buffer.from(text), 2 * O + 1, () => 7)).toHaveLength(3);
+ const invalid = Buffer.concat([Buffer.from('a\xff\xfe\n'), Buffer.from([0xe6, 0x97, 0x0a, 0xc3]), Buffer.from(' sk-' + rs(40) + '\n'), Buffer.alloc(3 * O, 0x61)]);
+ expect(await expectSameAsWhole(invalid, W, () => 3)).toHaveLength(1);
+ });
+
+ test('work counters bound the window and cover every byte', async () => {
+ const buf = Buffer.from(Array.from({ length: 20_000 }, () => rs(99, ALNUM + ' ')).join('\n'));
+ for (const k of Object.keys(streamScanWork) as Array<keyof typeof streamScanWork>) streamScanWork[k] = 0;
+ await scanTextStream(chunks(buf, () => 65_536), {}, W);
+ expect(streamScanWork.bytes).toBe(buf.length);
+ expect(streamScanWork.chars).toBeGreaterThanOrEqual(buf.length);
+ expect(streamScanWork.largestWindow).toBe(W);
+ expect(streamScanWork.windows).toBeGreaterThanOrEqual(Math.ceil(buf.length / W));
+ expect(streamScanWork.windows).toBeLessThanOrEqual(Math.ceil(buf.length / (W - O - 100)) + 1);
+ });
+
+ test('a window under twice the overlap is refused', async () => {
+ await expect(scanTextStream(chunks(Buffer.from('x'), () => 1), {}, 2 * O - 1)).rejects.toThrow(RangeError);
+ });
+});
diff --git a/test/sources-push-cli.serial.test.ts b/test/sources-push-cli.serial.test.ts
index 83509d700d..9ca9cf9af4 100644
--- a/test/sources-push-cli.serial.test.ts
+++ b/test/sources-push-cli.serial.test.ts
@@ -16,13 +16,13 @@
* (Bun snapshots env at startup — spawned git must see the swap, #2943).
*/
import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdtempSync, rmSync, writeFileSync, truncateSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { execFileSync, spawnSync } from 'node:child_process';
import { runSources } from '../src/commands/sources.ts';
-import { acquirePushLock, resolveWorkspaceRoot } from '../src/core/workspace-push.ts';
+import { acquirePushLock, resolveWorkspaceRoot, PUSH_STREAM_SCAN_MAX_BYTES } from '../src/core/workspace-push.ts';
import { SCAN_ALLOW_FILENAME } from '../src/core/secret-scan.ts';
import type { BrainEngine } from '../src/core/engine.ts';
@@ -254,8 +254,9 @@ describe('exit 5 — blocked and refused', () => {
expect(originHead(bare)).toBe(before); // nothing left the machine
}, T);
- test('unscannable staged blob (over the scan cap) → exit 5, fail-closed', async () => {
- writeFileSync(join(work, 'big.bin'), Buffer.alloc(26 * 1024 * 1024, 0x61));
+ test('unscannable staged blob (over the scan ceiling) → exit 5, fail-closed', async () => {
+ writeFileSync(join(work, 'big.bin'), '');
+ truncateSync(join(work, 'big.bin'), PUSH_STREAM_SCAN_MAX_BYTES + 1); // sparse: no disk blocks
const before = originHead(bare);
const r = await runPushCli(untouchableEngine, ['--path', work, '--allow-unverified-remote']);
expect(r.exitCode).toBe(5);
diff --git a/test/workspace-push-large-blob.serial.test.ts b/test/workspace-push-large-blob.serial.test.ts
new file mode 100644
index 0000000000..5e29b96a43
--- /dev/null
+++ b/test/workspace-push-large-blob.serial.test.ts
@@ -0,0 +1,159 @@
+/**
+ * workspace-push over a staged file larger than PUSH_MAX_SCAN_BYTES (25 MiB):
+ * the pre-push secret gate streams the blob and scans it in bounded windows
+ * (secret-scan-stream.ts) instead of refusing it as unscannable, against a
+ * real local bare remote as in workspace-push.serial.test.ts.
+ *
+ * The file is 314,573 lines of 99 characters plus a newline (100 bytes a
+ * line), so every window seam sits at a known line: window 0 ends at
+ * character STREAM_SCAN_WINDOW_CHARS, and each next window starts at the line
+ * start at or before its predecessor's end minus STREAM_SCAN_OVERLAP_CHARS.
+ * Secrets fill whole 99-character lines (a private key's fences and
+ * 99-character base64 body lines included), so placing one shifts nothing.
+ * Every secret is assembled at runtime from split literals.
+ */
+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync, truncateSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { execFileSync } from 'child_process';
+import { randomBytes } from 'crypto';
+import { workspacePush, PUSH_MAX_SCAN_BYTES, PUSH_STREAM_SCAN_MAX_BYTES } from '../src/core/workspace-push.ts';
+import { STREAM_SCAN_OVERLAP_CHARS, STREAM_SCAN_WINDOW_CHARS, streamScanWork } from '../src/core/secret-scan-stream.ts';
+
+const T = 180_000; // explicit per-test timeout — bun ignores bunfig.toml's key
+const LINE = 100;
+const LINES = 314_573;
+const SIZE = LINE * LINES;
+const FILLER = 'lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore'.padEnd(99, ' ').slice(0, 99);
+const OPENAI = 'sk-' + 'A1b2C3d4E5f6G7h8I9j0K1l2M3n4P5q6R7s8';
+const GITHUB = 'gh' + 'p_' + 'Z9y8X7w6V5u4T3s2R1q0P9o8N7m6L5k4J3i2';
+const BEGIN = ['-----BEGIN', ' RSA PRIVATE KEY', '-----'].join('');
+const END = ['-----END', ' RSA PRIVATE KEY', '-----'].join('');
+
+// #2943: env: process.env is REQUIRED, or spawned git misses the HOME swap.
+function git(cwd: string, ...args: string[]): string {
+ return execFileSync('git', ['-C', cwd, '-c', 'protocol.file.allow=always', ...args], {
+ stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', env: process.env,
+ }).trim();
+}
+
+let root: string;
+let work: string;
+let bare: string;
+let saved: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'wsp-large-'));
+ saved = {
+ HOME: process.env.HOME,
+ GBRAIN_HOME: process.env.GBRAIN_HOME,
+ GBRAIN_GIT_ALLOW_FILE_TRANSPORT: process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT,
+ };
+ process.env.HOME = mkdtempSync(join(root, 'home-'));
+ process.env.GBRAIN_HOME = process.env.HOME;
+ process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT = '1';
+ bare = mkdtempSync(join(root, 'origin-')) + '.git';
+ execFileSync('git', ['init', '-q', '--bare', '-b', 'main', bare], { stdio: 'ignore', env: process.env });
+ work = mkdtempSync(join(root, 'work-'));
+ execFileSync('git', ['-c', 'protocol.file.allow=always', 'clone', '-q', bare, work], { stdio: 'ignore', env: process.env });
+ git(work, 'config', 'user.email', '[email protected]');
+ git(work, 'config', 'user.name', 'tester');
+ writeFileSync(join(work, 'README.md'), 'init\n');
+ git(work, 'add', 'README.md');
+ git(work, 'commit', '-qm', 'init');
+ git(work, 'push', '-q', 'origin', 'main');
+});
+afterEach(() => {
+ for (const [k, v] of Object.entries(saved)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+ rmSync(root, { recursive: true, force: true });
+});
+
+function push() {
+ for (const k of Object.keys(streamScanWork) as Array<keyof typeof streamScanWork>) streamScanWork[k] = 0;
+ return workspacePush({ dir: work, branch: 'main', allowUnverifiedRemote: true });
+}
+
+/** The ~30 MiB file, with edits (0-based line index to a line of at most 99 chars) in place. */
+function writeBig(edits: Map<number, string> = new Map()): void {
+ const lines = new Array<string>(LINES).fill(FILLER);
+ for (const [i, text] of edits) {
+ expect(text.length).toBeLessThanOrEqual(99);
+ lines[i] = text.padEnd(99, ' ');
+ }
+ writeFileSync(join(work, 'big.md'), lines.join('\n') + '\n');
+}
+
+/** A private key: header on line first, bodyLines base64 lines, footer after them. */
+function placeKey(edits: Map<number, string>, first: number, bodyLines: number): void {
+ edits.set(first, ' '.repeat(99 - BEGIN.length) + BEGIN);
+ for (let i = 1; i <= bodyLines; i++) edits.set(first + i, randomBytes(75).toString('base64').slice(0, 99));
+ edits.set(first + bodyLines + 1, END);
+}
+
+// Window 0 is [0, W); window k + 1 starts STEP after window k.
+const W = STREAM_SCAN_WINDOW_CHARS;
+const STEP = Math.floor((W - STREAM_SCAN_OVERLAP_CHARS) / LINE) * LINE;
+
+describe('pre-push secret scan over the 25 MiB cap', () => {
+ test('a clean ~30 MiB staged file is scanned in bounded windows and pushed', async () => {
+ expect(SIZE).toBeGreaterThan(PUSH_MAX_SCAN_BYTES);
+ writeBig();
+ const r = await push();
+ expect(r.status).toBe('pushed');
+ expect(r.ok).toBe(true);
+ expect(Number(git(bare, 'cat-file', '-s', 'refs/heads/main:big.md'))).toBe(SIZE);
+ expect(streamScanWork.bytes).toBe(SIZE);
+ expect(streamScanWork.chars).toBeGreaterThanOrEqual(SIZE);
+ expect(streamScanWork.largestWindow).toBeLessThanOrEqual(STREAM_SCAN_WINDOW_CHARS);
+ expect(streamScanWork.windows).toBe(Math.ceil((SIZE - W) / STEP) + 1);
+ }, T);
+
+ test('secrets across window seams and near the end block with their file and line, once each', async () => {
+ const edits = new Map<number, string>();
+ const acrossEnd = Math.floor(W / LINE); // the line window 0 cuts (at column W % 100)
+ edits.set(acrossEnd, OPENAI + ' token');
+ const keyAcrossStart = STEP / LINE - 10; // header before window 1's start, footer after it
+ placeKey(edits, keyAcrossStart, 19);
+ const keyAcrossEnd = Math.floor((STEP + W) / LINE) - 10; // straddles window 1's end
+ placeKey(edits, keyAcrossEnd, 19);
+ const nearEnd = LINES - 3;
+ edits.set(nearEnd, 'deploy ' + GITHUB);
+ expect(acrossEnd * LINE).toBeLessThan(W);
+ expect(acrossEnd * LINE + OPENAI.length).toBeGreaterThan(W);
+ writeBig(edits);
+ const before = git(bare, 'rev-parse', 'refs/heads/main');
+ const r = await push();
+ expect(r.status).toBe('blocked_secrets');
+ expect(r.ok).toBe(false);
+ const got = (r.findings ?? []).map((f) => ({ file: f.file, line: f.line, pattern: f.pattern })).sort((a, b) => a.line - b.line);
+ expect(got).toEqual([
+ { file: 'big.md', line: keyAcrossStart + 1, pattern: 'private_key_pem' },
+ { file: 'big.md', line: acrossEnd + 1, pattern: 'openai' },
+ { file: 'big.md', line: keyAcrossEnd + 1, pattern: 'private_key_pem' },
+ { file: 'big.md', line: nearEnd + 1, pattern: 'github_token' },
+ ]);
+ expect(JSON.stringify(r).includes(OPENAI)).toBe(false);
+ expect(git(bare, 'rev-parse', 'refs/heads/main')).toBe(before); // nothing pushed
+ expect(git(work, 'diff', '--cached', '--name-only')).toBe(''); // index restored
+ expect(streamScanWork.largestWindow).toBeLessThanOrEqual(STREAM_SCAN_WINDOW_CHARS);
+ expect(streamScanWork.bytes).toBe(SIZE);
+ }, T);
+
+ test('a staged blob over the streamed-scan ceiling still blocks as unscannable', async () => {
+ const huge = join(work, 'huge.bin');
+ writeFileSync(huge, '');
+ truncateSync(huge, PUSH_STREAM_SCAN_MAX_BYTES + 1); // sparse: no disk blocks, still that many bytes for git
+ const before = git(bare, 'rev-parse', 'refs/heads/main');
+ const r = await push();
+ expect(r.status).toBe('blocked_unscannable');
+ expect(r.unscannable?.some((u) => u.startsWith('huge.bin') && u.includes('scan ceiling'))).toBe(true);
+ expect(r.reason).toContain('scan ceiling');
+ expect(streamScanWork.bytes).toBe(0); // refused by its recorded size, never read
+ expect(git(bare, 'rev-parse', 'refs/heads/main')).toBe(before);
+ expect(git(work, 'diff', '--cached', '--name-only')).toBe('');
+ }, T);
+});
diff --git a/test/workspace-push.serial.test.ts b/test/workspace-push.serial.test.ts
index 40c2b9d37e..3815e81a83 100644
--- a/test/workspace-push.serial.test.ts
+++ b/test/workspace-push.serial.test.ts
@@ -10,7 +10,7 @@
*/
import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import {
- mkdtempSync, mkdirSync, rmSync, writeFileSync, readFileSync, existsSync, statSync, utimesSync, symlinkSync,
+ mkdtempSync, mkdirSync, rmSync, writeFileSync, readFileSync, existsSync, statSync, utimesSync, symlinkSync, truncateSync,
} from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
@@ -19,7 +19,7 @@ import {
workspacePush, acquirePushLock, pushLockDir, pushStatusPath, pushStatusPathForRoot,
readPushStatuses, readPushStatusForRoot, summarizePushStatuses, verifyRemotePrivacy,
parseGithubOwnerRepo, resolveWorkspaceRoot, PUSH_LOCK_STALE_MS, PUSH_DENY_GLOBS,
- sanitizePushReason, SECRET_SCAN_REFUSAL_DOCS,
+ sanitizePushReason, SECRET_SCAN_REFUSAL_DOCS, PUSH_STREAM_SCAN_MAX_BYTES,
} from '../src/core/workspace-push.ts';
import { SCAN_ALLOW_FILENAME } from '../src/core/secret-scan.ts';
import { visibilityCachePath } from '../src/core/repo-visibility.ts';
@@ -363,17 +363,20 @@ describe('secret-scan gate — fails CLOSED on unscannable staged blobs', () =>
expect(readPushStatuses()[0]!.ok).toBe(false);
}, T);
- test('an oversized staged blob (> scan cap) BLOCKS the push', async () => {
- // 26MiB > SCAN_MAX_FILE_BYTES (25MiB): too big to scan in-memory, so it
- // must block rather than sail through the sole pre-push secret gate.
- writeFileSync(join(work, 'big.bin'), Buffer.alloc(26 * 1024 * 1024, 0x61));
+ test('an oversized staged blob (> scan ceiling) BLOCKS the push', async () => {
+ // Over PUSH_STREAM_SCAN_MAX_BYTES: too big even for the streamed scan
+ // (blobs over the 25 MiB in-memory cap are streamed up to it,
+ // test/workspace-push-large-blob.serial.test.ts), so it must block rather
+ // than sail through the sole pre-push secret gate. Sparse: no disk blocks.
+ writeFileSync(join(work, 'big.bin'), '');
+ truncateSync(join(work, 'big.bin'), PUSH_STREAM_SCAN_MAX_BYTES + 1);
const before = originHead(bare);
const beforeCount = commitCount(work);
const r = await push();
expect(r.status).toBe('blocked_unscannable');
expect(r.ok).toBe(false);
expect(r.unscannable?.some((u) => u.startsWith('big.bin'))).toBe(true);
- expect(r.reason).toContain('scan cap');
+ expect(r.reason).toContain('scan ceiling');
expect(commitCount(work)).toBe(beforeCount); // nothing committed
expect(originHead(bare)).toBe(before); // nothing pushed
expect(git(work, 'diff', '--cached', '--name-only')).toBe('');