Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.60.31.0 fix: security fix wave: credential redaction everywhere, credential-safe chunking, private Google files (#5348 #5080 #5148 #5746) (#5843)
Garry Tan2d8801b4eb5e
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex da1215e4fe..a0df4d502d 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.30.0",+ "version": "0.60.31.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 6cccef2633..cfdc71e86b 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.30.0",+ "version": "0.60.31.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex 5ca737791e..4764467a79 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.60.30.0 -->+<!-- gbrain-runbook-stamp: 0.60.31.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 01a8e265a4..7b514c61c1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,188 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.31.0] - 2026-10-02++**Your brain stops handing stored passwords and keys back to your agents, catches credential shapes it used to miss, and keeps your Gmail pages private on disk.**++If a password, API key or private key ever landed in a note, an email or a chat transcript, older releases could hand it back in a search result or a memory read, straight into an agent's context and from there into transcripts. They also missed some common shapes entirely: a password inside a clone URL, an `Authorization: Basic` header, and a private key whose last line got cut off by a snippet, which printed the key itself. This release closes those gaps. Retrieval now replaces those values with a `<REDACTED:...>` marker, search chunks never hold private-key material at all, pushes and compiled context catch the new shapes, and your stored pages never change.++Separately, if you sync Google into a folder you picked yourself (outside `~/.gbrain`), older releases wrote your mail, calendar and contact pages readable by every account on the machine. New writes are now private, and one command tightens the old ones.++### Action required / behavior changes++- **A push can newly be refused.** `gbrain sources push` and bootstrap now block on URLs with a password, Basic auth headers, DigitalOcean tokens and cut-off private keys. The refusal prints the fix: remove and rotate a real credential, or allowlist a reviewed false positive with the exact command it gives you. An old allowlist entry for a cut-off private key stops matching (its fingerprint now covers the key body); the refusal names the stale line and its replacement.+- **Pages that hold a private key are re-chunked on upgrade.** Until that finishes they are left out of search. The upgrade does it with no provider calls; afterwards run `gbrain embed --stale` when you are ready to pay for their new vectors.+- **Memory reads redact credentials.** `recall`, `context_pack`, `delta` and `entity` now return `<REDACTED:pattern>` like search does. A credential you asked the brain to remember is withheld from MCP and thin clients by design; read it on the brain host with `gbrain recall`.+- **Check your custom Google folder.** Files written there before this release keep their old permissions. `gbrain doctor` tells you.+- **A password inside an `http(s)` URL (`https://<user>:<password>@host`) now counts as a credential.** Placeholder passwords (`<password>`, `${VAR}`, `$VAR`, `****`, `xxxx`) are still ignored.++### How to check you're covered++On a throwaway brain, with a value made up on the spot:++```bash+export GBRAIN_HOME="$(mktemp -d)" # your real brain is untouched+gbrain init --pglite --no-embedding+PW="Gx7$(openssl rand -hex 12)"+gbrain capture --stdin <<EOT+Deploy notes for the scratch redaction check.+clone https://deploy:${PW}@git.example.com/team/repo.git+staging DB_PASSWORD="${PW}#x"+EOT+gbrain search "scratch redaction check" --json | grep chunk_text+```++You should see `clone <REDACTED:url_credentials>git.example.com/team/repo.git` and `DB_PASSWORD=\"<REDACTED:high_entropy_assignment>\"`, and no trace of `$PW`. Unset `GBRAIN_HOME` afterwards.++On your real brain after upgrading:++```bash+gbrain doctor # credential_projection_pending: ok once the re-chunk is done+```++If a Google source lives outside `~/.gbrain`:++```bash+gbrain doctor # google_file_modes names the folder and counts+find /path/to/google/dir \( -perm -040 -o -perm -004 \) -print | head # readable by others?+gbrain repair google-file-modes --source <id> # preview+gbrain repair google-file-modes --source <id> --apply+```++Without gbrain, for a folder that holds only this source: `chmod -R go-rwx /path/to/google/dir`. For a folder you share with other files, limit it to gbrain's: `chmod go-rwx <dir>/.google-source.json*` and `chmod -R go-rwx <dir>/emails <dir>/calendar <dir>/people`.++### What changes where++| Shape | Blocks a push | Drops a compiled-context entry | Refuses a memory relay | Redacted in retrieval |+| --- | --- | --- | --- | --- |+| `http(s)` URL with a password | new | new | new | new |+| `Authorization: Basic ...` | new | new | new | new |+| DigitalOcean token (`dop_v1_...`) | new | new | new | new |+| Private key with its `BEGIN` line cut off (a chunk that starts mid-key) | new | new | new | new |+| Private key with its `END` line cut off | already (new fingerprint) | already (new fingerprint) | already | new: the key body is redacted, not just the `BEGIN` line |+| Password assignment with punctuation (`password="ab!#..."`) | no | no | new | new |+| Any `KEY=value` assignment with a random-looking value | no | no | already | new |++A memory relay is the compaction-time handoff of a conversation window; a refused window is skipped and the next one is checked again. Pushes and compiled context never run the assignment rule, so a plain `DB_PASSWORD=...` line does not block a push.++### What stays raw, and what this does not cover++This release protects against stored credentials leaking into agent context and transcripts through retrieval, and against other local users reading your Google pages. It does not:++- **Redact page reads.** `get_page`, `fetch`, `get_chunks`, `get_raw_data` and `get_versions` still return stored text as written. They are explicit requests for a page and follow page visibility.+- **Redact what goes to providers you configured.** The embedding provider at import, a hosted reranker and `synthesize`/`think` generation still receive unredacted text, except private keys, which never enter chunks. That is the next step.+- **Change your files or database.** If a real credential reached the brain, rotate it and follow the "If a secret reached the brain" steps in `SECURITY.md`.++### Things to watch++- **The `http(s)` URL password reversal is on purpose.** Earlier releases treated a password in an `http(s)` URL as fine. Clone URLs with tokens in them are the most common real leak, so they now fire. A documentation example with a real-looking password in a URL now blocks a push; use a placeholder.+- **A cut-off key's fingerprint is not stable.** It covers the key body up to the cut, so the same key cut at a different point gets a different fingerprint. Do not rely on allowlisting sample keys in docs; show a placeholder.+- **gbrain enforces 0600 on Google files.** Every rewrite sets 0600 again, so a looser `chmod` you apply by hand is reverted on the next sync that rewrites that page. Pages that did not change are not rewritten. The pages are your private mail, so a private default that cannot quietly drift is the point.+- **The Google repair is opt-in.** The upgrade prints a one-time notice per Google folder outside `~/.gbrain`; nothing is chmod-ed until you run `--apply`. It never touches the folder you chose itself, never follows a symlink, and skips files another user owns.+- **Agents see `<REDACTED:pattern>`.** That means the brain holds a value of that shape and withheld it. Allowlisting a fingerprint for pushes does not turn retrieval redaction off.++Full guides: [secret scan refusals and redaction](docs/guides/write-refusals.md#secret-scan-refusals-and-redaction), [Google file permissions](docs/guides/google-connect.md#file-permissions).++### Pages that hold a private key++A long private key can span several search chunks, and a chunk from its middle holds key lines with neither the `BEGIN` nor the `END` line, so no output check can recognize it. Pages are now chunked from a copy in which every private key is replaced by `<REDACTED:private_key_pem>`, with line breaks kept so nothing else shifts. Evidence delivery (`--return-unit window`, `section`, `page`) cuts from the same copy. Key material never reaches a chunk, the embedding provider or delivered evidence. The stored page is unchanged, and `get_page` still returns it.++Pages indexed before this release that contain a `BEGIN` or `END … PRIVATE KEY` line are withheld from search, for every caller, from the first command after the upgrade until the upgrade's migration re-chunks them. The re-chunk makes no provider calls and runs one page at a time, so an interrupted run resumes. Their new chunks have no vectors until you run `gbrain embed --stale`, so until then keyword search finds them and vector search does not. `gbrain doctor` reports pages still waiting as `credential_projection_pending`. A code page with no recorded source file stays withheld until its source syncs again (`gbrain sync --source <id>`).++Not covered: keys inside image OCR text, and key material with no `BEGIN` or `END` line anywhere on the page.++**The post-upgrade re-embed now asks first.** When a chunker change leaves pages to re-embed, `gbrain post-upgrade` prints the cost estimate and asks `Re-embed now? [y/N]`. Enter, `n`, a closed input and every non-interactive upgrade decline and print what to run instead (`gbrain reindex --markdown`, or `gbrain repair safe-chunks --apply --no-embed` then `gbrain embed --stale`). The old 10-second Ctrl-C window and `GBRAIN_REEMBED_GRACE_SECONDS` are gone; `GBRAIN_NO_REEMBED=1` still skips the step. An unattended upgrade never spends money on embeddings.++## To take advantage of v0.60.31.0++`gbrain upgrade` should do this automatically. If it didn't, or if `gbrain doctor` warns about a partial migration:++1. **Run the orchestrator manually:**+ ```bash+ gbrain apply-migrations --yes --no-autopilot-install+ ```+ It re-chunks pages that hold a private key without provider calls (a failed page leaves the run partial; run the command again to retry), then prints the one-time notice for each Google source outside `~/.gbrain`. It changes no file permissions.+2. **Embed the re-chunked pages when you are ready.** This calls your embedding provider and can cost money, so it is never automatic:+ ```bash+ gbrain embed --stale+ ```+3. **Your agent reads `skills/migrations/v0.60.31.0.md` the next time you interact with it.** It finishes the migration, asks before embedding or repairing Google file permissions, and explains push refusals and `<REDACTED:...>` tokens. Headless agents need nothing beyond step 1.+4. **Restart anything long-running** (`gbrain serve`, your agent harness for stdio MCP, `gbrain jobs supervisor`, autopilot) so retrieval redaction applies to every caller.+5. **Verify the outcome:**+ ```bash+ gbrain doctor # credential_projection_pending: ok; google_file_modes: ok, or a warning with the exact repair commands+ ```+6. **If any step fails or the numbers look wrong,** please file an issue:+ https://github.com/garrytan/gbrain/issues with:+ - output of `gbrain doctor`+ - contents of `~/.gbrain/upgrade-errors.jsonl` if it exists+ - which step broke++ This feedback loop is how the gbrain maintainers find fragile upgrade paths. Thank you.++**Say to your agent:** *"Check whether my Google folder is readable by other users and show me the fix before applying it."* or *"My brain push was refused for a secret. Show me what it found."*++### Itemized changes++#### Secret scanner (`src/core/secret-scan.ts`)++- New `url_credentials`: the `scheme://user:password@` span of `http`/`https` URLs (scheme case-insensitive; host and path kept). User up to 128 characters, password 1 to 256 without whitespace, `@`, quotes, `/`, `?` or `#`. Placeholder passwords are skipped. A URL with a user and no password, and paths such as `/@scope/pkg` or `localhost:5173/@vite/client`, never fire.+- New `basic_auth`: `Authorization: Basic <value>` (4 or more characters) and bare `Basic <value>` (16 or more), both case-insensitive, capped at 2048 characters, and only when the value decodes to printable text containing `:`. Prose such as "Basic responsibilities" is left alone.+- New `digitalocean`: `dop_v1_`, `doo_v1_` and `dor_v1_` followed by exactly 64 hex characters.+- Private keys: a key whose `END` line is missing (an excerpt cut it off) is claimed with its body, not just the `BEGIN` line, and a chunk that starts mid-key is claimed back from its `END` line. Handles indented bodies, CRLF, JSON-escaped (`\n`) keys, encrypted-key header lines and partial first or last lines. A key body produces one finding, not one per line. Linear time on adversarial input (20k unterminated fences, 1 MB of base64 lines).+- The assignment rule (`high_entropy_assignment`, used by retrieval, transcript import, hooks and the memory relay) now matches punctuated passwords: any non-space run inside quotes, and `!#$%*@^~.?<>` unquoted. It still needs 12 or more characters, a digit and high randomness, and rejects URLs, paths, shell expansions, already-redacted tokens and dotted code paths such as `process.env.X`.+- Findings carry `since` (the version that added or changed the rule) and, for cut-off keys, the old header-only fingerprint so a refusal can point at a stale allowlist line.+- Known misses (by design, documented): a key body on the same line as its header, keys joined with spaces or quoted with `> `, base64 runs over 128 characters, URL passwords containing a literal `/`, `?` or `#`, Basic values over 2048 characters, digitless assignment values, and unquoted passwords containing `,` or `;`.++#### Private keys in chunks and evidence++- `credentialSafeProjection` (`src/core/credential-projection.ts`) replaces every private-key span the scanner finds with `<REDACTED:private_key_pem>` plus the same number of newlines. The markdown chunker (and the embed paths that use it), fenced-code extraction, the code chunker and evidence delivery's page text all apply it after protected-content sanitizing. Chunker versions are unchanged, so no brain-wide re-chunk or re-embed is triggered.+- Schema migration v187 marks only live markdown and code pages whose body holds a private-key marker as needing a new text projection, which withholds their old chunks from every search path, local and remote, including the code-walk path. The orchestrated migration re-chunks them provider-free through the same installer as `gbrain repair safe-chunks`, one page per transaction.+- New doctor check `credential_projection_pending` (brain): pages still waiting, and code pages without a recorded source path that wait for a re-import.+- `gbrain post-upgrade`'s chunker-bump re-embed needs a `y` on a TTY; otherwise it declines and prints the commands. `GBRAIN_REEMBED_GRACE_SECONDS` is removed.++#### Push and bootstrap refusals++- A blocked `gbrain sources push` prints, per finding: file and line, pattern, redacted preview, fingerprint, the version that made the rule blocking, the exact append command for the absolute, quoted `.gbrain-scan-allow` path, and once at the end the remove-first advice, the retry command and a docs link. `--json` carries the same data in `findings[]` (`allowlistPath`, `allowCommand`, `retryCommand`, `since`, `docs`, `staleAllowlistEntry`).+- The push-status `reason` is a one-line summary of at most 140 characters (count, first location, pattern), so hook and doctor surfaces show it whole.+- `gbrain bootstrap verify` and `gbrain bootstrap repo`'s first push name fingerprints, the rule's version, the absolute allowlist path and the docs link, and say to remove a real credential first.++#### Retrieval output++- Every operation now declares how its response treats stored text. Retrieval operations (search, query, evidence delivery, recall, context_pack, delta, entity, synthesize, think, takes, timelines, transcripts, chronicle, code-intel and the rest) are redacted once at registration, so the CLI, both MCP transports, subagent tools and `gbrain call` all get the same pass, early returns included.+- Search, query and evidence output now run the assignment rule, so `GITHUB_TOKEN=...` and `client_secret: ...` lines are redacted.+- `recall`, `context_pack` and `delta` pack and price the text they deliver, so budgets and the `delta` cursor stay correct, and their rendered `text` is redacted whole instead of being replaced when large. Remembered facts (`fact`, `context`, `source`) are redacted for remote callers and returned as stored to the local CLI on the brain host; stdio MCP and thin clients count as remote. `fact_id` and `entity_slug` are never redacted.+- Transcript summaries, entity-card summaries and compiled-context excerpts redact the whole field before clipping, so a credential crossing the clip boundary leaves no fragment.++#### Compiled context and memory relay++- `gbrain compile-context` prints one line per dropped entry with the reason, pattern, fingerprint and the `.gbrain-scan-allow` path, never the value.+- A memory relay refused by the secret re-scan writes a heartbeat line (`reason: secret_scan_refused`, pattern, fingerprint, a fixed hint) to `~/.gbrain/integrations/hooks/heartbeat.jsonl`. The checkpoint is unaffected.++#### Google connector files++- Sync state (`.google-source.json`), its `.corrupt` quarantine and every Gmail, Calendar and Contacts page are written 0600, by the classic writer and by managed persistence alike. Directories gbrain creates for a Google source are 0700. A folder that already exists is never chmod-ed. A crash-left page `.tmp` is removed (never followed) before the new one is created private. Windows is unchanged.+- If the damaged-state quarantine cannot be secured, stderr names the file, the failed step and the fix (`chmod 600 <path>` or delete it); the sync continues.+- New doctor check `google_file_modes` (ops): per Google folder outside `~/.gbrain`, counts of readable files and directories gbrain wrote (never file names, since Gmail page names contain subject words) with the exact preview and apply commands.+- New explicit-only repair kind `gbrain repair google-file-modes [--source <id>] [--apply]`: it runs only when named, never under `--all` or `gbrain doctor --remediate`, which list it with its preview command. It clears group and other bits only on gbrain's own files and the folders between the source folder and its pages.+- The upgrade prints a one-time notice per Google source outside `~/.gbrain` (config marker `google.file_modes_notice`).++### For contributors++- `Operation.outputRedaction` is required (`src/core/ops/contract.ts`): `'retrieval'`, `{ retrieval: { localVerbatim } }`, `{ exempt: reason }` or `'no_stored_text'`. Typecheck refuses an unclassified op. `withOutputRedaction` in `src/core/search/output-redaction.ts` applies it; `test/retrieval-op-redaction.test.ts` runs every classified op through MCP dispatch with a planted secret.+- `redactRetrievalOutput` gains `uncapped` and `verbatim` options; `planRedaction` runs with `highEntropy: true` there.+- `AtomicWriteOpts.mode` and `mkdirPrivate(dir, root)` in `src/core/atomic-write.ts`; page publication carries `publishMode` for Google pages without changing request ids.+- `scripts/check-pg-url-redaction.sh` now covers every database scheme the scanner knows: mysql, mongodb and mongodb+srv, redis and rediss, amqp, mssql. Contributed by @Masashi-Ono0611 (#5148).+- `scripts/secret-scan-fp-budget.ts` reports new findings against a base ref (`--dir <brain>` prints per-pattern counts only). On this repository's ~3,460 tracked source, doc and skill files the new rules add two hits, both deliberate example URLs in error text and a comment; a synthetic brain-like fixture shows zero new hits on its non-secret part.+- Credential test fixtures are assembled at runtime from parts, so gitleaks and pre-push scanners stay quiet.++### Thanks++- @lubosxyz (#5348) for the search-output credential redaction work. Its shape tests now run against the canonical scanner, and the gaps they found are fixed there.+- @tarush1989 (#5080) for the private Google cursor file and quarantine handling, extended here to pages, folders and managed persistence.+- @Masashi-Ono0611 (#5148) for widening the database URL guard, and for the fast-uri pin (#5746), which had already shipped in v0.60.11.0.+## [0.60.30.0] - 2026-10-01**Fix wave 6: two privacy leaks closed, "who invested" and "who attended" answer the right way round, facts saved without a person get one, contradiction checks get much more accurate, and hybrid search on big Postgres brains stops falling back to keyword-only.**diff --git a/TODOS.md b/TODOS.mdindex 56624eec0c..7d2ba4e437 100644--- a/TODOS.md+++ b/TODOS.md@@ -1,5 +1,28 @@# TODOS+## Secret redaction and Google file modes follow-ups (filed 2026-10-01, follow-up from v0.60.31.0)++- [ ] **P2 — Sanitize text sent to configured providers (reranker, embeddings, synthesis).**+ **What:** retrieval output is redacted, but the hosted reranker, the embedding provider at ingest and `synthesize`/`think` generation still receive stored text unredacted. **Why:** a stored credential can leave the machine through a provider call even though no retrieval op returns it. **Fix:** run the canonical scanner over provider-bound text at the gateway seam (`src/core/ai/gateway.ts`), with the same echo dictionary, and record a content-free count. **Cons:** redacted embedding input changes vectors for affected chunks; the change needs a measured recall check. **Effort:** M. **Priority:** P2.+- [ ] **P2 — Dispatcher-level default redaction for remote callers.**+ **What:** every operation now declares `outputRedaction`, and only `'retrieval'` ops are wrapped. An op misclassified as `'no_stored_text'` or `{ exempt }` would return stored text raw to an MCP caller. **Fix:** in the shared dispatch path, run `redactRetrievalOutput` over every remote response unless the op is on the explicit raw-read exempt list (`get_page`, `fetch`, `get_chunks`, `get_raw_data`, `get_versions`, the skill catalog, admin job ops). **Effort:** S. **Priority:** P2.+- [ ] **P3 — `.netrc` and `curl -u` credential shapes.**+ **What:** `machine <host> login <user> password <pw>` lines and `curl -u user:pw` / `--user user:pw` arguments are not matched by any `secret-scan.ts` pattern. **Fix:** two keyword-anchored patterns with bounded values and placeholder rejection, perf-pinned in `test/secret-scan-perf.test.ts`. **Effort:** S. **Priority:** P3.+- [ ] **P3 — Should `pass` and `password` count as URL placeholder passwords?**+ **What:** `url_credentials` skips `<...>`, `${...}`, `$VAR`, all-`*` and all-`x` passwords, but a documentation URL whose password is literally `pass` or `password` now fires (two such literals exist in `src/`). **Decision needed:** treat those two words as placeholders (fewer documentation false positives, misses a real password that happens to be one of them) or keep firing. **Effort:** XS. **Priority:** P3.+- [ ] **P3 — Evaluate gitleaks-derived vendor rules under the linear-time contract.**+ **What:** compare the vendor prefixes in the upstream gitleaks rule set with `CORE_PATTERNS` and add the ones with a fixed, low-false-positive shape. **Why:** vendor coverage is the cheapest recall gain. **Cons:** every new rule needs a perf pin and a false-positive budget run (`scripts/secret-scan-fp-budget.ts`). **Effort:** M. **Priority:** P3.+- [ ] **P3 — Runtime counter for context entries dropped by the sensitivity scan.**+ **What:** each drop prints one content-free line (`compile-context: omitted <slug> ...`), but there is no running count in doctor or status, so a brain that silently loses many entries looks healthy. **Fix:** a counter (per pattern family, no values) surfaced by `gbrain doctor`. **Effort:** S. **Priority:** P3.+- [ ] **P3 — Per-brain retrieval redaction override.**+ **What:** a reviewed false positive can be allowlisted for pushes and compiled context (`.gbrain-scan-allow`), but retrieval redaction has no override. **Fix:** a fingerprint allowlist or `redaction.retrieval.disabled_patterns`, local-config only, never settable over MCP. **Effort:** S. **Priority:** P3.+- [ ] **P3 — Per-source Google file-mode override.**+ **What:** Google pages and cursor state are always written 0600, and a looser chmod is reverted on the next rewrite. A user who shares the directory with a group on purpose has no setting. **Fix:** an opt-in per-source mode (for example `g_file_mode`), validated to never grant world access. **Effort:** S. **Priority:** P3.+- [ ] **P3 — Vault, connector spool and connector credentials adopt `AtomicWriteOpts.mode`.**+ **What:** `src/core/creds/vault.ts`, `src/core/connectors/spool.ts` and `src/core/connectors/credentials.ts` each set 0600 their own way. Moving them to `atomicWriteFileSync(..., { mode: 0o600 })` reasserts the mode on every write, so a restored or copied loose file tightens. **Effort:** S. **Priority:** P3.+- [ ] **P3 — Exercise the skipped rows of the retrieval redaction sweep.**+ **What:** `test/retrieval-op-redaction.test.ts` plants a secret and runs every retrieval op through remote MCP dispatch, but skips the code-intel ops, `synthesize`/`think`, `search_by_image` and `get_agent_job` (wrapper coverage comes from the registration test). **Fix:** run each once fixtures exist (a code-index fixture, a keyed or stubbed composition, image embeddings, a submitted agent job). **Effort:** M. **Priority:** P3.+## System One v1 follow-ups (filed 2026-09-30; plan: docs/designs/SYSTEM_ONE_JEV_V1.md)- [ ] **P2 — Local decide provider (CEO E6).**@@ -270,8 +293,6 @@ Evidence for each item is in `docs/test-audit/2026-09-29/`.**What:** `sensitivity-scan.ts` bridges the gap by fingerprint dedupe so short bearer tokens still surface as `pii:bearer`; making secret-scan the single owner would let the PII family drop `jwt` / `bearer` entirely. **Effort:** S. **Priority:** P3.- [ ] **P3 — Bulk purge for a leaked transcript session.****What:** a long session lands as `-pN` part pages plus raw metadata; after a leak the operator hand-lists slugs for `gbrain delete <slug> --purge`. A `gbrain transcripts purge --session <file>` would purge every part + raw row of one session. **Effort:** S. **Priority:** P3.-- [ ] **P3 — Widen `scripts/check-pg-url-redaction.sh` to every scheme `db_url_credentials` covers.**- **What:** the guard greps `src/` for `postgres(ql)://…@` literals only; comments could still spell a mysql/mongodb/redis URL with userinfo. **Effort:** XS. **Priority:** P3.- [ ] **P3 — `gbrain jobs submit shell --follow` (inline execution) reads the shell opt-in from env only.****What:** `jobs work` gained `--allow-shell-jobs` because the cwd-`.env` quarantine can drop `GBRAIN_ALLOW_SHELL_JOBS`; the inline `--follow` path has no flag equivalent. **Effort:** XS. **Priority:** P3.- [ ] **P3 — CLI-spawning tests fail on the runtime gate instead of skipping when the host Bun is below `MINIMUM_BUN_VERSION`.**diff --git a/VERSION b/VERSIONindex 150cc79a03..d1155b9e4b 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.60.30.0+0.60.31.0diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex 8063cc475e..42c4b63f99 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -191,6 +191,7 @@ src/core/schema-migrations/v048-takes-weight-round-to-grid.ts 1 schema Schema insrc/core/schema-migrations/v123-configurable-fts-language.ts 1 schema Schema installation and forward-reference DDL; coordinated activation quiesces canonical writers.src/core/schema-migrations/v142-takes-embedding-dimension-matches-config.ts 1 schema Schema installation and forward-reference DDL; coordinated activation quiesces canonical writers.src/core/schema-migrations/v144-open-loops.ts 1 schema Schema installation and forward-reference DDL; coordinated activation quiesces canonical writers.+src/core/schema-migrations/v189-pages-credential-projection-pending.ts 1 schema Projection-only: unseals live pages whose canonical body holds a private-key marker and queues their keyless rebuild; canonical page columns are unchanged.src/core/persistence/connector-path.ts 1 coordinator Connector path clear locks the source row, refuses filesystem sources and bound connectors, and runs as a coordinated write on managed brains.src/core/source-delete.ts 1 engine_guard Unmanaged source delete with its incarnation binding; managed brains route removal through source lifecycle first and the writer guard refuses a direct delete.src/core/repair/extractor-facts.ts 1 coordinator `gbrain repair extractor-facts` (#5731) clears expired_at on preview-approved conversation-extractor facts and gives each a fresh row number. On a managed brain the UPDATE runs only inside the managed_maintenance_restore_extractor_facts publication (withCoordinatedWrite, page key locked, each fact reclassified first); an unmanaged brain runs the same function in one transaction under the page lock.diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.mdindex 176626ce9c..7d7065193f 100644--- a/docs/architecture/key-files/agent-bootstrap-continued.md+++ b/docs/architecture/key-files/agent-bootstrap-continued.md@@ -23,12 +23,12 @@- `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; sidecar-marked exactly-once; dream outputs and claude-cli self-captures classified by `isClaudeCliSelfSessionId` get a terminal `.ingested` sidecar with `skipped: dream_output` / `self_capture` (the shared `selfCaptureSidecarJson` writer) and are never extracted; the extractor input is `corpusTextForExtraction`, so pasted blocks never reach it). Bounded, fail-soft, never throws; armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `GBRAIN_SWEEP=0` kills it. `gbrain sweep --once` is the trusted CLI seam `bootstrap verify` uses (CLI-only, never over MCP). The link pass threads the same `link_resolution.cross_source` opt-in and configured `sources.default` the CLI extract lanes pass into `resolveCandidateSources`, so an edge into another source is created (flag on) or counted as `cross_source_link` in `skipped` (flag off) — never silently dropped, and the reconcile never deletes a cross-source edge `extract links --source db` created.- `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/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, gbrain), JWTs, whole-block PEM keys, plus two 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). 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 clears 3.5 bits/char. 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 URL with userinfo in this file's comments (`scripts/check-pg-url-redaction.sh`). 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), and `PEM_BLOCK_RE`'s lazy body (≤`PEM_BODY_MAX_CHARS` = 16384; a longer body degrades to the header-only match) — plus a per-pattern `precheck` substring gate on the two catch-alls (`@`; `earer`/`EARER`, since an all-caps `BEARER` scheme is accepted), 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). Perf pins: `test/secret-scan-perf.test.ts`. Retrieval output is another consumer of its canonical scanner; that output boundary does not sanitize internal evaluation/provider inputs.+- `src/core/secret-scan.ts` — pattern-based secret detection shared by `sources push`, bootstrap verify, the compiled-context sensitivity scan and the transcripts redactor. Detection is FORMAT-based, not prefix-only: vendor shapes (anthropic, openai, voyage, github, gitlab, slack, aws AKIA/ASIA, google, stripe, sendgrid, twilio, supabase sb_secret_/sbp_, npm, huggingface, `digitalocean` `do[opr]_v1_` + 64 hex, gbrain), JWTs, private keys (whole-text claims, below), plus four catch-alls appended LAST (`bearer` — prebuilt two-group layout so only the token is the value; `db_url_credentials` — the `scheme://user:pass@` span of database URLs, host/db kept; `url_credentials` — the same span for `http(s)` (scheme case-insensitive, `gi`), user 0–128 stopping at `:`/`/`, password 1–256 excluding whitespace, `@`, `"`, `'`, `/`, `?`, `#`, with a `validate` hook that rejects placeholder passwords (`<...>`, `${...}`, `$VAR`, all `*`, all `x`); `basic_auth` — two prebuilt case-insensitive forms, `Authorization: Basic` with a 4–2048 char value and bare `Basic` with 16–2048, both with a hard right edge and a `validate` that requires the value to base64-decode to printable ASCII containing `:`; it is NOT in the bearer family, so it joins neither the echo dictionary nor `secret:bearer`). The pattern contract: `CorePattern` carries optional `flags` (default `'g'`), `precheck`, `validate(value)` (O(value), run on the whole match before the claim and the union split; a rejected match is not re-tried from inside) and `since` (the gbrain version that added or last changed the rule; `SECURITY_WAVE_SINCE` = `0.60.31.0` on `digitalocean`, `url_credentials`, `basic_auth` and `private_key_pem`, kept in step with the release that ships a rule change). Compiled patterns keep group 1 = anchor, group 2 = value. `patternSince(pattern)` reads the map; every finding of such a pattern carries `SecretFinding.since`, which the push and bootstrap refusals render. Fixed-length shapes carry a trailing negative lookahead. Per-line claimed-span dedupe is first-wins for ATTRIBUTION (order matters: `Bearer <vendor key>` keeps the vendor name, a fully covered later span is skipped) but coverage is the UNION: every unclaimed slice of a later overlapping span is claimed as a hit of the later pattern (own value, own fingerprint), so a database URL whose username is a vendor-shaped id still loses its password. The opt-in `high_entropy_assignment` rule (`ScanOpts.highEntropy`) requires a 12+ char value that contains a digit AND clears 3.5 bits/char. 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 under the embed-skip threshold. 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/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.+- `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-v1`; 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. Tests: `test/backup-verification.serial.test.ts`, `test/backup-git-env.test.ts`, `test/backup-coverage.serial.test.ts`, `test/e2e/backup-coverage-parity.test.ts`.-- `src/core/workspace-push.ts` — `gbrain sources push`: deny-glob backstop (tracked `*.pglite`/`.env*` refused regardless of .gitignore state) → 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). 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).+- `src/core/workspace-push.ts` — `gbrain sources push`: deny-glob backstop (tracked `*.pglite`/`.env*` refused regardless of .gitignore state) → 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). 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. Tests: `test/workspace-push-guidance.test.ts`, `test/sources-push-cli.serial.test.ts`.- `src/core/gbrain-home.ts` — the single GBRAIN_HOME resolution choke point (delegates to config's parent-dir semantics; 0700 on create) — durability, push, hooks, and bootstrap all route through it so home semantics cannot drift.- `src/core/bootstrap/verify.ts` + `status.ts` — verify is the definition of done: fail-soft check suite over the REAL write path (put_page op → write-through file under `brain/` → in-process sweep → graph floor via link tables → recall), the keyless magic-moment check (`## Facts` fence → zero-LLM reconciliation → world-visibility read-back), source_id collision resolution (as the one bootstrap subcommand holding an engine: a manifest `source_id` already registered to a DIFFERENT checkout → derives a stable `workspace-<8char-path-hash>`, persists it to agent.json, names the re-register steps — every consumer reads `manifest.source_id`), the `embedding_plane` check (keyed installs live-embed ONE probe string and compare the RETURNED width to the actual `content_chunks.embedding` width — a plane split is a named FAIL with the recovery command, keyless passes, a dead probe warns; runs BEFORE the roundtrip so a keyless-passing roundtrip can never certify a brain whose keyed writes all fail), token sweep, byte floors, secret scan, deny globs, repo privacy, hooks smoke (in-process IPC), capability report, first-run tour; snapshots kept last-5 under `<home>/bootstrap/`. status owns the ordered PHASES list (the runbook defers to it), artifact-first detection, install.jsonl, the runbook version-stamp skew check, and the support blob doctor/agents relay verbatim.- `src/core/bootstrap/template-repo.ts` + `scripts/generate-template-repo.ts` — deterministic public-template generation (render `--minimal` + placeholder manifest + stamped README); published only by the release workflow after diffing against the vendored tree.diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex 3ea4cd9b3e..21d6a09fa6 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -27,6 +27,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/migrations/` — TS migration registry (compiled into the binary; no runtime walk of `skills/migrations/*.md`). `index.ts` lists migrations in semver order. `v0_11_0.ts` = Minions adoption orchestrator (8 phases). `v0_12_0.ts` = Knowledge Graph auto-wire orchestrator (5 phases: schema → config check → backfill links → backfill timeline → verify); `phaseASchema` has a 600s timeout for duplicate-heavy brains. `v0_12_2.ts` = JSONB double-encode repair orchestrator (4 phases: schema → repair-jsonb → verify → record). `v0_14_0.ts` = shell-jobs + autopilot cooperative (pending-host-work ping for skills/migrations/v0.14.0.md). All orchestrators are idempotent and resumable from `partial` status. The RUNNER owns all ledger writes — orchestrators return `OrchestratorResult` and `apply-migrations.ts` persists a canonical `{version, status, phases}` shape (orchestrators never call `appendCompletedMigration`). `statusForVersion` prefers `complete` over `partial` (never regresses); 3 consecutive partials → wedged → `--force-retry <version>` writes a `'retry'` reset marker. Schema-only migrations v14 (`pages_updated_at_index`) + v15 (`minion_jobs_max_stalled_default_5` with UPDATE backfill) live in `src/core/schema-migrations/v014-pages-updated-at-index.ts` and `v015-minion-jobs-max-stalled-default-5.ts` (one file per schema migration; `migrate.ts` is the runner). `in-process.ts` exports `runMigrateOnlyCore({timeoutMs?})` — single source of truth for "bring schema to head" (`configureGateway` → `createEngine` → `connect` → `initSchema` → `disconnect`, idempotent, 600s `MIGRATE_ONLY_TIMEOUT_MS` guard, throws `MigrateOnlyError` on no-config / timeout); the orchestrators' 9 schema phases AND `init.ts:initMigrateOnly` both delegate to it so schema bring-up can't drift (in-process, so no spawn can die with `getaddrinfo ENOTFOUND` on Windows + bun + Supabase pooler). `runGbrainSubprocess` is the diagnostic wrapper for the remaining non-schema spawns (extract/repair/stats): captures child stderr (64MB buffer) into the thrown error. `v0_13_1.ts:phaseCGrandfather` is a CHUNKED bulk SQL pass keyed on `pages.id` (globally unique PK, NOT slug — slug uniqueness is `(source_id, slug)`), filters `deleted_at IS NULL` (no tombstones), chunked in `CHUNK_SIZE` batches (DELETE_BATCH_SIZE convention) for bounded lock-hold; the rollback log carries `{id, slug, source_id, pre_frontmatter}` so rollback is unambiguous across sources; idempotent + resumable (each UPDATE flips its rows out of `GRANDFATHER_WHERE`). Pinned by `test/migration-in-process.serial.test.ts` and `test/migrations-v0_13_1-grandfather.test.ts`.- `src/commands/migrations/v0_46_3.ts` — idempotent no-op for a retired notification. Returns a complete migration with a skipped notice phase; performs no database, config, provider, vector or pending-work writes. Its feature pitch points to read-only status and explicit-target migration previews.+- `src/commands/migrations/v0_60_31.ts` — the security fix wave orchestrated migration (ledger `0.60.31`), two phases. `credential_projection`: runs `runMigrateOnlyCore` first (schema v189 marks the pages; PGLite skips the runner's schema pre-flight), then `resealCredentialProjections`, provider-free and never embedding; a dry run reports the count; any failed page makes the run `partial`, so `gbrain apply-migrations --yes --no-autopilot-install` retries it, and re-sealed pages are no longer pending, so a rerun resumes. `google_file_modes_notice`: `googleFileModesNoticePhase` from `v0_60_31-google-file-modes.ts`. A brain without config completes with the phase skipped. Agent instructions: `skills/migrations/v0.60.31.0.md`.- `src/commands/models.ts` — `gbrain models [--json]` read-only routing dashboard: prints tier defaults (`utility`/`reasoning`/`deep`/`subagent`), the resolved value for each (re-walking the resolution chain), every per-task override (14 `PER_TASK_KEYS`, including provider-neutral `models.contextual_synopsis` with legacy-key/env attribution and `models.dream.extract_atoms` which reports via its own caller-specific resolver — `resolveExtractAtomsModel()` in `extract-atoms.ts` — rather than the generic chain, so the report can't diverge from what the phase actually calls), the alias map, and a source-of-truth column (`default` / `config: <key>` / `env: <VAR>`) derived from `resolveModelDetailed`, so a tier key is attributed before `models.default`. A resolved Anthropic haiku/sonnet/opus id older (by major, minor) than the anthropic recipe's newest priced same-family id gets an advisory `[newer <family> available: <id>] (gbrain config set ...)` hint (JSON: `newer_available`); version parsing lives in `src/core/ai/anthropic-model-ids.ts` (8-digit segment is a date, so dated and undated forms compare equal; fable, non-Anthropic, newer-than-recipe and unparseable ids get no hint). The hint never changes a default. `gbrain models doctor [--skip=<provider>] [--json]` fires a 1-token `gateway.chat()` probe against each configured chat + expansion model and classifies failures into `{model_not_found, auth, rate_limit, network, unknown}`. The probe timeout resolves per model via `resolveChatProbeTimeoutMs` — the recipe touchpoint's `default_timeout_ms` when declared, else the flat 5000ms default (mirrors the reranker probe's recipe-default fallback; `claude-cli` declares 30s because its `claude -p` subprocess cold start routinely outruns 5s and would false-fail every run as `unknown`). Wired into `cli.ts` dispatch + `CLI_ONLY` set. A zero-token `embedding_config` probe runs FIRST, before any chat/expansion probes spend money: `probeEmbeddingConfig()` reads `getEmbeddingModel()` + `getEmbeddingDimensions()` and (for Voyage flexible-dim models) checks `isValidVoyageOutputDim(dims)` against `VOYAGE_VALID_OUTPUT_DIMS`. `ProbeStatus` variant `'config'` + optional `fix?: string` on `ProbeResult` surface a paste-ready `gbrain config set ...` line in human + JSON output; touchpoint label `'embedding_config'` joins `'chat'` and `'expansion'`.diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex 401a28fa8a..cce9d227eb 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/commands/repair.ts` — `gbrain repair [<kind>] [--apply] [--source <id>] [--limit <n>] [--no-embed] [--json]` and `gbrain repair --all`. Kinds `timeline` (#5567 materialize), `visibility` (#5525 tighten-only backfill) `safe-chunks` (#5050/#5247 projection-only re-seal of pages of every kind below the safe-chunk fence; `--no-embed` defers embedding to `embed --stale`), `contextual-mode` (#5621 projection-only stamp of the import-time contextual retrieval mode on pages that have none; honors `--no-embed`) `connector-checkpoints` (#5686 brain-wide cleanup of connector checkpoint rows no source can load), `orphan-bindings` (#5732 brain-wide cleanup of persistence source bindings whose source or incarnation is gone) and `embedding-effects` (#5629/#5734 settlement of stale queued and failed embedding effects: reconciled, superseded, retry_queued or blocked, reported per item in `outcomes` / `outcome_items`); no kind previews every kind. Dry run unless `--apply` (no prompt; `--yes` refused). `parseRepairArgs` is strict: any unknown option or a second positional refuses `invalid_params` before anything runs, and `--max-usd`/`--max-cost` name the capped route `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. Help lines come from `REPAIR_REGISTRY`; `--json` adds `paid` per kind and `paid_kinds`. Output carries the resolved scope, affected count, a capped `source:slug` sample, residual counts, request-ID / receipt-byte / re-embedding cost and capacity, and the apply command; `--json` has the same fields. Host-only: thin clients refuse via `THIN_CLIENT_REFUSED_COMMANDS`. Logic lives in `src/core/repair/`.+- `src/commands/repair.ts` — `gbrain repair [<kind>] [--apply] [--source <id>] [--limit <n>] [--no-embed] [--json]` and `gbrain repair --all`. Kinds `timeline` (#5567 materialize), `visibility` (#5525 tighten-only backfill) `safe-chunks` (#5050/#5247 projection-only re-seal of pages of every kind below the safe-chunk fence; `--no-embed` defers embedding to `embed --stale`), `contextual-mode` (#5621 projection-only stamp of the import-time contextual retrieval mode on pages that have none; honors `--no-embed`) `connector-checkpoints` (#5686 brain-wide cleanup of connector checkpoint rows no source can load), `orphan-bindings` (#5732 brain-wide cleanup of persistence source bindings whose source or incarnation is gone) and `embedding-effects` (#5629/#5734 settlement of stale queued and failed embedding effects: reconciled, superseded, retry_queued or blocked, reported per item in `outcomes` / `outcome_items`) and `google-file-modes` (clears group/other bits on gbrain's own files under Google source dirs outside `~/.gbrain`; filesystem only); no kind previews every kind. Dry run unless `--apply` (no prompt; `--yes` refused). `parseRepairArgs` is strict: any unknown option or a second positional refuses `invalid_params` before anything runs, and `--max-usd`/`--max-cost` name the capped route `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. Help lines come from `REPAIR_REGISTRY`; `--json` adds `paid` per kind and `paid_kinds`. Output carries the resolved scope, affected count, a capped `source:slug` sample, residual counts, request-ID / receipt-byte / re-embedding cost and capacity, and the apply command; `--json` has the same fields. Host-only: thin clients refuse via `THIN_CLIENT_REFUSED_COMMANDS`. Logic lives in `src/core/repair/`.- `src/commands/reindex.ts` — `gbrain reindex --markdown [--type PAGE_TYPE] [--limit N] [--dry-run] [--json] [--no-embed] [--repo PATH]`. Walks markdown pages with stale `chunker_version` (plus unstamped contextual-retrieval mode when embedding is enabled; `--no-embed` still stamps the mode of every page it re-chunks) in 100-row id-keyset batches; a failed row cannot starve later batches in the same invocation. `--type` adds a bound-parameter `pages.type = $N` scope for focused backfills such as atom pages and is rejected by reindex modes that do not consume it. Current-version chunkless healing deliberately remains owned by the native, bounded `embed --stale` path. Rows with non-null `source_path` re-import via `importFromFile`; rows without fall back to `importFromContent`. Both paths pass `forceRechunk: true` to bypass `importFromContent`'s `content_hash` short-circuit — without it the chunker version bump never reaches pages whose source content hasn't changed, AND the stripFactsFence privacy strip never applies to chunks stored without it. Wired into `src/commands/upgrade.ts:runPostUpgrade` after `apply-migrations`. The DB-only fallback (no source file on disk) does NOT pass body-only `compiled_truth` to `importFromContent` (that path re-parses with EMPTY frontmatter and OVERWRITES the page's real frontmatter/title/timeline); it `getPage`+`getTags`, reconstructs FULL markdown via `serializeMarkdown(frontmatter, compiled_truth, timeline, {type, title, tags})`, and re-imports THAT so re-chunking a DB-only page preserves everything while bumping `chunker_version`. Pinned by `test/reindex-preserve-tags.test.ts` and `test/reindex.test.ts`.- `src/commands/repair-jsonb.ts` — `gbrain repair-jsonb [--dry-run] [--json]`: rewrites `jsonb_typeof='string'` rows in place across 8 affected columns (pages.frontmatter, raw_data.data, ingest_log.pages_updated, files.metadata, page_versions.frontmatter, subagent_messages.content_blocks, subagent_tool_executions.input, subagent_tool_executions.output). The subagent targets are `jsonPayloadOnly`: those columns can legitimately hold jsonb string scalars (persistToolExec binds a tool's pre-serialized string payload as-is), so their damage predicate additionally requires container-shaped content (`^\s*[\[{]`) that `pg_input_is_valid(..., 'jsonb')` (PG16+ floor, same as the IS JSON predicate `updateSourceConfig` relies on) actually parses — a plain-text value that merely starts with `[` or `{` is never flagged or corrupted. Targets whose table doesn't exist on the brain are skipped via `to_regclass` (brains without the subagent tables), and one target's failure is recorded on stderr while the run continues — earlier repairs are already committed and the v0_12_2 migration orchestrator JSON-parses stdout. `runDoctor`'s `jsonb_integrity` check counts damage with the same predicate over the same target list. Repairs double-encoded rows on Postgres; PGLite no-ops. Idempotent. Pinned by `test/repair-jsonb.test.ts` + `test/doctor.test.ts`.diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex ed6de7a3e5..77e36089e9 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -57,7 +57,7 @@ The page operations that submit through this layer are in [Core Services (2/3)](- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection. A lock holder that is not a serve and answers no owner socket (a concurrent CLI call) is not a resident owner: `maybeDelegateLocalOperation` returns unhandled and the engine path waits for the PGLite lock instead of answering `owner_unavailable`; a serve holder or an answering socket keeps every failure final. Owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. `residentPersistenceConfig` resolves a resident serve's brain the same way (`--brain`, `GBRAIN_BRAIN_ID`, `.gbrain-mount`, mount path), so the owner socket and the provider's consumer config follow a mounted brain instead of the host config (#5237); hook IPC stays keyed off the host config. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`, `test/serve-mounted-owner.serial.test.ts`. A credential-free, read-only `projection_status` request (like `capabilities`) returns the resident's projection backlog counts (`PersistenceProjectionStatus`, no identifiers) so doctor's `text_projection_readiness` can report it while the resident holds a PGLite datastore (#5401, `test/projection-resident-doctor.test.ts`).-- `src/core/persistence/{schema,model,journal,authority,identity,ownership,coordinator,consumer,service,page-mutations,page-prepare,source-storage,control,context,digest,prepared-import}.ts` — dedicated durable mutation admission and permanent principal-scoped replay IDs, atomic quota reservations, registered canonical worktree ownership, native lock publication, conditional file recovery, and coherent receipt completion. Recovery presence blocks its whole worktree even when the receipt is terminal; admission and publication both enforce the fence. A file write is not claimed while a queued or running withdrawal mirror targets its page (any page, for an untargeted mirror), so the mirror cannot rewrite the file under an accepted request; when file bytes differ from preparation and the page revision also moved, publication reprepares (`revision_conflict`) instead of refusing as `raw_file_changed`, which stays the outcome for changed bytes at an unchanged revision (`test/withdrawal-followup-writes.test.ts`). Migration 159 adds a partial worktree/sequence recovery index so permanent receipt retention does not turn the fence into a history scan. Canonical file preparation honors a recorded source path or contained absolute capture file URI within the registered owner root (relative or host-only `file://` URIs are absent); symlink confinement and coherent snapshot checks still apply. A slug under a `storage.db_only` dir declared in `gbrain.yml` (matched case-insensitively, derive-phase defaults excluded) publishes database-only when a live page's file is absent (the case that otherwise refuses as an uncoordinated removal), with receipt `write_through.skipped: db_only`; new pages, tombstones, missing-file-tolerant callers and present cache files keep the full file treatment and never read `gbrain.yml`. `gbrain.yml` is read from the source root, like doctor, export and backup, not the git root `manageGitignore` uses, which differs for a monorepo-subdir source. `source-storage.ts` caches the parsed file per version and logs an invalid one (unreadable, overlapping tiers, db_only declared in syntax that resolves nothing) once; that missing-file refusal then reports `storage_error`, and the Git effect treats the page as not db_only. The drift guard applies the import rule for a file without an explicit `type:` (the stored type stands) and compares titles trimmed, as the parser reads them; a real drift refuses with `detail: file_database_drift` and a filled `sources reconcile` command. The first write that binds an origin in a Git-subdirectory source with no slug-root pin pins the inferred mode in its publication transaction (a concurrent different pin refuses with `revision_conflict`), so later pages cannot flip the inference. A new page captured from a file inside the source (`capture_path`, resolved from the trusted CLI `local_file` in `page-mutations`, only when sync would give that file the capture slug under the source's slug-root mode) publishes to that file when its bytes are exactly the captured input; otherwise capture records `source_uri: cli-file`, never a host path. `acquireWorktree(binding, waitMs, signal, engine)` re-stamps a device-only physical-root change under the native lock (see `physical-root.ts`); without an engine, or when birth time is zero, it refuses with `detail: physical_root_device_changed` and the filled self-transfer commands. Version snapshots retain nullable `is_deleted`: new snapshots restore recorded deletion state atomically with content, tags, files and receipts; legacy NULL preserves current deletion state. Canonical no-op detection compares deletion state as well as content. Page replacement preconditions are checked before no-op detection; providers prepare outside publication transactions; recovery never restores unexpected bytes. Local registrations retain immutable CLI/stdio trust lanes and hashed credentials; accepted authority is intersected with current grants. `limits.ts` reads every `persistence.limits.*` cap and `persistence.receipt_retention_days` (default 30) from the database config table (`JOURNAL_CONFIG_KEYS`, registered for `gbrain config set`; malformed values are rejected at set time). Cumulative defaults (250,000 lifetime IDs and 1.5 GiB receipt bytes per principal, 8 GiB brain receipt bytes) cover 600 admissions a day for a year; each admission reserves at least 16 KiB and a compacted receipt keeps about 4 KiB. A cumulative `queue_capacity` refusal names its key in `detail` and suggests a `gbrain config set` value covering one more year at the recent admission rate (`oneYearCapacity`). Compaction filters out receipts with unfinished effects before its batch limit. `test/persistence-journal.test.ts` exercises real PGLite and optional guarded Postgres admission, cancellation, compaction, conflict and publication recovery; `test/persistence-capacity.test.ts` covers retention, the compaction filter, capacity hints and default sizing. `service.ts` also dispatches operation `decide_proposal` (S9 proposal accept/undo) to `facts/proposal-supersede.ts`.+- `src/core/persistence/{schema,model,journal,authority,identity,ownership,coordinator,consumer,service,page-mutations,page-prepare,source-storage,control,context,digest,prepared-import}.ts` — dedicated durable mutation admission and permanent principal-scoped replay IDs, atomic quota reservations, registered canonical worktree ownership, native lock publication, conditional file recovery, and coherent receipt completion. Recovery presence blocks its whole worktree even when the receipt is terminal; admission and publication both enforce the fence. A file write is not claimed while a queued or running withdrawal mirror targets its page (any page, for an untargeted mirror), so the mirror cannot rewrite the file under an accepted request; when file bytes differ from preparation and the page revision also moved, publication reprepares (`revision_conflict`) instead of refusing as `raw_file_changed`, which stays the outcome for changed bytes at an unchanged revision (`test/withdrawal-followup-writes.test.ts`). Migration 159 adds a partial worktree/sequence recovery index so permanent receipt retention does not turn the fence into a history scan. Canonical file preparation honors a recorded source path or contained absolute capture file URI within the registered owner root (relative or host-only `file://` URIs are absent); symlink confinement and coherent snapshot checks still apply. A slug under a `storage.db_only` dir declared in `gbrain.yml` (matched case-insensitively, derive-phase defaults excluded) publishes database-only when a live page's file is absent (the case that otherwise refuses as an uncoordinated removal), with receipt `write_through.skipped: db_only`; new pages, tombstones, missing-file-tolerant callers and present cache files keep the full file treatment and never read `gbrain.yml`. `gbrain.yml` is read from the source root, like doctor, export and backup, not the git root `manageGitignore` uses, which differs for a monorepo-subdir source. `source-storage.ts` caches the parsed file per version and logs an invalid one (unreadable, overlapping tiers, db_only declared in syntax that resolves nothing) once; that missing-file refusal then reports `storage_error`, and the Git effect treats the page as not db_only. The drift guard applies the import rule for a file without an explicit `type:` (the stored type stands) and compares titles trimmed, as the parser reads them; a real drift refuses with `detail: file_database_drift` and a filled `sources reconcile` command. The first write that binds an origin in a Git-subdirectory source with no slug-root pin pins the inferred mode in its publication transaction (a concurrent different pin refuses with `revision_conflict`), so later pages cannot flip the inference. A new page captured from a file inside the source (`capture_path`, resolved from the trusted CLI `local_file` in `page-mutations`, only when sync would give that file the capture slug under the source's slug-root mode) publishes to that file when its bytes are exactly the captured input; otherwise capture records `source_uri: cli-file`, never a host path. `acquireWorktree(binding, waitMs, signal, engine)` re-stamps a device-only physical-root change under the native lock (see `physical-root.ts`); without an engine, or when birth time is zero, it refuses with `detail: physical_root_device_changed` and the filled self-transfer commands. Version snapshots retain nullable `is_deleted`: new snapshots restore recorded deletion state atomically with content, tags, files and receipts; legacy NULL preserves current deletion state. Canonical no-op detection compares deletion state as well as content. Page replacement preconditions are checked before no-op detection; providers prepare outside publication transactions; recovery never restores unexpected bytes. Local registrations retain immutable CLI/stdio trust lanes and hashed credentials; accepted authority is intersected with current grants. `limits.ts` reads every `persistence.limits.*` cap and `persistence.receipt_retention_days` (default 30) from the database config table (`JOURNAL_CONFIG_KEYS`, registered for `gbrain config set`; malformed values are rejected at set time). Cumulative defaults (250,000 lifetime IDs and 1.5 GiB receipt bytes per principal, 8 GiB brain receipt bytes) cover 600 admissions a day for a year; each admission reserves at least 16 KiB and a compacted receipt keeps about 4 KiB. A cumulative `queue_capacity` refusal names its key in `detail` and suggests a `gbrain config set` value covering one more year at the recent admission rate (`oneYearCapacity`). Compaction filters out receipts with unfinished effects before its batch limit. `test/persistence-journal.test.ts` exercises real PGLite and optional guarded Postgres admission, cancellation, compaction, conflict and publication recovery; `test/persistence-capacity.test.ts` covers retention, the compaction filter, capacity hints and default sizing. `service.ts` also dispatches operation `decide_proposal` (S9 proposal accept/undo) to `facts/proposal-supersede.ts`. GOOGLE PUBLISH MODE: a page target is a `PageMutationFile` (`MutationFile` plus optional `publishMode`). The Google callers set `publishMode: 0o600` at prepare time from the stored connector (`prepareConnectorMutation` in `connector-sync.ts` when `p.connector === 'google'`, and `prepareGoogleReceiptPatch`); it is never part of the submitted intent, so request ids are unchanged. `publishFile` then creates missing directories with `mkdirPrivate(dirname(path), root)` (0700) instead of `mkdirSync` and opens the stage with `mode ?? publishMode` through `AtomicWriteOpts.mode`, so a rewrite of a legacy 0644 page lands 0600. Restoration keeps restoring the journaled before-mode and opens its stage with it (the post-flush chmod stays), so a restored private page is never staged wider than its mode.- `src/core/persistence/unbound-source.ts` — #5254 policy for a Postgres page write to a filesystem source (`local_path`, or `sync.repo_path` for `default`) with default write-through and no worktree binding. `submitPageMutation` refuses `owner_unavailable` with `detail: unbound_source`, a `docs` pointer to `write-refusals.md#unbound-sources-on-postgres`, and a hint naming the filled `sources writer status`/`writer claim ... --admin-intent writer_claim --expected-state <admin_state>` bind command (host path only for trusted local callers) and, for `put_page` to a page without `source_path`, `gbrain config set persistence.unbound_write database_only`. That key (`refuse` default, validated by `config set`; any other stored value refuses) lets such a `put_page` admit with `databaseOnlyReason: 'unbound_source'`. Publication rechecks inside its transaction, after `authorizeStoredRequest` share-locks the source row, that the source is still unbound and the page still has no `source_path` (else `owner_unavailable`/`unbound_source`, hint rebuilt from the persisted message by `writeResponse`), then stamps `pages.database_only_reason='unbound_source'` (migration 177). After binding, `prepareFileTarget` keeps a stamped page with no file database-only (receipt `write_through.skipped: unbound_source` with a warning) and managed sync refuses to import a file at its path (`source_changed`, diagnostic reason `unbound_source`). PGLite keeps auto-claiming. Tests: `test/e2e/unbound-source-postgres.test.ts`, `test/persistence-unbound-source.test.ts`.diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 747200a839..3515381e6c 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -3,11 +3,11 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/core/search/evidence-delivery.ts` — the `return_unit` evidence assembler (default `auto`: conversation pages by type or `chat/`/`conversations/` slug come back whole under `search.return_budget_conversation` (24,000), every other hit is its unchanged chunk; `effectivePlan` skips the stage when an implied `auto` sees no conversation hit, so that path and `chunk` stay byte-identical). `resolveEvidencePlan` validates `return_unit` / `return_window` (invalid_params naming the allowed values and an example), reads `search.return_unit` / `think.return_unit`, `search.return_window`, `search.return_budget_default` (6,000), `search.return_budget_conversation` (24,000) and clamps remote budgets to `search.return_budget_max_remote` (32,000, reported). Snippet precedence: explicit `snippet_chars` > explicit `return_unit` > subagent default cap > config unit. `deliverEvidence` groups hits by page_id (one block per page at its best rank), makes ONE `engine.getChunkWindows` call (re-authorizes every page; unauthorized pages are dropped, never served from hit text), builds the page text from the stored body sanitized whole before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded), locates the hit chunks in it (`locateChunks`: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts `window` / `section` (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / `page` / `auto` (fenced-code hits are placed by their code minus the chunker's synthesized header), counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with `delivered` plus a `delivery` meta. Fetch failure/timeout (5 s) falls back to the hit chunk only for live hits. `assembleEvidenceForHits` / op `assemble_evidence` deliver the exact evidence `query` returns for a frozen `(source_id, slug, chunk_id)` list; `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). Normative spec: `docs/evidence-delivery.md`. Tests: `test/evidence-delivery.test.ts`, `test/evidence-delivery-golden.test.ts`, `test/e2e/evidence-delivery-leak.test.ts`, `test/e2e/evidence-delivery-parity.test.ts`; bench `scripts/bench-evidence-delivery.ts`.+- `src/core/search/evidence-delivery.ts` — the `return_unit` evidence assembler (default `auto`: conversation pages by type or `chat/`/`conversations/` slug come back whole under `search.return_budget_conversation` (24,000), every other hit is its unchanged chunk; `effectivePlan` skips the stage when an implied `auto` sees no conversation hit, so that path and `chunk` stay byte-identical). `resolveEvidencePlan` validates `return_unit` / `return_window` (invalid_params naming the allowed values and an example), reads `search.return_unit` / `think.return_unit`, `search.return_window`, `search.return_budget_default` (6,000), `search.return_budget_conversation` (24,000) and clamps remote budgets to `search.return_budget_max_remote` (32,000, reported). Snippet precedence: explicit `snippet_chars` > explicit `return_unit` > subagent default cap > config unit. `deliverEvidence` groups hits by page_id (one block per page at its best rank), makes ONE `engine.getChunkWindows` call (re-authorizes every page; unauthorized pages are dropped, never served from hit text), builds the page text from the stored body sanitized whole and passed through `credentialSafeProjection` before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded; private-key spans become newline-padded `<REDACTED:private_key_pem>` tokens, the same text the chunkers cut from), locates the hit chunks in it (`locateChunks`: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts `window` / `section` (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / `page` / `auto` (fenced-code hits are placed by their code minus the chunker's synthesized header), counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with `delivered` plus a `delivery` meta. Fetch failure/timeout (5 s) falls back to the hit chunk only for live hits. `assembleEvidenceForHits` / op `assemble_evidence` deliver the exact evidence `query` returns for a frozen `(source_id, slug, chunk_id)` list; `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). Normative spec: `docs/evidence-delivery.md`. Tests: `test/evidence-delivery.test.ts`, `test/evidence-delivery-golden.test.ts`, `test/e2e/evidence-delivery-leak.test.ts`, `test/e2e/evidence-delivery-parity.test.ts`; bench `scripts/bench-evidence-delivery.ts`.- `src/core/search/chunk-windows.ts` — request/response shapes and the row mapper for `BrainEngine.getChunkWindows`. The SQL lives once in `src/core/engine-sql/chunks.ts` (`getChunkWindows`): page rows (authorization + seal + max chunk index + raw body columns) and chunk rows (inside the requested chunk_index ranges, text modality, requested chunk sources, row cap) come back in one UNION so the row cap never hides a page's authorization; the predicate is the search legs' (source scope, deleted, current text projection, archived source, quarantine, private pages, safe chunks). Postgres runs it inside the scoped read transaction.-- `src/core/search/output-redaction.ts` — copies retrieval results and metadata before output sanitation, sharing the canonical `secret-scan.ts` plan and echo dictionary. Keyword, hybrid, image, exact and CRAG paths sanitize after internal grading/capture and before snippet truncation; CLI search/query JSON, explain and human rendering repeat the defense-in-depth pass. Identity fields (`id`, `slug`, `source_id`, `page_id`, `chunk_id`, `message_id`, `thread_id`, `graph_session_prefix`, relational seed/path, `superseded_by`) remain byte-identical: never put secrets in IDs. Each field is capped at 64 Ki UTF-16 characters, the response at 1 Mi characters/8192 text fields, and nesting at 24 levels; oversized/unscannable text becomes `<REDACTED:output_limit>`. Unknown formats, high-entropy assignments and short fragments can escape default detection. This is output hygiene, not authorization or provider/eval no-egress; internal pages and capture retain originals. Tests: `test/search/output-redaction.serial.test.ts`, `test/search/output-redaction.test.ts`.+- `src/core/search/output-redaction.ts` — copies retrieval results and metadata before output sanitation, sharing the canonical `secret-scan.ts` plan and echo dictionary. Keyword, hybrid, image, exact and CRAG paths sanitize after internal grading/capture and before snippet truncation; CLI search/query JSON, explain and human rendering repeat the defense-in-depth pass. Every field is planned with `highEntropy: true`, so `KEY=value` assignments redact alongside the named shapes. Identity fields (`id`, `slug`, `source_id`, `page_id`, `chunk_id`, `message_id`, `thread_id`, `graph_session_prefix`, relational seed/path, `superseded_by`, `fact_id`, `entity_slug`) remain byte-identical: never put secrets in IDs. By default each field is capped at 64 Ki UTF-16 characters, the response at 1 Mi characters/8192 text fields, and nesting at 24 levels; oversized/unscannable text becomes `<REDACTED:output_limit>`. `RetrievalRedactionOpts.uncapped` scans every field whole (no `output_limit` replacement; one echo dictionary, every field planned before any write; the depth cap stays) and `verbatim` copies the named keys of each top-level result unscanned. `withOutputRedaction(op)` is the registration-time wrapper behind `Operation.outputRedaction` (`src/core/ops/contract.ts`): `operations.ts` wraps every `'retrieval'` op's handler once, so the CLI, stdio and HTTP MCP, subagent tools and `gbrain call` all pass the whole response (early returns included) through the uncapped redactor, linear in output size; `{ retrieval: { localVerbatim } }` leaves the named keys raw only when `ctx.remote === false`. The memory verbs: `recall`, `context_pack` and `delta` redact their presentation sets with one echo dictionary before packing, so budgets, `budget_used` and the delta cursor follow the delivered text, and their rendered `text` is never replaced by `output_limit`; facts (`fact`, `context`, `source`) are `localVerbatim`, so a remembered credential is readable raw only by the trusted local CLI on the brain host (stdio MCP and thin clients are remote). Handlers that clip or summarize stored text (transcript summaries, entity-card and compiled-context excerpts) redact the whole field before clipping. THREAT MODEL: this defends against accidental exposure of stored credentials into agent context and transcripts through retrieval ops. It does not cover the raw-read exemptions (`get_page`, `fetch`, `get_chunks`, `get_raw_data`, `get_versions`, the skill catalog, admin job ops), stored content (unchanged), or configured providers (embeddings at ingest, the hosted reranker, synthesis/think generation still receive unredacted text, except private keys, which the credential-safe projection keeps out of chunks). Unknown formats and short fragments can escape detection. This is output hygiene, not authorization or provider/eval no-egress. Tests: `test/search/output-redaction.serial.test.ts`, `test/search/output-redaction.test.ts`, `test/retrieval-op-redaction.test.ts` (every `'retrieval'` and `'no_stored_text'` op run through MCP dispatch with `remote = true` against a planted secret, plus the registration wrapper), `test/transcripts-redaction.test.ts`.- `src/core/search/return-policy.ts` (default OFF) — intent-aware adaptive return-sizing. Pure, dependency-light module that trims the final ranked candidate set to an intent-driven cap instead of returning the full top-K. `entity` intent gets a tight cap; `temporal`/`event`/`general` get a recall-preserving cap (`concept` is coerced to `general` by `hybrid.ts` before the call — concept queries want breadth). A `minKeep` failsafe (≥1) guarantees a human never gets a silent blank when candidates exist. WHY a cap, not a score-cliff detector: PrecisionMemBench instrumentation (gbrain-evals) measured the rank1→rank2 RRF gap is ~identical whether rank-1 is correct (0.602) or wrong (0.569) — mechanical decay, not a separatrix; rank-1 is right in 94% of single-answer cases, so "return a tight set" is the whole win and cliff-cutting just adds noise. Exports `AdaptiveReturnConfig`, `DEFAULT_ADAPTIVE_RETURN` (frozen: `enabled=false`, `entityMax=2`, `otherMax=6`, `minKeep=1`), `AdaptiveReturnDecision` (`{applied, intent, cap, kept, total}`), `AdaptiveReturnInput` (`boolean | Partial<AdaptiveReturnConfig> | undefined`), `adaptiveReturnFromConfig(cfg)`, `resolveAdaptiveReturn(perCall, fromConfig)` (defaults → config → per-call merge), `adaptiveReturnEnabled(...)` (cache-skip gate check), `applyAdaptiveReturn(results, intent, cfg)` (the trim). Config knobs (DB or file plane): `search.adaptive_return` (master switch), `search.adaptive_return_entity_max`, `search.adaptive_return_other_max`, `search.adaptive_return_min_keep` (each clamped ≥1). Wired into `hybridSearch` AFTER `applyReranker`, BEFORE the `limit` slice, and ONLY on the first page (`offset===0`) — paginating a confidence-gated set is incoherent, so paginated calls fall through to the fixed limit. Stamps the decision onto `HybridSearchMeta.adaptive_return` for `gbrain search --explain`. `hybridSearchCached` SKIPS the cache when the gate is on (a trimmed set must not be served to a gate-off lookup and vice versa). `SearchOpts.adaptiveReturn` + `HybridSearchMeta.adaptive_return` declared in `src/core/types.ts`. Agent-facing: the `query` op (`src/core/operations.ts`) exposes an `adaptive_return` boolean param whose description instructs the agent WHEN to set it (single-answer → on; breadth/exploration → off; pass `limit:1` for a hard single-answer cap), threaded into `hybridSearchCached` — end users never touch the config knob; their agent decides per query (same pattern as `salience`/`recency`). Pinned by `test/search/return-policy.test.ts` (mechanism) + `test/search/query-op-adaptive-return.test.ts` (agent surface: param exists + description teaches both directions + the never-empty contract).diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.mdindex f83899604d..9e4555a5c7 100644--- a/docs/architecture/key-files/core-services-1.md+++ b/docs/architecture/key-files/core-services-1.md@@ -33,7 +33,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/chunkers/llm.ts` — LLM-guided chunking: pre-splits into 128-word candidates via the recursive chunker, then asks a Haiku-class model "where does the FIRST topic shift occur?" per window.-- `src/core/chunkers/recursive.ts` — base chunker: 300-word chunks, 50-word sentence-aware overlap, 5-level delimiter hierarchy. Applies `sanitizeRemoteBody` before splitting so only world Facts and ordinary prose enter retrieval text; all Takes and malformed protected sections are omitted. Non-overlapping portions reassemble to that sanitized input. The overlap extractor counts chars (not whitespace tokens) for CJK-dominant chunks — same unit as `countWords` — and aligns to `。!?` or a whitespace-followed ASCII `.!?`; the L4 char-slice fallback advances through `safeSplitIndex` so astral pairs (emoji, non-BMP CJK) are never halved. Both are gated on `isCJKDominant`, so English output is byte-identical (pinned by `test/chunkers/recursive-cjk-overlap.test.ts`). The markdown chunker version records the current index format.+- `src/core/chunkers/recursive.ts` — base chunker: 300-word chunks, 50-word sentence-aware overlap, 5-level delimiter hierarchy. Applies `sanitizeRemoteBody` and then `credentialSafeProjection` (`src/core/credential-projection.ts`) before splitting, so only world Facts and ordinary prose enter retrieval text and private keys enter only as `<REDACTED:private_key_pem>`; all Takes and malformed protected sections are omitted. Non-overlapping portions reassemble to that sanitized input. The overlap extractor counts chars (not whitespace tokens) for CJK-dominant chunks — same unit as `countWords` — and aligns to `。!?` or a whitespace-followed ASCII `.!?`; the L4 char-slice fallback advances through `safeSplitIndex` so astral pairs (emoji, non-BMP CJK) are never halved. Both are gated on `isCJKDominant`, so English output is byte-identical (pinned by `test/chunkers/recursive-cjk-overlap.test.ts`). The markdown chunker version records the current index format.- `src/core/chunkers/semantic.ts` — embedding-based topic-boundary detection: embeds sentences, computes cosine-similarity valleys, smooths with a Savitzky-Golay filter (5-window, 3rd-order polynomial) to find chunk boundaries. Sanitizes the full body before sentence embedding and boundary detection.@@ -42,5 +42,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/connectors/` (directory) — the LIVE chat-history connector layer (front-end to the transcripts pipeline). `types.ts`: the `ChatHistoryProvider` contract (mirror of `TranscriptAdapter` — leaf module per provider; `spoolFormat` names the adapter that parses its output; dated `HostSpecTarget`). `credentials.ts`: file-plane store at `~/.gbrain/connectors/<provider>.json` (0600, dir 0700, atomic tmp+rename), env-above-file `resolveCredential` returning `{cred, source}`; credentials NEVER touch the DB / `sources.config` / config planes / op payloads. `classify.ts`: the pure §2A/§2B response classifier — distinguishes a Cloudflare-fingerprint 403 (`forbidden_fingerprint`, dead-end) from an auth-expired 403 (`auth_required`, re-auth) and flags a parses-but-no-`items` body as `drift`. `client.ts`: `ConnectorClient` modeled on `GitHubClient` (plain fetch against a hardcoded ORIGIN + off-origin guard so the cookie/bearer never leaks, browser UA, refresh-once-on-401, Retry-After backoff; `fetchImpl`/`sleep`/`now` injectable — NOT `fetchWithSSRFGuard`, which breaks SNI on Cloudflare hosts). `providers/chatgpt.ts` + `providers/claude.ts` (registry in `registry.ts`; Perplexity deliberately absent — no adapter): offset/updated pagination with a per-pass 500-page cap and a `stopBefore` watermark break, epoch/ISO normalization, ChatGPT's `is_archived` second pass, Claude's `chat_conversations` paged with `limit`/`offset` across every chat-capable org (conversations fetched from the org that listed them; timestamps normalized with ChatGPT's `toIso`), a ChatGPT walk that steps back when `total` shrinks mid-walk (a removal shifts later items to lower offsets) and yields each id once across both passes, content-block text assembly for Claude, and a `refreshAccessToken` (ChatGPT re-mints from the cookie via `/api/auth/session`; Claude's cookie is terminal). `spool.ts`: writes fetched conversations in native-export shape (0600, batched, pruned in the orchestrator `finally`). `sync.ts`: `runConnectorSync` — resolve credential → probe → read the **per-(provider, source) config-scalar watermark** `connectors.<p>.source.<id>.watermark_iso` (NOT op_checkpoint, whose 7-day GC would wipe it → full re-fetch) → list to `watermark − windowDays` → skip stubs whose `updatedAt` the source's `synced` ledger already holds and stubs quarantined in its `failed` ledger (after `QUARANTINE_ATTEMPTS` = 3 fetch OR ingest failures at one `updatedAt`; ingest outcomes are attributed per conversation by session id, a spool-file-level failure fails the batch; an edit or `--full` retries) BEFORE the `--limit` cap, so capped runs progress → fetch → spool → `runTranscriptsIngest` → record each successfully ingested conversation as synced → advance the watermark ONLY on a clean run (quarantined ids no longer block it; ledger entries older than the next list window are pruned) → `logIngest` receipt → stamp per-source `last_sync_at` → engine-branched embed kickoff (`maybeKickoffEmbed`: Postgres `submitEmbedBackfill`, PGLite `runEmbedCore` inline — NEVER `submitEmbedBackfill`, which refuses `no_worker_surface`). `config-keys.ts`: the `connectors.` key builders (sync progress keyed by `(provider, source)`; `auth_error_at` stays per provider because it describes the shared credential), `readConnectorState`/`writeConnectorState` (a legacy per-provider `watermark_iso`/`last_sync_at` is honored only for the scheduled `connectors.source_id` source until that source writes its own key, which retires it), and the pure `isConnectorSyncStale(last, now, floor)` dispatch gate. Status, doctor and the autopilot gate read the scheduled source's state. `oauth-pkce.ts`: dependency-free S256 PKCE loopback (`Bun.serve`, timing-safe state) — best-effort `--try-oauth` only. Surfaces: the `connectors_status`/`connector_sync` ops (`src/core/ops/connectors.ts`, both `localOnly`), the `gbrain connectors` command family (`src/commands/connectors/` peeled dir), the `connector-sync` minion handler (`src/core/minions/handlers/connector-sync.ts`, single-flight lock), the autopilot `maybeDispatchConnectorSyncs` gate, and the `connectors` doctor check. Pinned by `test/connectors-*.test.ts` + `test/e2e/connectors-sync-checkpoints-pglite.test.ts` (per-source watermark, `--limit` progress, quarantine, retitle) + `test/e2e/connectors-sync-pglite.test.ts` (full pipeline against a `Bun.serve` fixture backend, keyless) + `test/e2e/connector-sync-handler-pglite.test.ts` + `test/e2e/doctor-connectors-pglite.test.ts`.- `src/core/context/` — Retrieval Reflex (Layer 1). `entity-salience.ts`: pure, zero-LLM, precision-biased `extractCandidates(text)` (capitalized runs + `@handles`, STOPWORDS + soft COMMON_WORDS + sentence-start guard, deterministic, capped; a lowercase weak pass additionally emits `weak: true` candidates — lowercase words ≥3 chars on a separate `MAX_WEAK_CANDIDATES=32` budget that never evicts strong candidates — which downstream may resolve through the alias arm ONLY) + `extractCandidatesFromWindow(turns)` (merges per-turn extraction across the last N turns by normalizeAlias form with occurrence/newest-turn/user-mention metadata; salience-ordered — recency > frequency > user-role — so the cap drops stale assistant chatter first). `retrieval-reflex.ts`: `resolveEntitiesToPointers(engine, sourceId, candidates, opts)` — alias arm (`resolveAliases`, caught per-arm for pre-v110 brains) + exact title/slug-suffix arm (real slugs are namespaced `people/x` but `slugify` drops the prefix) + two lexical identity arms behind `opts.lexicalArms` (kill switch: config `retrieval_reflex_lexical_arms` / env `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`, default on): weak lowercase candidates probe the ALIAS arm ONLY (never title/slug-suffix, where ordinary lowercase words would fabricate pointers) and require GLOBAL uniqueness across all sources in play; the surname arm resolves a strong single capitalized token ≥3 chars via a `lower(title) LIKE '% <token>'` predicate on the same query, with exact-arm precedence and ambiguity counted over ALL person rows carrying the surname — ambiguity in either arm injects nothing; pointers carry `source_id`/`arm`/`confidence`/`matchedNorm` (`ARM_CONFIDENCE` alias 0.9 / title 0.8 / title-surname 0.72 (deliberately above the volunteer layer's 0.70 gate, below title) / slug-suffix 0.6 lives next to the arm definitions; arm-2 provenance classified in JS since the combined OR can't report which predicate matched); opts: `sourceIds?` federated scope (alias arm loops per source, arm 2 uses `source_id = ANY`), `suppression?` ('slug-and-title' default; 'slug-only' REQUIRED under windowing — the title rule would suppress every entity merely mentioned in a prior window turn), ambient-channel event logging is DELIVERY-side, not in-resolver — `logDeliveredReflexPointers(engine, pointers)` fires only once a block is actually handed to the consumer (serve's resolve-IPC `onDelivered` hook post-write; `buildReflexAddition` post-timeout on the direct rung), so abandoned/timed-out blocks never pollute the volunteered-vs-used stats; its event write is registered synchronously before return so the CLI background-work drain cannot miss it; synopsis runs through `stripTakesFence`/`stripFactsFence` (the same privacy boundary `get_page` applies) so private facts never reach the prompt; `visibility: private` (and derived-private) pages never resolve on any arm unless the caller passes `excludePrivate: false` (default true, the remote-search predicate `privatePagesFilterFragment`; only `volunteer_context` widens, via `resolveExcludePrivatePages` for a trusted local caller — gbrain-evals N8-1/N8-2, pinned by `test/reflex-private-visibility.test.ts`); capped at `MAX_POINTERS`. `reflex.ts`: the orchestrator + engine-aware resolver ladder (host `resolveEntities` → PGLite serve IPC → Postgres cached process-singleton → disabled), zero-candidate fast path, fail-open + timeout, heartbeat write for the doctor check, `reflexEnabled(cfg)` (file/env gate, default ON; DB-plane does NOT gate — `assemble()` is sync); windowed extraction when `windowTurns` present and `retrieval_reflex_window_turns` (default 4; 1 = single-turn behavior) > 1 — switches suppression to slug-only; accept-side reflex-channel logging fires after the per-turn timeout admits the block (direct-Postgres rung only — IPC logs server-side at delivery; host-injected resolvers are a documented gap). `resolve-ipc.ts`: local unix-socket resolve protocol (client + server) so PGLite resolves through the single connection `gbrain serve` holds (a second opener would hit the exclusive lock; a subprocess would force-steal it past the 5-min staleness window and crash). Wired into both serve transports via `src/mcp/resolve-ipc-binding.ts` (engine-uniform; socket + secret keyed off `hash12(database_url)` under `~/.gbrain/run`, cleaned up on shutdown). Doctor surface: `retrieval_reflex_health` in `src/commands/doctor/checks/verbs-reflex.ts` (reads the heartbeat for truthful runtime status; categorized in `doctor-categories.ts`) + `volunteer_channels` (engine-aware sibling: groups `context_volunteer_events` by channel over 7 days so operators see which push channels — reflex/op/watch/claude-code/codex — actually fire; info-only; the LOCAL doctor runs it brain-wide while the remote report path threads the caller's source scope, so a source-bound token never sees other sources' activity counts/timestamps; counts are reconciled against the hook heartbeat over the same 7-day window — a mostly-degraded week gets a CAUTION note, since a server-side delivery count isn't proof of injection; quiet-channel guidance is engine-aware — Postgres brains are told the hook lane is quiet by design rather than to chase registration — and walks both quiet classes (installed-but-unregistered vs registered-but-quiet; the check can't inspect registration itself); pre-v117 tolerant, and transient DB errors are reported as such, never as an old schema; pinned by `test/doctor-volunteer-channels.test.ts`). Config: `retrieval_reflex` + `retrieval_reflex_max_pointers` + `retrieval_reflex_window_turns` + `retrieval_reflex_lexical_arms` in `src/core/config.ts` (env `GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS`, `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`). `volunteer.ts`: `parseWindow` (lenient `user:`/`assistant:` prefixes, unprefixed → one user turn), `volunteerContext` (extract → resolve → +0.05 multi-turn/newest-turn boost → `min_confidence` 0.7 gate → cap 3/5; deterministic rationale strings, never raw conversation text; slug-only suppression), `volunteerUsageStats` (per-arm/channel precision from the `pages.last_retrieved_at > volunteered_at` join — APPROXIMATE: the 5-min last-retrieved throttle causes false negatives, unrelated reads false positives). `volunteer-events.ts`: `insertVolunteerEvents` (ONE multi-row parameterized INSERT), `logVolunteerEventsFireAndForget` + bounded drain registered as the `volunteer-events` background-work sink (order 4), `purgeStaleVolunteerEvents` (90-day GC, called from the dream cycle's purge phase). Policy layer ships as the `retrieval-reflex` recipe (`recipes/retrieval-reflex/`). Pinned by `test/context/entity-salience.test.ts`, `test/retrieval-reflex.test.ts`, `test/retrieval-reflex-pre-v110.test.ts`, `test/context/resolve-ipc.test.ts`, `test/doctor-retrieval-reflex.test.ts`, `test/volunteer-context.test.ts`, `test/e2e/volunteer-context-postgres.test.ts`. Checkpoint-compaction modules in this dir: `corpus-segments.ts` — engine-free content-addressed compaction segments (`<session>.seg-<hash24>.txt`, idempotent by name; parsers accept 12–64 hex), the hash-keyed per-session ledger (atomic tmp+rename, fail-open, entry order = the only ordinal), `sliceBoundaryWindow`/`splitByBoundaries`, the redacted `renderSegmentText` (a segment is NEVER written unscanned — unlike the session-end full write, which degrades-and-writes), exact-set `coverageComplete`/`decideCorpusMode` (count equality can be fooled by a duplicated boundary), the compact-time `bankCompactSegment` step (per-step deadline degrades, segment-then-ledger crash order), the openclaw tail boundary reader (`readOpenclawBoundaryTail`, delegates mapping to the adapter's exported `mapOpenclawLine`; also returns turn-stamped `toolCalls`/`toolCallTurnIndexes` for the Memorable receipt — name-only v1, `input: null` by design until an observation run characterizes OpenClaw's args field), and orphan-sidecar/aged-ledger GC — pinned by `test/corpus-segments.test.ts`. `checkpoint-harvest.ts` — the serve-side prompt harvest of a segment: bounded FIFO (cap 8, 60s abort), sweep-shared claim fencing, capability-then-kill-switch gates, `signal.aborted` POST-check (the pipeline returns partials on abort; an aborted run writes nothing and stays retryable), receipt sidecar before idempotent manifest publish (source-scoped `getPage` verification — a link that resolves to nothing is never banked), `.ingested` last, explicit `shutdownCheckpointHarvest()` called by serve BEFORE `engine.disconnect()` (the background-work drain is CLI-exit-only by contract) — pinned by `test/checkpoint-harvest.serial.test.ts`. `hook-heartbeat.ts` — the hooks telemetry JSONL extracted from hook.ts (hook.ts re-exports; serve-side writers never import the command module); allowlist carries the checkpoint `segment`/`inserted`/`duplicate`/`links` count-only fields. `session-state.ts` also carries the v132 `checkpoint_manifest` helpers (`getCheckpointManifest`/`appendCheckpointManifest`: newest-first, dedup-by-slug, cap 20, seg-hash completion key, fail-open on pre-v132 schema) — pinned by `test/checkpoint-manifest.test.ts`. `sensitivity-scan.ts` + `compile-view.ts` — the compile-context stack: composed detector (secret-scan + ordered `PII_PATTERNS` + path/blocklist families + operator pattern file; uniform `.gbrain-scan-allow` fingerprint escape hatch; CONTENT hits drop an entry, CONFIG/loader failures THROW so the caller aborts without writing) and the deterministic compiled-view builder (recency decay anchored to the newest candidate `updated_at`, never wall-clock; total-order (score desc, slug asc); source-scoped listPages/getPage reads that skip op-layer write-backs and pass `excludePrivate: true` on every arm, so private pages never reach the compiled file; whole-file `packToBudget` math that never passes a <=0 budget) — pinned by `test/sensitivity-scan.test.ts` + `test/compile-view.test.ts` + `test/e2e/compile-context-pglite.test.ts`; the CLI shell is `src/commands/compile-context.ts` (targets claude-code|codex|openclaw, AGENTS.md managed-marker splice that throws on damaged markers, atomic writes, `--check` recompile-and-compare exit codes; the guide is `docs/guides/checkpoint-compaction.md`). It also owns the whole Memorable seam's engine-free plumbing: the session-receipt JSONL (`session-receipts.jsonl`, `appendSessionReceipt` — dedup by post-redaction `content_hash` so a resumed session neither duplicates its receipt nor re-fires the relay; tail-rewrite compaction triggered by the 32 MB byte ceiling alone — the read fires exactly when the pass will act, with the 2000-line budget enforced inside the pass — and a `skipCompaction` seam the openclaw compact() lane sets unconditionally: the hook lane is the ONE receipts compactor, so two processes can never race the read-filter-rename rewrite); ONE bounded adaptive `readJsonlTail` reader shared by `lastReceiptMatches`, `lastRelayResult` and `readSessionReceiptsTail` (a receipt line can exceed the 1 MB window — the window doubles rather than reading "empty"); `maybeTrimRelayResults` (BOTH capture lanes trim the child-appended `memorable-relay.jsonl` — an openclaw-only host has no hook lane, and converging newest-keeping trims make concurrent trims safe: mtime-stale preferred, hard 8 MB force backstop, line-boundary cut keeping the newest lines — the child appends open-by-path, so the residual loss window is one in-flight write); the CONSENT STAMP (`memorable-consent.json`, 0600, written ONLY by config-set's disclosure flow — deliberately outside config.json, which the external CLI full-file-rewrites; scope-bound to the disclosure sha256 + `MEMORABLE_CAPTURE_HARNESSES`, so widening the capture surface invalidates old stamps); `memorableGateAllowed(cfg)` ({allowed, reason: kill_switch|disabled|disclosure_missing} — one reason vocabulary for hook, context-engine and doctor); `memorableConsentEvidence()` (the CLI-side opt-in read fail-closed from ~/.memorable/config.json, dated provisional spec note, GBRAIN_MEMORABLE_CONFIG test seam); `redactedToolCallsJson` (the security-load-bearing span-filter + highEntropy redaction, ONE implementation for both capture lanes; string LEAVES are redacted raw before serialization — scanning the serialized JSON would let quoted secrets through via \" escaping — with a post-serialization re-scan as belt-and-braces); `recordAndRelayReceipt` (per-receipt harness scope-binding first — a harness outside `MEMORABLE_CAPTURE_HARNESSES` is refused with `memorable_harness_undisclosed` → receipt → prior-run outcome surfacing with the child's reason clamped via the shared `clampRelayCause` (32 chars, so the 16-char prefix keeps composites inside the 48-char reason bound) and appended LAST → consent evidence → `resolveMemorableBin` → detached spawn; never throws; `spawnFn` test seam); and `priorRelayFailure`, which surfaces the PREVIOUS relay run's self-reported exit status so a relay that records nothing is never reported healthy. `resolveMemorableBin` does the pre-spawn PATH/`MEMORABLE_BIN` resolution so a missing CLI is a named heartbeat reason rather than a silent async ENOENT.+- `src/core/context/hook-heartbeat.ts` — the hooks telemetry plane under `<gbrain home>/integrations/hooks/` (`heartbeat.jsonl`, `status.json`, session receipts, the memorable relay log; directories 0700, appends 0600). Entries hold counters, durations and codes only: `HEARTBEAT_ALLOWED_KEYS` is the full key allowlist CI greps the fixture against, and includes `pattern` (scanner pattern name), `fingerprint` (`sha256:<16 hex>`) and `hint` (fixed text) for refusals. `relayRefusalHeartbeat(hit)` builds the line `context-engine.ts` writes when its high-entropy re-scan refuses a memorable relay (`event: relay`, `outcome: degraded`, `reason: secret_scan_refused`); the receipt and relay are skipped for that compaction window and the checkpoint is kept. `memorableGateAllowed` gates the relay lane; span redaction runs `redactFindings` with `highEntropy: true`. Tests: `test/context-engine-checkpoint.serial.test.ts`.- `src/core/context/ipc-path.ts` — engine-free local socket discovery and private Unix fallback when the complete role-specific address exceeds 103 UTF8 bytes. Hashes the physical parent plus basename under a fixed OS temporary root, verifies ownership/0700 directory/0600 client socket without following fallback symlinks, and retains a native binding claim through actual server close. Existing Unix socket accessibility is rechecked even when a runtime reports ENOENT; permission/resource probe failures never authorize stale takeover; Windows named pipes retain a native Global mutex through actual close; `windows-ipc.ts` normalizes namespace prefixes while native Windows Unicode casing defines the mutex identity. `test/local-ipc-path.test.ts` covers concurrent real processes, SIGKILL recovery, active-connection shutdown, aliases and unsafe paths. The published CLI smoke also uses a long Unicode datastore path.diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex ec52e4023c..252fb91347 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -43,6 +43,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction; callers lock sources before authority/request/fact rows. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `rename-alias.ts` records `slug_aliases(old -> new)` inside both engines' `updateSlug` transaction, repoints aliases that named the old slug and drops one spelled like the new slug; `moveSlugBindings` moves the page's facts (`entity_slug`, `source_markdown_slug`) and `page_aliases` in the same transaction, letting a purged page's leftovers at the new slug yield (`test/rename-slug-alias.test.ts`); `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: missing revision is create-only, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.- `src/core/page-state/projections.ts` — captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts`, `page-projection-vector-preservation.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. A preserving rebuild keeps a vector only when its `content_chunks.embedding_input_hash` (`src/core/embedding-input-hash.ts`) equals one recomputed from the current page, or, with no recorded hash, when the page is non-contextual and the legacy model/text-hash checks pass; a contextual chunk without provenance is nulled once. `installPageEmbeddings` records the hash in the vector's UPDATE (the plain re-embed tier by default, or the caller's `built` tier and corpus generation), and `stampEmbeddingInputs` does the same for full imports. `resealSafeChunks` re-seals a page below the safe-chunk fence from its unchanged body with no canonical write; `projectionBelowSafeFence` is its predicate. Tests add `projection-embedding-input-hash.test.ts` and `safe-chunk-reseal.test.ts`. It replaces outgoing code edges without deleting incoming edges to retained chunks and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics. `rebuildPendingPageProjections(engine, limit, { deadlineMs, now, notAfter, retryCooldown, onFailure })` (#5401) checks an injectable clock between pages, bounds a run to rows queued at or before its start (`notAfter`, cast from text in SQL so microseconds survive the driver), applies the 30 s `rebuild_failed` cooldown for the resident, and treats a lock or snapshot error as that page's failure instead of aborting the batch; `projectionBacklog` returns counts only (pending, failed, oldest age) for the drain command and the resident's `projection_status` IPC reply.+- `src/core/page-state/credential-reseal.ts` + `src/core/schema-migrations/v189-pages-credential-projection-pending.ts` + `src/commands/doctor/checks/credential-projection.ts` — the targeted re-chunk of pages indexed before the credential-safe projection. Schema migration v187 (on the first connect after upgrade) sets `text_projection_revision = NULL` on every live markdown/code page whose `compiled_truth` or `timeline` matches `-----(BEGIN|END) [A-Z ]*PRIVATE KEY-----` and upserts a `page_projection_jobs` row (reason `credential_projection`), so the current-text-projection seal withholds their old chunks from every retrieval path, local and remote (code-walk `hydrateChunks` in `search/two-pass.ts` applies the same filter). The marker literal is frozen as shipped. `credentialProjectionPending(engine, sourceIds?)` counts pending pages in active sources as `rebuildable` and `kept` (code pages with no `frontmatter.file` or `source_path`, which wait for their importer). `resealCredentialProjections` re-seals each rebuildable page from its unchanged body through `resealSafeChunks` (the `repair safe-chunks` installer), one page per transaction, with no page write, journal admission or provider call; vectors of unchanged chunk text are kept and re-chunked key chunks wait for `gbrain embed --stale`; a revision conflict counts as superseded, a failure prints the retry command and leaves the page withheld. The doctor check `credential_projection_pending` (a `WAVE_CHECKS` entry, `resolution: 'operator'`, brain category) reports `pages_pending` and `kept_pages` and warns while either is non-zero, naming `gbrain apply-migrations --yes --no-autopilot-install` (no provider calls), then `gbrain embed --stale`, and the re-import for kept code pages; a read error is `warn` with unknown health.Embedding-only publication also requires a live, unarchived source and nondeleted page under the same source/page row locks. A prepared vector cannot bypass a later archive, model change or withdrawal. `test/e2e/migration-wave-prepared-withdrawal.test.ts` exercises both publication orders and exact unchanged-vector refusal on both engines.diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex bb4bbd9599..1fcd86c18a 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -12,6 +12,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/brain-score-recommendations.ts` — pure data layer consumed by both `gbrain doctor --remediation-plan` / `--remediate` and `gbrain features`. Extraction-watermark staleness produces source-scoped `extract.stale` against database pages, including DB-only pages without a checkout; it does not imply a filesystem sync or block embedding on one. `RecommendationContext.staleExtractionBlocked` (probed by `staleExtractionBlocked()` in `remediation/context.ts`, shared with autopilot) withholds `extract.stale` and classifies `links_extraction_lag` as blocked while the remediated source, or any source with stale pages in an all-source sweep, cannot load its active schema pack, so no dispatch fails every cycle. `computeRecommendations(checks, opts)` returns `Remediation[]` with stable `id`, content-hash `idempotency_key`, `severity`, `est_seconds`, `est_usd_cost`, `depends_on` (references stable ids, not check names — so plan order is reproducible). `classifyChecks(report)` triages every doctor check three-state into `remediable | human_only | blocked` (`human_only` covers RLS warnings and other human-judgment gates; `blocked` covers dependency chains where a parent check failed). `maxReachableScore(checks)` computes the ceiling for empty/under-configured brains (no entity pages → graph_coverage caps at 70; no embedding key → embedding_coverage caps at 60). Cost estimates pull from `anthropic-pricing.ts` (synthesize/patterns/consolidate) and `embedding-pricing.ts` (embed jobs). Pinned by `test/brain-score-recommendations.test.ts` (~27 cases incl. determinism, content-hash idempotency, DB-backed checkpoint provenance, three-state triage).- `src/core/cjk.ts` — Single source of truth for CJK detection. Exports `CJK_RANGES_REGEX`, `CJK_SLUG_CHARS` (character-class fragment for embedding inside other regexes), `SLUG_WORD_CHARS` + `PAGE_SLUG_SEG` (the shared slug-grammar fragments) and `SLUG_VARIATION_SELECTORS_RE` (the Mn-invisible emoji-VS16 / ideographic-IVS strip that BOTH `sync.ts:slugifySegment` and its twin `link-extraction.ts:normalizeBasename` apply, so the two grammars cannot drift on selectors), `CJK_SENTENCE_DELIMITERS` (`。!?`), `CJK_CLAUSE_DELIMITERS` (`;:,、`), `CJK_DENSITY_THRESHOLD = 0.30`, `hasCJK(s)`, `isCJKDominant(s)` (the ONE density test: CJK chars ≥ 30% of non-whitespace chars), `countCJKAwareWords(s)` (routes through `isCJKDominant` — English docs with one Japanese term stay whitespace-tokenized; Chinese-dominant docs get char-counted), and `escapeLikePattern(s)` (escapes `%`, `_`, `\\` for `ILIKE ... ESCAPE '\\'`). BMP-only ranges (Han / Hiragana / Katakana / Hangul Syllables). Consumers: `expansion.ts`, `sync.ts:slugifySegment`, `operations.ts:validatePageSlug + validateFilename`, `chunkers/recursive.ts:countWords + DELIMITERS + extractTrailingContext` (the overlap extractor branches on `isCJKDominant` so it counts the same unit `countWords` does), `pglite-engine.ts:searchKeyword + searchKeywordChunks`.+- `src/core/credential-projection.ts` — `credentialSafeProjection(text)`: the retrieval text of a canonical body. Every private-key span from `privateKeySpans` (`secret-scan.ts`: complete keys and keys cut off at their `BEGIN` or `END` line) becomes `PRIVATE_KEY_PROJECTION_TOKEN` (`<REDACTED:private_key_pem>`) followed by as many newlines as the span held, so line offsets and chunk anchors stay stable. A cheap `PRIVATE KEY-----` substring gate returns the text unchanged otherwise; idempotent (the token holds no marker). Applied after `sanitizeRemoteBody` by the recursive chunker (`chunkers/recursive.ts`, markdown and embed paths), fenced-code extraction (`markdown-chunks.ts`), `prepareCodeChunks` (`code-chunks.ts`) and evidence delivery's `pageEvidenceText` (`window`/`section`/`page` units), so no chunk, embedding input or delivered evidence carries key material, including a mid-key chunk with neither fence. The stored body and the raw page reads are unchanged. Not covered: image OCR chunks, and key material with no `BEGIN`/`END` marker anywhere on the page. Existing pages are re-chunked by `page-state/credential-reseal.ts`. Chunker and safe-fence versions are unchanged (4).- `src/core/code-graph-readiness.ts` — shared seven-state code readiness: not_built, no_symbols, indexing, ready, out_of_scope, projection_pending, unknown. Checks scoped current-projection readiness before accepting nonempty results as ready; empty probes apply the same live/current policy as code reads. The brain-wide out_of_scope comparison remains trusted-local-only. Edge readiness uses the resolver backfill watermark. Code definitions/references, callers/callees and recursive operations expose the result; code_blast/code_flow bypass traversal caching until cached data can be revalidated. Recursive disambiguation, language probes and concrete edge endpoints also require current live pages. All six agent-facing code tools remain suspended.@@ -48,7 +49,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/operations-descriptions.ts` — Constants module for tool descriptions. Pinned via `test/operations-descriptions.test.ts`. Houses `GET_RECENT_SALIENCE_DESCRIPTION`, `FIND_ANOMALIES_DESCRIPTION`, `GET_RECENT_TRANSCRIPTS_DESCRIPTION` plus `LIST_PAGES_DESCRIPTION`, `QUERY_DESCRIPTION`, `SEARCH_DESCRIPTION`. Stable surface for the Tier-2 LLM routing eval — keeping them here keeps the test from binding to whatever is in `operations.ts` at test-run time.-- `src/core/operations.ts` — Contract-first operation contract, served through a ~300-line assembly façade: the op definitions live in the domain modules under `src/core/ops/` (next entry) and are spread into the single exported `operations` array here; the shared contract types (`src/core/ops/contract.ts`) and the security/scope layer (`src/core/ops/context.ts`) are re-exported through this file, so every import path below resolves through the façade unchanged. The rest of this entry describes the surface as consumers see it. Fresh same-source graph mutations (`add_link`, `add_timeline_entry`) preflight each endpoint against the scalar write source via `requireWritablePage` (`ops/context.ts`); `add_timeline_entry` resolves an authorized stored request before that fresh-write preflight so exact replay retains its outcome after page purge or recreation: a page readable only from another granted source returns endpoint-specific `permission_denied` naming the boundary, pages outside the caller's `get_page` visibility scope stay `page_not_found` (a soft-deleted foreign page is indistinguishable from absence), and a mutation-time engine miss — the typed `PageMissingError` from `src/core/engine-errors.ts`, thrown by both engines' single-statement endpoint resolution — is reclassified into the same envelope by `instanceof`, never message matching. Exports upload validators `validateUploadPath`, `validatePageSlug`, `validateFilename`, plus `matchesSlugAllowList(slug, prefixes)` (glob matcher: `<prefix>/*` matches recursive children; bare `<prefix>` matches exact only). `OperationContext.remote` is a REQUIRED field flagging untrusted callers; `OperationContext.allowedSlugPrefixes` is the trusted-workspace allow-list set by the dream cycle; `OperationContext.auth?: AuthInfo` is threaded through HTTP dispatch for scope enforcement in `serve-http.ts` before the op runs. OAuth `whoami` exposes the authenticated `AuthInfo.sourceId` and `AuthInfo.allowedSources` grants as `source_id` and `federated_read`; absent grants serialize fail-closed as `null` and `[]`, while local, legacy, and stdio response shapes stay unchanged. `enforceSubagentSlugFence(ctx, slug, opName)` is the shared fail-closed subagent write fence: when `viaSubagent` and `allowedSlugPrefixes` is set, the slug must match the allow-list; else the legacy `wiki/agents/<id>/...` namespace check applies. Both `put_page` and `add_timeline_entry` (subagent-allowlisted) route through it. Auto-link/timeline hooks are skipped for remote-owned subagents even with explicit prefixes; only local subagents qualify as trusted workspaces. `enforceClientSlugFence(ctx, slug, opName)` is the OAuth-client write fence: when `ctx.auth.boundSlugPrefixes` is present (threaded from `oauth_clients.bound_slug_prefixes` at token-verification time), every direct slug-mutating write op — `put_page`, `delete_page`, `restore_page`, `add_tag`, `remove_tag`, `add_link`/`remove_link` (`from` endpoint only; linking TO a readable page is a reference), `add_timeline_entry`, `revert_version`, `put_raw_data` — rejects out-of-prefix slugs with `permission_denied`, BEFORE each op's dry-run short-circuit. Direct writes use the shared boundary-aware prefix rules; empty-array binding is deny-all (fail-closed); no auth / no binding = no fence. The match rule itself lives in the exported `slugUnderBoundPrefixes(prefixes, slug)` so non-op write surfaces reuse it verbatim. It is BOUNDARY-AWARE (a prefix matches whole segments, so `emp-alice` does not admit `emp-alice-2/…`), lowercases both sides (stored slugs are lowercased by `validateSlug`, so comparing the caller's raw string would let a mixed-case slug commit and only then trip the resolved-slug re-check), accepts BOTH the trailing-slash and the `<prefix>/*` glob spelling via `normalizeSlugPrefix` (direct and delegated fences share normalization while storing independently reviewed spans), and ignores empty-string prefixes. `assertValidSlugPrefixes` (`oauth-provider.ts`) rejects empty, whitespace-bearing, non-lowercase, and boundary-less entries at registration and rescope. `submit_agent` validates tools and namespaces against the independently stored `bound_tools`, `delegated_slug_prefixes`, and `delegated_namespace` grants. It normalizes accepted prefixes for `matchesSlugAllowList` and rejects explicit empty remote tool or prefix overrides. Workers interpret explicit empty tool lists as no tools, with defaults reserved for absent trusted-local bindings. `put_page` deduplication may resolve another slug by content hash or `frontmatter.id`, but returns an authorized read-only `duplicate` outcome. The original target's revision never authorizes publication to that other page. Preparation and guarded validation recheck the duplicate's current authority, readability, concrete page identity and revision; neither its canonical fields nor its file are written. OAuth and delegated subagent fences still apply, and denials do not name an inaccessible duplicate. Pinned by `test/put-page-dedup-fence.test.ts`. `CLIENT_FENCED_WRITE_OPS` + `enforceBoundClientOpAllowList(auth, op)` are the fail-closed companion, applied once in `src/mcp/dispatch.ts` (the choke point both MCP transports share): a slug-bound client calling ANY `write`/`admin` op not on the allow-list gets `permission_denied`. This covers the ops that write by a key other than a slug and therefore cannot be fenced — `extract_entities`/`extract_facts` (mutate `people/*`, `companies/*`), `forget_fact` (numeric fact id, crosses sources), `ontology_propose` — and makes a write op added later denied-by-default instead of silently unfenced. `think` is on the allow-list because remote callers cannot persist from it. Pinned by `test/client-slug-fence.test.ts` and over-the-wire by `test/qm-provisioning.test.ts`. Every `Operation` carries `scope?: 'read' | 'write' | 'admin'` + `localOnly?: boolean`; `think` is read-scoped for OAuth/MCP because remote callers have `save`/`take` forced off before persistence, while local CLI can still persist via `remote:false`; `sync_brain`, `file_upload`, `file_list`, `file_url` are `admin + localOnly` (rejected over HTTP). Four trust-boundary call sites (`put_page` allowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) use FAIL-CLOSED semantics: `ctx.remote === false` for trusted-only sites, `ctx.remote !== false` for "untrust unless explicit-false" — anything not strictly `false` is treated as remote (so a read+write OAuth token over HTTP MCP cannot submit `shell` jobs). `sourceScopeOpts(ctx)` encodes the source-scoped read precedence ladder — federated array (`ctx.auth.allowedSources`) wins over scalar (`ctx.sourceId`/`ctx.auth.sourceId`) over nothing; every read-side op handler routes through it so a source-bound OAuth client can't see neighboring sources via `search`/`query`/`list_pages`/`get_page`/`find_experts`/query's image path, plus the by-slug reads `get_tags`/`get_links`/`get_backlinks`/`get_timeline`/`get_chunks` (chunks follow the same ladder as `get_page`, so a federated grant that can open a page can read its chunks — and the chunk payload never carries embedding vectors) (and `get_page`'s tag fetch, which resolves against the concrete page's own `source_id`). `get_tags` resolves `readPolicyOpts`, so an untrusted caller gets no tags for a `visibility: private` page (unless the operator's private-pages opt-out is on) or a soft-deleted page. `assertExplicitSourceLive(ctx, sourceIdParam)` is the async companion for the ops that accept a per-call `source_id` (`get_page`, `list_pages`, `search`, `query`): called right after `federatedSearchScope` (so the grant check has already run and it can only name a granted source), an explicit id with no live unarchived `sources` row throws `unknown_source` instead of silently scoping the read to an empty source — the CLI's `--source` existence rule applied to the op path; `__all__` and an omitted param skip it. `linkReadScopeOpts(ctx, scope?)` is the link-read sibling for `get_links`/`get_backlinks`/`traverse_graph` (`scope` defaults to `sourceScopeOpts(ctx)`; the link ops pass their resolved per-call `federatedSearchScope`): a link row references three pages (from/to/origin), and the engine's federated (`sourceIds[]`) branch scopes ALL THREE while its scalar (`sourceId`) branch scopes only the near endpoint (by design — trusted internal callers like `reconcileLinks` and back-link validators call the engine with a scalar scope and need the cross-source view). For an UNTRUSTED remote caller (`ctx.remote !== false`) carrying only a scalar scope it promotes that scope to a single-element `sourceIds:[id]`, routing them through the all-endpoint branch so a far/origin slug from outside the grant isn't disclosed; a federated array passes through unchanged and trusted local CLI (`ctx.remote === false`) keeps the scalar cross-source view. `thinkSourceScopeOpts(ctx)` maps the same precedence ladder onto `runThink`'s public options (`allowedSources`/`sourceId`) so the `think` op's gather and trajectory stages inherit the caller's source grant. `put_page` submits through `submitPageMutation` to the durable journal. Existing-page replacements require `expected_revision` or explicit `force`; omission is create-only. The designated owner publishes under native root and database guards, with recoverable file replacement and a terminal receipt committed with canonical state. Accepted contention returns `write_pending` after the synchronous wait; admission failure does not fabricate a queued receipt. Git and embeddings report separate effect outcomes. Trusted-local `delete_page` with `purge: true` uses the same journal, revision and recovery protocol: artifact-removal failure preserves the prior row, and exact replay retains the original terminal outcome after deletion. Link provenance surface: `add_link` (`gbrain link`/`link-add`) + `remove_link` (`gbrain unlink`/`link-rm`) expose `link_source`/`link_type`; `add_link` rejects the reconciliation-managed built-ins via `MANAGED_LINK_SOURCES` (`markdown`/`frontmatter`/`mentions`/`wikilink-resolved`) and defaults omitted provenance to `'manual'` (the engine's own default stays `'markdown'` for internal callers); `list_link_sources` (`gbrain link-sources`, read) lists provenances via `sourceScopeOpts`. CLI aliases register through `cliHints.aliases` (collision-guarded in `src/cli.ts`).+- `src/core/operations.ts` — Contract-first operation contract, served through a ~300-line assembly façade: the op definitions live in the domain modules under `src/core/ops/` (next entry) and are spread into the single exported `operations` array here; the registration loop replaces each handler with `withOutputRedaction(op)`, so a `'retrieval'` op's output is redacted on every dispatch path (see `src/core/ops/contract.ts`); the shared contract types (`src/core/ops/contract.ts`) and the security/scope layer (`src/core/ops/context.ts`) are re-exported through this file, so every import path below resolves through the façade unchanged. The rest of this entry describes the surface as consumers see it. Fresh same-source graph mutations (`add_link`, `add_timeline_entry`) preflight each endpoint against the scalar write source via `requireWritablePage` (`ops/context.ts`); `add_timeline_entry` resolves an authorized stored request before that fresh-write preflight so exact replay retains its outcome after page purge or recreation: a page readable only from another granted source returns endpoint-specific `permission_denied` naming the boundary, pages outside the caller's `get_page` visibility scope stay `page_not_found` (a soft-deleted foreign page is indistinguishable from absence), and a mutation-time engine miss — the typed `PageMissingError` from `src/core/engine-errors.ts`, thrown by both engines' single-statement endpoint resolution — is reclassified into the same envelope by `instanceof`, never message matching. Exports upload validators `validateUploadPath`, `validatePageSlug`, `validateFilename`, plus `matchesSlugAllowList(slug, prefixes)` (glob matcher: `<prefix>/*` matches recursive children; bare `<prefix>` matches exact only). `OperationContext.remote` is a REQUIRED field flagging untrusted callers; `OperationContext.allowedSlugPrefixes` is the trusted-workspace allow-list set by the dream cycle; `OperationContext.auth?: AuthInfo` is threaded through HTTP dispatch for scope enforcement in `serve-http.ts` before the op runs. OAuth `whoami` exposes the authenticated `AuthInfo.sourceId` and `AuthInfo.allowedSources` grants as `source_id` and `federated_read`; absent grants serialize fail-closed as `null` and `[]`, while local, legacy, and stdio response shapes stay unchanged. `enforceSubagentSlugFence(ctx, slug, opName)` is the shared fail-closed subagent write fence: when `viaSubagent` and `allowedSlugPrefixes` is set, the slug must match the allow-list; else the legacy `wiki/agents/<id>/...` namespace check applies. Both `put_page` and `add_timeline_entry` (subagent-allowlisted) route through it. Auto-link/timeline hooks are skipped for remote-owned subagents even with explicit prefixes; only local subagents qualify as trusted workspaces. `enforceClientSlugFence(ctx, slug, opName)` is the OAuth-client write fence: when `ctx.auth.boundSlugPrefixes` is present (threaded from `oauth_clients.bound_slug_prefixes` at token-verification time), every direct slug-mutating write op — `put_page`, `delete_page`, `restore_page`, `add_tag`, `remove_tag`, `add_link`/`remove_link` (`from` endpoint only; linking TO a readable page is a reference), `add_timeline_entry`, `revert_version`, `put_raw_data` — rejects out-of-prefix slugs with `permission_denied`, BEFORE each op's dry-run short-circuit. Direct writes use the shared boundary-aware prefix rules; empty-array binding is deny-all (fail-closed); no auth / no binding = no fence. The match rule itself lives in the exported `slugUnderBoundPrefixes(prefixes, slug)` so non-op write surfaces reuse it verbatim. It is BOUNDARY-AWARE (a prefix matches whole segments, so `emp-alice` does not admit `emp-alice-2/…`), lowercases both sides (stored slugs are lowercased by `validateSlug`, so comparing the caller's raw string would let a mixed-case slug commit and only then trip the resolved-slug re-check), accepts BOTH the trailing-slash and the `<prefix>/*` glob spelling via `normalizeSlugPrefix` (direct and delegated fences share normalization while storing independently reviewed spans), and ignores empty-string prefixes. `assertValidSlugPrefixes` (`oauth-provider.ts`) rejects empty, whitespace-bearing, non-lowercase, and boundary-less entries at registration and rescope. `submit_agent` validates tools and namespaces against the independently stored `bound_tools`, `delegated_slug_prefixes`, and `delegated_namespace` grants. It normalizes accepted prefixes for `matchesSlugAllowList` and rejects explicit empty remote tool or prefix overrides. Workers interpret explicit empty tool lists as no tools, with defaults reserved for absent trusted-local bindings. `put_page` deduplication may resolve another slug by content hash or `frontmatter.id`, but returns an authorized read-only `duplicate` outcome. The original target's revision never authorizes publication to that other page. Preparation and guarded validation recheck the duplicate's current authority, readability, concrete page identity and revision; neither its canonical fields nor its file are written. OAuth and delegated subagent fences still apply, and denials do not name an inaccessible duplicate. Pinned by `test/put-page-dedup-fence.test.ts`. `CLIENT_FENCED_WRITE_OPS` + `enforceBoundClientOpAllowList(auth, op)` are the fail-closed companion, applied once in `src/mcp/dispatch.ts` (the choke point both MCP transports share): a slug-bound client calling ANY `write`/`admin` op not on the allow-list gets `permission_denied`. This covers the ops that write by a key other than a slug and therefore cannot be fenced — `extract_entities`/`extract_facts` (mutate `people/*`, `companies/*`), `forget_fact` (numeric fact id, crosses sources), `ontology_propose` — and makes a write op added later denied-by-default instead of silently unfenced. `think` is on the allow-list because remote callers cannot persist from it. Pinned by `test/client-slug-fence.test.ts` and over-the-wire by `test/qm-provisioning.test.ts`. Every `Operation` carries `scope?: 'read' | 'write' | 'admin'` + `localOnly?: boolean`; `think` is read-scoped for OAuth/MCP because remote callers have `save`/`take` forced off before persistence, while local CLI can still persist via `remote:false`; `sync_brain`, `file_upload`, `file_list`, `file_url` are `admin + localOnly` (rejected over HTTP). Four trust-boundary call sites (`put_page` allowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) use FAIL-CLOSED semantics: `ctx.remote === false` for trusted-only sites, `ctx.remote !== false` for "untrust unless explicit-false" — anything not strictly `false` is treated as remote (so a read+write OAuth token over HTTP MCP cannot submit `shell` jobs). `sourceScopeOpts(ctx)` encodes the source-scoped read precedence ladder — federated array (`ctx.auth.allowedSources`) wins over scalar (`ctx.sourceId`/`ctx.auth.sourceId`) over nothing; every read-side op handler routes through it so a source-bound OAuth client can't see neighboring sources via `search`/`query`/`list_pages`/`get_page`/`find_experts`/query's image path, plus the by-slug reads `get_tags`/`get_links`/`get_backlinks`/`get_timeline`/`get_chunks` (chunks follow the same ladder as `get_page`, so a federated grant that can open a page can read its chunks — and the chunk payload never carries embedding vectors) (and `get_page`'s tag fetch, which resolves against the concrete page's own `source_id`). `get_tags` resolves `readPolicyOpts`, so an untrusted caller gets no tags for a `visibility: private` page (unless the operator's private-pages opt-out is on) or a soft-deleted page. `assertExplicitSourceLive(ctx, sourceIdParam)` is the async companion for the ops that accept a per-call `source_id` (`get_page`, `list_pages`, `search`, `query`): called right after `federatedSearchScope` (so the grant check has already run and it can only name a granted source), an explicit id with no live unarchived `sources` row throws `unknown_source` instead of silently scoping the read to an empty source — the CLI's `--source` existence rule applied to the op path; `__all__` and an omitted param skip it. `linkReadScopeOpts(ctx, scope?)` is the link-read sibling for `get_links`/`get_backlinks`/`traverse_graph` (`scope` defaults to `sourceScopeOpts(ctx)`; the link ops pass their resolved per-call `federatedSearchScope`): a link row references three pages (from/to/origin), and the engine's federated (`sourceIds[]`) branch scopes ALL THREE while its scalar (`sourceId`) branch scopes only the near endpoint (by design — trusted internal callers like `reconcileLinks` and back-link validators call the engine with a scalar scope and need the cross-source view). For an UNTRUSTED remote caller (`ctx.remote !== false`) carrying only a scalar scope it promotes that scope to a single-element `sourceIds:[id]`, routing them through the all-endpoint branch so a far/origin slug from outside the grant isn't disclosed; a federated array passes through unchanged and trusted local CLI (`ctx.remote === false`) keeps the scalar cross-source view. `thinkSourceScopeOpts(ctx)` maps the same precedence ladder onto `runThink`'s public options (`allowedSources`/`sourceId`) so the `think` op's gather and trajectory stages inherit the caller's source grant. `put_page` submits through `submitPageMutation` to the durable journal. Existing-page replacements require `expected_revision` or explicit `force`; omission is create-only. The designated owner publishes under native root and database guards, with recoverable file replacement and a terminal receipt committed with canonical state. Accepted contention returns `write_pending` after the synchronous wait; admission failure does not fabricate a queued receipt. Git and embeddings report separate effect outcomes. Trusted-local `delete_page` with `purge: true` uses the same journal, revision and recovery protocol: artifact-removal failure preserves the prior row, and exact replay retains the original terminal outcome after deletion. Link provenance surface: `add_link` (`gbrain link`/`link-add`) + `remove_link` (`gbrain unlink`/`link-rm`) expose `link_source`/`link_type`; `add_link` rejects the reconciliation-managed built-ins via `MANAGED_LINK_SOURCES` (`markdown`/`frontmatter`/`mentions`/`wikilink-resolved`) and defaults omitted provenance to `'manual'` (the engine's own default stays `'markdown'` for internal callers); `list_link_sources` (`gbrain link-sources`, read) lists provenances via `sourceScopeOpts`. CLI aliases register through `cliHints.aliases` (collision-guarded in `src/cli.ts`).+- `src/core/ops/contract.ts` — the shared operation types (`Operation`, `OperationContext`, `ParamDef`, `OperationError`). `Operation.outputRedaction: OutputRedactionPolicy` is REQUIRED, so typecheck forces every op to say how its response treats stored text: `'retrieval'` (the whole response passes `redactRetrievalOutput`, uncapped, assignment rule on), `{ retrieval: { localVerbatim: [...] } }` (same, but the named top-level keys stay raw for the trusted local CLI, `ctx.remote === false`; the memory verbs' `facts`), `{ exempt: reason }` (deliberately raw with a one-line reason: page reads `get_page`/`fetch`/`get_chunks`/`get_raw_data`/`get_versions`, skill-catalog files, admin job ops) or `'no_stored_text'` (returns no page, chunk, fact, take or transcript text). `operations.ts` applies the policy at registration (`withOutputRedaction` in `src/core/search/output-redaction.ts`); `test/retrieval-op-redaction.test.ts` sweeps every classified op with a planted secret.- `src/core/pg-access-classify.ts` — Postgres ACCESS-error classifier, the reason/remediation layer of the db-availability loop (detect → `GBRAIN_DB_ACCESS` marker → skills/db-repair → `gbrain db-repair`). Two entry points, one diagnosis type: `classifyPgAccessError(err, ctx?)` for thrown errors (data-driven ordered `REASON_ROWS` table, first match wins — specific rows before general ones) and `diagnoseDbConfig(ctx)` for errorless config-plane reasons (`no_url`, `env_shadowed` — there is no error object at connectEngine's no-config exit or under an env shadow; never fake one). The `PgAccessReason` union (16 reasons) is APPEND-ONLY — a compatibility surface once the bundled skills are in the wild, like progress phase names; consumers switch exhaustively with a `never` sentinel. Invariants: `message`/`remediation` are ALWAYS pre-redacted (safe for transcripts/receipts/issues); every `fix` descriptor is hardcoded or derived from the CURRENT config URL (`deriveSessionPoolerUrl`/`deriveDirectUrl`), never from anything parsed out of error text, and `run_command` argv[0] is always `gbrain`; **remediation copy has exactly ONE home: this module** — db-repair, doctor, and MCP dispatch all render `diagnosis.remediation`, skills reference the command and never duplicate recipe text. TWO-AXIS design note (mirrored in `retry-matcher.ts`'s header — do not "fix" one side to match the other): retry-matcher answers "should I retry?" and deliberately treats `password authentication failed` as retryable (auth race during DNS failover); this module answers "what went wrong?" and reports the same error `auth_failed` + `transient: false` — both correct on their own axis; unknown reasons defer `transient` to `isRetryableConnError`. Also exports `DB_ACCESS_MARKER_PREFIX`/`formatDbAccessMarker` (the single source of the marker literal that skills/db-repair pins in both `description:` and `triggers:`; the action a reader takes is ALWAYS the hardcoded `gbrain db-repair`, never a command parsed from the marker), `isDbAccessFailure` (the ACCESS-class subset fail-open recall arms use to tell "one arm degraded" from "the DB is down"), and Supabase enrichment `{pooler, projectRef, pausedSuspect}` (paused projects aren't a distinct wire error — modeled as a suspicion flag on dns/timeout/tenant reasons). Pinned by `test/pg-access-classify.test.ts`.diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex 9a27ccc6c4..8853a8c8f6 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/core/repair/` — `gbrain repair` core. `core.ts`: `resolveRepairScope` (default every active source; prints brain and source ids), `runRepair` (dry run unless `apply`; each item is one revision-bound `put_page` with a deterministic request id (replayed while pending, a new attempt id after a terminal failure), re-decided against current state just before it is applied; a cursor in `op_checkpoints` keyed by kind + scope resumes an interrupted or `--limit` run and is cleared when a scan completes; the same row carries the run id (written before the first applied item and passed to `apply` as `runId`), so a resumed run keeps the id that any authorization it granted is bound to; a kind may return a named per-item outcome (`RepairItemOutcome`), tallied in `outcomes` and `outcome_items`; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with the `gbrain config set` value that finishes; a held writer stops with `gbrain sources writer status <source>`). `timeline.ts`: `scanTimelineHistory` (bounded id-order scan shared with the doctor) and the materialize kind. `visibility.ts`: `planVisibilityRepair`, the tighten-only atom/concept backfill (atoms from `effectiveVisibility` of their origin, concepts from the strictest input over provenance edges and atoms' `concepts:`; no-lineage concepts are counted and left alone). `safe-chunks.ts`: a `publication: 'projection'` kind (no admission, zero lifetime-ID and receipt cost, no capacity stop) that re-seals markdown and code pages below the safe-chunk fence through `resealSafeChunks`, then embeds their NULL chunks unless `--no-embed`; code pages without a recorded path and other page kinds are residuals. The pending count is reported only by the doctor check `safe_index_pending`, which the post-upgrade recovery banner uses. `contextual-mode.ts`: a `publication: 'projection'` kind (#5621) that stamps `contextual_retrieval_mode` + `corpus_generation` on sealed live markdown pages with a NULL mode through `resolveImportContextualMode` (`src/core/import-contextual-mode.ts`, the resolver `importFromContent` also uses, strict source-row read), then under the page guard clears only vectors whose recorded embedding input the stamped convention no longer accepts (the #5553 rule) and re-embeds that page once unless `--no-embed`; unsealed pages are the `unsealed_projection` residual. `connector-checkpoints.ts`: a `publication: 'projection'` bookkeeping kind (#5686, `embeds: false`) that deletes connector checkpoint rows and retry pointers no registered source can load and that are older than 7 days, keeping rows a non-terminal request or recorded pending set references; brain-wide. `request-indexes.ts`: a `publication: 'projection'` brain-wide kind (#5762, `embeds: false`) that builds a missing managed sync request index or drops an INVALID one and rebuilds it through `buildIndexOnline` (`src/core/schema-migrations/helpers.ts`: CONCURRENTLY on Postgres under the session's startup timeouts with no session SET, inline on PGLite, the result re-checked for validity, an index another session is still building is left alone); it clears `persistence_request_indexes`. `orphan-bindings.ts`: a projection bookkeeping kind (#5732) over `persistence/orphan-bindings.ts` that deletes persistence source bindings of a removed source or an earlier incarnation, brain-wide, keeping one a pending request of that incarnation references. `embedding-effects.ts`: a projection kind (#5629/#5734, `embeds: 'effect'`) over `persistence/embedding-settlement.ts`; each stale queued or failed embedding effect of a committed write is `reconciled` (the effect projection verifier passes), `superseded` (page deleted, or a newer revision of the same page owns its own effect), `retry_queued` (stale queued re-queued for the owner; failed granted the retry-effects allowance; an exhausted allowance gets one new bounded cycle under `embeddingGrantId(runId, effect)`, which a resumed run replays) or `blocked` with a reason; every change is a compare-and-set on state, attempts, execution token and recovery, and a changed candidate is `changed_since_preview`. Retry items count the whole retry budget in the embedding estimate. `registry.ts`: `REPAIR_REGISTRY` (one entry per `REPAIR_KINDS` name in `--all` order: handler, help summary, `embeds` — `effect` when the publication's embedding effect re-embeds each page outside the run, `inline` when the kind embeds in-process and honors `--no-embed`, `none` for bookkeeping kinds — and the doctor `checks` it clears), `repairForCheck`, `repairApplyCommand` and `repairRunner`, the one trusted local runner that both `gbrain repair` and doctor remediation use; a new kind plugs in by adding its name to `REPAIR_KINDS` and one registry entry. A kind with `explicit_only` (`stale-atoms`, `extractor-facts`; the `extractor-facts.ts` stub refuses with `unavailable` until its fix wave 5 lane lands) runs only when named: `AUTO_REPAIR_REGISTRY` is the `--all`, no-kind and remediation set, `explicitRepairNotices` lists the rest as `explicit_kind_required` with `repairPreviewCommand`, and `runRepair` refuses an unnamed explicit-only kind (`explicitKindRequired`), so a supplied remediation step cannot run one. Only explicit-only kinds accept `--expect <hash>` and `--include-ambiguous`, passed to `plan` as `RepairPlanOptions`; a plan's `preview_hash` is appended to its apply command, and its `listing` (every previewed item with its class) is printed by the dry run. `stale-atoms.ts` (#5770): live page-bound atoms (never `imported_from`, never `source_path`-only) whose source page is gone (`origin_gone`) or whose stripped 16-character `source_hash` differs from a source page that already completed an extraction at its current hash (`origin_changed`; managed evidence is the completed `managed-atoms` checkpoint via `managedAtomCompletedSql`, unmanaged evidence a non-managed atom at that hash). The preview saves the set with `saveApprovedSet`; `--apply --expect <hash>` loads it (`preview_changed` otherwise; `--apply` alone refuses with the filled commands), rechecks each atom (revision, class, origin, evidence) and reports `retired`, `changed_since_preview` or `file_conflict` (an uncoordinated edit of the atom file; its attempt-aware `repairRequestId` lets a later apply retry once the file is fixed). An approved set applies only under the source selection it was previewed with, and the apply's resume cursor is keyed by its approval hash. Managed brains admit one `managed_maintenance_retire_stale_atoms` request per atom bound to its revision (`prepareStaleAtomRetirement`, rechecked under the atom and origin page locks, no live origin needed); unmanaged brains soft-delete in one locked transaction. Both stamp `retired_by: stale-atoms`/`retired_at` and bump the origin page's `managed-atoms-generation` (clearing its page state and completed checkpoints, keeping the current hash for `origin_changed`), so a restored page is extracted again and `publishManagedAtoms` restores the retired atoms. Tests: `test/repair-explicit-only.test.ts`, `test/repair-stale-atoms.test.ts` and `test/journey-atoms-sync-race.test.ts` (PGLite and Postgres). Tests: `test/repair-command.test.ts`, `test/derived-visibility-repair.test.ts`, `test/safe-chunk-reseal.test.ts` (PGLite and Postgres), `test/repair-contextual-mode-5621.serial.test.ts` (PGLite and Postgres), `test/repair-flags.test.ts`, `test/persistence-request-indexes.test.ts`.+- `src/core/repair/` — `gbrain repair` core. `core.ts`: `resolveRepairScope` (default every active source; prints brain and source ids), `runRepair` (dry run unless `apply`; each item is one revision-bound `put_page` with a deterministic request id (replayed while pending, a new attempt id after a terminal failure), re-decided against current state just before it is applied; a cursor in `op_checkpoints` keyed by kind + scope resumes an interrupted or `--limit` run and is cleared when a scan completes; the same row carries the run id (written before the first applied item and passed to `apply` as `runId`), so a resumed run keeps the id that any authorization it granted is bound to; a kind may return a named per-item outcome (`RepairItemOutcome`), tallied in `outcomes` and `outcome_items`; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with the `gbrain config set` value that finishes; a held writer stops with `gbrain sources writer status <source>`). `timeline.ts`: `scanTimelineHistory` (bounded id-order scan shared with the doctor) and the materialize kind. `visibility.ts`: `planVisibilityRepair`, the tighten-only atom/concept backfill (atoms from `effectiveVisibility` of their origin, concepts from the strictest input over provenance edges and atoms' `concepts:`; no-lineage concepts are counted and left alone). `safe-chunks.ts`: a `publication: 'projection'` kind (no admission, zero lifetime-ID and receipt cost, no capacity stop) that re-seals markdown and code pages below the safe-chunk fence through `resealSafeChunks`, then embeds their NULL chunks unless `--no-embed`; code pages without a recorded path and other page kinds are residuals. The pending count is reported only by the doctor check `safe_index_pending`, which the post-upgrade recovery banner uses. `contextual-mode.ts`: a `publication: 'projection'` kind (#5621) that stamps `contextual_retrieval_mode` + `corpus_generation` on sealed live markdown pages with a NULL mode through `resolveImportContextualMode` (`src/core/import-contextual-mode.ts`, the resolver `importFromContent` also uses, strict source-row read), then under the page guard clears only vectors whose recorded embedding input the stamped convention no longer accepts (the #5553 rule) and re-embeds that page once unless `--no-embed`; unsealed pages are the `unsealed_projection` residual. `connector-checkpoints.ts`: a `publication: 'projection'` bookkeeping kind (#5686, `embeds: false`) that deletes connector checkpoint rows and retry pointers no registered source can load and that are older than 7 days, keeping rows a non-terminal request or recorded pending set references; brain-wide. `request-indexes.ts`: a `publication: 'projection'` brain-wide kind (#5762, `embeds: false`) that builds a missing managed sync request index or drops an INVALID one and rebuilds it through `buildIndexOnline` (`src/core/schema-migrations/helpers.ts`: CONCURRENTLY on Postgres under the session's startup timeouts with no session SET, inline on PGLite, the result re-checked for validity, an index another session is still building is left alone); it clears `persistence_request_indexes`. `orphan-bindings.ts`: a projection bookkeeping kind (#5732) over `persistence/orphan-bindings.ts` that deletes persistence source bindings of a removed source or an earlier incarnation, brain-wide, keeping one a pending request of that incarnation references. `embedding-effects.ts`: a projection kind (#5629/#5734, `embeds: 'effect'`) over `persistence/embedding-settlement.ts`; each stale queued or failed embedding effect of a committed write is `reconciled` (the effect projection verifier passes), `superseded` (page deleted, or a newer revision of the same page owns its own effect), `retry_queued` (stale queued re-queued for the owner; failed granted the retry-effects allowance; an exhausted allowance gets one new bounded cycle under `embeddingGrantId(runId, effect)`, which a resumed run replays) or `blocked` with a reason; every change is a compare-and-set on state, attempts, execution token and recovery, and a changed candidate is `changed_since_preview`. Retry items count the whole retry budget in the embedding estimate. `registry.ts`: `REPAIR_REGISTRY` (one entry per `REPAIR_KINDS` name in `--all` order: handler, help summary, `embeds` — `effect` when the publication's embedding effect re-embeds each page outside the run, `inline` when the kind embeds in-process and honors `--no-embed`, `none` for bookkeeping kinds — and the doctor `checks` it clears), `repairForCheck`, `repairApplyCommand` and `repairRunner`, the one trusted local runner that both `gbrain repair` and doctor remediation use; a new kind plugs in by adding its name to `REPAIR_KINDS` and one registry entry. A kind with `explicit_only` (`stale-atoms`, `extractor-facts`; the `extractor-facts.ts` stub refuses with `unavailable` until its fix wave 5 lane lands) runs only when named: `AUTO_REPAIR_REGISTRY` is the `--all`, no-kind and remediation set, `explicitRepairNotices` lists the rest as `explicit_kind_required` with `repairPreviewCommand`, and `runRepair` refuses an unnamed explicit-only kind (`explicitKindRequired`), so a supplied remediation step cannot run one. Only explicit-only kinds accept `--expect <hash>` and `--include-ambiguous`, passed to `plan` as `RepairPlanOptions`; a plan's `preview_hash` is appended to its apply command, and its `listing` (every previewed item with its class) is printed by the dry run. `stale-atoms.ts` (#5770): live page-bound atoms (never `imported_from`, never `source_path`-only) whose source page is gone (`origin_gone`) or whose stripped 16-character `source_hash` differs from a source page that already completed an extraction at its current hash (`origin_changed`; managed evidence is the completed `managed-atoms` checkpoint via `managedAtomCompletedSql`, unmanaged evidence a non-managed atom at that hash). The preview saves the set with `saveApprovedSet`; `--apply --expect <hash>` loads it (`preview_changed` otherwise; `--apply` alone refuses with the filled commands), rechecks each atom (revision, class, origin, evidence) and reports `retired`, `changed_since_preview` or `file_conflict` (an uncoordinated edit of the atom file; its attempt-aware `repairRequestId` lets a later apply retry once the file is fixed). An approved set applies only under the source selection it was previewed with, and the apply's resume cursor is keyed by its approval hash. Managed brains admit one `managed_maintenance_retire_stale_atoms` request per atom bound to its revision (`prepareStaleAtomRetirement`, rechecked under the atom and origin page locks, no live origin needed); unmanaged brains soft-delete in one locked transaction. Both stamp `retired_by: stale-atoms`/`retired_at` and bump the origin page's `managed-atoms-generation` (clearing its page state and completed checkpoints, keeping the current hash for `origin_changed`), so a restored page is extracted again and `publishManagedAtoms` restores the retired atoms. Tests: `test/repair-explicit-only.test.ts`, `test/repair-stale-atoms.test.ts` and `test/journey-atoms-sync-race.test.ts` (PGLite and Postgres). Tests: `test/repair-command.test.ts`, `test/derived-visibility-repair.test.ts`, `test/safe-chunk-reseal.test.ts` (PGLite and Postgres), `test/repair-contextual-mode-5621.serial.test.ts` (PGLite and Postgres), `test/repair-flags.test.ts`, `test/persistence-request-indexes.test.ts`. `google-file-modes.ts`: an explicit-only (`explicit_only: true`), `publication: 'projection'` filesystem-only kind (`embeds: false`, no admission, no request ids) that plans one item per loose entry from `scanGoogleFileModes` (cursor phase = source index; the item carries root, relative path, kind and old mode) and applies `tightenGoogleEntry` (outcomes `tightened`, `already_private`, `skipped` with a reason); symlink, foreign-owner and wrong-type entries are `skipped_*` residuals. It is last in `REPAIR_KINDS`, so `--all` runs it after `embedding-effects`; registry check `google_file_modes`. Every run re-scans, so a rerun after `--limit` picks up exactly what is still loose.- `src/core/rerank-audit.ts` — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. The `no_key` reason is written ONCE per process per model by the gateway itself (not per query by `applyReranker`): the provider key is absent, so calls are skipped without HTTP and results pass through unreranked; `auth` means key present but rejected. Deliberately no `logRerankSuccess`: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check (`doctor/checks/calibration.ts`) resolves enablement + model through `resolveSearchMode(loadSearchModeConfig)` — the plane search reranks with — and `rerankerReadiness` before reading the audit: readiness is evaluated against the DB-merged config plane (`loadConfigWithEngine`, so DB-plane provider keys and `provider_base_urls` self-host overrides count, exactly like the gateway the CLI configures): a brain with NO embedding provider (`isAvailable('embedding')` false on a configured gateway) is `ok` even when not ready — search runs keyword-only there and never reaches `applyReranker`, so there is nothing to fix; otherwise enabled-but-not-ready (key absent / unknown model) warns with the paste-ready fix; only audit rows for the RESOLVED model count (rows for any other model never make the live default warn or send the operator to verify the wrong key); `no_key` skip rows are informational once ready (those processes ran unreranked; a long-lived worker started before the key was added keeps skipping until restarted) and never outlive the fix as a warn; then the auth / payload / budget / transient / unknown ladders on the non-skip rows; disabled → ok (with an enable hint when the default is ready). Query text SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.- `src/core/repair/extractor-facts.ts` — `gbrain repair extractor-facts` (#5731), explicit-only and preview-bound. `classifyExtractorFacts` (read-only; also the doctor check's count) takes conversation-extractor facts with `expired_at` set and `row_num` NULL and classes each: `excluded` (page missing or deleted, `superseded_by` set, withdrawn, an active same-text fact on the page, or an earlier same-text candidate), `ambiguous` (unmanaged brain; no committed request of the page with `completed_at = expired_at`, compared in SQL as microsecond UTC text, which only a same-transaction completion satisfies on Postgres; a consumer at or above v0.60.11.0; or the page has ever held fence-projected facts) or `evidenced`. The preview lists every candidate, hashes them with the selection (`--include-ambiguous`) and saves one approved item per page (with its request id) through `preview-approval.ts`; the apply loads only that set, skips pages whose request already committed or whose facts are active again, and restores each still-identical fact with a fresh `row_num` above the page's facts and fence rows. Managed brains publish one database-only `managed_maintenance_restore_extractor_facts` request per page (`submitDatabaseMaintenanceIntent`, dispatched by `prepareMaintenanceMutation` to `prepareExtractorFactsRestore`, which reclassifies under the page lock); unmanaged brains run the same restore in one locked transaction. Previews warn, naming the host, when a consumer older than this release published after `writer_version_cutoff`. On PGLite `now()` has millisecond resolution, so the same-transaction rule is millisecond-exact there.- `src/core/persistence/mirror-read-only.ts` and `src/commands/sources-mirror.ts` — #5409 read-only mirror sources. `sourceMirrorReadOnly(engine, sourceId)` reads `sources.config.mirror_read_only` (default false). When true, `prepareFileTarget` (`page-prepare.ts`) returns no file for any coordinated page write into the source (receipt `write_through.skipped: 'mirror_read_only'`, `storage: 'database_only'`, set in `coordinator.ts`), and managed sync (`sync-prepare.ts`) imports an overlay (canonical form differs from the file bytes) database-only: no `file`, no newer-working-tree refusal, and `contentUnchanged` ignores the overlay. A page created that way with no recorded file is stamped `pages.database_only_reason='mirror_read_only'` (`classifyMirrorPage`, in the publication) and stays database-only after the flag is cleared; the coordinator refuses (`source_changed`) a file target prepared before the flag was set (rechecked under the publication with the source row `FOR SHARE`); `gitPage` (`effects.ts`) completes a mirror source's Git effects as skipped. `gbrain sources mirror-readonly|mirror-writable <id>` set and clear the key like `federate`/`unfederate`; `sources list --json` reports `mirror_read_only`.diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.mdindex 0cc393fa63..67e85c7059 100644--- a/docs/architecture/key-files/google-and-loops.md+++ b/docs/architecture/key-files/google-and-loops.md@@ -23,7 +23,8 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding- `src/core/google/access.ts` — the pluggable Google-access seam: `GoogleAccessProvider` (`getAccessToken`/`forceRefresh`) with `CommandAccessProvider` (`--access command`: any CLI that prints a token — gog/gcloud/a gateway's mint command; parsed as a bare token line or JSON `{token|access_token, expiry|expires_in}`, cached until expiry with a 60s margin, 30s exec timeout, failures = `access_command_failed` carrying the stderr tail) and `EnvAccessProvider` (`--access env`: a live token read from a NAMED env var each call, refreshed outside gbrain; missing = `access_env_missing`). The vault flow's `GoogleTokenProvider` satisfies the same interface. The token command executes only in the locally-running sync (google config keys are unreachable over MCP; same trust class as recipe health-check argv).- `src/core/google/google-clients.ts` — hand-rolled Gmail/Calendar/People REST clients (house style, no googleapis dependency): auth via any `GoogleAccessProvider` (vault-backed `GoogleTokenProvider` by default), 401 → forceRefresh + single retry, Retry-After honored (delta-seconds AND http-date), 403 accessNotConfigured → `api_not_enabled` carrying the exact enable deep link (project number extracted from the client id), uniform pageToken pagination with a safety cap, `fetchImpl` injectable for tests. `extractCalendarMethod(part)` walks the MIME tree for a `text/calendar`/`application/ics` part and reads the iCalendar `method=` parameter from the PART's own `Content-Type` header (`headers[]` on nested parts with `format=full` — Gmail's `MessagePart.mimeType` is the BARE media type, so a mimeType-only parse would read '' for every real invite and silently downgrade the structural signal to the subject fallback); a mimeType that still carries params is the fallback parse; a bare `.ics` filename with a non-calendar MIME type claims nothing. `CalendarClient.listEvents({calendarId})` sweeps one calendar (default `DEFAULT_CALENDAR_ID`). A People request with a nonempty `syncToken` maps HTTP 400 to `GoogleCursorExpiredError` only for typed `google.rpc.ErrorInfo` reason `EXPIRED_SYNC_TOKEN` or a message beginning `Sync token [is] expired`; unrelated 400s, initial-list requests, and other APIs remain upstream failures. The contacts sweep uses its existing bounded full re-list recovery without restarting Gmail. Pinned by injected-response tests in `test/google-clients.test.ts` and `test/google-source-reconcile.test.ts`, not live-provider validation.- `src/core/google/google-render.ts` — pure render functions (`{relPath, markdown}` out; no I/O, no engine): thread pages under `emails/YYYY/MM/` (type email), events under `calendar/YYYY/MM/` (type meeting), contacts under `people/` (type person). Gmail deep links are code-generated via the typed `emailCitation` scaffold, never LLM-composed. The noise/signature rules `recipes/email-to-brain.md` specifies as prose for agent-authored collectors are implemented here — keep the recipe and this module in sync. `isCalendarSystemMail({calendarMethod, subject})` gates BOTH loop detectors: the PRIMARY signal is a `calendarMethod` in the `CALENDAR_METHODS` allowlist (RFC 5546 — REQUEST, REPLY, CANCEL, PUBLISH, COUNTER, DECLINECOUNTER, REFRESH, ADD; case-insensitive); an empty or unrecognised method is NOT a stamp and falls to the subject fallback, which is anchored to the start of the subject, refuses any Re:/Fwd: prefix, and matches only Calendar's OWN localised headers (`Invitation:`, `Updated invitation:`, `Accepted:`, `Declined:`, `Tentative:`, `Canceled event:` + localised equivalents) — a generic word like `Notification:` is a human/vendor subject and never matches. `renderThreadPage` stamps `participants:` (every address on the thread) AND `senders:` (sorted unique message AUTHORS only — the list `loops mute sender` gates on, so muting one person cannot silence a whole group thread). Pinned by `test/google-render.test.ts`.-- `src/core/google/google-source.ts` — the Google API source sweep. Unmanaged mode materializes Markdown under the source directory and imports through the standard chunks/aliases/links pipeline; managed mode uses journaled connector admission. Sweep order contacts → calendar → gmail: alias rows must exist before the loop detector resolves counterparties. Per-service independent cursors: contacts/calendar syncToken commits only after that service's fully-successful sweep (410 GONE drops the token and re-runs windowed); gmail delta rides history.list with an expired-history windowed fallback; the INITIAL backfill drains newest→oldest with a batch-committed floor cursor so a killed 50k-message backfill resumes at the floor instead of restarting, and the historyId anchor is captured BEFORE the backfill so the delta lane takes over with zero gap (overlap re-renders are idempotent). Emits the `sync.google_materialize` progress phase (docs/progress-events.md). Access resolves per source config: the vault (default), a token-printing command (`g_access: command` — gog/gcloud/gateway; identity entry synthesized, scope preflight trusts the configured services, send-as aliases fetched live best-effort), or a named env var (`g_access: env`). Secrets never land in `sources.config` (the command/env NAME is config; tokens are not). Honesty invariants: `last_sync_at` is gated on the GMAIL sweep's success (it feeds `gbrain waiting`'s trust-critical staleness gate, which protects loop freshness — a gmail sweep with real thread failures must not advance it); contacts/calendar failures mark the run `partial` but do not block the stamp, and a source without gmail in its services stamps unconditionally. A thread whose fetch fails on consecutive sweeps lands in the poison ledger and is skipped (steady-state runs honor the ledger; `--full` retries with a fresh one), so one bad thread can't wedge the sync while a poison-skip alone doesn't count as failure. Contact reconcile resolves by contact resourceName (DB lookup by contact id FIRST): deletion tombstones carry only `resourceName + deleted` (no names — slug derivation yields null) and a renamed contact derives a DIFFERENT slug, so both must land on the existing page by id, never by slug. The calendar sweep binds its sync token to its calendar: `sweepCalendar` compares `state.calendar_id` (legacy state without it is treated as primary's) with the configured `calendarId`; on a mismatch it logs `[google] calendar changed (<old> → <new>)`, discards the token and takes the windowed first-sync path (no `syncToken` on the wire), and a freshly banked token stores the calendar id beside it — pairing a re-pointed source with the previous calendar's cursor would import a foreign delta. Pages from the previous calendar are not reconciled on the switch (logged; a filed follow-up). `enqueueLoopsExtraction` enqueues EVERY eligible thread (newest first) under a waiting-depth budget `LOOPS_EXTRACT_ENQUEUE_CEILING − waiting` that counts only THIS source's waiting `loops_extract` jobs (`data->>'sourceId'`), so one account's stalled backlog cannot pin another source's budget at 0; overflow is a logged deferral (a deferred thread re-candidates when it changes) and a failed probe fails open. The budget probe counts PENDING rows — `status IN ('waiting','delayed','active')` — so a retry backlog parked in `delayed` during a flapping provider cannot stack past the ceiling. With no chat provider available (`isAvailable('chat')` false) the enqueue is skipped entirely and one stderr line per sweep names the reason and the count; pages still import and the threads re-candidate on their next touch or a `--full` sweep. Managed Google API sync uses journaled connector checkpoints; an unbound source is explicitly `connector_database`, while a bound source publishes canonical files. Identity-query storage failures do not become successful absence or advance the checkpoint. Unsupported Git/dry-run flags refuse before credentials/network; legacy materialization remains the unmanaged path.+- `src/core/google/google-source.ts` — the Google API source sweep. Unmanaged mode materializes Markdown under the source directory and imports through the standard chunks/aliases/links pipeline; managed mode uses journaled connector admission. Sweep order contacts → calendar → gmail: alias rows must exist before the loop detector resolves counterparties. Per-service independent cursors: contacts/calendar syncToken commits only after that service's fully-successful sweep (410 GONE drops the token and re-runs windowed); gmail delta rides history.list with an expired-history windowed fallback; the INITIAL backfill drains newest→oldest with a batch-committed floor cursor so a killed 50k-message backfill resumes at the floor instead of restarting, and the historyId anchor is captured BEFORE the backfill so the delta lane takes over with zero gap (overlap re-renders are idempotent). Emits the `sync.google_materialize` progress phase (docs/progress-events.md). Access resolves per source config: the vault (default), a token-printing command (`g_access: command` — gog/gcloud/gateway; identity entry synthesized, scope preflight trusts the configured services, send-as aliases fetched live best-effort), or a named env var (`g_access: env`). Secrets never land in `sources.config` (the command/env NAME is config; tokens are not). Honesty invariants: `last_sync_at` is gated on the GMAIL sweep's success (it feeds `gbrain waiting`'s trust-critical staleness gate, which protects loop freshness — a gmail sweep with real thread failures must not advance it); contacts/calendar failures mark the run `partial` but do not block the stamp, and a source without gmail in its services stamps unconditionally. A thread whose fetch fails on consecutive sweeps lands in the poison ledger and is skipped (steady-state runs honor the ledger; `--full` retries with a fresh one), so one bad thread can't wedge the sync while a poison-skip alone doesn't count as failure. Contact reconcile resolves by contact resourceName (DB lookup by contact id FIRST): deletion tombstones carry only `resourceName + deleted` (no names — slug derivation yields null) and a renamed contact derives a DIFFERENT slug, so both must land on the existing page by id, never by slug. The calendar sweep binds its sync token to its calendar: `sweepCalendar` compares `state.calendar_id` (legacy state without it is treated as primary's) with the configured `calendarId`; on a mismatch it logs `[google] calendar changed (<old> → <new>)`, discards the token and takes the windowed first-sync path (no `syncToken` on the wire), and a freshly banked token stores the calendar id beside it — pairing a re-pointed source with the previous calendar's cursor would import a foreign delta. Pages from the previous calendar are not reconciled on the switch (logged; a filed follow-up). `enqueueLoopsExtraction` enqueues EVERY eligible thread (newest first) under a waiting-depth budget `LOOPS_EXTRACT_ENQUEUE_CEILING − waiting` that counts only THIS source's waiting `loops_extract` jobs (`data->>'sourceId'`), so one account's stalled backlog cannot pin another source's budget at 0; overflow is a logged deferral (a deferred thread re-candidates when it changes) and a failed probe fails open. The budget probe counts PENDING rows — `status IN ('waiting','delayed','active')` — so a retry backlog parked in `delayed` during a flapping provider cannot stack past the ceiling. With no chat provider available (`isAvailable('chat')` false) the enqueue is skipped entirely and one stderr line per sweep names the reason and the count; pages still import and the threads re-candidate on their next touch or a `--full` sweep. Managed Google API sync uses journaled connector checkpoints; an unbound source is explicitly `connector_database`, while a bound source publishes canonical files. Identity-query storage failures do not become successful absence or advance the checkpoint. Unsupported Git/dry-run flags refuse before credentials/network; legacy materialization remains the unmanaged path. FILE MODES (every write, both paths): `writeGoogleState` writes `.google-source.json` through `atomicWriteFileSync(..., { mode: 0o600 })` under `mkdirPrivate(dir)`; a corrupt state file is chmod-ed 0600 and then renamed to `.corrupt`, and if either step fails stderr names the path, the failed step, the exposure and the fix (`chmod 600 <path>` or delete it) while the sync continues with empty cursors. A legacy page goes through `writePrivateTemp`: a stale `<page>.tmp` is removed with `lstat` (never followed; a stale `.tmp` directory fails that item with `Stale temporary path <path> is a directory; remove it and re-run the sync.`), the temp file is created `wx` at 0600 and fchmod-ed past the umask, imported, then renamed over the page; page directories come from `mkdirPrivate(dirname(page), cfg.dir)`. 0600 is reasserted on every rewrite, so a looser mode set by hand is reverted on the next rewrite (unchanged pages are not rewritten). Managed pages get the same modes through `publishMode` (see the persistence coordinator). Mode assertions are skipped on win32. Tests: `test/google-file-modes.test.ts` (child process under umask 0000, `test/helpers/google-file-modes-child.ts`).+- `src/core/google/file-modes.ts` — detection and tightening for group/world-readable files gbrain wrote under a Google source directory outside `~/.gbrain` (inside it the 0700 home already protects them). `scanGoogleFileModes(engine, { sourceIds? })` reads non-archived Google sources, skips dirs inside the home (`outsideGbrainHome`, realpath-aware), and inspects only gbrain's own layout: `.google-source.json*` in the root, every recorded page `source_path` under `emails/`, `calendar/`, `people/` (malformed paths ignored), each page's `.tmp`, and the directories between the root and those pages. Each path is `lstat`-ed component by component (a symlink anywhere on the path, another owner, or the wrong file type is counted in `skipped`, never followed); an entry is loose when `mode & 0o077`. `tightenGoogleEntry(root, entry)` re-checks the path, opens the leaf `O_NOFOLLOW` (`O_DIRECTORY` for dirs), re-checks the owner on the fd and `fchmod`s `mode & ~0o077`, so a swap after the scan is refused, not followed; the user-chosen root is never in the candidate set. `googleFileModesPreviewCommand`/`googleFileModesApplyCommand` build the `gbrain repair google-file-modes --source <id> [--apply]` strings every surface prints. win32: scan returns nothing. Tests: `test/google-file-modes-repair.test.ts`.- `src/core/google/loop-detect.ts` — the zero-LLM thread-state machine: last substantive message inbound + user in To: + unanswered ≥24h → `unanswered_inbound`; last outbound + contains a question + unanswered ≥72h → `unanswered_outbound` (both grace windows measured from the oldest owed message in the trailing run since the last turn flip, so a nudge or follow-up never restarts the clock — gbrain-evals N7-1); a reply closes the loop (`closed_by: reply_detected`). Precision IS the product: noise senders, list mail (List-Unsubscribe), CC-only delivery, FYI/forwards without a question, self-threads, and muted senders/threads never open loops — pinned by the labeled fixture corpus in `test/google-loop-detect.test.ts` (every false-positive class gets a fixture before its fix). Pure verdict function + a thin apply step called per touched thread from the sync; the apply step must never fail the sync.- `src/core/google/loops-extract.ts` — the LLM half of the open-loop engine: ONE extractor per recent thread page projects each commitment into THREE substrates in the same pass — the `open_loops` row (dedup `commit:<sha8>`), a facts row via writeSingleFact (kind=commitment, fence-first, deduped; its id lands on `open_loops.fact_id` so entity cards / recall / context_pack see the commitment through existing read paths with zero new read code), and a typed edge thread-page → person-page (`owes_to` / `awaiting_reply_from`) for relational search. `extract_facts` never runs separately on google-source email pages. Guardrails: injection-hardened input, ALL-or-nothing parse barrier (a malformed model response writes NOTHING), a structural eligibility gate (`loopExtractionEligibility` — Gmail labels, `List-Unsubscribe`, calendar part, who wrote the message; no vendor lists) plus the per-source waiting-depth enqueue budget (`LOOPS_EXTRACT_ENQUEUE_CEILING`, a spend backstop — see `google-source.ts`), only the last `LOOPS_EXTRACT_WINDOW_DAYS` (30) of mail (the deep backfill is never extracted), kill switch `loops.extraction_enabled` (default ON for google sources). Suppressions gate the lane before any model/facts/edge write: a muted thread id, or a muted SENDER — `fm.from` ∪ `fm.senders`, every address that AUTHORED a message, so a muted counterparty who wrote earlier in the thread still suppresses — returns `reason: 'suppressed'`; recipients/CC never count (muting one person must not hide everyone else's commitments in a group thread, and an outside sender must not be able to dodge extraction by CC'ing a muted address). Pages without a `senders:` field fall back to `fm.from` alone until their next re-render. Eligibility computes the substantive (non-noise, non-calendar) message set FIRST and `owner_participated` requires the owner to have written a SUBSTANTIVE message — a pure-calendar thread the owner RSVP'd to stays `no_substantive_messages`. When the chat provider is unavailable, `runLoopsExtract` throws `LoopsExtractRetryableError` (reason `llm_unavailable`) rather than returning a skipped result: a completed no-work row would hold the revision-keyed idempotency slot forever, while a retried-then-dead row frees it so the same revision re-enqueues on the next sweep. On a managed brain `managedFactWritePreflight` checks the managed fact authority and canonical owner before chat (an unaccepted writer refuses with `writer_coordinator_required`), and the commitment fact publishes through writeSingleFact's coordinator path; disabled, missing-page and suppressed cases retain their existing no-work outcomes.- `src/core/loops/loops-store.ts` — SQL accessors for the `open_loops` + `loop_suppressions` tables over `engine.executeRaw` with IDENTICAL SQL text on both engines (parity by construction, the sources-ops.ts pattern — no per-engine method twins). JSONB discipline: evidence binds through `$N::text::jsonb`, never a bare `::jsonb` cast over JSON.stringify. Loops close by state transition, never delete: reply-driven auto-close flips status to `done` and stamps `closed_by`, keeping the audit trail. The upsert's DO UPDATE carries a manual-close guard in its WHERE: a closed row (done/dropped/stale) only reopens on GENUINELY newer activity, so a routine sweep re-seeing the same thread never resurrects a hand-closed loop, and the staleness auto-close (`closed_by: 'staleness'`) is likewise guarded against the upsert's reopen. `removeSuppression(engine, sourceId, kind, value)` is the exact inverse of the mute write — deletes the one `(source_id, kind, value)` row with the same lower-casing, returns `{removed: boolean}` (false = was not muted, callers treat it as a no-op success), and never reopens loops: suppressions gate NEW detection only.@@ -33,6 +34,8 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding- `src/commands/loops.ts` — `gbrain waiting [--top N] [--json] [--stale-ok]` + `gbrain loops list|show|done|drop|mute`: all paths dispatch through the trusted-local op layer (`handleToolCall`, remote:false) so CLI and MCP share one behavior. `waiting` REFUSES when EVERY google source has gone >24h without a successful sync and prints the exact fix (`--stale-ok` bypasses; per-source sync ages are always reported) — stale-but-confident output is worse than none. Output per counterparty: what's owed, evidence quotes, Gmail deep links, entity-card context, a paste-ready digest. Reads default to the `__all__` brain span (loops live in google sources, not `default` — a default-scoped read would say "all clean" while people wait); `--source <id>` narrows explicitly. An unqualified `mute`/`unmute` resolves the brain's google source (never `default`) through the SAME resolution — an unmute can never aim at a different source than the mute it reverses — and refuses with the exact fix when none or multiple exist. `unmute sender <email> | thread <id>` is exact and forward-only; a repeated unmute is a no-op success (`removed: false`, exit 0) so scripts can call it unconditionally.- `src/commands/google-setup.ts` + `google-setup-tail.ts` — the one-command orchestrator behind `gbrain google setup`: connect (skipped when tokens exist) → source registration (skipped when registered) → first bounded sync under a wall-clock budget (the newest-first backfill floor means whatever lands is the NEWEST mail — exactly what `waiting` needs; the remainder resumes on every later sync, and setup says so honestly) → the first `gbrain waiting` digest in the same session as consent. Split in two so the connect half stays engine-free. Every step idempotent; re-running resumes wherever the last run stopped.- `src/commands/doctor/checks/google-oauth.ts` — the `google_oauth` doctor check: zero-network vault health (live refresh probes belong to `gbrain google status`; doctor stays fast and offline-safe). fail: a connected account with an expired access token AND no successful refresh in >2 days (refresh is broken — revoked, rotated client, or the Testing-mode expiry already hit); warn: a consent screen not known Production whose last proof of life is ≥5 days old (the proactive day-6 re-auth demand, cheaper than a dead pipeline on day 8); ok: accounts healthy or nothing connected (the connector is optional, not an error).+- `src/commands/doctor/checks/google-file-modes.ts` — the `google_file_modes` doctor check (ops category; a `WAVE_CHECKS` entry in `src/commands/doctor/wave-checks.ts`, `resolution: 'repair'`, host-only so remote doctor never sees host paths). Detection only: warns per Google source dir outside `~/.gbrain` with `loose_files`/`loose_dirs` counts and the exact preview and apply commands (`details.sources[]`, `details.count`, `repair: 'google-file-modes'`); never prints file names, because Gmail page names embed subject words. A scan error is `warn` with `count: 'unknown'`, never ok. Remediation runs the `google-file-modes` repair kind.+- `src/commands/migrations/v0_60_31-google-file-modes.ts` — the Google file-mode notice phase of the v0.60.31 orchestrated migration (`v0_60_31.ts`, which runs it after the credential re-chunk phase). `googleFileModesNoticePhase` prints one content-free line per Google source outside `~/.gbrain` (source id, dir, count of readable entries found now, preview and apply commands, the `docs/guides/google-connect.md` pointer) and sets the brain config marker `google.file_modes_notice` so it prints once per brain; dry runs and brains without a config skip it. Detection only: nothing is chmod-ed.- `src/core/agent-install/` + `scripts/setup-in-agent.sh` — Package-versioned non-root installation into a verified persistent root. Absolute launchers isolate ambient routing and credentials; local launchers pin the host brain and installed source, while thin-client launchers leave unqualified routing to the remote grant and preserve explicit CLI arguments. Receipts track ownership, pending enablement, non-secret failure codes, and an exact repair command, and repair retains database contents. Upgrades journal pending schema migrations before switching runtime metadata; retries use schema-only initialization without invoking host orchestration. Busy results remain structured and retryable without deleting live locks. Native instructions/routines remain pending until observed in the actual harness.- `src/core/backup/{archive,snapshot,quarantine,private-path}.ts` — bounded full-PGLite snapshots with checksums, credential-reference exclusions and fresh-root restoration. Portable entry validation rejects traversal, Windows aliases and case/normalization/file-directory collisions independently of native confinement. Recorded path flavor controls nested managed-path rebasing; unrecognized absolute page origins stay unchanged with reconnect guidance. Hold the database lock, detect changing inventories, detach external roots and quarantine unfinished jobs without deleting spending evidence. Windows uses direct .NET file/directory security APIs through bounded built-in PowerShell, without cmdlets, to protect new empty work/root/archive-temp paths before payload writes. Readback requires the current owner, protected DACL and exact deduplicated owner-plus-SYSTEM full-control rules, inheritance and propagation; unavailable enforcement refuses without changing existing parents or source data. Never replace the source installation. `backup-portability-native.serial.test.ts` checks real restore, fresh-process reopen, failure preservation and platform-native access controls with an independent read-only ACL inspector.diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.mdindex d754662579..52538ff7fd 100644--- a/docs/architecture/key-files/providers.md+++ b/docs/architecture/key-files/providers.md@@ -49,7 +49,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/model-pricing.ts` — single source of truth for paid-cloud CHAT/completion model pricing (USD per 1M tokens, input | output). `CANONICAL_PRICING` is a `provider:model`-keyed table (Anthropic Opus 5/4.8/4.7/4.6 `$5/$25`, Sonnet 4.6 `$3/$15`, Haiku 4.5 `$1/$5` both dateless + dated, plus OpenAI / Google / Together / DeepSeek panel models). Exported as `gbrain/core/model-pricing` for companion evaluators to enforce the canonical price cap. `canonicalLookup(modelId)` resolves bare (`claude-opus-4-8`), colon (`anthropic:claude-opus-4-8`), and slash (`anthropic/...`) forms — bare ids default to the `anthropic:` provider; nested OpenRouter ids (`openrouter:anthropic/...`) intentionally MISS so OpenRouter markup isn't repriced as the inner vendor; after the exact match, a case-insensitive fallback folds BOTH sides (some canonical keys carry cased model tails verbatim), safe only while no two canonical keys collide case-insensitively (pinned by the drift guard). Every other chat-pricing table is a DERIVED view of this one (NOT a hand-copied duplicate), so cross-table price drift is structurally impossible. Embeddings live separately in `embedding-pricing.ts` (different unit). Pinned by `test/model-pricing.test.ts` whose drift guard asserts each derived view equals canonical and that the cross-modal panel models are all present.-- `src/core/post-upgrade-reembed.ts` — Pure functions backing the `gbrain upgrade` chunker-bump cost prompt. `computeReembedEstimate(engine, model)` queries real SQL (`COUNT(*)` + `COALESCE(SUM(LENGTH(compiled_truth)) + SUM(LENGTH(timeline)), 0)`) on `pages WHERE chunker_version < MARKDOWN_CHUNKER_VERSION`. `formatReembedPrompt(est, graceSeconds)` is the stderr-line formatter. `runPostUpgradeReembedPrompt(engine, model, opts)` orchestrates the 10-second Ctrl-C window; TTY-only wait (non-TTY auto-proceeds for CI / cron); `GBRAIN_NO_REEMBED=1` bails with a doctor-warning marker; `GBRAIN_REEMBED_GRACE_SECONDS=0` skips the wait.+- `src/core/post-upgrade-reembed.ts` — Pure functions backing the `gbrain upgrade` chunker-bump cost prompt. `computeReembedEstimate(engine, model)` queries real SQL (`COUNT(*)` + `COALESCE(SUM(LENGTH(compiled_truth)) + SUM(LENGTH(timeline)), 0)`) on `pages WHERE chunker_version < MARKDOWN_CHUNKER_VERSION`. `formatReembedPrompt(est)` is the stderr-line formatter (count, model, cost estimate when priced). `runPostUpgradeReembedPrompt(engine, model, opts)` re-embeds only on consent: a TTY operator must answer `y` to `[chunker-bump] Re-embed now? [y/N]`; the default, EOF and every non-TTY run decline and print `REEMBED_DEFERRED_HINT` (`gbrain reindex --markdown`, or `gbrain repair safe-chunks --apply --no-embed` then `gbrain embed --stale`), so an unattended upgrade never spends. Reasons: `no_pending`, `bypassed_no_reembed`, `consent_required`, `tty_declined`, `tty_consented`. `GBRAIN_NO_REEMBED=1` skips the prompt with a doctor-warning marker. `opts.confirm` and `opts.isTTY` are test seams.- `src/core/schema-embedded.generated.ts` — AUTO-GENERATED from schema.sql by `scripts/build-schema.ts` (run `bun run build:schema`, which also regenerates schema.sql's fragment regions and the PGLite template `src/core/pglite-schema.generated.ts`, exposed through the `src/core/pglite-schema.ts` façade; canonical-source graph in `docs/ENGINES.md#canonical-schema-sources`; the `.generated.ts` suffix exempts it from the module-size ratchet's new-file cap, per the guard's generated-file carve-out)diff --git a/docs/architecture/key-files/schema-mutation.md b/docs/architecture/key-files/schema-mutation.mdindex afcc9fb5e6..4c9f4b69bc 100644--- a/docs/architecture/key-files/schema-mutation.md+++ b/docs/architecture/key-files/schema-mutation.md@@ -7,7 +7,7 @@ stats/sync data plane + CLI verbs + MCP ops + a first-class agent skill.Key files:- `src/core/persistence/staging.ts` — journaled same-directory staging descriptors reserve names, expected sizes and full hashes before any sink. Owner-locked recovery removes only known complete regular files; partial/unexpected bytes keep the root and recovery quota blocked, including committed receipt cleanup. Legacy records acquire durable staging descriptors before any new restoration. Final accounting requires verified absence and parent-directory durability. A regular-file ancestor proves an uncreated staging leaf is absent; recovery flushes the containing directory and settles the storage failure without deleting that ancestor or retaining a false recovery fence. Tests: `atomic-write.test.ts`, `persistence-staging.test.ts`, and eight-boundary process-crash harness.-- `src/core/atomic-write.ts` — the shared atomic file writer for brain-repo markdown writers: unique tmp sibling (`.tmp.<pid>.<rand>`) → write loop until every byte lands (writeSync may legally short-write under disk pressure; a silent short write could atomically install truncated content) → fsync → close → synchronous staging boundary → optional `verify(onDiskBytes)` callback (throw = abort, tmp removed, target untouched) → mode-preserving atomic rename → best-effort parent-directory fsync (rename durability). Consumed by `src/commands/backlinks.ts` (which verifies with `parseMarkdown({validate:true})` before the rename). Rename prevents torn writes, NOT lost updates — read-modify-write callers pair it with `withPageLock` (backlinks does). Unifying the per-module copies (skillopt/apply-edits, write-through, lint) is a filed TODO.+- `src/core/atomic-write.ts` — the shared atomic file writer for brain-repo markdown writers: unique tmp sibling (`.tmp.<pid>.<rand>`) → write loop until every byte lands (writeSync may legally short-write under disk pressure; a silent short write could atomically install truncated content) → fsync → close → synchronous staging boundary → optional `verify(onDiskBytes)` callback (throw = abort, tmp removed, target untouched) → atomic rename → best-effort parent-directory fsync (rename durability). The stage is opened with its final mode and `fchmod`-ed on the descriptor past the umask before any byte is written: `AtomicWriteOpts.mode` sets exact bits and reasserts them over an existing target's mode (a legacy 0644 file tightens on its next write); omitted, the target's existing mode is preserved, else 0644 & ~umask. `mkdirPrivate(dir, root = dir)` creates gbrain-private directories: a missing `root` gets default-permission ancestors and is itself made exactly 0700, each missing directory between `root` and `dir` is created 0700 (`O_NOFOLLOW` fchmod), and a directory that already exists, possibly one the user chose, is never chmod-ed; `dir` outside `root` throws. Consumers of the private modes: the Google connector (`google-source.ts`, `sources-ops.ts` Google add) and the persistence coordinator's Google publication. Consumed by `src/commands/backlinks.ts` (which verifies with `parseMarkdown({validate:true})` before the rename). Rename prevents torn writes, NOT lost updates — read-modify-write callers pair it with `withPageLock` (backlinks does). Unifying the per-module copies (skillopt/apply-edits, write-through, lint) is a filed TODO.- `src/core/schema-pack/pack-lock.ts` — Atomic `O_CREAT|O_EXCL` per-pack lock. DELIBERATELY NOT the `existsSync + writeFileSync` TOCTOU shape from `src/core/page-lock.ts`. Default 60s TTL, refresh every 10s while `withPackLock(fn)` runs, `--force` semantics = "steal stale lock" NOT "skip locking." Lock path per-pack so two packs never block each other.- `src/core/schema-pack/write-vocabulary.ts` — write-time pack-vocabulary enforcement shared by the write surfaces (capture op, `add_link` op, `gbrain capture` CLI). `loadActivePackForWriteVocabulary(ctx)` pairs the engine's DB-plane `schema_pack` key with FILE-ONLY config (the `loadActivePackForLocalEngine` posture) while threading `remote` (fail-closed: anything not strictly false is remote) + `sourceId`; NEVER throws — null means "no resolvable pack", which callers MUST treat as "no vocabulary to enforce" (the write proceeds exactly as before). `packDeclaresPageType`/`packDeclaresLinkType` + message/suggestion formatters reject an EXPLICIT undeclared name with the pack's declared vocabulary in the error so agents self-correct without a `gbrain schema explain` round-trip. The DEFAULT `note` path is never checked here — callers validate EXPLICIT names only, so bare `gbrain capture` works under a pack that doesn't declare `note`. `loadActivePackForWriteVocabulary` also swallows a rejecting `getConfig`; `previewNames` bounds the vocabulary preview in the error (the first 12 names + `(N total)`). Pinned by `test/write-vocabulary.test.ts`.- `src/core/schema-pack/mutate-audit.ts` — ISO-week JSONL at `~/.gbrain/audit/schema-mutations-YYYY-Www.jsonl`. Privacy-redacted: type names → sha8, prefixes → first slug segment only, matches `candidate-audit.ts` privacy posture. Logs BOTH success AND failure events so a future `schema_pack_writability` doctor check has signal. `summarizeMutations()` is the cross-surface parity primitive.diff --git a/docs/evidence-delivery.md b/docs/evidence-delivery.mdindex 8f764fc905..04d6bc82df 100644--- a/docs/evidence-delivery.md+++ b/docs/evidence-delivery.md@@ -239,8 +239,12 @@ warning naming the minimum server version.sanitized WHOLE before any slicing with the same strict boundary the chunkeruses (Takes fences removed, only world and not-withdrawn Facts rows kept,malformed or unterminated protected tails dropped, materialized markers- stripped), `compiled_truth` and `timeline` each sanitized whole. This applies- to every caller, including trusted local ones. Chunks only anchor the hits in+ stripped), `compiled_truth` and `timeline` each sanitized whole, then run+ through the credential-safe projection the chunkers also cut from: every+ private-key span (complete, or cut off at its `BEGIN` or `END` line) becomes+ `<REDACTED:private_key_pem>` followed by as many newlines as the span held,+ so line positions and chunk anchors stay aligned and no key material is+ delivered. This applies to every caller, including trusted local ones. Chunks only anchor the hits inthat text, and the page must hold a sealed chunk index. Delivered text nevercontains anything `get_page` would not return to the same caller.`detail: "low"` never adds timeline text.@@ -260,10 +264,14 @@ warning naming the minimum server version.chunks never contribute neighbor text.2. **Fetch.** One query returns each page's authorization, seal, stored bodyand the chunks within ±`return_window` of each hit (at most 1,024 rows).-3. **Page text and anchors.** The page text is `sanitize(compiled_truth)`,- plus `\n\n<!-- timeline -->\n\n` + `sanitize(timeline)` when the+3. **Page text and anchors.** The page text is+ `project(sanitize(compiled_truth))`, plus `\n\n<!-- timeline -->\n\n` ++ `project(sanitize(timeline))` when thetimeline is non-empty after sanitizing and `detail` is not `low` (the join- `serializeMarkdown` writes). Each fetched chunk is located in that text in+ `serializeMarkdown` writes); `project` is `credentialSafeProjection`+ (`src/core/credential-projection.ts`), the function the markdown and code+ chunkers apply before splitting, so chunks and page text agree on every+ redacted key. Each fetched chunk is located in that text in`chunk_index` order: exact match first, then a whitespace-insensitive match(the chunker trims chunks and folds some whitespace-only runs, so chunk textis not always verbatim). A fenced-code hit is placed by its code without thediff --git a/docs/guides/data-ingestion.md b/docs/guides/data-ingestion.mdindex c8fcc326c5..a653845a64 100644--- a/docs/guides/data-ingestion.md+++ b/docs/guides/data-ingestion.md@@ -15,6 +15,17 @@ Page writes return durable receipts. Replacements require the revision you read**Ambient memory writeback (opt-in, personal brains).** Stop having to say "remember this": once enabled, your agents save durable facts you state in passing — preferences, decisions, commitments — with provenance, and transient facts (a cold, a trip) expire when saved with an explicit TTL. Off by default; on a personal brain gbrain asks you once at init/upgrade; company brains are never nudged. **Say to your agent:** *"Turn on ambient memory writeback"* — your agent runs `gbrain config set memory.auto_writeback salient` and `gbrain bootstrap harness --yes`. Full mechanics, privacy posture, and per-harness limitations: [`docs/guides/ambient-writeback.md`](ambient-writeback.md).+**Credentials you save stay in the brain, but retrieval withholds them.** What+you capture or `remember` is stored as written. When a search, query or memory+read returns text containing a credential-shaped value (an API key, a password+assignment, a URL with a password, a private key), the value comes back as+`<REDACTED:pattern>`. A credential you ask the brain to remember is withheld+from remote recall by design: every MCP caller, including stdio MCP, and a+thin-client install count as remote. On the brain host, `gbrain recall` shows+remembered facts as written. Full page reads (`get_page`) are not redacted;+they follow page visibility. Details and the full list of what stays raw:+[secret scan refusals and redaction](write-refusals.md#secret-scan-refusals-and-redaction).+For webhook ingestion (Zapier / IFTTT / Apple Shortcuts):```bash@@ -52,8 +63,10 @@ parses agent session logs (Claude Code, Codex, OpenClaw, Hermes, Grok Build) andconsumer chat exports (ChatGPT / Claude.ai `conversations.json`) into readableconversation pages with provenance back to the exact session file. Pattern-based redaction runs over message bodies, titles, speakers, and sessionmetadata before anything is written — vendor key prefixes, JWTs, cloud/API key-shapes, `Bearer` headers, connection-string credentials, and high-entropy-`KEY=`/`TOKEN=` assignments become `<REDACTED:…>` placeholders (preview with+shapes, `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`--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 defaultdiff --git a/docs/guides/google-connect.md b/docs/guides/google-connect.mdindex a8f42dec5a..5fb23d9b67 100644--- a/docs/guides/google-connect.md+++ b/docs/guides/google-connect.md@@ -302,6 +302,8 @@ upstream failures rather than triggering a full re-list.- Tokens: local vault only, 0600, atomic writes. `sources.config` stores anaccount *pointer*, never a secret. `gbrain creds list` is always redacted.+- Mail, calendar and contact pages and the sync state: 0600 files in 0700+ directories gbrain creates. See [File permissions](#file-permissions).- Disconnect: `gbrain google disconnect <email>` removes local tokens; revokeGoogle-side at <https://myaccount.google.com/permissions>.- Upgrade/transfer: `gbrain creds export` produces a passphrase-encrypted@@ -312,6 +314,103 @@ upstream failures rather than triggering a full re-list.`gbrain config set loops.extraction_enabled false`. The deterministicunanswered-thread detector is free and always on.+## File permissions++A Google source keeps its files in one directory: by default+`~/.gbrain/clones/<source-id>-google`, or the directory you passed with+`gbrain sources add <id> --kind google --account <email> --dir <path>`. gbrain+writes these files there:++- `.google-source.json`, the sync cursors (and `.google-source.json.corrupt`+ if a damaged state file was set aside),+- one Markdown page per email thread under `emails/`, per event under+ `calendar/` and per contact under `people/`.++Each of those files is written with mode 0600 (readable only by you).+Directories gbrain creates for the source, including the source directory+itself when it does not exist yet, are created 0700. A directory that+already exists, such as one you chose with `--dir`, is never chmod-ed. The+same modes apply when managed persistence publishes the pages. On Windows+gbrain does not set modes.++**gbrain enforces 0600.** Every time gbrain rewrites one of these files it+sets 0600 again, so a looser mode you set by hand (for example+`chmod 644` to share a page with a group) is reverted on the next rewrite.+Pages that did not change are not rewritten and keep whatever mode they have.+This is deliberate: the pages are your private mail, calendar and contacts,+and a page that quietly stays group-readable after a sync is the failure+this rule prevents. There is no per-source setting for a looser mode yet.++### Files written before v0.60.31.0++Older releases wrote these files with your umask, typically 0644 (readable by+every local user), and an upgrade does not rewrite them. In the default+directory that is harmless, because gbrain keeps `~/.gbrain` at 0700. In a+custom `--dir` outside `~/.gbrain`, older pages stay readable by other local+users until they are rewritten.++The upgrade prints a one-time notice for each Google source outside+`~/.gbrain`, naming the directory, how many readable entries it found and+the repair commands. `gbrain doctor` checks the same thing on every run:++```text+ [WARN] google_file_modes: Google source gmail-you: 412 file(s) and 9 directories gbrain wrote under /data/mail are readable by other local users (written before this release). Preview: gbrain repair google-file-modes --source gmail-you — apply after the user agrees: gbrain repair google-file-modes --source gmail-you --apply+```++The check reports counts per directory, never file names (Gmail page names+contain subject words). `gbrain doctor --json` carries `source_id`, `dir`,+`loose_files`, `loose_dirs` and both commands under `details.sources`.++**Fix it with gbrain (recommended):**++```bash+gbrain repair google-file-modes --source <id> # preview: counts and up to 10 sample paths+gbrain repair google-file-modes --source <id> --apply # clear group and other permission bits+```++The repair only touches gbrain's own layout: `.google-source.json*`, the+pages gbrain recorded for that source under `emails/`, `calendar/` and+`people/` (and their leftover `.tmp` files), and the directories between the+source directory and those pages. It clears the group and other bits and+keeps your own. It never changes the source directory itself, never follows+a symlink, and skips files owned by another user (counted as residuals).+Without `--source` it covers every Google source outside `~/.gbrain`. The+preview's sample paths are relative to the source directory, so they can+show subject words; run it on the brain host. See+[`gbrain repair`](repair.md#what-each-kind-fixes).++**Or fix it with chmod.** If the directory holds only this source:++```bash+chmod -R go-rwx /path/to/google/dir+```++If the directory also holds other files you want to keep shared, limit the+change to gbrain's files:++```bash+DIR=/path/to/google/dir+chmod go-rwx "$DIR"/.google-source.json*+chmod -R go-rwx "$DIR"/emails "$DIR"/calendar "$DIR"/people+```++**Verify:**++```bash+find /path/to/google/dir \( -perm -040 -o -perm -004 \) -print | head # prints nothing+gbrain doctor # [OK] google_file_modes+```++### Related messages++- `[google] could not secure the quarantined state file <path>: <chmod|rename> failed (<error>). It may be readable by other local users; run chmod 600 <path> or delete it.`+ A damaged state file was set aside, but gbrain could not make the copy+ private. The sync continues from empty cursors. Run the printed `chmod` or+ delete the file.+- `Stale temporary path <path>.tmp is a directory; remove it and re-run the sync.`+ A directory sits where gbrain writes a page's temporary file. That item+ fails until you remove the directory.+## For agents ([SHOW USER] protocol)Every `gbrain google`/`creds`/`waiting` command supports `--json` and emitsdiff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 4944406117..0cdfbe16e5 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -3,10 +3,12 @@`gbrain doctor` finds some damage that it cannot fix on its own: timelinehistory that exists only in the database, derived pages without an explicitvisibility, pages indexed before the safe-chunk fence, pages imported-without a contextual retrieval mode, and connector checkpoint rows no source-can load. `gbrain repair` fixes those five kinds. Every run is a preview-unless you pass `--apply`.-Two explicit-only kinds, `stale-atoms` and `extractor-facts`, run only when+without a contextual retrieval mode, connector checkpoint rows no source+can load, and Google source files other local users can read. `gbrain repair`+fixes those and the other kinds listed in+[What each kind fixes](#what-each-kind-fixes). Every run is a preview unless+you pass `--apply`.+Three explicit-only kinds, `google-file-modes`, `stale-atoms` and `extractor-facts`, run only whenyou name them (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).`gbrain doctor --remediation-plan` lists the same kinds as repair steps, and`gbrain doctor --remediate --yes --include-repairs` runs them under a budget@@ -62,6 +64,7 @@ gbrain repair safe-chunks --applygbrain repair safe-chunks --apply --no-embed # re-seal text now, embed latergbrain repair contextual-mode --applygbrain repair request-indexes --apply+gbrain repair google-file-modes --apply # explicit-only: runs only when namedgbrain repair --all --apply # every automatic kind in order```@@ -72,7 +75,7 @@ refused run changes nothing. To cap paid embedding work, run the repairsthrough `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. `--all`runs `timeline`, then `visibility`, then `safe-chunks`, then `contextual-mode`, then `connector-checkpoints`, then `request-indexes`, then `connector-fences`, then `orphan-bindings`, then `embedding-effects`, and stops at thefirst kind that stops.-The explicit-only kinds (`stale-atoms`, `extractor-facts`) never run under+The explicit-only kinds (`google-file-modes`, `stale-atoms`, `extractor-facts`) never run under`--all`; it lists each with its preview command and still exits 0 when theyare the only findings left. `gbrain repair` with no kind does the same for apreview. With `--json` the list is `explicit_kinds[]` (`kind`, `code:@@ -117,8 +120,8 @@ should also check `results[].complete`.| `embedding-effects` | `stale_embedding_effects` | Settles stale queued and failed embedding effects of committed writes, which block receipt compaction and activation: `reconciled` when current vectors pass the effect verifier, `superseded` when the page was deleted or a newer revision owns its own effect, `retry_queued` for the owner (paid; a used-up retry allowance gets one new bounded cycle per explicit apply). See [stale queued embedding effects](#stale-queued-embedding-effects). | `blocked` effects, counted by reason (`owner_unavailable`, `embedding_disabled`, `embedding_unconfigured`, `projection_pending`, `no_replacement_obligation`). || `safe-chunks` | `safe_index_pending` (also `contextual_retrieval_coverage`, `details.unsealed_pages`) | Rebuilds the chunks of markdown and code pages indexed before the safe-chunk fence, which remote and MCP search withhold. It rebuilds projections only: no page write, no new page version and no request ID. Vectors whose embedding input did not change are kept; the rest are embedded unless you pass `--no-embed` or no embedding model is configured. | `code_without_source_path`: code pages with no recorded file to re-chunk. `unsupported_page_kind`: other page kinds, such as images. Their importer re-seals them. || `contextual-mode` | `contextual_retrieval_coverage` (pages with no recorded mode) | Stamps the contextual retrieval mode on markdown pages imported without one (for example by a large `--no-embed` sync or a connector source before this release), exactly as a fresh import of the page would: the page, source and brain settings decide, and the per-chunk synopsis tier lands at the free title tier. It rebuilds projections only: no page write, no new page version and no request ID. A page whose stored vectors already match the stamped convention keeps them and queues no re-embedding; a page whose embedding input changes has only those vectors cleared and is re-embedded once, unless you pass `--no-embed`. | `unsealed_projection`: pages whose chunks lag their text; `gbrain embed --stale` or `safe-chunks` seals them first, and the next run stamps them. `embed_skip`: pages marked to skip embedding keep their stored vectors and are not stamped. |-| `stale-atoms` (explicit-only) | `atom_provenance_drift` | Retires, by soft delete, live page-bound atoms whose source page is gone (`origin_gone`), or whose source page was edited and its current text already extracted (`origin_changed`). Preview-bound: `--apply --expect <hash>` retires exactly the previewed set. See [Stale atoms](#stale-atoms). | Atoms with `imported_from`, transcript (file-bound) atoms, and atoms of an edited page that was not extracted again yet (the `extract_atoms` backlog). |-| `extractor-facts` (explicit-only) | `extractor_facts_expired` | Restores conversation-extractor facts the pre-v0.60.11.0 canonical projection expired (#5731). Restores `evidenced` facts by default, `ambiguous` ones only with `--include-ambiguous`; database-only. See [Extractor facts](#extractor-facts). | `excluded:<reason>` facts: page missing or deleted, superseded, withdrawn, an active duplicate, or a duplicate candidate. |+gbrain repair google-file-modes --apply # explicit-only: runs only when named+gbrain repair --all --apply # every automatic kind in orderTimeline rows that an earlier version of a page produced and its current textno longer has are removals, not history, so `timeline` neither counts nor@@ -570,6 +573,7 @@ walk me through it before changing anything."*| Doctor `persistence_request_growth` warns | #5751, #5762 | `gbrain doctor --json` | the printed `gbrain config set persistence.limits.<limit> <value>` | `gbrain doctor --json` (check `persistence_request_growth`) || Working-tree sync prints `legacy file(s) skipped … no contextual retrieval mode` | #5751 | `gbrain repair contextual-mode` | `gbrain repair contextual-mode --apply` | the next `gbrain sync --working-tree` no longer prints the line || Working-tree sync prints `legacy file(s) skipped … not valid UTF-8` | #5751 | `find <checkout> -name '*.md' ! -exec iconv -f UTF-8 -t UTF-8 -o /dev/null {} \; -print` | re-save each listed file as UTF-8 | the next `gbrain sync --working-tree` no longer prints the line |+| Doctor `google_file_modes` warns, or the upgrade printed `[google] Google source <id> keeps its files in <dir>, outside ~/.gbrain` | #5080 | `gbrain repair google-file-modes --source <id>` | `gbrain repair google-file-modes --source <id> --apply` | `gbrain doctor` (`google_file_modes` ok) |Hosted and thin-client callers see the same checks in `gbrain remote doctor`as one line each, for example@@ -745,9 +749,11 @@ Each heading below is the `docs` anchor a refusal carries.### Explicit-only repair kinds-`stale-atoms` and `extractor-facts` run only when named:-`gbrain repair <kind>` previews, and `gbrain repair <kind> --apply --expect <hash>`-applies exactly the previewed set. They are excluded everywhere else:+`google-file-modes`, `stale-atoms` and `extractor-facts` run only when named:+`gbrain repair <kind>` previews, and `gbrain repair <kind> --apply` applies+(`stale-atoms` and `extractor-facts` also need `--expect <hash>`, so they apply+exactly the previewed set; `google-file-modes` re-checks each file's owner,+type and mode at apply time). They are excluded everywhere else:- `gbrain repair --all` (and `gbrain repair` with no kind) lists each with itspreview command (`--json`: `explicit_kinds[]`) and never runs it. Adiff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 49e2b09b89..50b9f037e7 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -151,6 +151,196 @@ after binding it warns, because those pages sit outside the canonical files.There is no command yet that turns them into files; to move one, save itscontent under a new slug and delete the database-only page.+## Secret scan refusals and redaction++GBrain runs one secret scanner in several places. Depending on where a+credential-shaped value turns up, it blocks a push, leaves an entry out of+compiled context, skips a relay, or is replaced in output with a+`<REDACTED:pattern>` token (for example `<REDACTED:url_credentials>`). The+stored page never changes: redaction applies to what a caller receives, not+to your files or database.++| Where | What happens | What to do |+| --- | --- | --- |+| `gbrain sources push` | Refused with `blocked_secrets`, exit code 5. Nothing is committed; the index is reset to `HEAD` and files on disk are untouched. | Remove a real credential and rotate it. Allowlist only a reviewed false positive (below). |+| `gbrain bootstrap verify`, `gbrain bootstrap repo` | The secret-scan check fails, or the first push stops before anything is committed or pushed. Each finding shows its file, line, pattern, fingerprint and the version that added the rule. | Same as push. |+| Compiled context (`gbrain compile-context`) | The entry is left out. One line on stderr names the page, the pattern and the fingerprint, never the value. | Remove the value from the page, or allowlist a reviewed false positive. |+| Memory relay at compaction | The receipt and relay are skipped for that compaction window only; the checkpoint is kept. A content-free line (`reason: secret_scan_refused`, pattern, fingerprint, hint) goes to `~/.gbrain/integrations/hooks/heartbeat.jsonl`. | Nothing to run; the next window is scanned again. Remove the value from the transcript source if it keeps recurring. |+| Retrieval output | The value is replaced with `<REDACTED:pattern>`; everything else in the result is unchanged. | Nothing. Read the page on the brain host if you need the value (see what stays raw below). |+| Page reads | Not redacted. | See [what stays raw by design](#what-stays-raw-by-design). |+| Configured providers | Not redacted yet. | See [what stays raw by design](#what-stays-raw-by-design). |++An allowlist entry stops pushes and compiled context from refusing a+finding. It does not turn off retrieval redaction: search and recall still+replace an allowlisted value.++### Shapes this scanner catches++Vendor key prefixes (OpenAI, Anthropic, Voyage, GitHub, GitLab, Slack, AWS, Google,+Stripe, SendGrid, Twilio, Supabase, npm, Hugging Face, DigitalOcean, gbrain+tokens), JWTs, `Bearer` tokens, private keys, database URLs carrying a+password, `http(s)` URLs carrying a password (`url_credentials`) and+`Authorization: Basic` credentials (`basic_auth`). A private key is caught+even when a snippet or chunk cut off its `BEGIN` or `END` line: the key body+lines are redacted along with whichever fence is present.++Search chunks never hold key material. A page whose text contains a private+key is chunked from a copy in which each key is replaced by+`<REDACTED:private_key_pem>` (line breaks kept, so positions do not shift),+and evidence delivery cuts `window`, `section` and `page` text from the same+copy. A chunk from the middle of a long key, with neither its `BEGIN` nor+its `END` line, therefore carries the token instead of key lines, and key+material never reaches the embedding provider. The stored page is unchanged.+Pages indexed before v0.60.31.0 that contain a `BEGIN` or `END … PRIVATE+KEY` line are withheld from search until the upgrade re-chunks them, without+provider calls; `gbrain doctor` reports them as `credential_projection_pending`+until then, and `gbrain embed --stale` embeds the new chunks when you choose+to. Key material with no `BEGIN` or `END` line anywhere on the page, and keys+inside image OCR text, are not projected.++Retrieval output, transcript import, hooks and the memory relay also run the+assignment rule (`high_entropy_assignment`): a value of 12 or more characters+with at least one digit and enough randomness, assigned to a key such as+`password`, `token`, `secret` or `api_key`. Pushes and compiled context do+not run that rule, so a plain `DB_PASSWORD=...` line never blocks a push.++Placeholder passwords in URLs are skipped: `<password>`, `${VAR}`, `$VAR`,+and all-`*` or all-`x` masks. A URL with a user and no password, and paths+that only contain `@` (`https://registry.example/@scope/pkg`), are not+credentials.++### When a push is refused++```text+PUSH BLOCKED — secret scan findings (nothing committed):+ notes/deploy.md:12 [url_credentials] clone <REDACTED:url_credentials>git.example.com/team/repo.git+ fingerprint: sha256:<16 hex characters>+ rule [url_credentials] blocks pushes since gbrain v0.60.31.0+ allow this finding: printf '\n%s\n' sha256:<16 hex characters> >> '/home/you/brain/.gbrain-scan-allow'+Remove a real credential from the file (and rotate it) first. Allowlist only a reviewed false positive+with the "allow this finding" command above (it appends to '/home/you/brain/.gbrain-scan-allow'), then retry:+ gbrain sources push --path '/home/you/brain'+Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/write-refusals.md#secret-scan-refusals-and-redaction+```++Each finding carries:++- **fingerprint**: `sha256:` plus the first 16 hex characters of the+ value's hash. It identifies the value without revealing it.+- **rule ... since**: the gbrain version that added or changed the rule,+ shown for rules this release added or changed (`url_credentials`,+ `basic_auth`, `digitalocean` and private keys whose `BEGIN` or `END` line+ is missing). A push that worked before an upgrade and fails after it names+ the version here.+- **allow this finding**: the exact command that appends the fingerprint to+ the `.gbrain-scan-allow` file at the repository root. The path is absolute+ and quoted, so the command works from any directory.+- **retry**: the push command to run again, with the same `--path`,+ `--branch` and `--allow-unverified-remote` you used.++`gbrain sources push --json` returns the same data in `findings[]`, one+object per finding with `file`, `line`, `pattern`, `redactedPreview`,+`fingerprint`, `since`, `allowlistPath`, `allowCommand`, `retryCommand`,+`docs` and, when it applies, `staleAllowlistEntry`. The `reason` field+stays a one-line summary of at most 140 characters (count, first location,+pattern), so hook and doctor surfaces show it whole.++### Allowlisting a reviewed false positive++First decide whether the value is a real credential. If it is, remove it+from the file, rotate it with the provider, and push again; allowlisting a+real credential publishes it.++If it is not (a sample value in documentation, a test fixture), run the+"allow this finding" command from the refusal, review the change to+`.gbrain-scan-allow`, then run the retry command. The file holds one entry+per line: a fingerprint (`sha256:` and at least 16 hex characters) or a path+glob (a glob without `/` matches a file name at any depth; one with `/` is+anchored at the repository root), with `#` comments. Commit the file so+other machines push the same tree.++Prefer a fingerprint over a glob. A glob skips the scan for every file it+matches, including credentials added later.++### A stale allowlist entry for a private key++Before v0.60.31.0, a private key whose `END` line was missing (a cut-off+excerpt) was matched by its `BEGIN` line alone, and its fingerprint covered+only that line. The fingerprint now covers the key body too, so an old entry+for such a key no longer matches and the push is refused again. The refusal+says so and gives the replacement:++```text+ stale allowlist entry: sha256:<old> matched only this key's BEGIN header before gbrain v0.60.31.0; the fingerprint now covers the key body.+ if the key is a reviewed false positive, replace that line in '/home/you/brain/.gbrain-scan-allow' with: sha256:<new>+```++Replace the old line only if the key is a reviewed false positive. A cut-off+key's fingerprint depends on where the text was cut, so an entry for a+truncated key is not stable: if the excerpt changes, the fingerprint+changes and the push is refused again. For sample keys in documentation,+show a placeholder instead of key material.++### Redaction in retrieval output++Every operation that returns retrieved text redacts it before any caller+sees it: `search`, `query`, evidence delivery, `recall`, `context_pack`,+`delta`, `entity`, `synthesize`, `think`, takes, timelines, transcripts and+the other retrieval operations. The same pass applies on the CLI, both MCP+transports, subagent tools and `gbrain call`.++A safe way to see it, on a scratch brain with a value made up on the spot:++```bash+export GBRAIN_HOME="$(mktemp -d)"+gbrain init --pglite --no-embedding+PW="Gx7$(openssl rand -hex 12)"+gbrain capture --stdin <<EOF+Deploy notes for the scratch redaction check.+clone https://deploy:${PW}@git.example.com/team/repo.git+staging DB_PASSWORD="${PW}#x"+EOF+gbrain search "scratch redaction check" --json | grep chunk_text+```++Expected (one line, shown wrapped):++```text+"chunk_text": "# Deploy notes for the scratch redaction check.\n\nDeploy notes for the scratch redaction check.\n+clone <REDACTED:url_credentials>git.example.com/team/repo.git\nstaging DB_PASSWORD=\"<REDACTED:high_entropy_assignment>\"",+```++The host and path stay; only the user and password are replaced. IDs and+slugs are never redacted, so do not put secrets in page slugs.++Remembered facts are the one per-caller difference. The `fact`, `context`+and `source` fields of `recall`, `context_pack` and `delta` are redacted+for remote callers and returned raw to the trusted local CLI on the brain+host, so a credential you asked the brain to remember is readable with+`gbrain recall` there. Every MCP caller, including stdio MCP, and a thin+client connected over MCP count as remote. Search results, rendered `text`+and entity cards are redacted for every caller.++When an agent sees `<REDACTED:pattern>`, the brain holds a value of that+shape and withheld it. The agent should tell the user that, name the+pattern, and point to the brain host for the value. It should not retry+other operations to get around it.++### What stays raw by design++- **Page reads.** `get_page`, `fetch`, `get_chunks`, `get_raw_data` and+ `get_versions` return the stored text unredacted. They are explicit+ requests for a page and are governed by page visibility, not redaction.+ Installed skill files (`get_skill`, `get_skill_asset`, the skill catalog+ operations) and admin job operations are raw too.+- **Configured providers.** The embedding provider at import, a hosted+ reranker, and `synthesize`/`think` generation still receive stored text+ unredacted, except private keys, which chunks never contain. Redaction covers what callers receive, not what gbrain sends+ to a model provider you configured.+- **Your files and database.** Redaction never edits stored content. If a+ real credential reached the brain, rotate it, then follow+ ["If a secret reached the brain"](../../SECURITY.md#if-a-secret-reached-the-brain).+## Related- [Concurrent writes and durable receipts](concurrent-writes.md) — receipt states, retries, capacity limitsdiff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.mdindex e095da89d3..e555c78c39 100644--- a/docs/protocol/MEMORY_VERBS_v1.md+++ b/docs/protocol/MEMORY_VERBS_v1.md@@ -528,6 +528,17 @@ Verbs are ordinary operations: they inherit fail-closed `remote` semantics,OAuth scope enforcement (`remember`/`forget` are write-scope), and per-sourceisolation on every read. Remote callers see `visibility = world` facts only.+Read verbs redact credential-shaped values in their responses with the+canonical secret scanner: a value becomes `<REDACTED:pattern>`. `recall`,+`context_pack` and `delta` redact the facts' `fact`, `context` and `source`+fields for remote callers (`ctx.remote !== false`; every MCP transport,+including stdio, and thin clients) and return them as stored to the trusted+local CLI, so a remembered credential is readable only with `gbrain recall` on+the brain host. Search results, the rendered `text` and `entity` cards are+redacted for every caller. Budgets, `budget_used` and the `delta` cursor are+computed from the text each caller actually receives. See+[secret scan refusals and redaction](../guides/write-refusals.md#secret-scan-refusals-and-redaction).+## Conformance + certification```bashdiff --git a/llms-full.txt b/llms-full.txtindex 586cde6e05..53d90d6a17 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -7658,6 +7658,17 @@ Verbs are ordinary operations: they inherit fail-closed `remote` semantics,OAuth scope enforcement (`remember`/`forget` are write-scope), and per-sourceisolation on every read. Remote callers see `visibility = world` facts only.+Read verbs redact credential-shaped values in their responses with the+canonical secret scanner: a value becomes `<REDACTED:pattern>`. `recall`,+`context_pack` and `delta` redact the facts' `fact`, `context` and `source`+fields for remote callers (`ctx.remote !== false`; every MCP transport,+including stdio, and thin clients) and return them as stored to the trusted+local CLI, so a remembered credential is readable only with `gbrain recall` on+the brain host. Search results, the rendered `text` and `entity` cards are+redacted for every caller. Budgets, `budget_used` and the `delta` cursor are+computed from the text each caller actually receives. See+[secret scan refusals and redaction](../guides/write-refusals.md#secret-scan-refusals-and-redaction).+## Conformance + certification```bash@@ -8635,10 +8646,12 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/rep`gbrain doctor` finds some damage that it cannot fix on its own: timelinehistory that exists only in the database, derived pages without an explicitvisibility, pages indexed before the safe-chunk fence, pages imported-without a contextual retrieval mode, and connector checkpoint rows no source-can load. `gbrain repair` fixes those five kinds. Every run is a preview-unless you pass `--apply`.-Two explicit-only kinds, `stale-atoms` and `extractor-facts`, run only when+without a contextual retrieval mode, connector checkpoint rows no source+can load, and Google source files other local users can read. `gbrain repair`+fixes those and the other kinds listed in+[What each kind fixes](#what-each-kind-fixes). Every run is a preview unless+you pass `--apply`.+Three explicit-only kinds, `google-file-modes`, `stale-atoms` and `extractor-facts`, run only whenyou name them (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).`gbrain doctor --remediation-plan` lists the same kinds as repair steps, and`gbrain doctor --remediate --yes --include-repairs` runs them under a budget@@ -8694,6 +8707,7 @@ gbrain repair safe-chunks --applygbrain repair safe-chunks --apply --no-embed # re-seal text now, embed latergbrain repair contextual-mode --applygbrain repair request-indexes --apply+gbrain repair google-file-modes --apply # explicit-only: runs only when namedgbrain repair --all --apply # every automatic kind in order```@@ -8704,7 +8718,7 @@ refused run changes nothing. To cap paid embedding work, run the repairsthrough `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. `--all`runs `timeline`, then `visibility`, then `safe-chunks`, then `contextual-mode`, then `connector-checkpoints`, then `request-indexes`, then `connector-fences`, then `orphan-bindings`, then `embedding-effects`, and stops at thefirst kind that stops.-The explicit-only kinds (`stale-atoms`, `extractor-facts`) never run under+The explicit-only kinds (`google-file-modes`, `stale-atoms`, `extractor-facts`) never run under`--all`; it lists each with its preview command and still exits 0 when theyare the only findings left. `gbrain repair` with no kind does the same for apreview. With `--json` the list is `explicit_kinds[]` (`kind`, `code:@@ -8749,8 +8763,8 @@ should also check `results[].complete`.| `embedding-effects` | `stale_embedding_effects` | Settles stale queued and failed embedding effects of committed writes, which block receipt compaction and activation: `reconciled` when current vectors pass the effect verifier, `superseded` when the page was deleted or a newer revision owns its own effect, `retry_queued` for the owner (paid; a used-up retry allowance gets one new bounded cycle per explicit apply). See [stale queued embedding effects](#stale-queued-embedding-effects). | `blocked` effects, counted by reason (`owner_unavailable`, `embedding_disabled`, `embedding_unconfigured`, `projection_pending`, `no_replacement_obligation`). || `safe-chunks` | `safe_index_pending` (also `contextual_retrieval_coverage`, `details.unsealed_pages`) | Rebuilds the chunks of markdown and code pages indexed before the safe-chunk fence, which remote and MCP search withhold. It rebuilds projections only: no page write, no new page version and no request ID. Vectors whose embedding input did not change are kept; the rest are embedded unless you pass `--no-embed` or no embedding model is configured. | `code_without_source_path`: code pages with no recorded file to re-chunk. `unsupported_page_kind`: other page kinds, such as images. Their importer re-seals them. || `contextual-mode` | `contextual_retrieval_coverage` (pages with no recorded mode) | Stamps the contextual retrieval mode on markdown pages imported without one (for example by a large `--no-embed` sync or a connector source before this release), exactly as a fresh import of the page would: the page, source and brain settings decide, and the per-chunk synopsis tier lands at the free title tier. It rebuilds projections only: no page write, no new page version and no request ID. A page whose stored vectors already match the stamped convention keeps them and queues no re-embedding; a page whose embedding input changes has only those vectors cleared and is re-embedded once, unless you pass `--no-embed`. | `unsealed_projection`: pages whose chunks lag their text; `gbrain embed --stale` or `safe-chunks` seals them first, and the next run stamps them. `embed_skip`: pages marked to skip embedding keep their stored vectors and are not stamped. |-| `stale-atoms` (explicit-only) | `atom_provenance_drift` | Retires, by soft delete, live page-bound atoms whose source page is gone (`origin_gone`), or whose source page was edited and its current text already extracted (`origin_changed`). Preview-bound: `--apply --expect <hash>` retires exactly the previewed set. See [Stale atoms](#stale-atoms). | Atoms with `imported_from`, transcript (file-bound) atoms, and atoms of an edited page that was not extracted again yet (the `extract_atoms` backlog). |-| `extractor-facts` (explicit-only) | `extractor_facts_expired` | Restores conversation-extractor facts the pre-v0.60.11.0 canonical projection expired (#5731). Restores `evidenced` facts by default, `ambiguous` ones only with `--include-ambiguous`; database-only. See [Extractor facts](#extractor-facts). | `excluded:<reason>` facts: page missing or deleted, superseded, withdrawn, an active duplicate, or a duplicate candidate. |+gbrain repair google-file-modes --apply # explicit-only: runs only when named+gbrain repair --all --apply # every automatic kind in orderTimeline rows that an earlier version of a page produced and its current textno longer has are removals, not history, so `timeline` neither counts nor@@ -9202,6 +9216,7 @@ walk me through it before changing anything."*| Doctor `persistence_request_growth` warns | #5751, #5762 | `gbrain doctor --json` | the printed `gbrain config set persistence.limits.<limit> <value>` | `gbrain doctor --json` (check `persistence_request_growth`) || Working-tree sync prints `legacy file(s) skipped … no contextual retrieval mode` | #5751 | `gbrain repair contextual-mode` | `gbrain repair contextual-mode --apply` | the next `gbrain sync --working-tree` no longer prints the line || Working-tree sync prints `legacy file(s) skipped … not valid UTF-8` | #5751 | `find <checkout> -name '*.md' ! -exec iconv -f UTF-8 -t UTF-8 -o /dev/null {} \; -print` | re-save each listed file as UTF-8 | the next `gbrain sync --working-tree` no longer prints the line |+| Doctor `google_file_modes` warns, or the upgrade printed `[google] Google source <id> keeps its files in <dir>, outside ~/.gbrain` | #5080 | `gbrain repair google-file-modes --source <id>` | `gbrain repair google-file-modes --source <id> --apply` | `gbrain doctor` (`google_file_modes` ok) |Hosted and thin-client callers see the same checks in `gbrain remote doctor`as one line each, for example@@ -9377,9 +9392,11 @@ Each heading below is the `docs` anchor a refusal carries.### Explicit-only repair kinds-`stale-atoms` and `extractor-facts` run only when named:-`gbrain repair <kind>` previews, and `gbrain repair <kind> --apply --expect <hash>`-applies exactly the previewed set. They are excluded everywhere else:+`google-file-modes`, `stale-atoms` and `extractor-facts` run only when named:+`gbrain repair <kind>` previews, and `gbrain repair <kind> --apply` applies+(`stale-atoms` and `extractor-facts` also need `--expect <hash>`, so they apply+exactly the previewed set; `google-file-modes` re-checks each file's owner,+type and mode at apply time). They are excluded everywhere else:- `gbrain repair --all` (and `gbrain repair` with no kind) lists each with itspreview command (`--json`: `explicit_kinds[]`) and never runs it. A@@ -9653,6 +9670,196 @@ after binding it warns, because those pages sit outside the canonical files.There is no command yet that turns them into files; to move one, save itscontent under a new slug and delete the database-only page.+## Secret scan refusals and redaction++GBrain runs one secret scanner in several places. Depending on where a+credential-shaped value turns up, it blocks a push, leaves an entry out of+compiled context, skips a relay, or is replaced in output with a+`<REDACTED:pattern>` token (for example `<REDACTED:url_credentials>`). The+stored page never changes: redaction applies to what a caller receives, not+to your files or database.++| Where | What happens | What to do |+| --- | --- | --- |+| `gbrain sources push` | Refused with `blocked_secrets`, exit code 5. Nothing is committed; the index is reset to `HEAD` and files on disk are untouched. | Remove a real credential and rotate it. Allowlist only a reviewed false positive (below). |+| `gbrain bootstrap verify`, `gbrain bootstrap repo` | The secret-scan check fails, or the first push stops before anything is committed or pushed. Each finding shows its file, line, pattern, fingerprint and the version that added the rule. | Same as push. |+| Compiled context (`gbrain compile-context`) | The entry is left out. One line on stderr names the page, the pattern and the fingerprint, never the value. | Remove the value from the page, or allowlist a reviewed false positive. |+| Memory relay at compaction | The receipt and relay are skipped for that compaction window only; the checkpoint is kept. A content-free line (`reason: secret_scan_refused`, pattern, fingerprint, hint) goes to `~/.gbrain/integrations/hooks/heartbeat.jsonl`. | Nothing to run; the next window is scanned again. Remove the value from the transcript source if it keeps recurring. |+| Retrieval output | The value is replaced with `<REDACTED:pattern>`; everything else in the result is unchanged. | Nothing. Read the page on the brain host if you need the value (see what stays raw below). |+| Page reads | Not redacted. | See [what stays raw by design](#what-stays-raw-by-design). |+| Configured providers | Not redacted yet. | See [what stays raw by design](#what-stays-raw-by-design). |++An allowlist entry stops pushes and compiled context from refusing a+finding. It does not turn off retrieval redaction: search and recall still+replace an allowlisted value.++### Shapes this scanner catches++Vendor key prefixes (OpenAI, Anthropic, Voyage, GitHub, GitLab, Slack, AWS, Google,+Stripe, SendGrid, Twilio, Supabase, npm, Hugging Face, DigitalOcean, gbrain+tokens), JWTs, `Bearer` tokens, private keys, database URLs carrying a+password, `http(s)` URLs carrying a password (`url_credentials`) and+`Authorization: Basic` credentials (`basic_auth`). A private key is caught+even when a snippet or chunk cut off its `BEGIN` or `END` line: the key body+lines are redacted along with whichever fence is present.++Search chunks never hold key material. A page whose text contains a private+key is chunked from a copy in which each key is replaced by+`<REDACTED:private_key_pem>` (line breaks kept, so positions do not shift),+and evidence delivery cuts `window`, `section` and `page` text from the same+copy. A chunk from the middle of a long key, with neither its `BEGIN` nor+its `END` line, therefore carries the token instead of key lines, and key+material never reaches the embedding provider. The stored page is unchanged.+Pages indexed before v0.60.31.0 that contain a `BEGIN` or `END … PRIVATE+KEY` line are withheld from search until the upgrade re-chunks them, without+provider calls; `gbrain doctor` reports them as `credential_projection_pending`+until then, and `gbrain embed --stale` embeds the new chunks when you choose+to. Key material with no `BEGIN` or `END` line anywhere on the page, and keys+inside image OCR text, are not projected.++Retrieval output, transcript import, hooks and the memory relay also run the+assignment rule (`high_entropy_assignment`): a value of 12 or more characters+with at least one digit and enough randomness, assigned to a key such as+`password`, `token`, `secret` or `api_key`. Pushes and compiled context do+not run that rule, so a plain `DB_PASSWORD=...` line never blocks a push.++Placeholder passwords in URLs are skipped: `<password>`, `${VAR}`, `$VAR`,+and all-`*` or all-`x` masks. A URL with a user and no password, and paths+that only contain `@` (`https://registry.example/@scope/pkg`), are not+credentials.++### When a push is refused++```text+PUSH BLOCKED — secret scan findings (nothing committed):+ notes/deploy.md:12 [url_credentials] clone <REDACTED:url_credentials>git.example.com/team/repo.git+ fingerprint: sha256:<16 hex characters>+ rule [url_credentials] blocks pushes since gbrain v0.60.31.0+ allow this finding: printf '\n%s\n' sha256:<16 hex characters> >> '/home/you/brain/.gbrain-scan-allow'+Remove a real credential from the file (and rotate it) first. Allowlist only a reviewed false positive+with the "allow this finding" command above (it appends to '/home/you/brain/.gbrain-scan-allow'), then retry:+ gbrain sources push --path '/home/you/brain'+Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/write-refusals.md#secret-scan-refusals-and-redaction+```++Each finding carries:++- **fingerprint**: `sha256:` plus the first 16 hex characters of the+ value's hash. It identifies the value without revealing it.+- **rule ... since**: the gbrain version that added or changed the rule,+ shown for rules this release added or changed (`url_credentials`,+ `basic_auth`, `digitalocean` and private keys whose `BEGIN` or `END` line+ is missing). A push that worked before an upgrade and fails after it names+ the version here.+- **allow this finding**: the exact command that appends the fingerprint to+ the `.gbrain-scan-allow` file at the repository root. The path is absolute+ and quoted, so the command works from any directory.+- **retry**: the push command to run again, with the same `--path`,+ `--branch` and `--allow-unverified-remote` you used.++`gbrain sources push --json` returns the same data in `findings[]`, one+object per finding with `file`, `line`, `pattern`, `redactedPreview`,+`fingerprint`, `since`, `allowlistPath`, `allowCommand`, `retryCommand`,+`docs` and, when it applies, `staleAllowlistEntry`. The `reason` field+stays a one-line summary of at most 140 characters (count, first location,+pattern), so hook and doctor surfaces show it whole.++### Allowlisting a reviewed false positive++First decide whether the value is a real credential. If it is, remove it+from the file, rotate it with the provider, and push again; allowlisting a+real credential publishes it.++If it is not (a sample value in documentation, a test fixture), run the+"allow this finding" command from the refusal, review the change to+`.gbrain-scan-allow`, then run the retry command. The file holds one entry+per line: a fingerprint (`sha256:` and at least 16 hex characters) or a path+glob (a glob without `/` matches a file name at any depth; one with `/` is+anchored at the repository root), with `#` comments. Commit the file so+other machines push the same tree.++Prefer a fingerprint over a glob. A glob skips the scan for every file it+matches, including credentials added later.++### A stale allowlist entry for a private key++Before v0.60.31.0, a private key whose `END` line was missing (a cut-off+excerpt) was matched by its `BEGIN` line alone, and its fingerprint covered+only that line. The fingerprint now covers the key body too, so an old entry+for such a key no longer matches and the push is refused again. The refusal+says so and gives the replacement:++```text+ stale allowlist entry: sha256:<old> matched only this key's BEGIN header before gbrain v0.60.31.0; the fingerprint now covers the key body.+ if the key is a reviewed false positive, replace that line in '/home/you/brain/.gbrain-scan-allow' with: sha256:<new>+```++Replace the old line only if the key is a reviewed false positive. A cut-off+key's fingerprint depends on where the text was cut, so an entry for a+truncated key is not stable: if the excerpt changes, the fingerprint+changes and the push is refused again. For sample keys in documentation,+show a placeholder instead of key material.++### Redaction in retrieval output++Every operation that returns retrieved text redacts it before any caller+sees it: `search`, `query`, evidence delivery, `recall`, `context_pack`,+`delta`, `entity`, `synthesize`, `think`, takes, timelines, transcripts and+the other retrieval operations. The same pass applies on the CLI, both MCP+transports, subagent tools and `gbrain call`.++A safe way to see it, on a scratch brain with a value made up on the spot:++```bash+export GBRAIN_HOME="$(mktemp -d)"+gbrain init --pglite --no-embedding+PW="Gx7$(openssl rand -hex 12)"+gbrain capture --stdin <<EOF+Deploy notes for the scratch redaction check.+clone https://deploy:${PW}@git.example.com/team/repo.git+staging DB_PASSWORD="${PW}#x"+EOF+gbrain search "scratch redaction check" --json | grep chunk_text+```++Expected (one line, shown wrapped):++```text+"chunk_text": "# Deploy notes for the scratch redaction check.\n\nDeploy notes for the scratch redaction check.\n+clone <REDACTED:url_credentials>git.example.com/team/repo.git\nstaging DB_PASSWORD=\"<REDACTED:high_entropy_assignment>\"",+```++The host and path stay; only the user and password are replaced. IDs and+slugs are never redacted, so do not put secrets in page slugs.++Remembered facts are the one per-caller difference. The `fact`, `context`+and `source` fields of `recall`, `context_pack` and `delta` are redacted+for remote callers and returned raw to the trusted local CLI on the brain+host, so a credential you asked the brain to remember is readable with+`gbrain recall` there. Every MCP caller, including stdio MCP, and a thin+client connected over MCP count as remote. Search results, rendered `text`+and entity cards are redacted for every caller.++When an agent sees `<REDACTED:pattern>`, the brain holds a value of that+shape and withheld it. The agent should tell the user that, name the+pattern, and point to the brain host for the value. It should not retry+other operations to get around it.++### What stays raw by design++- **Page reads.** `get_page`, `fetch`, `get_chunks`, `get_raw_data` and+ `get_versions` return the stored text unredacted. They are explicit+ requests for a page and are governed by page visibility, not redaction.+ Installed skill files (`get_skill`, `get_skill_asset`, the skill catalog+ operations) and admin job operations are raw too.+- **Configured providers.** The embedding provider at import, a hosted+ reranker, and `synthesize`/`think` generation still receive stored text+ unredacted, except private keys, which chunks never contain. Redaction covers what callers receive, not what gbrain sends+ to a model provider you configured.+- **Your files and database.** Redaction never edits stored content. If a+ real credential reached the brain, rotate it, then follow+ ["If a secret reached the brain"](../../SECURITY.md#if-a-secret-reached-the-brain).+## Related- [Concurrent writes and durable receipts](concurrent-writes.md) — receipt states, retries, capacity limitsdiff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 3690e45e48..fac8d15ed6 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.60.30.0",+ "version": "0.60.31.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","kind": "context-engine",diff --git a/package.json b/package.jsonindex cab381910c..8596f78620 100644--- a/package.json+++ b/package.json@@ -205,7 +205,7 @@"bun": ">=1.4.0"},"license": "MIT",- "version": "0.60.30.0",+ "version": "0.60.31.0","overrides": {"@ai-sdk/provider-utils": "4.0.33","@hono/node-server": "^2.0.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex 57be063171..56db4a8148 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.60.30.0",+ "version": "0.60.31.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex b3577a8e2d..f1f03bd3b0 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.60.30.0",+ "version": "0.60.31.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex f701280c2c..b05824b95b 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.30.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.31.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md b/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.mdindex 1e0f74f7dc..2f1db55404 100644--- a/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md+++ b/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md@@ -77,6 +77,17 @@ suppresses writes for that turn, including when standing capture is enabled.> connection test, use only a harmless synthetic `visibility: "world"` fixture> with the user's test authorization, retain its ID, and withdraw it afterward.>+> **`<REDACTED:pattern>` in a result** (for example `<REDACTED:url_credentials>`+> or `<REDACTED:high_entropy_assignment>`) means the brain holds a+> credential-shaped value there and withheld it from this response; the stored+> page is unchanged. Tell the user which kind of value was withheld and that it+> is readable on the brain host. Do not retry other operations to recover it,+> and do not echo a guess. A credential the user asked you to `remember` is+> withheld from remote recall by design: every MCP caller, including stdio, and+> a thin CLI connected to MCP is remote, so only `gbrain recall` run on the+> brain host shows it as written. Docs:+> `docs/guides/write-refusals.md#secret-scan-refusals-and-redaction`.+>> **Keyless brains:** when `extract_facts` returns `skipped:> extraction_unavailable`, YOU are the extractor — pull the facts from the turn> yourself and write each one via `remember` with `kind` set (event | preferencediff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex e4f0c978dd..c7f4e2b799 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.60.30.0",+ "version": "0.60.31.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex 6f3ee63f21..7ac90dc031 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.60.30.0",+ "version": "0.60.31.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex 10bda5e967..c22c77da6b 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.30.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.31.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --git a/plugin/README.md b/plugin/README.mdindex 6b239a133e..3e47117376 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.30.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.31.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/plugin/skills/brain-ops/SKILL.md b/plugin/skills/brain-ops/SKILL.mdindex 1e0f74f7dc..2f1db55404 100644--- a/plugin/skills/brain-ops/SKILL.md+++ b/plugin/skills/brain-ops/SKILL.md@@ -77,6 +77,17 @@ suppresses writes for that turn, including when standing capture is enabled.> connection test, use only a harmless synthetic `visibility: "world"` fixture> with the user's test authorization, retain its ID, and withdraw it afterward.>+> **`<REDACTED:pattern>` in a result** (for example `<REDACTED:url_credentials>`+> or `<REDACTED:high_entropy_assignment>`) means the brain holds a+> credential-shaped value there and withheld it from this response; the stored+> page is unchanged. Tell the user which kind of value was withheld and that it+> is readable on the brain host. Do not retry other operations to recover it,+> and do not echo a guess. A credential the user asked you to `remember` is+> withheld from remote recall by design: every MCP caller, including stdio, and+> a thin CLI connected to MCP is remote, so only `gbrain recall` run on the+> brain host shows it as written. Docs:+> `docs/guides/write-refusals.md#secret-scan-refusals-and-redaction`.+>> **Keyless brains:** when `extract_facts` returns `skipped:> extraction_unavailable`, YOU are the extractor — pull the facts from the turn> yourself and write each one via `remember` with `kind` set (event | preferencediff --git a/scripts/check-admin-build.sh b/scripts/check-admin-build.shindex 7a43383cdd..028faa48ae 100755--- a/scripts/check-admin-build.sh+++ b/scripts/check-admin-build.sh@@ -30,6 +30,10 @@ cd admin# Idempotent install — bun is fast enough on no-op (~50ms).bun install --silent >/dev/null 2>&1 || bun install-# Build runs `tsc -b && vite build`. Output to admin/dist/. Exit non-zero-# on TS error, missing symbol, or Vite bundling error.-bun run build+# Build runs `vite build` into a throwaway directory. Exit non-zero on TS+# error, missing symbol, or Vite bundling error. Never into the committed+# admin/dist/: vite empties its outDir first, so a parallel verify check that+# reads tracked files (check:privacy) would find them missing mid-build.+out=$(mktemp -d "${TMPDIR:-/tmp}/gbrain-admin-build.XXXXXX")+trap 'rm -rf "$out"' EXIT+bun run build --outDir "$out" --emptyOutDirdiff --git a/scripts/check-pg-url-redaction.sh b/scripts/check-pg-url-redaction.shindex 97c33a8af9..300f3d93e7 100755--- a/scripts/check-pg-url-redaction.sh+++ b/scripts/check-pg-url-redaction.sh@@ -1,9 +1,12 @@#!/usr/bin/env bash-# CI grep guard (v0.30.1, finding F3): no source file under src/ may emit-# a postgresql:// URL with userinfo to a logging surface.+# CI grep guard (v0.30.1, finding F3; widened to every db_url_credentials+# scheme per TODOS.md): no source file under src/ may emit a credential-+# bearing database URL to a logging surface.## Specifically we forbid string literals or template substitutions that-# look like `postgresql://user:pass@host` being passed to:+# look like `postgresql://user:pass@host` (or the mysql/mongodb/redis/+# amqp/mssql equivalents — the same scheme set src/core/secret-scan.ts's+# `db_url_credentials` catch-all covers) being passed to:# - console.log / .warn / .error# - process.stderr.write / process.stdout.write# - appendFileSync / writeFileSync (audit JSONL writes)@@ -26,10 +29,12 @@ ROOT=$(cd "$(dirname "$0")/.." && pwd)# block-comment examples carry the bare marker).ALLOW_REGEX='url-redact\.ts|test/url-redact\.test\.ts|allow-pg-url-literal'-# The pattern matches an unredacted Postgres URL appearing in a string-# literal, NOT preceded by `redactPgUrl(` or `***@`. We also match any-# URL containing `[^*]@` (i.e. the `***@` redacted form passes).-PATTERN='postgres(ql)?://[^@*"`]+@'+# The pattern matches an unredacted, credential-bearing database URL+# appearing in a string literal, NOT preceded by `redactPgUrl(`/+# `redactUrlsInText(` or `***@`. We also match any URL containing `[^*]@`+# (i.e. the `***@` redacted form passes). Scheme set mirrors+# db_url_credentials in src/core/secret-scan.ts.+PATTERN='(postgres(ql)?|mysql|mongodb(\+srv)?|redis|rediss|amqp|mssql)://[^@*"`]+@'# Search src/ only — tests are excluded since they intentionally construct# unredacted URLs as input fixtures.@@ -46,7 +51,7 @@ if [ -z "$FILTERED" ]; thenexit 0fi-echo "ERROR: unredacted postgres:// URL found in source. Use redactPgUrl() before logging."+echo "ERROR: unredacted database URL found in source. Use redactPgUrl() / redactUrlsInText() before logging."echo ""echo "$FILTERED"echo ""diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex e9d801ce06..7d376a30e5 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -596,6 +596,13 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/repair/request-indexes.ts": ["test/e2e/persistence-request-indexes-postgres.test.ts"],"src/commands/doctor/checks/persistence-requests.ts": ["test/e2e/persistence-request-indexes-postgres.test.ts"],"src/core/schema-migrations/v179-persistence-request-sync-run-indexes.ts": ["test/e2e/persistence-request-indexes-postgres.test.ts"],+ // Security wave ENG-1/ENG-2: credential-safe projection and the existing-brain re-chunk.+ "src/core/credential-projection.ts": ["test/e2e/credential-projection-repair.test.ts"],+ "src/core/page-state/credential-reseal.ts": ["test/e2e/credential-projection-repair.test.ts"],+ "src/core/schema-migrations/v189-pages-credential-projection-pending.ts": ["test/e2e/credential-projection-repair.test.ts"],+ "src/commands/migrations/v0_60_31.ts": ["test/e2e/credential-projection-repair.test.ts"],+ "src/commands/doctor/checks/credential-projection.ts": ["test/e2e/credential-projection-repair.test.ts"],+ "src/core/search/two-pass.ts": ["test/e2e/credential-projection-repair.test.ts"],"src/core/persistence/accepted-pending.ts": ["test/e2e/connector-wave3.test.ts"],"src/commands/google-attachments.ts": ["test/e2e/google-attachments-postgres.test.ts"],"src/core/backup/**": ["test/e2e/backup-coverage-parity.test.ts"],diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 3bf44cc7c2..f18e97205a 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -19,7 +19,7 @@ src/core/cycle/extract-atoms.ts 1834 ratchet crossed the 1500 unlisted cap in thsrc/core/engine.ts 2674 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance optionsrc/core/import-file.ts 2230 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode)src/core/migrate.ts 599 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3)-src/core/operations.ts 329 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base+src/core/operations.ts 331 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registrationsrc/core/pglite-engine.ts 3225 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166)src/core/postgres-engine.ts 3252 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156)src/core/search/hybrid.ts 1584 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key@@ -39,6 +39,6 @@ src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap insrc/core/config.ts 1813 ratchet +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane mergesrc/core/bootstrap/harness.ts 2674 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts)src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option-src/core/ops/pages.ts 618 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy)+src/core/ops/pages.ts 626 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages opsrc/core/search/mode.ts 1527 ratchet +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= partsrc/commands/eval-longmemeval.ts 1518 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts)diff --git a/scripts/secret-scan-fp-budget.ts b/scripts/secret-scan-fp-budget.tsnew file mode 100644index 0000000000..b06679fb9d--- /dev/null+++ b/scripts/secret-scan-fp-budget.ts@@ -0,0 +1,334 @@+#!/usr/bin/env bun+/**+ * Secret-scan false-positive budget (security fix wave B3, CEO-8, CEO-18).+ * A measurement tool, not a test: it compares the scanner at a base git ref+ * with the working tree over the same corpus and reports the NEW hits the+ * current rules add. The CI-enforced thresholds on the synthetic fixture live+ * in test/secret-scan-fp-budget.test.ts, which imports the builder below.+ *+ * bun scripts/secret-scan-fp-budget.ts [--base origin/master] [--json]+ * bun scripts/secret-scan-fp-budget.ts --dir <brain-dir> [--base <ref>]+ *+ * Corpora: every tracked text file under src/, docs/ and skills/ (the repo+ * corpus) and the synthetic brain-like fixture (emails, invites, meeting+ * notes, agent transcripts, quoted docs, plus a secret-bearing part). Each+ * is scanned twice per scanner: `highEntropy: true` (retrieval output,+ * transcript ingest, hooks, the atoms drain, hook heartbeat, embed-facts+ * error text, the context-engine relay refusal) and `highEntropy: false`+ * (the `sources push` gate, bootstrap verify, bootstrap repo scan, corpus+ * segments, the compiled-context sensitivity scan). A hit is NEW when its+ * (pattern, fingerprint) pair is absent from the base scanner's findings for+ * the same document (multiset difference). A document is NEWLY FLAGGED when+ * the base scanner found nothing in it and the current one finds something:+ * with `highEntropy: false` that is a push newly blocked or a context entry+ * newly dropped, with `highEntropy: true` a relay newly refused.+ *+ * `--dir` is the opt-in maintainer run over a local brain: it walks the+ * markdown files under the directory and prints per-pattern counts ONLY —+ * never a path, line or any content. The repo report lists `path:line` for+ * new hits (public files) and never prints matched text either.+ */+import { execFileSync } from 'node:child_process';+import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { randomBytes } from 'node:crypto';+import * as current from '../src/core/secret-scan.ts';++interface Finding {+ pattern: string;+ line: number;+ fingerprint: string;+}++export interface Scanner {+ scanText(text: string, opts?: { highEntropy?: boolean }): Finding[];+}++export interface CorpusDoc {+ id: string;+ /** `clean`: must gain no finding. `secret`: every planted value must be redacted. */+ kind: 'clean' | 'secret';+ text: string;+ /** Secret docs: values that must not survive redaction with or without `highEntropy`. */+ secrets?: string[];+ /** Secret docs: values only the opt-in assignment rule claims (must not survive `highEntropy: true`). */+ assignmentSecrets?: string[];+}++const ALNUM = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';++function rand(n: number): string {+ const bytes = randomBytes(n);+ let s = '';+ for (let i = 0; i < n; i++) s += ALNUM[bytes[i]! % ALNUM.length];+ return s.slice(0, n - 1) + String(bytes[0]! % 10);+}++function b64Lines(count: number, last = 64): string[] {+ return Array.from({ length: count }, (_, i) =>+ randomBytes(64).toString('base64').replace(/=/g, '').slice(0, i === count - 1 ? last : 64));+}++/**+ * Synthetic, privacy-safe brain-like fixture, assembled at runtime so no+ * credential-shaped literal or userinfo URL appears in source (CEO-10).+ * Placeholder people and companies only.+ */+export function buildSyntheticBrainCorpus(): CorpusDoc[] {+ const sep = ':' + '//';+ const url = (scheme: string, rest: string) => [scheme, sep, rest].join('');+ const at = '@';+ const dashes = '-'.repeat(5);+ const marker = (word: 'BEGIN' | 'END') => [dashes, word, ' RSA PRIVATE KEY', dashes].join('');+ const clean: CorpusDoc[] = [+ {+ id: 'email-newsletter',+ kind: 'clean',+ text: [+ `From: alice-example <alice${at}acme-example.com>`,+ `To: charlie-example <charlie${at}widget-co.example>`,+ 'Subject: Pricing update for the Basic plan',+ '',+ 'Hi Charlie,',+ 'The Basic plan now includes SSO. Basic responsibilities for admins are listed here:',+ url('https', 'acme-example.com/pricing?ref=newsletter&utm_source=email&utm_campaign=q3-2026'),+ `Docs: ${url('https', 'docs.acme-example.com/auth/tokens#rotation')}`,+ 'Your password reset link expires in 24 hours. We will never ask for your password.',+ '',+ 'Thanks,',+ 'Alice',+ '--',+ 'alice-example | Head of Platform | acme-example',+ `m: +1 555 0100 | ${url('https', 'acme-example.com')} | ${url('https', 'x.example/acme-example')}`,+ `Unsubscribe: ${url('https', 'lists.acme-example.com/u/8f14e45fceea167a5a36dedd4bea2543?list=news')}`,+ 'Sent from my phone',+ ].join('\n'),+ },+ {+ id: 'calendar-invite',+ kind: 'clean',+ text: [+ 'BEGIN:VCALENDAR',+ 'SUMMARY:Weekly sync - acme-example / widget-co',+ 'DTSTART:20260115T170000Z',+ `ORGANIZER;CN=alice-example:mailto:alice${at}acme-example.com`,+ `DESCRIPTION:Join: ${url('https', 'meet.example.com/abc-defg-hij')}\\nOr by phone +1 555-0100 PIN 123 456 789#`,+ `LOCATION:${url('https', 'zoom.example/j/81234567890?pwd=Zk9sUm1QaE5vT3BxR2hYdz09')}`,+ `X-TEAMS:${url('https', 'teams.example/l/meetup-join/19%3ameeting_YTdkZDI3%40thread.v2/0?context=%7b%22Tid%22%3a%2272f988bf%22%7d')}`,+ `X-CAL:${url('https', 'calendar.example.com/event?eid=NWZ0aDd2cWdzNzN0OGtwM2Y5c2Rv&ctz=America/Los_Angeles')}`,+ 'END:VCALENDAR',+ ].join('\n'),+ },+ {+ id: 'meeting-notes',+ kind: 'clean',+ text: [+ '# 2026-01-15 platform sync',+ '- Decision: rotate the API token next week; owner alice-example.',+ '- The token budget per request stays at 4096; password_min_length: 12.',+ '- Basic auth is deprecated in v2, use Bearer tokens from the OAuth flow.',+ '- Authorization: Basic auth is deprecated (the header form is going away).',+ '- Credential rotation runbook lives in the wiki; the token is stored in the keychain, not in the repo.',+ '- TOKEN_TTL_SECONDS = 3600 and secret_name = my-app/prod/database-credentials',+ '- Follow-ups: basic internationalization support, Bearer of bad news slide.',+ `- Registry: ${url('https', 'registry.example/')}${at}scope/pkg and ${url('http', 'localhost:5173/')}${at}vite/client`,+ `- Status page ${url('https', 'status.example.com:443/')}${at}acme-example`,+ ].join('\n'),+ },+ {+ id: 'agent-transcript',+ kind: 'clean',+ text: [+ 'user: why does the deploy fail?',+ 'assistant: running the checks',+ `tool: git push ${url('https', 'github.com/acme-example/app.git')} main`,+ `tool: curl -H "Authorization: Bearer $TOKEN" ${url('https', 'api.acme-example.com/v1/items')}`,+ 'tool: export API_KEY=$(op read op://vault/item/field)',+ 'tool: grep -n "password = process.env.DB_PASSWORD_2" src/db.ts',+ 'tool: const token = await getToken(scope2, audience3)',+ 'tool: token_url: "https://oauth2.example.com/token"',+ 'tool: credentials_path: "/home/alice-example/.config/gcloud/application_default_credentials.json"',+ 'tool: secret_file = ./config/secrets2.example.json',+ 'tool: password: "${{ secrets.DB_PASSWORD }}"',+ `tool: clone ${url('https', `user:<password>${at}git.example.com/team/repo.git`)}`,+ `tool: clone ${url('https', `deploy:\${DEPLOY_TOKEN}${at}git.example.com/team/repo.git`)}`,+ `tool: ssh git${at}github.com:acme-example/app.git`,+ `tool: psql ${url('postgres', 'localhost:5432/app')}`,+ 'tool: commit 3e365f5f1a2b4c8d9e0f1a2b3c4d5e6f70819293 550e8400-e29b-41d4-a716-446655440000',+ 'tool: npm install @types/node [email protected]',+ 'assistant: the config uses config.secrets.apiKey2 and settings.token.refreshUrl2.',+ ].join('\n'),+ },+ {+ id: 'quoted-docs-end-marker',+ kind: 'clean',+ text: [+ 'Key files end with this line:',+ marker('END'),+ 'and nothing secret should follow it in docs.',+ 'For Basic auth the header looks like `Authorization: Basic <base64 of user:password>`.',+ ].join('\n'),+ },+ ];+ const ghp = ['ghp', rand(36)].join('_');+ const httpPw = rand(24);+ const basicValue = Buffer.from(`svc-acme:${rand(18)}`).toString('base64');+ const dop = ['dop', 'v1', randomBytes(32).toString('hex')].join('_');+ const punctuated = `${rand(10)}!#%${rand(8)}`;+ const quoted = `${rand(8)}&()<${rand(8)}`;+ const assigned = rand(28);+ const truncated = b64Lines(4, 21);+ const split = b64Lines(3, 30);+ const secret: CorpusDoc[] = [+ {+ id: 'secret-transcript',+ kind: 'secret',+ text: [+ `tool: git remote set-url origin ${url('https', `x-access-token:${httpPw}${at}github.com/acme-example/app.git`)}`,+ `tool: curl -H "authorization: basic ${basicValue}" ${url('https', 'api.acme-example.com')}`,+ `tool: export DIGITALOCEAN_ACCESS_TOKEN=${dop}`,+ `tool: export GITHUB_TOKEN=${ghp}`,+ `tool: DB_PASSWORD=${punctuated}`,+ `tool: {"client_secret": "${quoted}"}`,+ `tool: SMTP_TOKEN=${assigned}. retrying`,+ `assistant: I used ${assigned} for the retry.`,+ ].join('\n'),+ secrets: [httpPw, basicValue, dop, ghp],+ assignmentSecrets: [punctuated, quoted, assigned],+ },+ {+ id: 'secret-truncated-key-excerpt',+ kind: 'secret',+ text: `Deploy key excerpt from the ticket:\n${marker('BEGIN')}\n${truncated.join('\n')}`,+ secrets: truncated,+ },+ {+ id: 'secret-split-key-chunk',+ kind: 'secret',+ text: `${split.join('\n')}\n${marker('END')}\nrotate this one`,+ secrets: split,+ },+ ];+ return [...clean, ...secret];+}++/** Multiset of `pattern\0fingerprint` keys. */+function findingKeys(findings: Finding[]): Map<string, number> {+ const m = new Map<string, number>();+ for (const f of findings) {+ const k = `${f.pattern}\0${f.fingerprint}`;+ m.set(k, (m.get(k) ?? 0) + 1);+ }+ return m;+}++/** Findings of `after` whose (pattern, fingerprint) is not matched one-for-one in `before`. */+export function newFindings(before: Finding[], after: Finding[]): Finding[] {+ const remaining = findingKeys(before);+ const out: Finding[] = [];+ for (const f of after) {+ const k = `${f.pattern}\0${f.fingerprint}`;+ const n = remaining.get(k) ?? 0;+ if (n > 0) remaining.set(k, n - 1);+ else out.push(f);+ }+ return out;+}++export interface ModeReport {+ newHitsByPattern: Record<string, number>;+ docsNewlyFlagged: number;+ newHits: Array<{ doc: string; pattern: string; line: number }>;+}++export function measure(docs: Array<{ id: string; text: string }>, base: Scanner, head: Scanner, highEntropy: boolean): ModeReport {+ const report: ModeReport = { newHitsByPattern: {}, docsNewlyFlagged: 0, newHits: [] };+ for (const d of docs) {+ const before = base.scanText(d.text, { highEntropy });+ const after = head.scanText(d.text, { highEntropy });+ if (before.length === 0 && after.length > 0) report.docsNewlyFlagged++;+ for (const f of newFindings(before, after)) {+ report.newHitsByPattern[f.pattern] = (report.newHitsByPattern[f.pattern] ?? 0) + 1;+ report.newHits.push({ doc: d.id, pattern: f.pattern, line: f.line });+ }+ }+ return report;+}++async function loadBaseScanner(ref: string): Promise<Scanner> {+ const source = execFileSync('git', ['show', `${ref}:src/core/secret-scan.ts`], { encoding: 'utf-8' });+ const dir = mkdtempSync(join(tmpdir(), 'secret-scan-base-'));+ const file = join(dir, 'secret-scan.ts');+ writeFileSync(file, source);+ try {+ return (await import(file)) as Scanner;+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+}++function repoCorpus(): Array<{ id: string; text: string }> {+ const files = execFileSync('git', ['ls-files', 'src', 'docs', 'skills'], { encoding: 'utf-8' }).split('\n').filter(Boolean);+ const out: Array<{ id: string; text: string }> = [];+ for (const f of files) {+ const buf = readFileSync(f);+ if (buf.length > current.SCAN_MAX_FILE_BYTES || current.looksBinaryBuffer(buf)) continue;+ out.push({ id: f, text: buf.toString('utf-8') });+ }+ return out;+}++function brainCorpus(dir: string): Array<{ id: string; text: string }> {+ const out: Array<{ id: string; text: string }> = [];+ const walk = (d: string): void => {+ for (const name of readdirSync(d)) {+ if (name.startsWith('.')) continue;+ const p = join(d, name);+ const st = statSync(p);+ if (st.isDirectory()) walk(p);+ else if (name.endsWith('.md') && st.size <= current.SCAN_MAX_FILE_BYTES) out.push({ id: String(out.length), text: readFileSync(p, 'utf-8') });+ }+ };+ walk(resolve(dir));+ return out;+}++async function main(): Promise<void> {+ const args = process.argv.slice(2);+ const opt = (name: string): string | undefined => {+ const i = args.indexOf(name);+ return i >= 0 ? args[i + 1] : undefined;+ };+ const base = await loadBaseScanner(opt('--base') ?? 'origin/master');+ const head: Scanner = current;+ const dir = opt('--dir');+ const corpora: Record<string, Array<{ id: string; text: string }>> = dir+ ? { brain: brainCorpus(dir) }+ : { repo: repoCorpus(), synthetic: buildSyntheticBrainCorpus().filter((d) => d.kind === 'clean') };+ const result: Record<string, { docs: number; highEntropyTrue: ModeReport; highEntropyFalse: ModeReport }> = {};+ for (const [name, docs] of Object.entries(corpora)) {+ const t = measure(docs, base, head, true);+ const f = measure(docs, base, head, false);+ if (dir) {+ t.newHits = [];+ f.newHits = [];+ }+ result[name] = { docs: docs.length, highEntropyTrue: t, highEntropyFalse: f };+ }+ if (args.includes('--json')) {+ console.log(JSON.stringify(result, null, 2));+ return;+ }+ for (const [name, r] of Object.entries(result)) {+ console.log(`\n${name}: ${r.docs} documents`);+ for (const [mode, m] of [['highEntropy: true', r.highEntropyTrue], ['highEntropy: false', r.highEntropyFalse]] as const) {+ const total = Object.values(m.newHitsByPattern).reduce((a, b) => a + b, 0);+ console.log(` ${mode}: ${total} new hits, ${m.docsNewlyFlagged} documents newly flagged`);+ for (const [p, n] of Object.entries(m.newHitsByPattern).sort()) console.log(` ${p}: ${n}`);+ for (const h of m.newHits) console.log(` ${h.doc}:${h.line} ${h.pattern}`);+ }+ }+}++if (import.meta.main) await main();diff --git a/skills/brain-ops/SKILL.md b/skills/brain-ops/SKILL.mdindex 1e0f74f7dc..2f1db55404 100644--- a/skills/brain-ops/SKILL.md+++ b/skills/brain-ops/SKILL.md@@ -77,6 +77,17 @@ suppresses writes for that turn, including when standing capture is enabled.> connection test, use only a harmless synthetic `visibility: "world"` fixture> with the user's test authorization, retain its ID, and withdraw it afterward.>+> **`<REDACTED:pattern>` in a result** (for example `<REDACTED:url_credentials>`+> or `<REDACTED:high_entropy_assignment>`) means the brain holds a+> credential-shaped value there and withheld it from this response; the stored+> page is unchanged. Tell the user which kind of value was withheld and that it+> is readable on the brain host. Do not retry other operations to recover it,+> and do not echo a guess. A credential the user asked you to `remember` is+> withheld from remote recall by design: every MCP caller, including stdio, and+> a thin CLI connected to MCP is remote, so only `gbrain recall` run on the+> brain host shows it as written. Docs:+> `docs/guides/write-refusals.md#secret-scan-refusals-and-redaction`.+>> **Keyless brains:** when `extract_facts` returns `skipped:> extraction_unavailable`, YOU are the extractor — pull the facts from the turn> yourself and write each one via `remember` with `kind` set (event | preferencediff --git a/skills/migrations/v0.60.31.0.md b/skills/migrations/v0.60.31.0.mdnew file mode 100644index 0000000000..93f8a5c690--- /dev/null+++ b/skills/migrations/v0.60.31.0.md@@ -0,0 +1,91 @@+# Upgrade to v0.60.31.0: stored credentials stay out of retrieval, and Google files are private++This release changes what the brain hands back, not what it stores:++- Search, query, evidence and the memory verbs (`recall`, `context_pack`,+ `delta`, `entity`) replace credential-shaped values with+ `<REDACTED:pattern>`. Remembered facts are redacted for every MCP caller+ (stdio included) and thin clients, and returned as stored by `gbrain recall`+ on the brain host.+- Search chunks and delivered evidence never hold private-key material. Pages+ indexed earlier that contain a private key are withheld from search until+ this upgrade re-chunks them, with no provider calls.+- `gbrain sources push` and bootstrap catch more shapes (`http(s)` URLs with a+ password, `Authorization: Basic`, DigitalOcean tokens, cut-off private keys)+ and print the fix for each finding.+- Google sync state and pages are written 0600, directories 0700. Files+ written earlier in a Google folder outside `~/.gbrain` keep their old+ permissions until the user agrees to a repair.++Paid work and permission changes need the user's agreement. Never answer the+re-embed prompt, run `gbrain embed --stale`, run a repair with `--apply` or+add an allowlist entry on the user's behalf without asking.++1. **Finish the migration.** `gbrain upgrade` runs it. If `gbrain doctor`+ reports a partial migration, or to be sure, run on the brain host:+ ```bash+ gbrain apply-migrations --yes --no-autopilot-install+ ```+ It re-chunks the withheld pages without provider calls and prints a+ one-time `[google] Google source <id> keeps its files in <dir>, outside+ ~/.gbrain` line per Google folder outside `~/.gbrain`. It is idempotent:+ a rerun picks up only pages still pending.++2. **Check the re-chunk.** Run `gbrain doctor` and read+ `credential_projection_pending`. When it is ok, every page is searchable+ again. If it names code pages without a recorded source path, they stay+ withheld until their source is synced again: `gbrain sync --source <id>`.++3. **Ask before embedding the new chunks.** Re-chunked pages have no vectors+ until they are embedded, so keyword search finds them and vector search+ does not. Embedding calls the configured provider and can cost money. Tell+ the user, and only after they agree:+ ```bash+ gbrain embed --stale+ ```+ If the upgrade printed `[chunker-bump] Not re-embedding without your+ consent`, that is expected for a non-interactive upgrade; relay the+ commands it printed and let the user choose.++4. **Google folders outside `~/.gbrain`.** If step 1 printed a `[google]`+ line or `gbrain doctor` warns `google_file_modes`, show the user the+ preview, explain that it clears group and other permission bits on+ gbrain's own files only, and apply after they agree:+ ```bash+ gbrain repair google-file-modes --source <id> # preview+ gbrain repair google-file-modes --source <id> --apply+ ```+ gbrain now reasserts 0600 every time it rewrites one of these files, so a+ looser mode set by hand is reverted on the next rewrite.++5. **If a brain push is refused.** `gbrain sources push` may now stop with+ `PUSH BLOCKED`. Show the user each finding (file, line, pattern,+ fingerprint). A real credential must be removed from the file and rotated+ with its provider before pushing again. Only a value the user confirms is+ not a credential may be allowlisted, with the "allow this finding" command+ the refusal prints, followed by the printed retry command. A+ `stale allowlist entry` line means an old entry for a cut-off private key+ no longer matches; replace it with the printed line only if the user+ confirms the key is a false positive.++6. **Explain `<REDACTED:pattern>`.** When a result carries this token, tell+ the user the brain holds a value of that kind and withheld it; do not try+ other operations to recover it. A credential the user asked the brain to+ remember is readable with `gbrain recall` on the brain host only. Full+ page reads (`get_page`) are not redacted.++7. **Restart long-running processes** so the new code serves every caller:+ `gbrain serve` (stdio MCP: restart the agent harness; HTTP: restart the+ service), `gbrain jobs supervisor` and autopilot.++8. **Verify.**+ ```bash+ gbrain doctor+ ```+ `credential_projection_pending` and `google_file_modes` report ok (or+ only the warnings the user chose to leave). If a step failed, run+ `gbrain apply-migrations --yes --no-autopilot-install` once more and+ re-run `gbrain doctor`.++Details: `docs/guides/write-refusals.md#secret-scan-refusals-and-redaction`+and `docs/guides/google-connect.md#file-permissions`.diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex f696f495d3..7ea3242f0c 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -20,7 +20,7 @@"brain-ingest-gate/routing-eval.jsonl": "281e94affbb8631ef7ff44203884cce1c03c468b27f893829da1e6e439401a33","brain-link-discipline/SKILL.md": "489268f71a01abb6213df8a8bb5f4d16d587b09dd670ac3c47876a8ed808b5ae","brain-link-discipline/routing-eval.jsonl": "0adea4c6d72fdb849c12fe2cad718568b9ab704299b00b093c40c2284faf684c",- "brain-ops/SKILL.md": "075666e81df0b5f8ab23493d4972ef5ba42bc789ae213d3bc03e5d3b9c38a3bf",+ "brain-ops/SKILL.md": "6586d82a135f312dc330a3e7dc71f753285b639eb997740344e9521336cab109","brain-pdf/SKILL.md": "c24727ade7c222606249bbf690ddede1bebe218122c9cf9060a2baa6b63d3bc8","brain-pdf/routing-eval.jsonl": "119e4fa113ea45783cee4499e63a729fdeecb4d9a45d47497754b4f5b21d0734","brain-taxonomist/SKILL.md": "dea4557b540868ec2c56bf43ee7f63c5d03a22d4047cd0dfbeaf19adef334f60",@@ -157,6 +157,7 @@"migrations/v0.60.27.0.md": "1c3ac6a23ccfce8ad299457799b02958f7d21fcd967c471634f73bdb66f2b603","migrations/v0.60.28.0.md": "f7fa936066fb188f6f3f54bb6c720f57743792e4371d0b98dd3cb5a57d1bd9c9","migrations/v0.60.30.0.md": "2dd24bb319cad80ae15c52fb163c704fc3adfc1182d44ab563f636f07434a9e0",+ "migrations/v0.60.31.0.md": "fb8c0a98451a6f7826413ee7463421612511986252f6b803d91a26da94d378bf","migrations/v0.60.5.0.md": "0d3ee19359a2740de08ac9ec388ddc15e7c72d663afe33832e1e54170528acab","migrations/v0.60.6.0.md": "1cbfca2c899e1348acbd61f0baa4c8e723b5283ff868c710c74e116c0cb6726e","migrations/v0.7.0.md": "97c2740445a10b1c5c7123c17dbd625fa27a94095b85d27c2b278da756c4c59a",diff --git a/src/commands/compile-context.ts b/src/commands/compile-context.tsindex a710b4b52a..42d096ca41 100644--- a/src/commands/compile-context.ts+++ b/src/commands/compile-context.ts@@ -32,7 +32,7 @@ import { join, relative } from 'path';import type { BrainEngine } from '../core/engine.ts';import { atomicWriteTextFile } from '../core/bootstrap/atomic-write.ts';import { compileView, type CompileViewMeta } from '../core/context/compile-view.ts';-import { loadSensitivityConfig } from '../core/context/sensitivity-scan.ts';+import { formatSensitivityDrop, loadSensitivityConfig } from '../core/context/sensitivity-scan.ts';import { resolveSourceId, ALL_SOURCES } from '../core/source-resolver.ts';// ── Constants ───────────────────────────────────────────────────────────────@@ -274,9 +274,7 @@ export async function runCompileContext(// Drops are always reported: slug + family + fingerprint, never the text.for (const d of meta.scan_drops) {- process.stderr.write(- `compile-context: dropped ${d.slug} (${d.family} ${d.fingerprint})\n`,- );+ process.stderr.write(`compile-context: ${formatSensitivityDrop(d, cwd)}\n`);}const outPath = flags.out ?? defaultOutPath(flags.target, cwd);diff --git a/src/commands/doctor/checks/credential-projection.ts b/src/commands/doctor/checks/credential-projection.tsnew file mode 100644index 0000000000..2f4c2b4194--- /dev/null+++ b/src/commands/doctor/checks/credential-projection.ts@@ -0,0 +1,25 @@+/**+ * credential_projection_pending doctor check (security wave ENG-2): pages whose+ * canonical body holds a private-key marker and whose chunks are withheld from+ * every search path until the provider-free credential-safe re-chunk seals+ * them. Counts the pages the v0.60.31 migration can re-chunk and, separately,+ * code pages without a recorded source path that wait for their importer.+ */+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { credentialProjectionPending } from '../../../core/page-state/credential-reseal.ts';++export async function credentialProjectionPendingCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {+ const name = 'credential_projection_pending';+ try {+ const { rebuildable, kept } = await credentialProjectionPending(engine, sourceIds);+ const details = { pages_pending: rebuildable, kept_pages: kept, count: 'exact', truncated: false };+ const keptNote = kept ? ` ${kept} code page(s) without a recorded source path stay withheld until re-imported (gbrain sync --source <id>).` : '';+ if (rebuildable === 0) return { name, status: kept ? 'warn' : 'ok', details, message: `No page waits for the credential-safe re-chunk.${keptNote}` };+ return { name, status: 'warn', details, message: `${rebuildable} page(s) holding a private key are withheld from search until re-chunked without provider calls. `+ + `Run \`gbrain apply-migrations --yes --no-autopilot-install\`, then \`gbrain embed --stale\` when ready.${keptNote}` };+ } catch (error) {+ return { name, status: 'warn', message: `Credential-safe re-chunk state could not be read: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,+ details: { count: 'unknown', truncated: true, health: 'unknown' } };+ }+}diff --git a/src/commands/doctor/checks/google-file-modes.ts b/src/commands/doctor/checks/google-file-modes.tsnew file mode 100644index 0000000000..d80b57fd3e--- /dev/null+++ b/src/commands/doctor/checks/google-file-modes.ts@@ -0,0 +1,28 @@+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { googleFileModesApplyCommand, googleFileModesPreviewCommand, scanGoogleFileModes } from '../../../core/google/file-modes.ts';++/**+ * Security fix wave: group/world-readable files and directories gbrain wrote+ * under a Google source directory outside `~/.gbrain`. Detection only; the+ * message names each directory with its counts (file names embed mail+ * subjects, so none are printed) and the exact preview and apply commands.+ */+export async function checkGoogleFileModes(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {+ try {+ const scans = (await scanGoogleFileModes(engine, { sourceIds })).filter(scan => scan.loose.length);+ const sources = scans.map(scan => ({ source_id: scan.sourceId, dir: scan.dir,+ loose_files: scan.loose.filter(entry => entry.kind === 'file').length, loose_dirs: scan.loose.filter(entry => entry.kind === 'dir').length,+ preview_command: googleFileModesPreviewCommand(scan.sourceId), apply_command: googleFileModesApplyCommand(scan.sourceId) }));+ const details = { count: sources.reduce((sum, s) => sum + s.loose_files + s.loose_dirs, 0), sources, repair: 'google-file-modes',+ docs: 'docs/guides/google-connect.md' };+ if (!sources.length) return { name: 'google_file_modes', status: 'ok', message: 'No group- or world-readable gbrain files under Google source directories outside ~/.gbrain.', details };+ return { name: 'google_file_modes', status: 'warn', details,+ message: sources.map(s => `Google source ${s.source_id}: ${s.loose_files} file(s) and ${s.loose_dirs} director${s.loose_dirs === 1 ? 'y' : 'ies'} `+ + `gbrain wrote under ${s.dir} are readable by other local users (written before this release). `+ + `Preview: ${s.preview_command} — apply after the user agrees: ${s.apply_command}`).join(' ') };+ } catch (error) {+ return { name: 'google_file_modes', status: 'warn', details: { count: 'unknown' },+ message: `Google source file permissions could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.` };+ }+}diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.tsindex 70d92b0b20..84ca85f94f 100644--- a/src/commands/doctor/checks/graph-health.ts+++ b/src/commands/doctor/checks/graph-health.ts@@ -265,6 +265,7 @@ export const timelineHistoryEntry: DoctorEntry = {'timeline_history','derived_visibility','safe_index_pending',+ 'credential_projection_pending','connector_checkpoints','persistence_request_indexes','persistence_request_growth',@@ -275,6 +276,7 @@ export const timelineHistoryEntry: DoctorEntry = {'self_capture','vector_plan','stale_embedding_effects',+ 'google_file_modes','extractor_facts_expired',],run: runTimelineHistory,diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.tsindex 0a3c13aa67..9812aef570 100644--- a/src/commands/doctor/wave-checks.ts+++ b/src/commands/doctor/wave-checks.ts@@ -67,6 +67,13 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [impact: 'Some pages are below the safe-chunk index version and are withheld from remote search',run: async (engine, scope) => (await import('./checks/safe-index.ts')).safeIndexPendingCheck(engine, scope.sourceIds),},+ {+ id: 'credential_projection_pending', resolution: 'operator', registration: 'wave',+ count: d => Number(d.pages_pending ?? 0) + Number(d.kept_pages ?? 0),+ impact: 'Some pages holding a private key are withheld from search until their credential-safe re-chunk completes',+ instruction: 'Run `gbrain apply-migrations --yes --no-autopilot-install` on the brain host (no provider calls), then `gbrain embed --stale` when ready; re-import code pages without a recorded source path.',+ run: async (engine, scope) => (await import('./checks/credential-projection.ts')).credentialProjectionPendingCheck(engine, scope.sourceIds),+ },{id: 'connector_checkpoints', resolution: 'repair', registration: 'wave',count: d => Number(d.count ?? 0),@@ -155,6 +162,13 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [impact: 'A committed write still has a stale queued or failed embedding effect that blocks compaction and activation',run: async (engine, scope) => (await import('./checks/stale-embedding-effects.ts')).staleEmbeddingEffectsCheck(engine, scope.sourceIds),},+ {+ id: 'google_file_modes', resolution: 'repair', registration: 'wave',+ hostOnly: 'File permissions and directory paths on the brain host are host-local filesystem state.',+ count: d => Number(d.count ?? 0),+ impact: 'Some files gbrain wrote under a Google source directory outside ~/.gbrain are readable by other local users',+ run: async (engine, scope) => (await import('./checks/google-file-modes.ts')).checkGoogleFileModes(engine, scope.sourceIds),+ },{id: 'atom_provenance_drift', resolution: 'repair', registration: 'doctor.ts',hostOnly: 'Retiring stale atoms is a host-side, explicit-only repair.',diff --git a/src/commands/migrations/index.ts b/src/commands/migrations/index.tsindex 3b2a69e546..c9a6355f0d 100644--- a/src/commands/migrations/index.ts+++ b/src/commands/migrations/index.ts@@ -33,6 +33,7 @@ import { v0_31_0 } from './v0_31_0.ts';import { v0_32_2 } from './v0_32_2.ts';import { v0_43_0 } from './v0_43_0.ts';import { v0_46_3 } from './v0_46_3.ts';+import { v0_60_31 } from './v0_60_31.ts';import { sharedContentMigration } from './shared-content.ts';export const migrations: Migration[] = [@@ -54,6 +55,7 @@ export const migrations: Migration[] = [v0_43_0,v0_46_3,sharedContentMigration,+ v0_60_31,];/** Look up a migration by exact version string. */diff --git a/src/commands/migrations/v0_60_31-google-file-modes.ts b/src/commands/migrations/v0_60_31-google-file-modes.tsnew file mode 100644index 0000000000..99121b728d--- /dev/null+++ b/src/commands/migrations/v0_60_31-google-file-modes.ts@@ -0,0 +1,30 @@+/**+ * Security fix wave: the one-time notice for Google sources whose directory+ * is outside `~/.gbrain`. Files gbrain wrote there before this release keep+ * the permissions they were written with (typically 0644), and only a rewrite+ * tightens them. Detection only: the notice names each directory, the count+ * of group/world-readable entries found now and the opt-in repair commands.+ * Nothing is chmod-ed here. A config marker makes it print once per brain.+ */+import type { BrainEngine } from '../../core/engine.ts';+import { googleFileModesApplyCommand, googleFileModesPreviewCommand, scanGoogleFileModes } from '../../core/google/file-modes.ts';+import type { OrchestratorPhaseResult } from './types.ts';++export const GOOGLE_FILE_MODES_NOTICE_KEY = 'google.file_modes_notice';++export function googleFileModesNoticeLines(scans: Awaited<ReturnType<typeof scanGoogleFileModes>>): string[] {+ return scans.map(scan => `[google] Google source ${scan.sourceId} keeps its files in ${scan.dir}, outside ~/.gbrain. `+ + 'Files gbrain wrote there before this version keep their old permissions and may be readable by other local users '+ + `(${scan.loose.length} found now). Preview the fix: ${googleFileModesPreviewCommand(scan.sourceId)} — `+ + `apply after review: ${googleFileModesApplyCommand(scan.sourceId)}. Verify and repair options: docs/guides/google-connect.md`);+}++export async function googleFileModesNoticePhase(engine: BrainEngine | null, opts: { dryRun: boolean; print?: (line: string) => void }): Promise<OrchestratorPhaseResult> {+ if (opts.dryRun) return { name: 'google_file_modes_notice', status: 'skipped', detail: 'dry-run' };+ if (!engine) return { name: 'google_file_modes_notice', status: 'skipped', detail: 'no_brain_configured' };+ if (await engine.getConfig(GOOGLE_FILE_MODES_NOTICE_KEY)) return { name: 'google_file_modes_notice', status: 'skipped', detail: 'already_shown' };+ const lines = googleFileModesNoticeLines(await scanGoogleFileModes(engine));+ for (const line of lines) (opts.print ?? console.log)(line);+ await engine.setConfig(GOOGLE_FILE_MODES_NOTICE_KEY, new Date().toISOString());+ return { name: 'google_file_modes_notice', status: 'complete', detail: `${lines.length} custom-dir Google source(s)` };+}diff --git a/src/commands/migrations/v0_60_31.ts b/src/commands/migrations/v0_60_31.tsnew file mode 100644index 0000000000..3835313666--- /dev/null+++ b/src/commands/migrations/v0_60_31.ts@@ -0,0 +1,80 @@+/**+ * v0.60.31 migration — security fix wave. Two phases:+ * 1. credential-safe re-chunk of existing pages (ENG-2), below;+ * 2. the one-time notice for Google sources outside `~/.gbrain`, whose files+ * written before this version keep their old permissions until+ * `gbrain repair google-file-modes` (opt-in) or a rewrite tightens them+ * (v0_60_31-google-file-modes.ts; detection only).+ *+ * Schema migration v189 already withheld the old chunks of every page whose+ * canonical body carries a private-key marker. This orchestrator re-chunks+ * those pages through the credential-safe projection, provider-free (see+ * src/core/page-state/credential-reseal.ts). It never embeds: re-chunked key+ * chunks wait for the consent-gated `gbrain embed --stale`.+ *+ * Idempotent: each page re-seals in its own transaction and a re-sealed page+ * is no longer pending, so a rerun after an interruption resumes with the+ * pages still withheld. A failed page records the run as partial so the next+ * `gbrain apply-migrations --yes` retries it.+ */+import type { Migration, OrchestratorOpts, OrchestratorPhaseResult, OrchestratorResult } from './types.ts';+import type { BrainEngine } from '../../core/engine.ts';+import { loadConfig, toEngineConfig } from '../../core/config.ts';+import { createEngine } from '../../core/engine-factory.ts';+import { buildGatewayConfig } from '../../core/ai/build-gateway-config.ts';+import { credentialProjectionPending, resealCredentialProjections } from '../../core/page-state/credential-reseal.ts';+import { runMigrateOnlyCore } from './in-process.ts';+import { googleFileModesNoticePhase } from './v0_60_31-google-file-modes.ts';++let testEngineOverride: BrainEngine | null = null;+export function __setTestEngineOverride(engine: BrainEngine | null): void {+ testEngineOverride = engine;+}++async function credentialProjectionPhase(engine: BrainEngine, opts: OrchestratorOpts): Promise<OrchestratorPhaseResult> {+ const name = 'credential_projection';+ if (opts.dryRun) {+ const pending = await credentialProjectionPending(engine);+ return { name, status: 'skipped', detail: `dry-run: ${pending.rebuildable} page(s) would be re-chunked without provider calls` };+ }+ const result = await resealCredentialProjections(engine);+ const kept = result.kept ? `; ${result.kept} code page(s) without a recorded source path stay withheld until re-imported` : '';+ const detail = `${result.resealed} page(s) re-chunked without provider calls, ${result.superseded} superseded by newer writes${kept}. `+ + 'Embed the re-chunked text when ready: gbrain embed --stale';+ if (result.failed) return { name, status: 'failed', detail: `${result.failed} page(s) failed to re-chunk and stay withheld; ${detail}` };+ return { name, status: 'complete', detail };+}++async function orchestrator(opts: OrchestratorOpts): Promise<OrchestratorResult> {+ let engine = testEngineOverride;+ if (!engine) {+ const config = loadConfig();+ if (!config) return { version: '0.60.31', status: 'complete', phases: [{ name: 'credential_projection', status: 'skipped', detail: 'no_brain_configured' }] };+ // Schema migration v189 marks the pages this phase re-chunks; PGLite skips the runner's schema pre-flight.+ if (!opts.dryRun) await runMigrateOnlyCore();+ const { configureGateway } = await import('../../core/ai/gateway.ts');+ configureGateway(buildGatewayConfig(config));+ engine = await createEngine(toEngineConfig(config));+ await engine.connect(toEngineConfig(config));+ }+ try {+ const phases = [+ await credentialProjectionPhase(engine, opts),+ await googleFileModesNoticePhase(engine, { dryRun: opts.dryRun }),+ ];+ return { version: '0.60.31', status: phases.some(p => p.status === 'failed') ? 'partial' : 'complete', phases };+ } finally {+ if (!testEngineOverride) await engine.disconnect().catch(() => {});+ }+}++export const v0_60_31: Migration = {+ version: '0.60.31',+ featurePitch: {+ headline: 'Stored private keys no longer reach search chunks or delivered evidence, and Google connector files are written private.',+ description: 'Pages whose body holds a private key are withheld from search until they are re-chunked with the key replaced by a <REDACTED:private_key_pem> token. This migration re-chunks them with no provider calls; run `gbrain embed --stale` afterwards to embed the new chunks. Stored page bodies are unchanged. '+ + 'Google connector files are now written 0600 (directories 0700); files written before this version under a Google source directory outside ~/.gbrain keep their old permissions. '+ + 'gbrain doctor lists them; preview the opt-in fix with gbrain repair google-file-modes and apply it with --apply.',+ },+ orchestrator,+};diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex 88b39bcb79..abc0e42213 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -642,7 +642,7 @@ async function runPush(engine: BrainEngine, args: string[]): Promise<void> {dir = src.local_path;}- const { workspacePush } = await import('../core/workspace-push.ts');+ const { workspacePush, formatBlockedSecrets } = await import('../core/workspace-push.ts');const { SCAN_ALLOW_FILENAME } = await import('../core/secret-scan.ts');const res = await workspacePush({dir: dir!,@@ -672,11 +672,7 @@ async function runPush(engine: BrainEngine, args: string[]): Promise<void> {return;case 'blocked_secrets':if (!json) {- console.error('PUSH BLOCKED — secret scan findings (nothing committed):');- for (const f of res.findings ?? []) {- console.error(` ${f.file}:${f.line} [${f.pattern}] ${f.redactedPreview}`);- console.error(` allow this finding: echo '${f.fingerprint}' >> ${SCAN_ALLOW_FILENAME}`);- }+ for (const line of formatBlockedSecrets(res.findings ?? [])) console.error(line);}process.exit(5);break;diff --git a/src/core/atomic-write.ts b/src/core/atomic-write.tsindex 6d41f109df..56d4a8bb4f 100644--- a/src/core/atomic-write.ts+++ b/src/core/atomic-write.ts@@ -1,8 +1,9 @@/*** Atomic file write for brain-repo markdown writers.*- * Write path: unique tmp sibling → write → fsync → close → (optional verify- * of the on-disk bytes) → chmod to the original mode → rename over the target.+ * Write path: unique tmp sibling opened with the requested (or the target's+ * original) mode and fchmod-ed to it → write → fsync → close → (optional+ * verify of the on-disk bytes) → rename over the target.* The rename is atomic on POSIX filesystems, so readers never observe a torn* file; a crash mid-write leaves only a tmp sibling, never a corrupt target.*@@ -17,12 +18,14 @@*/import {- chmodSync,closeSync,+ constants,existsSync,+ fchmodSync,fsyncSync,fstatSync,lstatSync,+ mkdirSync,openSync,readFileSync,renameSync,@@ -31,7 +34,7 @@ import {writeSync,} from 'fs';import { randomBytes, randomUUID } from 'crypto';-import { dirname, resolve } from 'path';+import { dirname, isAbsolute, join, relative, resolve, sep } from 'path';import { assertManagedFilesystemWrite } from './persistence/filesystem-guard.ts';export interface AtomicWriteOpts {@@ -48,6 +51,49 @@ export interface AtomicWriteOpts {* still parses (backlinks uses parseMarkdown here).*/verify?: (onDisk: string) => void;+ /**+ * Exact permission bits for the written file. The stage is opened with this+ * mode and then fchmod-ed on its descriptor past the umask before any byte is+ * written, so content never sits in a looser file; a rewrite reasserts it over+ * the existing target's mode. Omitted: preserve the existing target's mode,+ * else 0644 & ~umask.+ */+ mode?: number;+}++function createPrivateDir(dir: string): void {+ try {+ mkdirSync(dir, { mode: 0o700 });+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') return;+ throw error;+ }+ if (process.platform === 'win32') return;+ const fd = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);+ try { fchmodSync(fd, 0o700); } finally { closeSync(fd); }+}++/**+ * Create `dir` for gbrain-private files. A missing `root` is created with+ * default-permission ancestors and only `root` itself made exactly 0700 (past+ * the umask); each missing directory between `root` and `dir` is gbrain's own+ * layout and is created 0700 too. A directory that already exists, which may+ * be one the user chose, is never chmod-ed.+ */+export function mkdirPrivate(dir: string, root: string = dir): void {+ if (existsSync(dir)) return;+ const below = relative(root, dir);+ if (below === '..' || below.startsWith(`..${sep}`) || isAbsolute(below)) throw new Error(`mkdirPrivate: ${dir} is outside ${root}`);+ if (!existsSync(root)) {+ mkdirSync(dirname(root), { recursive: true });+ createPrivateDir(root);+ }+ let current = root;+ for (const part of below ? below.split(sep) : []) {+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- `below` is relative(root, dir), rejected above when it escapes root; parts walk only between root and dir.+ current = join(current, part);+ createPrivateDir(current);+ }}export function atomicStagingPath(filePath: string): string {@@ -74,7 +120,9 @@ export function atomicWriteFileSync(filePath: string, content: string | Uint8Arrlet created: ReturnType<typeof fstatSync> | undefined;// Preserve the target's mode across the rename (a fresh tmp file gets the- // process umask, which can silently drop e.g. group-write bits).+ // process umask, which can silently drop e.g. group-write bits). open(2)'s+ // mode argument is masked by the umask, so the descriptor is fchmod-ed to+ // the exact mode; a path chmod could follow a swapped stage.let mode: number | null = null;try {if (existsSync(filePath)) mode = statSync(filePath).mode & 0o7777;@@ -82,9 +130,11 @@ export function atomicWriteFileSync(filePath: string, content: string | Uint8Arr/* stat raced a delete — fall through with default mode */}+ const finalMode = opts?.mode ?? mode;try {- const fd = openSync(tmpPath, 'wx', mode ?? 0o644);+ const fd = openSync(tmpPath, 'wx', finalMode ?? 0o644);try {+ if (finalMode !== null) fchmodSync(fd, finalMode);created = fstatSync(fd);// Loop until every byte lands: writeSync may legally return a short// count under disk pressure/quotas, and a silent short write that@@ -96,16 +146,11 @@ export function atomicWriteFileSync(filePath: string, content: string | Uint8Arrif (n <= 0) throw new Error(`atomic-write: short write at offset ${off}/${buf.length}`);off += n;}- if (mode !== null) chmodSync(tmpPath, mode);fsyncSync(fd);} finally {closeSync(fd);}opts?.afterStagingFlush?.();- // open(2)'s mode argument is masked by the process umask (0664 & ~022 →- // 0644), so an explicit chmod is required to actually PRESERVE the- // target's mode across the rename — the pre-wave in-place write kept the- // inode's mode exactly; this keeps that property.if (opts?.verify) {opts.verify(readFileSync(tmpPath, 'utf-8'));}diff --git a/src/core/bootstrap/repo.ts b/src/core/bootstrap/repo.tsindex 0e87983c31..3e8e1baebe 100644--- a/src/core/bootstrap/repo.ts+++ b/src/core/bootstrap/repo.ts@@ -32,13 +32,15 @@*/import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';-import { join } from 'node:path';+import { join, resolve } from 'node:path';import { configDir } from '../config.ts';import { invalidateBackupStatus } from '../backup/status-file.ts';import { realpathOrResolve } from '../path-confine.ts';import { defaultRunner, isProxyBlocked403, parseGithubOwnerRepo, type ExecRunner } from '../repo-visibility.ts';import { detectExecutionEnvironment } from '../execution-env.ts';-import { loadWorkspaceAllowlist, scanFiles, SCAN_ALLOW_FILENAME } from '../secret-scan.ts';+import { loadWorkspaceAllowlist, scanFiles, SCAN_ALLOW_FILENAME, type SecretFinding } from '../secret-scan.ts';+import { SECRET_SCAN_REFUSAL_DOCS } from '../workspace-push.ts';+import { shellQuote } from '../mcp-registration.ts';import { GITHUB_URL_PLACEHOLDER } from './assets.ts';import {guardReceiptOverwrite,@@ -415,12 +417,16 @@ function secretScanOrThrow(workspaceDir: string, relFiles: string[]): void {workspaceRoot: workspaceDir,});if (findings.length > 0) {- const sample = findings.slice(0, 5).map((f) => `${f.file}:${f.line} [${f.pattern}]`).join('; ');+ const sample = findings.slice(0, 5).map((f) => {+ const { since } = f as SecretFinding & { since?: string };+ return `${f.file}:${f.line} [${f.pattern}${since ? ` since gbrain v${since.replace(/^v/, '')}` : ''}] ${f.fingerprint}`;+ }).join('; ');throw new BootstrapError('SECRET_SCAN_BLOCKED',`secret scan found ${findings.length} finding(s) before the first push: ${sample}` +`${findings.length > 5 ? '; …' : ''} — nothing was committed or pushed. ` +- `Remove the secret(s), or allowlist a false positive in ${SCAN_ALLOW_FILENAME}, then re-run \`gbrain bootstrap repo\`.`,+ 'Remove a real credential first; allowlist only a reviewed false positive by appending its fingerprint to ' ++ `${shellQuote(resolve(workspaceDir, SCAN_ALLOW_FILENAME))} (${SECRET_SCAN_REFUSAL_DOCS}), then re-run \`gbrain bootstrap repo\`.`,{ details: { findings: findings.length } },);}diff --git a/src/core/bootstrap/verify.ts b/src/core/bootstrap/verify.tsindex 5c8024a758..1cff68860d 100644--- a/src/core/bootstrap/verify.ts+++ b/src/core/bootstrap/verify.ts@@ -33,7 +33,7 @@ import { withCoordinatedWrite } from '../persistence/context.ts';import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';import { createHash, randomUUID } from 'node:crypto';import { execFileSync } from 'node:child_process';-import { join } from 'node:path';+import { join, resolve } from 'node:path';import type { BrainEngine } from '../engine.ts';import { operations, type Operation, type OperationContext } from '../operations.ts';@@ -43,8 +43,11 @@ import { resolveGbrainHome } from '../gbrain-home.ts';import { realpathOrResolve } from '../path-confine.ts';import { runMaintenanceSweep } from '../sweep.ts';import { detectCapabilities, renderCapabilityReport, type CapabilityReport } from '../capability.ts';-import { loadWorkspaceAllowlist, matchesGlob, scanFiles, type SecretFinding } from '../secret-scan.ts';-import { PUSH_DENY_GLOBS, verifyRemotePrivacy, readPushStatuses, summarizePushStatuses } from '../workspace-push.ts';+import { loadWorkspaceAllowlist, matchesGlob, SCAN_ALLOW_FILENAME, scanFiles, type SecretFinding } from '../secret-scan.ts';+import {+ PUSH_DENY_GLOBS, SECRET_SCAN_REFUSAL_DOCS, verifyRemotePrivacy, readPushStatuses, summarizePushStatuses,+} from '../workspace-push.ts';+import { shellQuote } from '../mcp-registration.ts';import { FACTS_DEFAULT_VISIBILITY_KEY } from '../facts/visibility.ts';import { byteFloors } from './render.ts';import { CLAUDE_HOOK_EVENTS, GBRAIN_HOOK_MARKER_KEY, claudeUserSettingsPath } from './host-specs.ts';@@ -345,8 +348,16 @@ function checkSecretScan(ws: string): VerifyCheck {workspaceRoot: ws,});if (findings.length > 0) {- const sample = findings.slice(0, 5).map((f) => `${f.file}:${f.line} [${f.pattern}] ${f.fingerprint}`).join('; ');- return { id, ok: false, detail: `${findings.length} secret-scan finding(s): ${sample}${findings.length > 5 ? '; …' : ''} — fix, or allowlist a false positive in .gbrain-scan-allow` };+ const sample = findings.slice(0, 5).map((f) => {+ const { since } = f as SecretFinding & { since?: string };+ return `${f.file}:${f.line} [${f.pattern}${since ? ` since gbrain v${since.replace(/^v/, '')}` : ''}] ${f.fingerprint}`;+ }).join('; ');+ return {+ id, ok: false,+ detail: `${findings.length} secret-scan finding(s): ${sample}${findings.length > 5 ? '; …' : ''} — ` ++ 'remove a real credential first; allowlist only a reviewed false positive by appending its fingerprint to ' ++ `${shellQuote(resolve(ws, SCAN_ALLOW_FILENAME))} (${SECRET_SCAN_REFUSAL_DOCS})`,+ };}return { id, ok: true, detail: `no secrets in ${files.length} ${via === 'git' ? 'tracked' : 'workspace'} file(s)` };} catch (e) {diff --git a/src/core/chunkers/recursive.ts b/src/core/chunkers/recursive.tsindex 3aa755496b..f7f4ab000a 100644--- a/src/core/chunkers/recursive.ts+++ b/src/core/chunkers/recursive.ts@@ -24,6 +24,7 @@ import { countCJKAwareWords, isCJKDominant, CJK_SENTENCE_DELIMITERS, CJK_CLAUSE_import { estimateEmbedTokens, DEFAULT_MAX_CHUNK_TOKENS } from './token-estimate.ts';import { safeSplitIndex } from '../text-safe.ts';import { sanitizeRemoteBody } from '../remote-body.ts';+import { credentialSafeProjection } from '../credential-projection.ts';import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';/**@@ -109,7 +110,7 @@ export function chunkText(text: string, opts?: ChunkOptions): TextChunk[] {// v0.32.2: also strip private facts (Codex R2-#1). World facts stay so// search retains its public-knowledge surface; private rows are filtered// out at the fence-row level via stripFactsFence({keepVisibility:['world']}).- const stripped = sanitizeRemoteBody(text);+ const stripped = credentialSafeProjection(sanitizeRemoteBody(text));if (!stripped || stripped.trim().length === 0) return [];const wordCount = countWords(stripped);diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 0d76efcc54..6b9da0a73d 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -46,7 +46,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--apply', '--apply-rewrites', '--brain', '--break-lock', '--db-url', '--dry-run', '--filter', '--force', '--force-retry', '--format', '--help', '--json', '--locks', '--name', '--path', '--prefer-postgres', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--undo-last-rewrite', '--url', '--version', '--yes'],'decide': ['--all', '--all-from', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--from', '--help', '--input', '--json', '--limit', '--min', '--out', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--what-if-threshold', '--yes'],- 'doctor': ['--abbrev-ref', '--abort', '--admin-intent', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--older-than', '--once', '--others', '--out', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--recommended', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],+ 'doctor': ['--abbrev-ref', '--abort', '--admin-intent', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--older-than', '--once', '--others', '--out', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--recommended', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],'embed': ['--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--yes'],@@ -65,7 +65,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'frontmatter': ['--allow-catch-all', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fix', '--force', '--get', '--git-common-dir', '--help', '--include-catch-all', '--json', '--name-only', '--no-verify', '--others', '--source', '--type', '--uninstall'],'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--port', '--prefer-postgres', '--provenance', '--purge-client', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],'graph-query': ['--brain', '--depth', '--direction', '--help', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],- 'hook': ['--allow-unverified-remote', '--auto', '--brain', '--cached', '--count', '--diff-filter', '--end-of-options', '--env', '--exclude-standard', '--get', '--harness', '--help', '--jq', '--json', '--name-only', '--others', '--path', '--porcelain', '--pure', '--quiet', '--session', '--show-current', '--show-toplevel', '--source'],+ 'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--name-only', '--others', '--path', '--porcelain', '--pure', '--quiet', '--session', '--show-current', '--show-toplevel', '--source'],'import': ['--allow-empty', '--allow-noncanonical-root', '--background', '--brain', '--cached', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--name-only', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-renames', '--no-verify', '--others', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--workers'],'init': ['--all', '--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--quiet', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--version', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],@@ -74,7 +74,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'lint': ['--abbrev-ref', '--abort', '--all', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-cron', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all'],'loops': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--no-embed', '--no-pull', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],+ 'maintain': ['--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'migrate': ['--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-retry', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--max-cost-usd', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--yes'],'models': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--skip', '--source', '--status'],@@ -84,7 +84,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'orphans': ['--background', '--brain', '--count', '--explain', '--follow', '--help', '--include-pseudo', '--json', '--mode', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],'pages': ['--brain', '--dry-run', '--help', '--json', '--older-than', '--source'],'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--help', '--json', '--path', '--source', '--vectors', '--yes'],- 'post-upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],+ 'post-upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],'projections': ['--brain', '--enable-dcr', '--help', '--http', '--install', '--json', '--limit', '--now', '--port', '--public-url', '--remove', '--source', '--status', '--surface', '--user'],'protocol': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--federated-read', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--synthesize', '--target', '--token', '--trusted-extraction', '--types', '--url', '--yes'],'providers': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--status', '--touchpoint'],@@ -101,7 +101,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'repair': ['--all', '--apply', '--brain', '--expect', '--help', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-usd', '--no-embed', '--remediate', '--source', '--stale', '--yes'],'repair-jsonb': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],- 'repos': ['--abbrev-ref', '--abort', '--access', '--account', '--admin-intent', '--after', '--all', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--cleanup-dead-local-locks', '--clear', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exclude-standard', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],+ 'repos': ['--abbrev-ref', '--abort', '--access', '--account', '--admin-intent', '--after', '--all', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--cleanup-dead-local-locks', '--clear', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],'retrieval-upgrade': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--yes'],'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],@@ -114,15 +114,15 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--workspace', '--yes'],'skillpack-check': ['--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--yes'],'smoke-test': ['--brain', '--help', '--json', '--source'],- 'sources': ['--abbrev-ref', '--abort', '--access', '--account', '--admin-intent', '--after', '--all', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--cleanup-dead-local-locks', '--clear', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exclude-standard', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],+ 'sources': ['--abbrev-ref', '--abort', '--access', '--account', '--admin-intent', '--after', '--all', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--cleanup-dead-local-locks', '--clear', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--help', '--json', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],- 'sync': ['--abbrev-ref', '--abort', '--account', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--watch', '--window', '--workers', '--working-tree', '--yes'],+ 'sync': ['--abbrev-ref', '--abort', '--account', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-auto-embed', '--no-autopilot-install', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--watch', '--window', '--workers', '--working-tree', '--yes'],'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--pglite', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],'transcripts': ['--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout'],- 'upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],+ 'upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],'waiting': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],'whoknows': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--explain', '--federated-read', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--url', '--yes'],diff --git a/src/core/code-chunks.ts b/src/core/code-chunks.tsindex fdc044083b..5528088f81 100644--- a/src/core/code-chunks.ts+++ b/src/core/code-chunks.ts@@ -3,11 +3,12 @@ import type { ChunkInput, CodeEdgeInput } from './types.ts';import { chunkCodeTextFull } from './chunkers/code.ts';import { findChunkForOffset } from './chunkers/edge-extractor.ts';import { sanitizeRemoteBody } from './remote-body.ts';+import { credentialSafeProjection } from './credential-projection.ts';import { isEmbedSkipped } from './embed-skip.ts';import { isQuarantined } from './quarantine.ts';export async function prepareCodeChunks(page: { compiled_truth: string; frontmatter?: Record<string, unknown> | null }, path: string) {- const content = sanitizeRemoteBody(page.compiled_truth);+ const content = credentialSafeProjection(sanitizeRemoteBody(page.compiled_truth));const prepared = isEmbedSkipped(page.frontmatter) || isQuarantined(page.frontmatter)? { chunks: [], edges: [] } : await chunkCodeTextFull(content, path);const chunks: ChunkInput[] = prepared.chunks.map((c, i) => ({diff --git a/src/core/context-engine.ts b/src/core/context-engine.tsindex 11a2e48d7e..38ed31c24c 100644--- a/src/core/context-engine.ts+++ b/src/core/context-engine.ts@@ -981,14 +981,14 @@ export function createGBrainContextEngine(ctx: {try {const hb = await import('./context/hook-heartbeat.ts');if (!deadlineHit() && (await hb.memorableGateAllowed(cfg)).allowed) {- // Entropy parity with the hook lane [red-team]: the segment file was- // vendor-scanned only — its rendering feeds the Cathedral-5 ledger- // hash and cannot change — but the relay child derives its egress- // task line from that text. Re-scan with highEntropy and REFUSE the- // relay when it finds anything the vendor pass missed (fail-closed;- // the next compaction window re-evaluates).+ // Entropy parity with the hook lane [red-team]: the segment file was vendor-scanned+ // only (its rendering feeds the Cathedral-5 ledger hash), but the relay child derives+ // its egress task line from that text. Re-scan with highEntropy and REFUSE the relay on+ // any hit, logged content-free (fail-closed; the next compaction window re-evaluates).const scan = await import('./secret-scan.ts');- if (scan.redactFindings(rendered.text, { highEntropy: true }).redactions.length > 0) {+ const [hit] = scan.redactFindings(rendered.text, { highEntropy: true }).redactions;+ if (hit) {+ await hb.writeHeartbeat(hb.relayRefusalHeartbeat(hit), { trim: false });throw new Error('entropy_hit'); // caught below — receipt+relay skipped, checkpoint unaffected}// Same span rule as the hook lane: windowTurns is a suffix ofdiff --git a/src/core/context/hook-heartbeat.ts b/src/core/context/hook-heartbeat.tsindex bd63d007a8..cc2d02c54c 100644--- a/src/core/context/hook-heartbeat.ts+++ b/src/core/context/hook-heartbeat.ts@@ -56,14 +56,33 @@ export interface HookHeartbeatEntry {flush?: string;/** Cathedral 5 — checkpoint-harvest verified-link COUNT (never slugs) [S3#7]. */links?: number;+ /** Secret-scan pattern NAME behind a refusal (scanner vocabulary, never the value). */+ pattern?: string;+ /** `sha256:<hex16>` fingerprint of the refused value (never the value). */+ fingerprint?: string;+ /** Fixed recovery hint for the refusal reason (constant text, never content). */+ hint?: string;}/** The FULL key allowlist — CI greps the fixture against this [S3#7]. */export const HEARTBEAT_ALLOWED_KEYS = ['ts', 'event', 'outcome', 'reason', 'duration_ms', 'turns', 'bytes', 'redactions','segment', 'inserted', 'duplicate', 'superseded', 'links', 'flush',+ 'pattern', 'fingerprint', 'hint',] as const;+/**+ * The heartbeat line for a relay refused by the high-entropy re-scan: reason+ * code, scanner pattern name, value fingerprint and a fixed recovery hint.+ */+export function relayRefusalHeartbeat(hit: { pattern: string; fingerprint: string }): HookHeartbeatEntry {+ return {+ ts: new Date().toISOString(), event: 'relay', outcome: 'degraded', reason: 'secret_scan_refused',+ duration_ms: 0, pattern: hit.pattern, fingerprint: hit.fingerprint,+ hint: 'receipt and relay skipped for this compaction window only; the checkpoint is banked and the next window is re-scanned',+ };+}+/** Gbrain home resolver: the S3#10 choke point (create-or-resolve, fail-open). */async function resolveHome(): Promise<string> {try {@@ -141,6 +160,9 @@ export async function writeHeartbeat(...(entry.duplicate !== undefined ? { duplicate: entry.duplicate } : {}),...(entry.links !== undefined ? { links: entry.links } : {}),...(entry.flush !== undefined ? { flush: entry.flush } : {}),+ ...(entry.pattern !== undefined ? { pattern: entry.pattern } : {}),+ ...(entry.fingerprint !== undefined ? { fingerprint: entry.fingerprint } : {}),+ ...(entry.hint !== undefined ? { hint: entry.hint } : {}),});appendFileSync(p, line + '\n', { mode: 0o600 });if (opts?.trim === false) return;diff --git a/src/core/context/retrieval-reflex.ts b/src/core/context/retrieval-reflex.tsindex bb2cd6a26e..512561343b 100644--- a/src/core/context/retrieval-reflex.ts+++ b/src/core/context/retrieval-reflex.ts@@ -33,6 +33,7 @@ import { escapeLikePattern } from '../search/sql-ranking.ts';import { slugify } from '../entities/resolve.ts';import { stripTakesFence } from '../takes-fence.ts';import { stripFactsFence } from '../facts-fence.ts';+import { redactFindings } from '../secret-scan.ts';import { privatePagesFilterFragment } from '../search/private-visibility.ts';import type { EntityCandidate } from './entity-salience.ts';import { reflexPointerRationale } from './reflex-rationale.ts';@@ -556,13 +557,15 @@ export function safeSynopsis(// run world-only (turn mode never widens).const keepVisibility = opts.keepVisibility ?? ['world'];const maxLen = opts.maxLen ?? SYNOPSIS_MAX;+ // Redact the whole source field before collapse/clip: a cut or+ // space-joined credential no longer matches the scanner.const fmSummary = row.frontmatter?.summary;if (typeof fmSummary === 'string' && fmSummary.trim()) {- return clip(collapse(fmSummary), maxLen);+ return clip(collapse(redactFindings(fmSummary, { highEntropy: true }).text), maxLen);}const body = row.compiled_truth ?? '';if (!body) return '';- const stripped = stripFactsFence(stripTakesFence(body), { keepVisibility });+ const stripped = redactFindings(stripFactsFence(stripTakesFence(body), { keepVisibility }), { highEntropy: true }).text;// Drop frontmatter block, markdown headings, and blank lines; first real prose line.const firstProse = stripped.replace(/^---[\s\S]*?---\s*/m, '')diff --git a/src/core/context/sensitivity-scan.ts b/src/core/context/sensitivity-scan.tsindex 25226c2cf7..44267a8060 100644--- a/src/core/context/sensitivity-scan.ts+++ b/src/core/context/sensitivity-scan.ts@@ -265,3 +265,19 @@ export function scanSensitive(return out;}++/**+ * The one diagnostic line for an entry dropped by the scan: reason, family,+ * fingerprint and the recovery hint. Content-free by construction (the slug+ * is the page id the caller already reports; the value is never passed in).+ */+export function formatSensitivityDrop(+ drop: { slug: string; family: string; fingerprint: string },+ workspaceRoot: string,+): string {+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal+ const allowPath = join(workspaceRoot, SCAN_ALLOW_FILENAME);+ return `omitted ${drop.slug} from the compiled context (reason: sensitivity_scan, pattern: ${drop.family}, ` ++ `fingerprint: ${drop.fingerprint}). Remove the value from the page; if it is a reviewed false positive, ` ++ `add the line "${drop.fingerprint}" to ${allowPath}.`;+}diff --git a/src/core/credential-projection.ts b/src/core/credential-projection.tsnew file mode 100644index 0000000000..5224c5cc15--- /dev/null+++ b/src/core/credential-projection.ts@@ -0,0 +1,31 @@+import { privateKeySpans } from './secret-scan.ts';++export const PRIVATE_KEY_PROJECTION_TOKEN = '<REDACTED:private_key_pem>';++/**+ * Retrieval text for a canonical page body: every private-key span (the+ * scanner's whole-text rules, including truncated and split keys) becomes one+ * `<REDACTED:private_key_pem>` token followed by as many newlines as the span+ * held, so line numbers stay stable. Chunkers and evidence reconstruction both+ * cut from this text, which keeps chunk anchors aligned and keeps key material+ * out of chunks, embeddings and delivered evidence. The stored body and raw+ * page reads are unchanged. Idempotent: the token holds no key marker.+ */+export function credentialSafeProjection(text: string): string {+ if (!text.includes('PRIVATE KEY-----')) return text;+ const spans = privateKeySpans(text);+ if (spans.length === 0) return text;+ const parts: string[] = [];+ let cursor = 0;+ for (const { start, end } of spans) {+ if (end <= cursor) continue;+ const from = Math.max(start, cursor);+ parts.push(text.slice(cursor, from));+ let newlines = 0;+ for (let i = from; i < end; i++) if (text.charCodeAt(i) === 10) newlines++;+ parts.push(PRIVATE_KEY_PROJECTION_TOKEN + '\n'.repeat(newlines));+ cursor = end;+ }+ parts.push(text.slice(cursor));+ return parts.join('');+}diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 24819c9f40..331e55f8ba 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -59,6 +59,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['atom_provenance_drift','connector_checkpoints','connector_held_items',+ 'credential_projection_pending','derived_visibility','extractor_facts_expired','orphan_persistence_bindings',@@ -201,6 +202,7 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['connection','db_only_collector_collision','federation_health',+ 'google_file_modes','google_oauth','home_dir_in_worktree','index_audit',diff --git a/src/core/google/file-modes.ts b/src/core/google/file-modes.tsnew file mode 100644index 0000000000..0131721cd6--- /dev/null+++ b/src/core/google/file-modes.ts@@ -0,0 +1,142 @@+/**+ * Group/world-readable files that gbrain wrote under a Google source+ * directory outside `~/.gbrain` (the home is forced 0700, so files inside it+ * are already private). Releases before the security fix wave wrote pages+ * and cursor state with the process umask, typically 0644, and only a+ * rewrite tightens them, so historical mail can stay readable by other local+ * users.+ *+ * Only gbrain's own layout is considered: the cursor state file and its+ * siblings (`.google-source.json*`), page files recorded for the source+ * under `emails/`, `calendar/` and `people/`, their stale `.tmp` files, and+ * the directories between the source root and those pages. The root the+ * user chose is never reported or changed, no path through a symlink is+ * followed, and entries another user owns are counted and left alone.+ * Tightening clears the group and other bits and keeps the owner bits.+ */+import { closeSync, constants, fchmodSync, fstatSync, lstatSync, openSync, readdirSync, realpathSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import { configDir } from '../config.ts';+import { isPathContained } from '../path-confine.ts';+import { parseGoogleSourceConfig } from './source-config.ts';++const LAYOUT = new Set(['emails', 'calendar', 'people']);+const STATE_PREFIX = '.google-source.json';++export interface LooseEntry { rel: string; kind: 'file' | 'dir'; mode: number }++export interface GoogleDirScan {+ sourceId: string;+ dir: string;+ loose: LooseEntry[];+ /** Entries left alone: a symlink on the path, another owner, or not the expected file type. */+ skipped: { symlink: number; foreign_owner: number; not_regular: number };+}++/** The source dir is outside the brain home, where its own permissions are the only protection. */+export function outsideGbrainHome(dir: string): boolean {+ const resolve = (path: string) => { try { return realpathSync(path); } catch { return path; } };+ return !isPathContained(resolve(dir), resolve(configDir()));+}++function currentUid(): number | null {+ return typeof process.getuid === 'function' ? process.getuid() : null;+}++type Verdict = { ok: true; mode: number } | { ok: false; reason: 'symlink' | 'foreign_owner' | 'not_regular' | 'missing' };++/** Lstat every component below `root` without following a symlink; the leaf must be `kind` and owned by this user. */+function inspect(root: string, rel: string, kind: LooseEntry['kind'], dirs: Map<string, Verdict>): Verdict {+ const parts = rel.split('/');+ for (let i = 1; i < parts.length; i++) {+ const prefix = parts.slice(0, i).join('/');+ let verdict = dirs.get(prefix);+ if (!verdict) {+ verdict = check(join(root, ...parts.slice(0, i)), 'dir');+ dirs.set(prefix, verdict);+ }+ if (!verdict.ok) return verdict;+ }+ return check(join(root, ...parts), kind);+}++function check(path: string, kind: LooseEntry['kind']): Verdict {+ let stat;+ try { stat = lstatSync(path); } catch { return { ok: false, reason: 'missing' }; }+ if (stat.isSymbolicLink()) return { ok: false, reason: 'symlink' };+ if (kind === 'dir' ? !stat.isDirectory() : !stat.isFile()) return { ok: false, reason: 'not_regular' };+ const uid = currentUid();+ if (uid !== null && stat.uid !== uid) return { ok: false, reason: 'foreign_owner' };+ return { ok: true, mode: stat.mode & 0o7777 };+}++export async function scanGoogleFileModes(engine: BrainEngine, opts: { sourceIds?: string[] } = {}): Promise<GoogleDirScan[]> {+ if (process.platform === 'win32') return [];+ const sources = await engine.executeRaw<{ id: string; local_path: string | null; config: Record<string, unknown> }>(+ "SELECT id, local_path, config FROM sources WHERE archived IS NOT TRUE AND config->>'kind'='google' ORDER BY id");+ const scans: GoogleDirScan[] = [];+ for (const source of sources) {+ if (opts.sourceIds && !opts.sourceIds.includes(source.id)) continue;+ const dir = parseGoogleSourceConfig(source.config, source.local_path ?? '').dir;+ if (!dir || !outsideGbrainHome(dir)) continue;+ const scan: GoogleDirScan = { sourceId: source.id, dir, loose: [], skipped: { symlink: 0, foreign_owner: 0, not_regular: 0 } };+ const candidates = new Map<string, LooseEntry['kind']>();+ let names: string[] = [];+ try { names = readdirSync(dir); } catch { /* a missing dir has nothing to tighten */ }+ for (const name of names) if (name.startsWith(STATE_PREFIX)) candidates.set(name, 'file');+ const pages = await engine.executeRaw<{ source_path: string }>(+ 'SELECT source_path FROM pages WHERE source_id=$1 AND source_path IS NOT NULL ORDER BY source_path', [source.id]);+ for (const { source_path: rel } of pages) {+ const parts = rel.split('/');+ if (parts.length < 2 || !LAYOUT.has(parts[0]) || parts.some(part => !part || part === '.' || part === '..') || rel.includes('\\')) continue;+ for (let i = 1; i < parts.length; i++) candidates.set(parts.slice(0, i).join('/'), 'dir');+ candidates.set(rel, 'file');+ candidates.set(`${rel}.tmp`, 'file');+ }+ const dirs = new Map<string, Verdict>();+ for (const [rel, kind] of [...candidates].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {+ const verdict = inspect(dir, rel, kind, dirs);+ if (verdict.ok) { if (verdict.mode & 0o077) scan.loose.push({ rel, kind, mode: verdict.mode }); }+ else if (verdict.reason !== 'missing' && !(rel.endsWith('.tmp') && verdict.reason === 'not_regular')) scan.skipped[verdict.reason]++;+ }+ scans.push(scan);+ }+ return scans;+}++/**+ * Clear the group and other bits of one scanned entry. The path is re-checked+ * (no symlink on the way, owned by this user) and the leaf is opened with+ * O_NOFOLLOW, so a swap after the scan is refused rather than followed.+ */+export function tightenGoogleEntry(root: string, entry: Pick<LooseEntry, 'rel' | 'kind'>):+ { outcome: 'tightened' | 'already_private' | 'skipped'; reason?: string; mode?: number } {+ const verdict = inspect(root, entry.rel, entry.kind, new Map());+ if (!verdict.ok) return verdict.reason === 'missing' ? { outcome: 'skipped', reason: 'missing' } : { outcome: 'skipped', reason: verdict.reason };+ let fd: number;+ try {+ fd = openSync(join(root, ...entry.rel.split('/')), constants.O_RDONLY | constants.O_NOFOLLOW | (entry.kind === 'dir' ? constants.O_DIRECTORY : 0));+ } catch (error) {+ return { outcome: 'skipped', reason: (error as NodeJS.ErrnoException).code ?? 'open_failed' };+ }+ try {+ const stat = fstatSync(fd);+ const uid = currentUid();+ if (uid !== null && stat.uid !== uid) return { outcome: 'skipped', reason: 'foreign_owner' };+ const mode = stat.mode & 0o7777;+ if (!(mode & 0o077)) return { outcome: 'already_private', mode };+ fchmodSync(fd, mode & ~0o077);+ return { outcome: 'tightened', mode: mode & ~0o077 };+ } finally {+ closeSync(fd);+ }+}++export function googleFileModesPreviewCommand(sourceId: string): string {+ return `gbrain repair google-file-modes --source ${sourceId}`;+}++export function googleFileModesApplyCommand(sourceId: string): string {+ return `gbrain repair google-file-modes --source ${sourceId} --apply`;+}diff --git a/src/core/google/google-source.ts b/src/core/google/google-source.tsindex e42c4f86b5..747fe5fbd1 100644--- a/src/core/google/google-source.ts+++ b/src/core/google/google-source.ts@@ -29,7 +29,7 @@ import { carryLegacyFailCounts } from '../connectors/item-holds.ts';* sources.config, which stores only the account pointer.*/-import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { chmodSync, closeSync, existsSync, fchmodSync, lstatSync, openSync, readFileSync, renameSync, rmSync, unlinkSync, writeSync } from 'node:fs';import { dirname, join, relative } from 'node:path';import type { BrainEngine } from '../engine.ts';@@ -41,7 +41,7 @@ import { credentialId, openVault, type CredentialEntry, type CredentialVault } fimport { createProgress, startHeartbeat } from '../progress.ts';import { getCliOptions, cliOptsToProgressOptions } from '../cli-options.ts';import { isWriteTargetContained } from '../path-confine.ts';-import { atomicWriteFileSync } from '../atomic-write.ts';+import { atomicWriteFileSync, mkdirPrivate } from '../atomic-write.ts';import {CalendarClient,GmailClient,@@ -109,22 +109,70 @@ export function readGoogleState(dir: string): GoogleSourceState {// A CORRUPT existing state file is not a fresh install: silently// returning emptyState() would re-run the entire backfill with zero// diagnostic. Quarantine for forensics and say so loudly.+ const quarantine = `${file}.corrupt`;+ let failure: { step: 'chmod' | 'rename'; path: string; error: unknown } | null = null;try {- renameSync(file, `${file}.corrupt`);- } catch { /* best-effort */ }+ chmodSync(file, 0o600);+ } catch (error) {+ failure = { step: 'chmod', path: file, error };+ }+ try {+ renameSync(file, quarantine);+ if (failure) failure.path = quarantine;+ } catch (error) {+ failure ??= { step: 'rename', path: file, error };+ }process.stderr.write(`[google] state file ${file} was corrupt (${e instanceof Error ? e.message : String(e)}); ` +`quarantined to .corrupt — cursors reset, the next sync re-anchors and resumes.\n`,);+ if (failure) {+ process.stderr.write(+ `[google] could not secure the quarantined state file ${failure.path}: ${failure.step} failed ` ++ `(${failure.error instanceof Error ? failure.error.message : String(failure.error)}). ` ++ `It may be readable by other local users; run chmod 600 ${failure.path} or delete it.\n`,+ );+ }return emptyState();}}function writeGoogleState(dir: string, state: GoogleSourceState): void {- mkdirSync(dir, { recursive: true });+ mkdirPrivate(dir);// Atomic (tmp+fsync+rename): this file is written once per backfill batch;// a torn write would silently reset every cursor (full re-backfill).- atomicWriteFileSync(googleStateFile(dir), JSON.stringify(state, null, 2));+ // 0600 is reasserted on every write, so a legacy 0644 file tightens.+ atomicWriteFileSync(googleStateFile(dir), JSON.stringify(state, null, 2), { mode: 0o600 });+}++/**+ * Write a page's temp file privately: a stale `.tmp` left by a crash is+ * removed first (never followed), then the temp file is created exclusively at+ * 0600 and fchmod-ed past the umask before any byte lands. Renaming it over+ * the page makes new and rewritten pages 0600.+ */+function writePrivateTemp(tmpPath: string, markdown: string): void {+ let stale: ReturnType<typeof lstatSync> | null = null;+ try { stale = lstatSync(tmpPath); } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ if (stale?.isDirectory()) {+ throw new Error(`Stale temporary path ${tmpPath} is a directory; remove it and re-run the sync.`);+ }+ if (stale) unlinkSync(tmpPath);+ const buf = Buffer.from(markdown, 'utf-8');+ const fd = openSync(tmpPath, 'wx', 0o600);+ try {+ fchmodSync(fd, 0o600);+ let off = 0;+ while (off < buf.length) {+ const n = writeSync(fd, buf, off, buf.length - off);+ if (n <= 0) throw new Error(`Short write to ${tmpPath} at offset ${off}/${buf.length}`);+ off += n;+ }+ } finally {+ closeSync(fd);+ }}/** The "my addresses" identity set: account + Gmail sendAs aliases. */@@ -208,12 +256,12 @@ async function importRendered(}const filePath = join(deps.cfg.dir, relPath);assertContained(deps.cfg.dir, filePath);- mkdirSync(dirname(filePath), { recursive: true });+ mkdirPrivate(dirname(filePath), deps.cfg.dir);const before = existsSync(filePath);// Temp-write → import → rename: a failed import never destroys the// previously-good page (github-source pattern).const tmpPath = `${filePath}.tmp`;- writeFileSync(tmpPath, markdown, 'utf-8');+ writePrivateTemp(tmpPath, markdown);try {const { importFile } = await import('../import-file.ts');const result = await importFile(deps.engine, tmpPath, relPath, {diff --git a/src/core/markdown-chunks.ts b/src/core/markdown-chunks.tsindex 735d9023d5..4d967c339d 100644--- a/src/core/markdown-chunks.ts+++ b/src/core/markdown-chunks.ts@@ -2,6 +2,7 @@ import type { ChunkInput } from './types.ts';import { chunkText } from './chunkers/recursive.ts';import { chunkCodeText, detectCodeLanguage } from './chunkers/code.ts';import { sanitizeRemoteBody } from './remote-body.ts';+import { credentialSafeProjection } from './credential-projection.ts';import { scanFencedBlocks, MAX_FENCES_PER_PAGE } from './fence-scan.ts';import { isEmbedSkipped } from './embed-skip.ts';import { isQuarantined } from './quarantine.ts';@@ -51,7 +52,7 @@ async function extractFencedChunks(markdown: string,startChunkIndex: number,): Promise<ChunkInput[]> {- markdown = sanitizeRemoteBody(markdown);+ markdown = credentialSafeProjection(sanitizeRemoteBody(markdown));const out: ChunkInput[] = [];// Fast path: most pages (prose, tables, converted docs) contain no code// fence at all, so there is nothing for this function to extract — skipdiff --git a/src/core/migration-ledger.ts b/src/core/migration-ledger.tsindex 0499928186..4336cb06ad 100644--- a/src/core/migration-ledger.ts+++ b/src/core/migration-ledger.ts@@ -23,7 +23,7 @@ import { loadCompletedMigrations, type CompletedMigrationEntry } from './prefereexport const MIGRATION_VERSIONS: readonly string[] = ['0.11.0', '0.12.0', '0.12.2', '0.13.0', '0.13.1', '0.14.0', '0.16.0','0.18.0', '0.18.1', '0.21.0', '0.22.4', '0.28.0', '0.29.1', '0.31.0',- '0.32.2', '0.43.0', '0.46.3', '0.53.0',+ '0.32.2', '0.43.0', '0.46.3', '0.53.0', '0.60.31',];/** Bug 3 attempt cap — consecutive partials before a version counts wedged. */diff --git a/src/core/operations.ts b/src/core/operations.tsindex b9656fc93d..623385bd36 100644--- a/src/core/operations.ts+++ b/src/core/operations.ts@@ -12,6 +12,7 @@ export { MEMORY_VERBS_VERSION };// operations.ts is unchanged.import type { Operation } from './ops/contract.ts';+import { withOutputRedaction } from './search/output-redaction.ts';// Re-exports: the full previously-exported foundation surface of this module.// The formerly file-private helpers (enforceSubagentSlugFence, slugUnderSubagentFence,@@ -322,6 +323,7 @@ for (const op of operations) {if (op.area === undefined && OP_AREAS[op.name] !== undefined) {op.area = OP_AREAS[op.name];}+ op.handler = withOutputRedaction(op);}export const operationsByName = Object.fromEntries(diff --git a/src/core/ops/admin.ts b/src/core/ops/admin.tsindex 5436d3bb3f..461c043b89 100644--- a/src/core/ops/admin.ts+++ b/src/core/ops/admin.ts@@ -32,6 +32,7 @@ function diagnosticScope(ctx: OperationContext): { sourceId?: string; sourceIds?const get_stats: Operation = {name: 'get_stats',+ outputRedaction: 'no_stored_text',description: 'Brain statistics (page count, chunk count, etc.) — remote callers see counters confined to their source grant.',params: {},handler: async (ctx) => {@@ -43,6 +44,7 @@ const get_stats: Operation = {const get_health: Operation = {name: 'get_health',+ outputRedaction: 'no_stored_text',description: 'Brain health dashboard (embed coverage, stale pages, orphans) — remote callers see counters confined to their source grant. Includes a `migrations {pending, partial, wedged, skipped_future}` block from the host migration ledger so remote agents can detect wedged/outstanding host migrations without shelling into the brain host.',params: {},handler: async (ctx) => {@@ -85,6 +87,7 @@ const get_health: Operation = {*/const get_brain_identity: Operation = {name: 'get_brain_identity',+ outputRedaction: 'no_stored_text',description: 'Brain identity + counters for thin-client banner — remote callers see counters confined to their source grant. Returns version, engine kind, and page/chunk counts. Read-scope.',params: {},handler: async (ctx) => {@@ -141,6 +144,7 @@ const get_brain_identity: Operation = {*/const run_doctor: Operation = {name: 'run_doctor',+ outputRedaction: 'no_stored_text',description: 'Run brain health checks and return a structured DoctorReport (thin-client doctor surface).',params: {},handler: async (ctx) => {@@ -161,6 +165,7 @@ const run_doctor: Operation = {const get_versions: Operation = {name: 'get_versions',+ outputRedaction: { exempt: 'full page version snapshots by slug; a page read governed by visibility like get_page (CEO-17)' },description: 'Page version history',params: {slug: { type: 'string', required: true, description: 'Slug of the page whose version history to list.' },@@ -177,6 +182,7 @@ const get_versions: Operation = {const revert_version: Operation = {name: 'revert_version',+ outputRedaction: 'no_stored_text',description: 'Revert page to a previous version',params: {...PAGE_MUTATION_PARAMS,@@ -205,6 +211,7 @@ const revert_version: Operation = {*/const quarantine_list: Operation = {name: 'quarantine_list',+ outputRedaction: 'retrieval',description:'List quarantined (hidden) and optionally content-flagged pages by scanning page ' +'frontmatter, newest-updated first. When truncated is true, count is a LOWER BOUND — ' +diff --git a/src/core/ops/brain-membership.ts b/src/core/ops/brain-membership.tsindex 043146ebd1..0241639bc3 100644--- a/src/core/ops/brain-membership.ts+++ b/src/core/ops/brain-membership.ts@@ -4,6 +4,7 @@ import { joinBrain, leaveBrain, syncBrain } from '../shared-skills/membership.tsexport const brainMembershipOperations: Operation[] = [{name: 'join_brain', description: 'Enroll this authenticated principal to follow approved shared skills. Shared credentials are one principal. Never grants memory-write or editor authority.',+ outputRedaction: 'no_stored_text',scope: 'read', mutating: true, requiredScopes: ['skills_member_self'],cliHints: { name: 'join-brain', positional: [] },params: { adapter: { type: 'string', required: true, description: 'Registered harness adapter ID for this authenticated installation.' }, follow_policy: { type: 'object', required: true, description: 'Explicit approved:true and optional source_ids narrowing.' } },@@ -11,6 +12,7 @@ export const brainMembershipOperations: Operation[] = [},{name: 'sync_brain_skills', description: 'Get a complete authorized shared-skills view and optionally record an own issued-batch delivery acknowledgment. Unavailable is never an empty catalog.',+ outputRedaction: { exempt: 'skill catalog files are installed instructions read verbatim; redaction would corrupt approved revisions' },scope: 'read', mutating: true, requiredScopes: ['skills_member_self'],cliHints: { name: 'sync-brain-skills', positional: [] },params: { installation_id: { type: 'string', required: true, description: 'Own server-issued installation UUID returned by join_brain.' }, enrollment_epoch: { type: 'number', required: true, description: 'Current enrollment epoch returned by join_brain; stale epochs cannot reactivate membership.' }, acknowledgment: { type: 'object', description: 'Optional issued batch token and exact delivery evidence for this installation, never proof of native use.' } },@@ -18,6 +20,7 @@ export const brainMembershipOperations: Operation[] = [},{name: 'leave_brain', description: 'Stop only this principal’s enrollment. Does not revoke credentials or prove native cached instructions were disabled.',+ outputRedaction: 'no_stored_text',scope: 'read', mutating: true, requiredScopes: ['skills_member_self'],cliHints: { name: 'leave-brain', positional: [] },params: { installation_id: { type: 'string', required: true, description: 'Own server-issued installation UUID to leave.' }, enrollment_epoch: { type: 'number', required: true, description: 'Current enrollment epoch; a previous installation cannot leave its replacement.' } },diff --git a/src/core/ops/calibration.ts b/src/core/ops/calibration.tsindex f524a58f35..c980712392 100644--- a/src/core/ops/calibration.ts+++ b/src/core/ops/calibration.ts@@ -12,6 +12,7 @@ import type { Operation } from './contract.ts';const get_calibration_profile: Operation = {name: 'get_calibration_profile',+ outputRedaction: 'retrieval',description:'Read the active calibration profile for a holder. Returns the latest row from calibration_profiles ' +'(per-source, per-holder) including Brier score, accuracy, pattern statements, and active bias tags. ' +diff --git a/src/core/ops/chronicle.ts b/src/core/ops/chronicle.tsindex 8450c91222..95aa501466 100644--- a/src/core/ops/chronicle.ts+++ b/src/core/ops/chronicle.ts@@ -33,6 +33,7 @@ function redactDiaryTimeline<// All route through sourceScopeOpts(ctx) so reads honor source isolation.const chronicle_day: Operation = {name: 'chronicle_day',+ outputRedaction: 'retrieval',description:'Life Chronicle: events + timeline entries on a given day (or its ISO week when week=true), ' +"ordered chronologically; each row backlinks to its depth page. Distinct from `get_timeline`/" +@@ -61,6 +62,7 @@ const chronicle_day: Operation = {const chronicle_on_this_day: Operation = {name: 'chronicle_on_this_day',+ outputRedaction: 'retrieval',description:'Life Chronicle: events from the same calendar day in PRIOR years ("on this day"). ' +'CLI: `gbrain on-this-day [--date YYYY-MM-DD]`.',@@ -79,6 +81,7 @@ const chronicle_on_this_day: Operation = {const chronicle_since: Operation = {name: 'chronicle_since',+ outputRedaction: 'retrieval',description:'Life Chronicle: events + timeline entries on or after a date, optionally filtered by event kind. ' +'CLI: `gbrain since <date> [--kind commitment]`.',@@ -100,6 +103,7 @@ const chronicle_since: Operation = {const chronicle_last_seen: Operation = {name: 'chronicle_last_seen',+ outputRedaction: 'retrieval',description:"Life Chronicle: when an entity was last seen — its own timeline rows OR an event's `who`. " +'Returns last_date, the event slug, and days_ago. CLI: `gbrain last-seen <entity-slug>`.',@@ -127,6 +131,7 @@ const chronicle_last_seen: Operation = {const ontology_get: Operation = {name: 'ontology_get',+ outputRedaction: 'retrieval',description:"Life Chronicle: the current resolved per-entity ontology (dimension → value) at `asof` " +"(default now), with provenance + confidence + validity. CLI: `gbrain ontology <entity> [--asof YYYY-MM-DD]`.",@@ -154,6 +159,7 @@ const ontology_get: Operation = {const ontology_propose: Operation = {name: 'ontology_propose',+ outputRedaction: 'retrieval',description:'Life Chronicle: record one ontology observation (entity has dimension=value), sourced + ' +'confidence-weighted + bi-temporal. Idempotent on (entity,dimension,value,source). A new value ' +@@ -198,6 +204,7 @@ const ontology_propose: Operation = {const ontology_dimensions: Operation = {name: 'ontology_dimensions',+ outputRedaction: 'no_stored_text',description:'Life Chronicle meta-ontology: which dimensions the brain tracks across entities, with ' +'entity + observation counts. CLI: `gbrain ontology-dimensions`.',@@ -209,6 +216,7 @@ const ontology_dimensions: Operation = {const ontology_conflicts: Operation = {name: 'ontology_conflicts',+ outputRedaction: 'retrieval',description:'Life Chronicle: dimensions with ≥2 distinct current values from ≥2 provenances (genuine ' +'disagreement, not temporal supersession). CLI: `gbrain ontology-contradictions`.',@@ -234,6 +242,7 @@ const ontology_conflicts: Operation = {const volunteer_chronicle: Operation = {name: 'volunteer_chronicle',+ outputRedaction: 'retrieval',description:'Life Chronicle agent-orientation: the recent timeline (last N days) + the current ' +'validity-resolved ontology for the named entities, in one zero-LLM payload, so an agent ' +@@ -266,6 +275,7 @@ const volunteer_chronicle: Operation = {const chronicle_backfill: Operation = {name: 'chronicle_backfill',+ outputRedaction: 'no_stored_text',description:'Life Chronicle: sweep existing meeting/conversation/calendar pages into timeline events by ' +'enqueuing chronicle_extract jobs (one per eligible page). --dry-run counts without enqueuing. ' +diff --git a/src/core/ops/chunks.ts b/src/core/ops/chunks.tsindex a9e96d0d07..25202d6287 100644--- a/src/core/ops/chunks.ts+++ b/src/core/ops/chunks.ts@@ -14,6 +14,7 @@ import { federatedSearchScope, parseSourceIdParam } from './context.ts';const resolve_slugs: Operation = {name: 'resolve_slugs',+ outputRedaction: 'no_stored_text',description: 'Fuzzy-resolve a partial slug to matching page slugs',params: {partial: { type: 'string', required: true, description: "Partial slug or title text to match, e.g. 'alice-ex' or 'meeting notes'. This is the search text param — there is no `text` param." },@@ -38,6 +39,7 @@ const resolve_slugs: Operation = {const get_chunks: Operation = {name: 'get_chunks',+ outputRedaction: { exempt: 'explicit chunk read by slug, the page-read twin of get_page (CEO-17 raw-read exception)' },description: 'Get content chunks for a page',params: {slug: { type: 'string', required: true, description: 'Slug of the page whose content chunks to return.' },diff --git a/src/core/ops/code-intel.ts b/src/core/ops/code-intel.tsindex 0b8ea88b3f..e6f48b579b 100644--- a/src/core/ops/code-intel.ts+++ b/src/core/ops/code-intel.ts@@ -35,6 +35,7 @@ import {const code_callers: Operation = {name: 'code_callers',+ outputRedaction: 'retrieval',description: CODE_CALLERS_DESCRIPTION,params: {symbol: { type: 'string', required: true, description: 'Symbol to find callers of (bare or qualified name).' },@@ -74,6 +75,7 @@ const code_callers: Operation = {const code_callees: Operation = {name: 'code_callees',+ outputRedaction: 'retrieval',description: CODE_CALLEES_DESCRIPTION,params: {symbol: { type: 'string', required: true, description: 'Symbol to find callees of (bare or qualified name).' },@@ -111,6 +113,7 @@ const code_callees: Operation = {const code_def: Operation = {name: 'code_def',+ outputRedaction: 'retrieval',description: CODE_DEF_DESCRIPTION,params: {symbol: { type: 'string', required: true, description: 'Symbol name (bare token; e.g., parseMarkdown, BrainEngine).' },@@ -135,6 +138,7 @@ const code_def: Operation = {const code_refs: Operation = {name: 'code_refs',+ outputRedaction: 'retrieval',description: CODE_REFS_DESCRIPTION,params: {symbol: { type: 'string', required: true, description: 'Symbol to find references to.' },@@ -189,6 +193,7 @@ async function attachWalkReadiness(ctx: OperationContext, walk: WalkResult, sourconst code_blast: Operation = {name: 'code_blast',+ outputRedaction: 'retrieval',description: 'BEFORE editing any function, run code_blast with the symbol name to surface every transitive caller grouped by depth (direct → 2-hop → 3-hop). Use this during plan-mode to size the change. Returns up to 200 nodes. Trust an empty/not_found result only when ready=true; ready=false means impact is unknown and requires a safe fallback. Returns: {result, status, ready, depth_groups?, truncation?, cycles_detected?, did_you_mean?, candidates?}. Example ok: {result:"ok", status:"ready", ready:true, depth_groups:[{depth:1, nodes:[{symbol,chunk_id}], confidence:0.77}], truncation:"none"}.',params: {symbol: { type: 'string', required: true, description: 'Bare or qualified symbol name (e.g. "performSync" or "src/foo::performSync")' },@@ -224,6 +229,7 @@ const code_blast: Operation = {const code_flow: Operation = {name: 'code_flow',+ outputRedaction: 'retrieval',description: 'When tracing how a request flows through the codebase from entry point to side effect (DB write, HTTP call, file I/O), run code_flow from the entry point. Returns ordered execution chain with terminal-node tags. Returns: same envelope as code_blast plus terminal_nodes: [{symbol, sink_kind}] where sink_kind ∈ "db_call"|"http_call"|"file_io"|"process_exec"|"unknown".',params: {entry_point: { type: 'string', required: true, description: 'Entry-point symbol name (bare or qualified)' },@@ -258,6 +264,7 @@ const code_flow: Operation = {const code_traversal_cache_clear: Operation = {name: 'code_traversal_cache_clear',+ outputRedaction: 'no_stored_text',description: 'Clear cached code_blast / code_flow traversal results. Source-scoped by default; pass all_sources=true to wipe everything (D8 destructive-guard).',params: {source_id: { type: 'string', description: 'Source to clear. Required unless all_sources=true.' },diff --git a/src/core/ops/connectors.ts b/src/core/ops/connectors.tsindex 73f8f5a3fb..48dcfcbcb1 100644--- a/src/core/ops/connectors.ts+++ b/src/core/ops/connectors.ts@@ -28,6 +28,7 @@ import { runConnectorSync } from '../connectors/sync.ts';const connectors_status: Operation = {name: 'connectors_status',+ outputRedaction: 'no_stored_text',description:'Per-provider chat-connector status: strategies, whether a credential is ' +'present and from where (env/file — never the value), token expiry, ' +@@ -71,6 +72,7 @@ const connectors_status: Operation = {const connector_sync: Operation = {name: 'connector_sync',+ outputRedaction: 'no_stored_text',description:'Sync a chat provider\'s conversation history into the brain: list new ' +'conversations since the watermark, fetch them, and ingest as pages under ' +diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.tsindex e6fb3333aa..316c172e08 100644--- a/src/core/ops/contract.ts+++ b/src/core/ops/contract.ts@@ -499,11 +499,29 @@ export interface ExplicitReadBinding {optedOut: string[];}+/**+ * How an op's response is treated before it reaches any caller. `operations.ts`+ * wraps the handler of every `'retrieval'` op once at registration, so the CLI,+ * both MCP transports, subagent tools and `gbrain call` all get the same pass:+ * `redactRetrievalOutput` (canonical scanner, assignment rule on, uncapped)+ * over the whole response, early returns included.+ * - `{ retrieval: { localVerbatim } }`: same pass, but the named top-level keys+ * are returned unscanned to the trusted local CLI owner (`ctx.remote === false`).+ * - `{ exempt }`: returns stored text deliberately raw; the reason is required.+ * - `'no_stored_text'`: returns no page, chunk, fact, take or transcript text.+ */+export type OutputRedactionPolicy =+ | 'retrieval'+ | { retrieval: { localVerbatim: readonly string[] } }+ | { exempt: string }+ | 'no_stored_text';+export interface Operation {name: string;description: string;params: Record<string, ParamDef>;handler: (ctx: OperationContext, params: Record<string, unknown>) => Promise<unknown>;+ outputRedaction: OutputRedactionPolicy;mutating?: boolean;/*** Capability scope required to invoke this op over an authenticateddiff --git a/src/core/ops/embedding-migration.ts b/src/core/ops/embedding-migration.tsindex 9acd51c73a..b5604aaffc 100644--- a/src/core/ops/embedding-migration.ts+++ b/src/core/ops/embedding-migration.ts@@ -16,6 +16,7 @@ import type { Operation } from './contract.ts';const migrate_embeddings: Operation = {name: 'migrate_embeddings',+ outputRedaction: 'no_stored_text',description: 'Re-embed the brain onto a different embedding provider/model (#3390): schema dimension transition, NULL-signature (#3391) invalidation, query-cache purge, resumable re-embed. Without yes=true returns the plan + cost estimate only. Local-only admin op; the primary surface is `gbrain migrate embeddings`.',params: {to: { type: 'string', required: true, description: 'Target provider:model (e.g. openai:text-embedding-3-small).' },diff --git a/src/core/ops/entity-identity.ts b/src/core/ops/entity-identity.tsindex 8dcf752f95..2e27e97751 100644--- a/src/core/ops/entity-identity.ts+++ b/src/core/ops/entity-identity.ts@@ -46,6 +46,7 @@ function resolveWriteSourceId(ctx: Parameters<Operation['handler']>[0], p: Recorconst entity_identity_link: Operation = {name: 'entity_identity_link',+ outputRedaction: 'no_stored_text',description:'Link a page into a cross-source entity identity group (v1 manual-only; no auto-matching). ' +'The identity key is (source_id, slug); a page belongs to at most one group and re-linking moves it. ' +@@ -80,6 +81,7 @@ const entity_identity_link: Operation = {const entity_identity_unlink: Operation = {name: 'entity_identity_unlink',+ outputRedaction: 'no_stored_text',description: 'Remove a page from a cross-source entity identity group (v1 manual-only).',params: {entity_id: { type: 'string', required: true, description: 'Identity handle the member currently belongs to.' },@@ -106,6 +108,7 @@ const entity_identity_unlink: Operation = {const entity_identity_list: Operation = {name: 'entity_identity_list',+ outputRedaction: 'no_stored_text',description:'List cross-source entity identity groups and their member pages. Filter by entity_id or by a member slug. ' +'Federated callers only see members in sources their grant covers.',diff --git a/src/core/ops/extraction.ts b/src/core/ops/extraction.tsindex f99103cf43..3ee67f526e 100644--- a/src/core/ops/extraction.ts+++ b/src/core/ops/extraction.ts@@ -46,6 +46,7 @@ const MAX_EXTRACT_ENTITIES = 200;const extract_entities: Operation = {name: 'extract_entities',+ outputRedaction: 'retrieval',description: 'Extract entity names (people, companies) from text and create/update their brain stub pages. Stubs from untrusted input land in the quarantine lane (frontmatter `provenance: auto-extracted` + `status: unverified`) — excluded from authoritative retrieval boosts until reviewed. Direct authoritative writes require the trusted local CLI AND --trusted-extraction.',params: {text: { type: 'string', required: true, description: 'The text to extract entities from (email, transcript, pasted content, …). Max 200k characters — split larger inputs.' },@@ -101,6 +102,7 @@ const extract_entities: Operation = {const extraction_pending: Operation = {name: 'extraction_pending',+ outputRedaction: 'retrieval',description: 'List unverified auto-extracted entity stubs awaiting owner review (the quarantine lane from extract_entities). Promote or reject them with extraction_review.',params: {limit: { type: 'number', required: false, description: 'Max rows (default 100, cap 500).' },@@ -146,6 +148,7 @@ const extraction_pending: Operation = {const extraction_review: Operation = {name: 'extraction_review',+ outputRedaction: 'no_stored_text',description: 'Promote or reject unverified auto-extracted entity stubs (batch). Promote flips `status` to verified (provenance kept for audit); reject soft-deletes the stub. Owner-only: this op is refused for any non-local caller. (The markers are ordinary frontmatter — the boundary against rewriting them wholesale is put_page write authz, same as for any page.)',params: {action: { type: 'string', required: true, description: "'promote' or 'reject'." },diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex c933e51493..5ad05bd2a4 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -24,6 +24,7 @@ import { hybridSearchCached, stampContentFlags } from '../search/hybrid.ts';import { dedupResults } from '../search/dedup.ts';import { bumpLastRetrievedAt } from '../last-retrieved.ts';import { packToBudget, estimateTokens, resultTokens } from '../search/token-budget.ts';+import { redactRetrievalOutput } from '../search/output-redaction.ts';import { isAvailable } from '../ai/gateway.ts';// #4209: the named entity-hints cap — surfaced in the extract_facts param// description and the entity_hints_used/_dropped response fields.@@ -40,6 +41,7 @@ import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';const extract_facts: Operation = {name: 'extract_facts',+ outputRedaction: 'no_stored_text',description:'v0.31: extract personal-knowledge facts (events, preferences, commitments, beliefs, ideas, and plain facts) from a conversation turn into the per-source hot memory. Sanitizes turn_text via INJECTION_PATTERNS, calls the configured extraction model (key-aware: any servable provider — OpenAI or Anthropic key both work), runs the cosine fast-path + classifier dedup pipeline, INSERTs into facts. Returns counts by status. With NO servable chat model, returns skipped: extraction_unavailable + an agent_action telling YOU to extract and write via `remember` (visibility: "private"). Skips extraction when the turn is dream-generated content (anti-loop). For agent memory writes of a SINGLE already-formed fact, prefer the `remember` verb (zero LLM, mandatory provenance).',params: {@@ -199,6 +201,7 @@ function recallEvidencePlan(ctx: OperationContext, p: Record<string, unknown>):const recall: Operation = {name: 'recall',+ outputRedaction: { retrieval: { localVerbatim: ['facts'] } },description:'MEMORY VERB (v1): retrieve saved facts/snippets — the protocol read verb. Filters hot-memory facts by entity / since / session_id; pass `query` to ALSO run hybrid search over pages (results[] arm); pass `budget_tokens` for server-side packing (response reports budget_used + dropped_count — never trims client-side). Remote callers see visibility=world facts only. Routing: for ONE known person/company/project card use `entity` (zero LLM); for broad questions needing reasoning use `synthesize` (expensive). Branch on structured fields (status/kind/evidence), never on prose. Every response carries protocol_version.',params: {@@ -457,6 +460,11 @@ const recall: Operation = {if (applied) ({ results: searchResults, delivery } = await deliverEvidence(ctx.engine, searchResults, applied, { ...searchScope, excludePrivate, requireSafeChunks: ctx.remote !== false }));}+ // Pack what is delivered: results redacted for all; facts for remote only (localVerbatim).+ const view = redactRetrievalOutput([{ facts: rows.map(r => ({ fact: r.fact, context: r.context, source: r.source })), results: searchResults }], {}).results[0];+ searchResults = view.results;+ if (ctx.remote !== false) rows = rows.map((r, i) => ({ ...r, ...view.facts[i] }));+let packedFacts = rows;let packedResults = searchResults;let budgetUsed: number | undefined;@@ -597,6 +605,7 @@ const dropAll = <T>(items: T[]) => ({ items: [] as T[], meta: { budget: 0, used:const context_pack: Operation = {name: 'context_pack',+ outputRedaction: { retrieval: { localVerbatim: ['facts'] } },description:'MEMORY VERB (v1): budget-packed session-boundary bundle for a set of standing entities — entity cards + open threads + hot facts, zero-LLM, sub-second. Call at session start (warm cold context) and after compaction (rehydrate what the summary lost). WORLD-ONLY by default; pass include_private (honored for LOCAL trusted callers only) to widen all arms. budget_tokens packs server-side (response reports budget_used + dropped_count; cards pack first, then facts). Branch on structured fields, never prose. protocol_version rides every response.',params: {@@ -644,8 +653,12 @@ const context_pack: Operation = {maxEntities: PACK_DEFAULT_MAX_ENTITIES,});- let cards = res.cards ?? [];- let facts = res.facts ?? [];+ // Pack, price and render the redacted presentation sets (one echo+ // dictionary); local callers get the delivered facts back raw below.+ const rawFacts = res.facts ?? [];+ const view = redactRetrievalOutput([{ cards: res.cards ?? [], facts: rawFacts }], {}).results[0];+ let cards = view.cards;+ let facts = view.facts;// The SAME since filter the assembler applied (pre-landing review: the raw// flatMap silently dropped the documented `since` contract from the// structured array whenever budget packing ran) — shared with the card@@ -687,7 +700,7 @@ const context_pack: Operation = {backlink_count: c.backlink_count,})),open_threads,- facts: facts.map((f) => ({+ facts: (ctx.remote === false ? rawFacts.slice(0, facts.length) : facts).map((f) => ({fact: f.fact,kind: f.kind,entity_slug: f.entity_slug,@@ -707,6 +720,7 @@ const context_pack: Operation = {const delta: Operation = {name: 'delta',+ outputRedaction: { retrieval: { localVerbatim: ['facts'] } },description:'MEMORY VERB (v1): "what changed since T" for heartbeats — pages updated after `since` + hot facts newer than `since` + open-thread events after `since`, zero-LLM. Lets a periodic wake maintain warm state in O(changes) instead of re-deriving. Optionally scope thread deltas to `entities`. WORLD-ONLY by default; include_private honored for local trusted callers only. budget_tokens packs server-side (pages first, then facts; threads are never dropped). protocol_version rides every response.',params: {@@ -830,11 +844,17 @@ const delta: Operation = {// Pages arrive OLDEST first by (updated_at, slug) — no client-side dedup// needed; the keyset already excludes everything at/before the cursor.- let pages = res.deltaPages ?? [];- let facts = res.facts ?? [];+ // Pack, price and render the redacted presentation sets (one echo+ // dictionary). The cursor reads the raw page at the delivered index and+ // local callers get the delivered facts back raw below.+ const rawPages = res.deltaPages ?? [];+ const rawFacts = res.facts ?? [];+ const view = redactRetrievalOutput([{ pages: rawPages, facts: rawFacts, threads: res.openThreads ?? [] }], {}).results[0];+ let pages = view.pages;+ let facts = view.facts;// Threads are NEVER budget-dropped: they are the commitments a heartbeat// must not miss, and they have no keyset of their own to resume from.- const threads = res.openThreads ?? [];+ const threads = view.threads;let droppedCount: number | undefined;let factsDropped = 0;const fetchedPages = pages.length;@@ -874,7 +894,7 @@ const delta: Operation = {// NOT advance (deliver-before-advance; a too-small budget must not eat it).const nextCursor =pages.length > 0- ? { since: pages[pages.length - 1].updated_at, slug: pages[pages.length - 1].slug }+ ? { since: rawPages[pages.length - 1].updated_at, slug: rawPages[pages.length - 1].slug }: { since: effectiveSince, slug: sinceSlug ?? '' };if (sessionId) {if (pages.length > 0) {@@ -902,7 +922,7 @@ const delta: Operation = {protocol_version: MEMORY_VERBS_VERSION,since: effectiveSince,pages,- facts: facts.map((f) => ({+ facts: (ctx.remote === false ? rawFacts.slice(0, facts.length) : facts).map((f) => ({fact: f.fact,kind: f.kind,entity_slug: f.entity_slug,@@ -927,6 +947,7 @@ const delta: Operation = {const forget_fact: Operation = {name: 'forget_fact',+ outputRedaction: 'no_stored_text',description: 'Forget a fact by recording a durable withdrawal in its source and visibility. Strikes the Markdown facts fence when writable; otherwise keeps the withdrawal in the database. Stale imports cannot reactivate the same normalized claim. This retracts memory; original prose, files and backups may retain the text. Idempotent on already-expired or unknown ids.',params: {request_id: WRITE_REQUEST_PARAM,diff --git a/src/core/ops/files.ts b/src/core/ops/files.tsindex 1e7c1e9549..be8d0e97be 100644--- a/src/core/ops/files.ts+++ b/src/core/ops/files.ts@@ -18,6 +18,7 @@ const FILE_LIST_LIMIT = 100;const file_list: Operation = {name: 'file_list',+ outputRedaction: 'no_stored_text',description: 'List stored files',params: {slug: { type: 'string', description: 'Filter by page slug' },@@ -43,6 +44,7 @@ const file_list: Operation = {const file_upload: Operation = {name: 'file_upload',+ outputRedaction: 'no_stored_text',description: 'Upload a file to storage',params: {path: { type: 'string', required: true, description: 'Local file path' },@@ -151,6 +153,7 @@ const file_upload: Operation = {const file_url: Operation = {name: 'file_url',+ outputRedaction: 'no_stored_text',description: 'Get a URL for a stored file',params: {storage_path: { type: 'string', required: true },diff --git a/src/core/ops/image.ts b/src/core/ops/image.tsindex c183837350..46a29d6a92 100644--- a/src/core/ops/image.ts+++ b/src/core/ops/image.ts@@ -17,6 +17,7 @@ import { resolveRequestedScope } from './context.ts';const search_by_image: Operation = {name: 'search_by_image',+ outputRedaction: 'retrieval',description:'v0.36 cross-modal Phase 2: image-as-query retrieval. Accepts a local path (CLI), data: URI, or http(s):// URL ' +'(SSRF-defended). Returns visually-similar image chunks plus any OCR text they carry. Optional `query` text ' +diff --git a/src/core/ops/ingest-log.ts b/src/core/ops/ingest-log.tsindex b770e2cd98..c308d627e0 100644--- a/src/core/ops/ingest-log.ts+++ b/src/core/ops/ingest-log.ts@@ -14,6 +14,7 @@ import { linkReadScopeOpts } from './context.ts';const log_ingest: Operation = {name: 'log_ingest',+ outputRedaction: 'no_stored_text',description: 'Log an ingestion event',params: {source_type: { type: 'string', required: true, description: "Kind of ingest source, e.g. 'email', 'meeting', 'rss', 'api'." },@@ -42,6 +43,7 @@ const log_ingest: Operation = {const get_ingest_log: Operation = {name: 'get_ingest_log',+ outputRedaction: 'retrieval',description: 'Get recent ingestion log entries',params: {limit: { type: 'number', description: 'Max entries (default 20)' },diff --git a/src/core/ops/insights.ts b/src/core/ops/insights.tsindex d13ee088a2..97b2a16459 100644--- a/src/core/ops/insights.ts+++ b/src/core/ops/insights.ts@@ -22,6 +22,7 @@ import {const volunteer_context: Operation = {name: 'volunteer_context',+ outputRedaction: 'retrieval',description:'Push-based context: volunteer brain pages relevant to a rolling conversation window ' +'WITHOUT being asked. Zero-LLM, confidence-gated (alias 0.9 / exact-title 0.8 / ' +@@ -122,6 +123,7 @@ const volunteer_context: Operation = {// v0.33: expertise + relationship-proximity routing. CLI: gbrain whoknows.const find_experts: Operation = {name: 'find_experts',+ outputRedaction: 'retrieval',description: FIND_EXPERTS_DESCRIPTION,scope: 'read',params: {@@ -176,6 +178,7 @@ const find_experts: Operation = {// v0.32.6: contradiction probe MCP surface (M3)const find_contradictions: Operation = {name: 'find_contradictions',+ outputRedaction: 'retrieval',description: FIND_CONTRADICTIONS_DESCRIPTION,scope: 'read',// Reads eval_contradictions_runs.report_json for the latest run, then@@ -255,6 +258,7 @@ const find_contradictions: Operation = {const find_trajectory: Operation = {name: 'find_trajectory',+ outputRedaction: 'retrieval',description: FIND_TRAJECTORY_DESCRIPTION,scope: 'read',// localOnly intentionally NOT set — federated OAuth clients should bediff --git a/src/core/ops/jobs.ts b/src/core/ops/jobs.tsindex 3ae0db2293..d198c3c3c5 100644--- a/src/core/ops/jobs.ts+++ b/src/core/ops/jobs.ts@@ -79,6 +79,7 @@ async function assertJobOwned(ctx: OperationContext, id: number, owner: string):const submit_job: Operation = {name: 'submit_job',+ outputRedaction: { exempt: 'admin-scoped job introspection: job params and results are operator data, not retrieved brain text' },description: 'Submit a background job. Remote callers may submit sync, import, lint or lint-fix for their authenticated filesystem source. Other kinds require local CLI or a dedicated operation.',params: {name: { type: 'string', required: true, description: 'Remote job type: sync, import, lint, or lint-fix. Local CLI also supports other registered types.' },@@ -235,6 +236,7 @@ async function probeQueueStateSafe(// (agent.use_gateway_loop is auto-on for submit_agent jobs).const submit_agent: Operation = {name: 'submit_agent',+ outputRedaction: { exempt: 'admin-scoped job introspection: job params and results are operator data, not retrieved brain text' },description: 'Submit an LLM agent job that the worker dispatches via the gateway-native tool loop. Requires the `agent` OAuth scope. Tools, source, slug prefixes, max concurrency, and daily budget are bound at OAuth client registration time.',params: {prompt: { type: 'string', required: true, description: 'User prompt for the agent' },@@ -390,6 +392,7 @@ const submit_agent: Operation = {*/const get_agent_job: Operation = {name: 'get_agent_job',+ outputRedaction: 'retrieval',description: 'Poll an agent job submitted via submit_agent. Returns a trimmed status view (id, status, timestamps, error_text, result) plus queue_position (waiting jobs ahead in claim order; 0 = next) while the job is still waiting. Requires the `agent` OAuth scope; only jobs owned by the calling client are visible.',params: {id: { type: 'number', required: true, description: 'Job id returned by submit_agent' },@@ -472,6 +475,7 @@ const get_agent_job: Operation = {const get_job: Operation = {name: 'get_job',+ outputRedaction: { exempt: 'admin-scoped job introspection: job params and results are operator data, not retrieved brain text' },description: 'Get job status and details by ID. Agent-scoped tokens (no admin) see only jobs they own.',params: {id: { type: 'number', required: true, description: 'Job ID' },@@ -493,6 +497,7 @@ const get_job: Operation = {const list_jobs: Operation = {name: 'list_jobs',+ outputRedaction: { exempt: 'admin-scoped job introspection: job params and results are operator data, not retrieved brain text' },description: 'List jobs with optional filters. Agent-scoped tokens (no admin) see only jobs they own.',params: {status: { type: 'string', description: 'Filter by status (waiting, active, completed, failed, delayed, dead, cancelled)' },@@ -522,6 +527,7 @@ const list_jobs: Operation = {const cancel_job: Operation = {name: 'cancel_job',+ outputRedaction: { exempt: 'admin-scoped job introspection: job params and results are operator data, not retrieved brain text' },description: 'Cancel a waiting, active, or delayed job. Agent-scoped tokens (no admin) can cancel only jobs they own.',params: {id: { type: 'number', required: true, description: 'Job ID' },@@ -547,6 +553,7 @@ const cancel_job: Operation = {const retry_job: Operation = {name: 'retry_job',+ outputRedaction: { exempt: 'admin-scoped job introspection: job params and results are operator data, not retrieved brain text' },description: 'Re-queue a failed or dead job for retry',params: {id: { type: 'number', required: true, description: 'Job ID' },@@ -570,6 +577,7 @@ const retry_job: Operation = {const get_job_progress: Operation = {name: 'get_job_progress',+ outputRedaction: { exempt: 'admin-scoped job introspection: job params and results are operator data, not retrieved brain text' },description: 'Get structured progress for a running job. Agent-scoped tokens (no admin) see only jobs they own.',params: {id: { type: 'number', required: true, description: 'Job ID' },@@ -589,6 +597,7 @@ const get_job_progress: Operation = {const pause_job: Operation = {name: 'pause_job',+ outputRedaction: { exempt: 'admin-scoped job introspection: job params and results are operator data, not retrieved brain text' },description: 'Pause a waiting, active, or delayed job',params: {id: { type: 'number', required: true, description: 'Job ID' },@@ -607,6 +616,7 @@ const pause_job: Operation = {const resume_job: Operation = {name: 'resume_job',+ outputRedaction: { exempt: 'admin-scoped job introspection: job params and results are operator data, not retrieved brain text' },description: 'Resume a paused job back to waiting',params: {id: { type: 'number', required: true, description: 'Job ID' },@@ -628,6 +638,7 @@ const resume_job: Operation = {const replay_job: Operation = {name: 'replay_job',+ outputRedaction: { exempt: 'admin-scoped job introspection: job params and results are operator data, not retrieved brain text' },description: 'Replay a completed/failed/dead job, optionally with modified data',params: {id: { type: 'number', required: true, description: 'Source job ID to replay' },@@ -650,6 +661,7 @@ const replay_job: Operation = {const send_job_message: Operation = {name: 'send_job_message',+ outputRedaction: { exempt: 'admin-scoped job introspection: job params and results are operator data, not retrieved brain text' },description: 'Send a sidechannel message to a running job\'s inbox',params: {id: { type: 'number', required: true, description: 'Job ID to message' },@@ -711,6 +723,7 @@ const send_job_message: Operation = {*/const get_job_stats: Operation = {name: 'get_job_stats',+ outputRedaction: 'no_stored_text',description:'Job queue statistics. PER-BLOCK scoping: by_status and queue_health are GLOBAL ' +'(unfiltered); by_type is windowed by since_hours; only the wedge block is scoped to ' +diff --git a/src/core/ops/links.ts b/src/core/ops/links.tsindex eb34a74806..5a56efe070 100644--- a/src/core/ops/links.ts+++ b/src/core/ops/links.ts@@ -51,6 +51,7 @@ export const MANAGED_LINK_SOURCES = ['markdown', 'frontmatter', 'mentions', 'wikconst add_link: Operation = {name: 'add_link',+ outputRedaction: 'no_stored_text',description: 'Create link between pages',params: {from: { type: 'string', required: true, description: "Slug of the page the link originates from (the edge renders on this page), e.g. 'people/alice-example'. These are page slugs — there is no `source`/`target` pair." },@@ -127,6 +128,7 @@ const add_link: Operation = {const remove_link: Operation = {name: 'remove_link',+ outputRedaction: 'no_stored_text',description: 'Remove link between pages',params: {from: { type: 'string', required: true, description: 'Slug of the page the link originates from (same endpoint order as add_link).' },@@ -302,6 +304,7 @@ async function hintScopedLinkMiss(const get_links: Operation = {name: 'get_links',+ outputRedaction: 'retrieval',description: 'List outgoing links from a page',params: {slug: { type: 'string', required: true, description: 'Slug of the page whose outgoing links to list.' },@@ -315,6 +318,7 @@ const get_links: Operation = {const get_backlinks: Operation = {name: 'get_backlinks',+ outputRedaction: 'retrieval',description: 'List incoming links to a page',params: {slug: { type: 'string', required: true, description: 'Slug of the page whose incoming links to list.' },@@ -328,6 +332,7 @@ const get_backlinks: Operation = {const list_link_sources: Operation = {name: 'list_link_sources',+ outputRedaction: 'no_stored_text',// v114 (#1941): the read-side counterpart to link-add/link-rm. Since// link_source is now an open kebab provenance (no allowlist), this is how an// agent discovers which provenances a brain actually carries.@@ -366,6 +371,7 @@ const DEFAULT_TRAVERSE_DEPTH = 5;const traverse_graph: Operation = {name: 'traverse_graph',+ outputRedaction: 'retrieval',description: `Traverse link graph from a page. Remote callers default to bidirectional edges (GraphPath[]) at depth ${REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH} (pass depth explicitly for deeper walks); trusted local no-filter callers keep the legacy node shape at depth ${DEFAULT_TRAVERSE_DEPTH}.`,params: {slug: { type: 'string', required: true, description: "Slug of the page to start the traversal from, e.g. 'people/alice-example'. This is the start-node param — there is no `start` or `root` param." },diff --git a/src/core/ops/loops.ts b/src/core/ops/loops.tsindex 465e61c60c..af47558418 100644--- a/src/core/ops/loops.ts+++ b/src/core/ops/loops.ts@@ -276,6 +276,7 @@ function renderText(groups: CounterpartyGroup[], stale: boolean, noGoogleSourcesconst open_loops: Operation = {name: 'open_loops',+ outputRedaction: 'retrieval',description:'The open-loop engine\'s killer output: who is waiting on you, what you promised, and the context ' +'needed to respond. Grouped by counterparty (default, ranked) or flat. Loops come from the ' +@@ -452,6 +453,7 @@ const open_loops: Operation = {const loops_close: Operation = {name: 'loops_close',+ outputRedaction: 'no_stored_text',description:"Close an open loop by id: status 'done' (handled) or 'dropped' (not going to). Closing is a state " +'transition with an audit trail, never a delete. Thread loops also close automatically when a reply lands.',@@ -503,6 +505,7 @@ const loops_close: Operation = {const loops_mute: Operation = {name: 'loops_mute',+ outputRedaction: 'no_stored_text',description:'Suppress a sender (email address) or thread id from opening NEW loops — the detector feedback ' +'primitive behind "never track this sender". Existing loops keep their state.',@@ -541,6 +544,7 @@ const loops_mute: Operation = {const loops_unmute: Operation = {name: 'loops_unmute',+ outputRedaction: 'no_stored_text',description:'Remove a sender/thread suppression added by loops_mute, so the detector can open NEW loops for ' +'it again. Exact-match only. Does not reopen loops closed while the mute was in place.',diff --git a/src/core/ops/orphans.ts b/src/core/ops/orphans.tsindex e6a40924f2..dc66a4550e 100644--- a/src/core/ops/orphans.ts+++ b/src/core/ops/orphans.ts@@ -12,6 +12,7 @@ import { readPolicyOpts } from './context.ts';const find_orphans: Operation = {name: 'find_orphans',+ outputRedaction: 'retrieval',description: 'Find disconnected pages. Default mode "islanded" (no live inbound AND no outbound link) matches get_health.orphan_pages; mode "inbound" is the legacy no-inbound-only view. Essential for content enrichment cycles.',params: {include_pseudo: {diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 7779da250a..fb8db50b55 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -74,6 +74,7 @@ function stripPrivacyFencesForRemoteReader(page: Page): Page {const get_page: Operation = {name: 'get_page',+ outputRedaction: { exempt: 'explicit page read by slug/id; governed by page visibility, not output redaction (CEO-17 raw-read exception)' },description: 'Read a page by slug (supports optional fuzzy matching). Slug aliases left by renames redirect to the canonical page in the source that owns the alias (archived sources excluded); a redirected read reports `resolved_slug`. To edit a page, pass include_content: true — the returned `content` field is the canonical full markdown (frontmatter + body + timeline sentinel); edit THAT and pass it back to put_page to round-trip losslessly. Reassembling compiled_truth/timeline by hand risks dropping sections. Soft-deleted pages are hidden by default; pass include_deleted: true to surface them with deleted_at populated (see v0.26.5 recovery window). `timeline` is only the markdown section after the timeline sentinel; entries written by add_timeline_entry or extraction live in timeline rows, which include_timeline_entries: true returns as `timeline_entries` (the same rows get_timeline returns).',params: {slug: { type: 'string', required: true, description: 'Page slug' },@@ -209,6 +210,7 @@ const get_page: Operation = {const fetch_page: Operation = {name: 'fetch',+ outputRedaction: { exempt: 'explicit page read by slug/id; governed by page visibility, not output redaction (CEO-17 raw-read exception)' },description: "Fetch the full text of one search result by its opaque, source-qualified `id` (OpenAI deep-research contract: the search/fetch pair). Pass the id unchanged; it does not grant access. Legacy slug ids work only when unambiguous within your current read scope. Returns { id, title, text, url, metadata } — `text` is the page's canonical markdown. For fuzzy slugs, soft-delete recovery, or lossless edit round-trips, use get_page.",params: {id: { type: 'string', required: true, description: 'Opaque result id from a prior `search` call. Pass unchanged. Unambiguous legacy slugs are also accepted.' },@@ -279,6 +281,7 @@ const fetch_page: Operation = {const put_page: Operation = {name: 'put_page',+ outputRedaction: 'no_stored_text',description: 'Replace a complete canonical Markdown page. Read get_page with include_content:true and pass its revision as expected_revision; force explicitly overwrites the current revision. Omitting both permits creation only. Retain a UUID request_id and repeat identical arguments after transport failure or a pending receipt. Content, tags, sanitized text projections, versions and the committed receipt publish together; embedding and optional Git effects have separate status. Remote callers preserve protected facts/takes fences; automatic graph links are skipped for untrusted writes. A stdio `gbrain serve` sweeps them at startup + on idle; `gbrain serve --http` does not self-sweep — run `gbrain sweep --once` or use trusted local capture/put_page for inline link extraction. Remote callers receive write_through.warning when no repo is configured. For file input use gbrain capture --file PATH --slug SLUG.',params: {...PAGE_MUTATION_PARAMS,@@ -356,6 +359,7 @@ async function runAutoLink(const delete_page: Operation = {name: 'delete_page',+ outputRedaction: 'no_stored_text',description: 'Soft-delete a page and remove its markdown file from the source working tree (the source local_path, or sync.repo_path when the source has none). File removal is skipped when sync.write_through is off; the committed receipt reports the persistence mode and write_through outcome. Read the page revision first and pass expected_revision; retain request_id for replay. The row is hidden from search and from get_page/list_pages, but is recoverable via restore_page within 72h, which re-creates the file. The autopilot purge phase hard-deletes after the recovery window. Pass include_deleted: true to get_page to verify the soft-delete landed. purge: true is trusted-local CLI only and removes the row, chunks, links and raw data immediately after its recorded markdown artifact is removed. Purge uses the same revision, request_id and recovery protocol, including for existing tombstones. A removal failure preserves the prior row and never reports purge success; repair the artifact and submit a new request_id. A committed purge warns that git history, synced copies, exports and derived rows may retain content; rotate exposed credentials.',params: {...PAGE_MUTATION_PARAMS,@@ -383,6 +387,7 @@ const delete_page: Operation = {const restore_page: Operation = {name: 'restore_page',+ outputRedaction: 'no_stored_text',description: 'v0.26.5 — restore a soft-deleted page (clear deleted_at) and re-create its markdown file on disk (the counterpart to delete_page removing it; the result write_through field reports the outcome). Returns success only if the page was actually soft-deleted. After this op, the page reappears in search and in get_page/list_pages without the include_deleted flag.',params: {...PAGE_MUTATION_PARAMS,@@ -408,6 +413,7 @@ const restore_page: Operation = {const purge_deleted_pages: Operation = {name: 'purge_deleted_pages',+ outputRedaction: 'no_stored_text',description: 'v0.26.5 — admin-only. Hard-deletes pages whose deleted_at is older than older_than_hours (default 72). Cascades through content_chunks, page_links, chunk_relations. Local CLI only (not exposed over HTTP MCP). Manual escape hatch alongside the autopilot purge phase.',params: {older_than_hours: { type: 'number', description: 'Age cutoff in hours. Default 72.' },@@ -429,6 +435,7 @@ type ListPagesSort = typeof LIST_PAGES_SORT_VALUES[number];const list_pages: Operation = {name: 'list_pages',+ outputRedaction: 'retrieval',description: LIST_PAGES_DESCRIPTION,params: {type: { type: 'string', description: 'Filter by page type' },@@ -580,6 +587,7 @@ const list_pages: Operation = {*/const capture: Operation = {name: 'capture',+ outputRedaction: 'no_stored_text',description: CAPTURE_DESCRIPTION,params: {...PAGE_MUTATION_PARAMS,diff --git a/src/core/ops/persistence.ts b/src/core/ops/persistence.tsindex b80bb43012..a91224caff 100644--- a/src/core/ops/persistence.ts+++ b/src/core/ops/persistence.ts@@ -121,6 +121,7 @@ const requestParam = { type: 'string' as const, required: true, description: 'Thexport const persistenceOperations: Operation[] = [{name: 'get_write_request',+ outputRedaction: 'no_stored_text',description: 'Read your durable write receipt by request_id. Requires write scope and this operation in the current grant. Foreign, missing, and no-longer-accessible requests return the same not_found error; private journal input and recovery bytes are never returned.',params: { request_id: requestParam },scope: 'write', mutating: false, area: 'pages',@@ -136,6 +137,7 @@ export const persistenceOperations: Operation[] = [},{name: 'list_write_requests',+ outputRedaction: 'no_stored_text',description: 'List your currently authorized write receipts in one source, newest first. Useful when an acknowledgment was lost. Results and pagination exclude other principals and inaccessible targets; no private payloads or cross-principal queue counts are exposed.',params: {source_id: { type: 'string', description: 'Source to inspect. Defaults to the caller’s resolved source.' },@@ -167,6 +169,7 @@ export const persistenceOperations: Operation[] = [},{name: 'cancel_write_request',+ outputRedaction: 'no_stored_text',description: 'Cancel your accepted write before publication starts. Returns the actual receipt: running/recovering or already-terminal requests may remain unchanged. Cancellation cannot undo published bytes or a committed fact withdrawal.',params: { request_id: requestParam },scope: 'write', mutating: true, area: 'pages',diff --git a/src/core/ops/raw-data.ts b/src/core/ops/raw-data.tsindex 6b95d6cba6..f8d2b7e10e 100644--- a/src/core/ops/raw-data.ts+++ b/src/core/ops/raw-data.ts@@ -13,6 +13,7 @@ import { enforceClientSlugFence } from './context.ts';const put_raw_data: Operation = {name: 'put_raw_data',+ outputRedaction: 'no_stored_text',description: 'Store raw API response data for a page',params: {slug: { type: 'string', required: true, description: 'Slug of the page to attach the raw data to.' },@@ -33,6 +34,7 @@ const put_raw_data: Operation = {const get_raw_data: Operation = {name: 'get_raw_data',+ outputRedaction: { exempt: 'explicit raw sidecar read by slug; governed by page visibility (CEO-17 raw-read exception)' },description: 'Retrieve raw data for a page. Raw data follows the page\'s soft-delete: a tombstoned (soft-deleted) page returns [] exactly like a missing page; restore_page brings the rows back, and get_page include_deleted: true verifies the tombstone.',params: {slug: { type: 'string', required: true, description: 'Slug of the page whose raw data to fetch.' },diff --git a/src/core/ops/request-tools.ts b/src/core/ops/request-tools.tsindex 0cc27a423c..3579742042 100644--- a/src/core/ops/request-tools.ts+++ b/src/core/ops/request-tools.ts@@ -112,6 +112,7 @@ async function visibleOpsForCaller(const request_tools: Operation = {name: 'request_tools',+ outputRedaction: 'no_stored_text',description:'Discover this brain\'s tool catalog and optionally unlock a wider tool surface for your client. ' +'No arguments → the catalog visible to YOUR credentials, grouped by area (tool names + one-line summaries). ' +diff --git a/src/core/ops/salience.ts b/src/core/ops/salience.tsindex cf6cd35e51..24284b0af5 100644--- a/src/core/ops/salience.ts+++ b/src/core/ops/salience.ts@@ -19,6 +19,7 @@ import {const get_recent_salience: Operation = {name: 'get_recent_salience',+ outputRedaction: 'retrieval',description: GET_RECENT_SALIENCE_DESCRIPTION,scope: 'read',params: {@@ -67,6 +68,7 @@ const get_recent_salience: Operation = {const find_anomalies: Operation = {name: 'find_anomalies',+ outputRedaction: 'retrieval',description: FIND_ANOMALIES_DESCRIPTION,scope: 'read',params: {diff --git a/src/core/ops/schema-packs.ts b/src/core/ops/schema-packs.tsindex 65cc54c1a7..a79ad01f09 100644--- a/src/core/ops/schema-packs.ts+++ b/src/core/ops/schema-packs.ts@@ -27,6 +27,7 @@ import { sourceScopeOpts } from './context.ts';const get_active_schema_pack: Operation = {name: 'get_active_schema_pack',+ outputRedaction: 'no_stored_text',description: 'v0.40.6.0: cheap identity packet for the active schema pack. Returns {pack_name, version, sha8, page_types_count, link_types_count, primitive_summary, source_tier}. Useful for agents to know which pack they are operating against without paying full manifest load cost.',params: {},scope: 'read',@@ -63,6 +64,7 @@ const get_active_schema_pack: Operation = {const list_schema_packs: Operation = {name: 'list_schema_packs',+ outputRedaction: 'no_stored_text',description: 'v0.40.6.0: list installed schema packs (bundled + user-installed). Returns {bundled: string[], installed: string[]}. Read-only directory listing.',params: {},scope: 'read',@@ -88,6 +90,7 @@ const list_schema_packs: Operation = {const schema_stats: Operation = {name: 'schema_stats',+ outputRedaction: 'no_stored_text',description: 'v0.40.6.0: per-type page counts + typed-coverage from the DB. Returns {schema_version:1, pack_identity, aggregate, per_source, dead_prefixes}. Multi-source aware via ctx.sourceId/allowedSources.',params: {},scope: 'read',@@ -103,6 +106,7 @@ const schema_stats: Operation = {const schema_lint: Operation = {name: 'schema_lint',+ outputRedaction: 'no_stored_text',description: 'v0.40.6.0: lint the active (or named) schema pack. File-plane rules only over MCP — the with_db option is rejected for remote callers (DB-aware rules require local CLI). Returns {ok, errors, warnings} structured report.',params: {pack: { type: 'string', description: 'Pack name (default: active pack)' },@@ -155,6 +159,7 @@ const schema_lint: Operation = {const schema_graph: Operation = {name: 'schema_graph',+ outputRedaction: 'no_stored_text',description: 'v0.40.6.0: schema pack graph as JSON edges. Returns {nodes: [{name, primitive}], edges: [{from, verb, to}]} derived from link_types inference + frontmatter_links.',params: {},scope: 'read',@@ -186,6 +191,7 @@ const schema_graph: Operation = {const schema_explain_type: Operation = {name: 'schema_explain_type',+ outputRedaction: 'no_stored_text',description: 'v0.40.6.0: resolved settings for a single page_type in the active pack. Returns {pack, type, primitive, path_prefixes, aliases, extractable, expert_routing}.',params: {type: { type: 'string', required: true, description: 'Page type name to explain' },@@ -207,6 +213,7 @@ const schema_explain_type: Operation = {const schema_review_orphans: Operation = {name: 'schema_review_orphans',+ outputRedaction: 'no_stored_text',description: 'v0.40.6.0: list pages with no active-pack type match. Returns {orphan_count, orphans: [{slug, source_id}]}.',params: {limit: { type: 'number', description: 'Max orphans to return (default 100)' },@@ -242,6 +249,7 @@ const schema_review_orphans: Operation = {const schema_apply_mutations: Operation = {name: 'schema_apply_mutations',+ outputRedaction: 'no_stored_text',description: 'v0.40.7.0: batched schema pack mutation. ATOMIC: every mutation is validated against an in-memory manifest first, and the pack file is written to disk at most once, after the FULL batch has proven valid — so a failure at any point leaves the pack file byte-identical to its pre-batch state (never a partial write). Audit log records one batch_id. Admin scope; NOT localOnly so remote agents (your OpenClaw, etc.) can author packs over normal MCP. Mutation shape per ApplyMutationsRequest type — supports add_type / remove_type / update_type / add_alias / remove_alias / add_prefix / remove_prefix / add_link_type / remove_link_type / set_extractable / set_expert_routing.',params: {pack: { type: 'string', required: true, description: 'Pack to mutate (must not be bundled)' },@@ -311,6 +319,7 @@ const schema_apply_mutations: Operation = {const reload_schema_pack: Operation = {name: 'reload_schema_pack',+ outputRedaction: 'no_stored_text',description: 'v0.40.6.0: flush the in-process schema pack cache so the next loadActivePack re-reads from disk. Cascades through extends-chain (codex C6). Admin scope; NOT localOnly. Returns {invalidated: string[]}.',params: {pack: { type: 'string', description: 'Pack name to invalidate (omit to flush all)' },diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex b1a6ff675e..762d450d6b 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -320,6 +320,7 @@ async function resolveSnippetCap(ctx: OperationContext, p: Record<string, unknowconst search: Operation = {name: 'search',+ outputRedaction: 'retrieval',description: SEARCH_DESCRIPTION,params: {query: { type: 'string', required: true, description: "Search text. Exact tokens, names, and structured-field values work best here (e.g. 'acme-example series A'), since this op does no LLM expansion. This is the search text param — there is no `text` or `q` param." },@@ -454,6 +455,7 @@ const search: Operation = {const query: Operation = {name: 'query',+ outputRedaction: 'retrieval',description: QUERY_DESCRIPTION,params: {// v0.27.1: `query` is no longer strictly required — `--image <path>`@@ -911,6 +913,7 @@ const query: Operation = {*/const assemble_evidence: Operation = {name: 'assemble_evidence',+ outputRedaction: 'retrieval',description:'Deliver whole evidence for an ordered list of search hits (each {source_id, slug, chunk_id} from a prior search/query result): ' +"the same windows, sections or pages `query` returns with return_unit, packed into token_budget. Use it to widen hits you already have " +@@ -959,6 +962,7 @@ const assemble_evidence: Operation = {const search_stats: Operation = {name: 'search_stats',+ outputRedaction: 'no_stored_text',description:'Search observability over a window: cache hit rate, intent/mode mix, budget drops, ' +'rank-1 score drift, graph-signals failure counts. Same payload as the search-stats ' +@@ -999,6 +1003,7 @@ const search_stats: Operation = {const search_modes: Operation = {name: 'search_modes',+ outputRedaction: 'no_stored_text',description:'Read-only search-mode dashboard: active mode, EVERY mode-bundle knob resolved with ' +'attribution (mode default vs config override), the three frozen bundles, and a ' +@@ -1021,6 +1026,7 @@ const search_modes: Operation = {const search_tune: Operation = {name: 'search_tune',+ outputRedaction: 'no_stored_text',description:'Read-only tuning recommendations derived from the last 7 days of search telemetry: ' +'what should change, why, and the paste-ready config command per recommendation — relay ' +@@ -1039,6 +1045,7 @@ const search_tune: Operation = {const cache_stats: Operation = {name: 'cache_stats',+ outputRedaction: 'no_stored_text',description:'Semantic query-cache introspection: resolved knobs (enabled, similarity threshold, TTL) ' +'plus row counts and total hits. Read-only; clearing/pruning the cache stays on the CLI.',diff --git a/src/core/ops/skillopt.ts b/src/core/ops/skillopt.tsindex b134ce1309..f3b9eaa42e 100644--- a/src/core/ops/skillopt.ts+++ b/src/core/ops/skillopt.ts@@ -38,6 +38,7 @@ import { OperationError } from './contract.ts';// what they would have gotten with the right grants.const run_onboard: Operation = {name: 'run_onboard',+ outputRedaction: 'no_stored_text',description: 'Probe brain health + optionally submit onboard remediations. Admin scope required. Protected handlers (LLM-bearing) require run_protected_onboard scope ADDITIONALLY.',params: {mode: { type: 'string', description: "'check' (default), 'auto', or 'auto-with-prompt'" },@@ -125,6 +126,7 @@ const run_onboard: Operation = {// bundled-skill guard). NOT localOnly so admin HTTP MCP clients can invoke.const run_skillopt: Operation = {name: 'run_skillopt',+ outputRedaction: { exempt: 'skill catalog files are installed instructions read verbatim; redaction would corrupt approved revisions' },description: 'Run SkillOpt against a single skill. Admin scope and remote skill allowlist required. shared_skill stages an exact catalog revision privately and requires explicit skill_editor and put_skill grants; only accepted body changes publish through the original revision CAS. Rate-limited per-skill via DB lock.',params: {skill_name: { type: 'string', required: true, description: 'Kebab-case skill name (resolves to skills/<name>/SKILL.md)' },diff --git a/src/core/ops/skills-catalog.ts b/src/core/ops/skills-catalog.tsindex 2b68bae1bd..4668303ce0 100644--- a/src/core/ops/skills-catalog.ts+++ b/src/core/ops/skills-catalog.ts@@ -22,6 +22,7 @@ import {const list_skills: Operation = {name: 'list_skills',+ outputRedaction: 'no_stored_text',description: LIST_SKILLS_DESCRIPTION,publishGateKey: 'mcp.publish_skills',params: {@@ -53,6 +54,7 @@ const list_skills: Operation = {const get_skill: Operation = {name: 'get_skill',+ outputRedaction: { exempt: 'skill catalog files are installed instructions read verbatim; redaction would corrupt approved revisions' },description: GET_SKILL_DESCRIPTION,publishGateKey: 'mcp.publish_skills',params: {@@ -117,6 +119,7 @@ const sharedSkillMutationParams: Operation['params'] = {};const get_skill_asset: Operation = {name: 'get_skill_asset', description: 'Read a bounded, owner-approved file from an exact sealed skill revision. Does not execute downloaded bytes.',+ outputRedaction: { exempt: 'skill catalog files are installed instructions read verbatim; redaction would corrupt approved revisions' },scope: 'read', publishGateKey: 'mcp.publish_skills',cliHints: { name: 'skill-asset', positional: [] },params: { source_id: sharedSkillKeyParams.source_id, source_incarnation: sharedSkillKeyParams.source_incarnation,@@ -130,6 +133,7 @@ const get_skill_asset: Operation = {};const put_skill: Operation = {name: 'put_skill', description: 'Publish a complete file-canonical skill revision with CAS and a durable receipt. Requires explicit skill editor authority; cannot expand publication policy.',+ outputRedaction: 'no_stored_text',scope: 'write', requiredScopes: ['skill_editor'], mutating: true,cliHints: { name: 'put-skill', positional: [] },params: { ...sharedSkillMutationParams, description: { type: 'string', description: 'Compact routing description.' },@@ -141,18 +145,21 @@ const put_skill: Operation = {};const delete_skill: Operation = {name: 'delete_skill', description: 'CAS-delete a canonical shared skill and revoke future managed activation. Previously downloaded bytes are not recalled.',+ outputRedaction: 'no_stored_text',scope: 'write', requiredScopes: ['skill_editor'], mutating: true, params: sharedSkillMutationParams,cliHints: { name: 'delete-skill', positional: [] },handler: async (ctx, p) => (await import('../shared-skills/catalog.ts')).submitSharedSkillMutation(ctx, 'delete_skill', p),};const import_skill_proposal: Operation = {name: 'import_skill_proposal', description: 'Publish explicitly reviewed human-edited canonical skill files through the durable coordinator. Requires exact current file hashes and skill revision; trusted local operator only.',+ outputRedaction: 'no_stored_text',scope: 'admin', localOnly: true, mutating: true,params: { ...put_skill.params, expected_hashes: { type: 'object', required: true, description: 'Reviewed current SHA-256 hashes for every affected file and skillpack.json; null denotes an absent file.' } },handler: async (ctx, p) => (await import('../shared-skills/publication.ts')).importSharedSkillProposal(ctx, p),};const set_skill_policy: Operation = {name: 'set_skill_policy', description: 'Explicitly approve a versioned shared-skill disclosure and follow policy. Separate publisher authority is required; editing a skill never grants this permission.',+ outputRedaction: 'no_stored_text',scope: 'admin', requiredScopes: ['skill_publisher'], mutating: true,cliHints: { name: 'set-skill-policy', positional: [] },params: { source_id: { type: 'string', required: true, description: 'Source whose publication policy is approved.' },@@ -163,6 +170,7 @@ const set_skill_policy: Operation = {};const get_skill_policy: Operation = {name: 'get_skill_policy', description: 'Read the owner publication policy and CAS epoch, including when sharing is disabled. Does not approve or change disclosure.',+ outputRedaction: 'no_stored_text',scope: 'admin', requiredScopes: ['skill_publisher'],cliHints: { name: 'skill-policy', positional: [] },params: { source_id: { type: 'string', required: true, description: 'Source whose publication policy is reviewed.' } },@@ -170,6 +178,7 @@ const get_skill_policy: Operation = {};const get_skill_retention: Operation = {name: 'get_skill_retention', description: 'Inspect retained shared-skill revision counts, protected leases and source storage capacity. Trusted host operator only.',+ outputRedaction: 'no_stored_text',scope: 'admin', localOnly: true,cliHints: { name: 'skill-retention', positional: [] },params: { source_id: { type: 'string', description: 'Canonical source to inspect.' } },@@ -177,6 +186,7 @@ const get_skill_retention: Operation = {};const prune_skill_revisions: Operation = {name: 'prune_skill_revisions', description: 'Prune one bounded batch of expired shared-skill history. Preserves heads, tombstones, pending publication refs, delivery leases, pins and permanent write receipts.',+ outputRedaction: 'no_stored_text',scope: 'admin', localOnly: true, mutating: true,cliHints: { name: 'prune-skill-revisions', positional: [] },params: { source_id: { type: 'string', description: 'Canonical source to prune.' } },@@ -184,6 +194,7 @@ const prune_skill_revisions: Operation = {};const retain_skill_revision: Operation = {name: 'retain_skill_revision', description: 'Pin an exact shared-skill revision for up to 24 hours under a bounded operator quota. Does not grant read or execution permission.',+ outputRedaction: 'no_stored_text',scope: 'admin', localOnly: true, mutating: true,cliHints: { name: 'retain-skill-revision', positional: [] },params: { ...sharedSkillKeyParams, source_incarnation: { type: 'string', required: true, description: 'Exact source incarnation.' },@@ -194,6 +205,7 @@ const retain_skill_revision: Operation = {const list_brain_skillpack: Operation = {name: 'list_brain_skillpack',+ outputRedaction: { exempt: 'skill catalog files are installed instructions read verbatim; redaction would corrupt approved revisions' },description:'List brain-resident skillpacks this brain ships (per-source). Returns each pack\'s skills, ' +'one-line descriptions, the schema pack it targets + whether that matches this brain, and a ' +@@ -216,6 +228,7 @@ const list_brain_skillpack: Operation = {const advisor: Operation = {name: 'advisor',+ outputRedaction: 'retrieval',description:'Ranked, read-only "what to do next" for this brain: version drift, pending migrations, ' +'schema-pack issues, stalled jobs, usage-shape gaps, and setup smells. Each finding has a ' +@@ -299,6 +312,7 @@ const advisor: Operation = {*/const get_status_snapshot: Operation = {name: 'get_status_snapshot',+ outputRedaction: 'no_stored_text',description: 'Snapshot for `gbrain status` thin-client mode: sync freshness + last cycle + queue depths + worker liveness. Admin-scope.',params: {},handler: async (ctx) => {diff --git a/src/core/ops/sources.ts b/src/core/ops/sources.tsindex 5087ab7afd..988195b1d6 100644--- a/src/core/ops/sources.ts+++ b/src/core/ops/sources.ts@@ -15,6 +15,7 @@ import { resolveAuthCapabilities } from '../harness/capabilities.ts';const whoami: Operation = {name: 'whoami',+ outputRedaction: 'no_stored_text',description:'Introspect the calling identity. Returns one of three transport shapes: ' +'{transport: "oauth", client_id, client_name, scopes, expires_at, source_id, federated_read}, ' +@@ -72,6 +73,7 @@ const whoami: Operation = {const sources_add: Operation = {name: 'sources_add',+ outputRedaction: 'no_stored_text',description:'Register a new source. Supports either --path (existing v0.17 behavior) ' +'or --url (v0.28 federated remote-clone path: parses the URL through the ' +@@ -154,6 +156,7 @@ const sources_add: Operation = {const sources_list: Operation = {name: 'sources_list',+ outputRedaction: 'no_stored_text',description:'List registered sources with page counts and remote_url. v0.28 surfaces ' +'the new remote_url field so a remote MCP caller can confirm a source is ' +@@ -193,6 +196,7 @@ const sources_list: Operation = {const sources_remove: Operation = {name: 'sources_remove',+ outputRedaction: 'no_stored_text',description:'Hard-remove a source (cascades pages/chunks/embeddings). Refuses to ' +'delete the auto-managed clone dir unless its resolved path is confined ' +@@ -241,6 +245,7 @@ const sources_remove: Operation = {const sources_status: Operation = {name: 'sources_status',+ outputRedaction: 'no_stored_text',description:'Per-source diagnostic. Returns clone_state ("healthy" | "missing" | ' +'"not-a-dir" | "no-git" | "url-drift" | "corrupted" | "not-applicable") ' +@@ -269,6 +274,7 @@ const sources_status: Operation = {const sources_inspect: Operation = {name: 'sources_inspect',+ outputRedaction: 'no_stored_text',description: 'Inspect committed company Markdown on the trusted local host without importing, registering a source, changing access, or invoking providers.',params: {path: { type: 'string', required: true, description: 'Local committed Git repository directory.' },diff --git a/src/core/ops/sync-status.ts b/src/core/ops/sync-status.tsindex 501fb18412..d5ad4b90fa 100644--- a/src/core/ops/sync-status.ts+++ b/src/core/ops/sync-status.ts@@ -12,6 +12,7 @@ import { OperationError } from './contract.ts';const sync_brain: Operation = {name: 'sync_brain',+ outputRedaction: 'no_stored_text',description: 'Sync git repo to brain (incremental)',params: {repo: { type: 'string', description: 'Path to git repo (optional if configured)' },diff --git a/src/core/ops/tags.ts b/src/core/ops/tags.tsindex 01e2c24ff6..ae712ab5f7 100644--- a/src/core/ops/tags.ts+++ b/src/core/ops/tags.ts@@ -14,6 +14,7 @@ import { WRITE_REQUEST_PARAM } from '../persistence/params.ts';const add_tag: Operation = {name: 'add_tag',+ outputRedaction: 'no_stored_text',description: 'Add tag to page',params: {request_id: WRITE_REQUEST_PARAM,@@ -33,6 +34,7 @@ const add_tag: Operation = {const remove_tag: Operation = {name: 'remove_tag',+ outputRedaction: 'no_stored_text',description: 'Remove tag from page',params: {request_id: WRITE_REQUEST_PARAM,@@ -51,6 +53,7 @@ const remove_tag: Operation = {const get_tags: Operation = {name: 'get_tags',+ outputRedaction: 'no_stored_text',description: 'List tags for a page',params: {slug: { type: 'string', required: true, description: 'Slug of the page whose tags to list.' },diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.tsindex 6c47803f9a..4f110dd6b8 100644--- a/src/core/ops/takes.ts+++ b/src/core/ops/takes.ts@@ -31,6 +31,7 @@ import { privatePagesFilterFragment } from '../search/private-visibility.ts';const takes_list: Operation = {name: 'takes_list',+ outputRedaction: 'retrieval',description: 'List takes (typed/weighted/attributed claims) filtered by holder/kind/active/etc.',scope: 'read',params: {@@ -65,6 +66,7 @@ const takes_list: Operation = {const takes_search: Operation = {name: 'takes_search',+ outputRedaction: 'retrieval',description: 'Keyword search across takes (pg_trgm similarity over claim text)',scope: 'read',params: {@@ -91,6 +93,7 @@ const takes_search: Operation = {*/const takes_scorecard: Operation = {name: 'takes_scorecard',+ outputRedaction: 'no_stored_text',description: 'Calibration scorecard for resolved bets: counts, accuracy, Brier (correct ∨ incorrect only), partial_rate.',scope: 'read',params: {@@ -127,6 +130,7 @@ const takes_scorecard: Operation = {*/const takes_calibration: Operation = {name: 'takes_calibration',+ outputRedaction: 'no_stored_text',description: 'Calibration curve: resolved correct/incorrect bets binned by stated weight; observed vs predicted per bucket.',scope: 'read',params: {@@ -186,6 +190,7 @@ async function countMcpResolved(ctx: OperationContext): Promise<number> {const think: Operation = {name: 'think',+ outputRedaction: 'retrieval',description: 'Multi-hop synthesis across pages + takes + graph. Pulls relevant evidence and produces a cited answer with conflict + gap analysis.',scope: 'read',params: {@@ -391,6 +396,7 @@ function mirrorWarnFields(mirror: { mirror_warning?: string }): Record<string, sconst takes_add: Operation = {name: 'takes_add',+ outputRedaction: 'no_stored_text',description:'Record a take (typed claim) on a page: fact / take / bet / hunch, with a holder (who ' +'holds the belief: world, people/<slug>, companies/<slug>, or brain), weight 0..1, and ' +@@ -422,6 +428,7 @@ const takes_add: Operation = {const takes_update: Operation = {name: 'takes_update',+ outputRedaction: 'no_stored_text',description:'Update a take\'s mutable fields (weight, source, since date). Claim/kind/holder are ' +'immutable — supersede instead. Markdown-canonical: the target row must exist in the ' +@@ -450,6 +457,7 @@ const takes_update: Operation = {const takes_supersede: Operation = {name: 'takes_supersede',+ outputRedaction: 'no_stored_text',description:'Supersede a take with a replacement claim: the old row is struck through (kept for ' +'archaeology), the replacement appends at the next fence row number. Kind/holder inherit ' +@@ -481,6 +489,7 @@ const takes_supersede: Operation = {const takes_resolve: Operation = {name: 'takes_resolve',+ outputRedaction: 'no_stored_text',description:'Resolve a take: quality correct / incorrect / partial / unresolvable, with optional ' +'evidence text and measured value/unit. Resolutions feed the calibration scorecard. ' +diff --git a/src/core/ops/timeline.ts b/src/core/ops/timeline.tsindex 53e8cdb783..d28f9c53e1 100644--- a/src/core/ops/timeline.ts+++ b/src/core/ops/timeline.ts@@ -19,6 +19,7 @@ import {const add_timeline_entry: Operation = {name: 'add_timeline_entry',+ outputRedaction: 'retrieval',description: 'Append an entry to the canonical Markdown timeline and structured timeline store in one committed write. Exact replay changes neither store.',params: {request_id: WRITE_REQUEST_PARAM,@@ -61,6 +62,7 @@ const add_timeline_entry: Operation = {const get_timeline: Operation = {name: 'get_timeline',+ outputRedaction: 'retrieval',description: 'Get timeline entries for a page, optionally filtered by date window',params: {slug: { type: 'string', required: true, description: 'Slug of the page whose timeline entries to return.' },diff --git a/src/core/ops/transcripts.ts b/src/core/ops/transcripts.tsindex 731ec22260..8c7968746a 100644--- a/src/core/ops/transcripts.ts+++ b/src/core/ops/transcripts.ts@@ -12,6 +12,7 @@ import { GET_RECENT_TRANSCRIPTS_DESCRIPTION } from '../operations-descriptions.tconst get_recent_transcripts: Operation = {name: 'get_recent_transcripts',+ outputRedaction: 'retrieval',description: GET_RECENT_TRANSCRIPTS_DESCRIPTION,scope: 'read',// Local-only: rejects HTTP-borne MCP traffic at tool-list timediff --git a/src/core/ops/usage.ts b/src/core/ops/usage.tsindex 9ff7d95ca4..c6c8e5c38c 100644--- a/src/core/ops/usage.ts+++ b/src/core/ops/usage.ts@@ -29,6 +29,7 @@ const n = (v: number | string | null | undefined): number => Number(v ?? 0);const get_usage: Operation = {name: 'get_usage',+ outputRedaction: 'no_stored_text',description:'Aggregate chat usage + cost from the chat_usage_log ledger (per-model and per-phase token counts, cache reads/writes, USD estimates) with explicit coverage fields.',params: {diff --git a/src/core/page-state/credential-reseal.ts b/src/core/page-state/credential-reseal.tsnew file mode 100644index 0000000000..2c9063b7da--- /dev/null+++ b/src/core/page-state/credential-reseal.ts@@ -0,0 +1,53 @@+/**+ * Credential-safe re-chunk of existing pages (security wave ENG-2). Schema+ * migration v189 unseals every live markdown/code page whose canonical body+ * carries a private-key marker, which withholds its old chunks from every+ * retrieval path. This module counts those pages and re-seals them from their+ * unchanged canonical body through the projection installer: no page write,+ * no journal admission and no provider call. Vectors of chunks whose text is+ * unchanged are kept; re-chunked key chunks wait for `gbrain embed --stale`.+ */+import type { BrainEngine } from '../engine.ts';+import { resealSafeChunks } from './projections.ts';+import { PageRevisionConflictError } from './types.ts';++const KEY_MARKER = `'-----(BEGIN|END) [A-Z ]*PRIVATE KEY-----'`;+const REBUILDABLE = `(p.page_kind='markdown' OR (p.page_kind='code' AND COALESCE(p.frontmatter->>'file',p.source_path) IS NOT NULL))`;+const PENDING = `p.deleted_at IS NULL AND p.page_kind IN ('markdown','code')+ AND p.text_projection_revision IS DISTINCT FROM p.knowledge_revision+ AND (p.compiled_truth ~ ${KEY_MARKER} OR COALESCE(p.timeline,'') ~ ${KEY_MARKER})`;++export interface CredentialPending { rebuildable: number; kept: number }++/** Pending pages in active sources; `kept` cannot be rebuilt here (code without a recorded source path). */+export async function credentialProjectionPending(engine: Pick<BrainEngine, 'executeRaw'>, sourceIds?: string[]): Promise<CredentialPending> {+ const [row] = await engine.executeRaw<{ rebuildable: number; kept: number }>(`SELECT+ COUNT(*) FILTER (WHERE ${REBUILDABLE})::int AS rebuildable,+ COUNT(*) FILTER (WHERE NOT ${REBUILDABLE})::int AS kept+ FROM pages p JOIN sources s ON s.id=p.source_id AND s.archived IS NOT TRUE+ WHERE ${PENDING} ${sourceIds ? 'AND p.source_id=ANY($1::text[])' : ''}`, sourceIds ? [sourceIds] : []);+ return { rebuildable: Number(row?.rebuildable ?? 0), kept: Number(row?.kept ?? 0) };+}++export interface CredentialResealResult { resealed: number; superseded: number; failed: number; kept: number }++/** Re-seal every rebuildable pending page, one page per transaction, so an interrupted run resumes where it stopped. */+export async function resealCredentialProjections(engine: BrainEngine): Promise<CredentialResealResult> {+ const rows = await engine.executeRaw<{ source_id: string; slug: string }>(`SELECT p.source_id,p.slug+ FROM pages p JOIN sources s ON s.id=p.source_id AND s.archived IS NOT TRUE+ WHERE ${PENDING} AND ${REBUILDABLE} ORDER BY p.id`);+ const result: CredentialResealResult = { resealed: 0, superseded: 0, failed: 0, kept: 0 };+ for (const row of rows) {+ try {+ if (await resealSafeChunks(engine, row.slug, row.source_id)) result.resealed++;+ else result.superseded++;+ } catch (error) {+ if (error instanceof PageRevisionConflictError) { result.superseded++; continue; }+ result.failed++;+ process.stderr.write(`[gbrain] Credential-safe re-chunk failed for ${row.source_id}:${row.slug}; its chunks stay withheld. `+ + `Re-run: gbrain apply-migrations --yes --no-autopilot-install\n`);+ }+ }+ result.kept = (await credentialProjectionPending(engine)).kept;+ return result;+}diff --git a/src/core/persistence/connector-google-receipts.ts b/src/core/persistence/connector-google-receipts.tsindex 127875bf57..575444dd01 100644--- a/src/core/persistence/connector-google-receipts.ts+++ b/src/core/persistence/connector-google-receipts.ts@@ -69,7 +69,8 @@ export async function prepareGoogleReceiptPatch(engine: BrainEngine, row: WriteRconst frontmatter = { ...current.page.frontmatter, gmail_attachment_receipts: receipts };const page = { ...current.page, frontmatter };const noop = digest(current.page.frontmatter.gmail_attachment_receipts ?? null) === digest(receipts);- const file = await prepareFileTarget(engine, row, current, serializePageToMarkdown(page, current.tags));+ const target = await prepareFileTarget(engine, row, current, serializePageToMarkdown(page, current.tags));+ const file = target && { ...target, publishMode: 0o600 };const projection = noop ? null : await readProjectionSnapshot(engine, row.slug, row.source_id, { allowUnsealed: true });if (!noop && (!projection || projection.snapshot.revision !== current.revision)) throw new OperationError('revision_conflict', 'The Gmail page changed during receipt preparation.');const chunks = projection ? await preparePageProjection(projection) : null;diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.tsindex 36d8b75a6a..20d2fd07c4 100644--- a/src/core/persistence/connector-sync.ts+++ b/src/core/persistence/connector-sync.ts@@ -935,7 +935,9 @@ export async function prepareConnectorMutation(engine: BrainEngine, row: WriteReconst project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, snapshot, 'preserving');const tags = [...new Set([...(snapshot?.tags ?? []), ...ready.parsedPage.tags])].sort();const page: Page = { ...(snapshot?.page ?? { id: 0, slug: row.slug, source_id: row.source_id, created_at: new Date(row.created_at), updated_at: new Date(row.created_at) }), ...ready.parsedPage };- const file = await connectorFileTarget(engine, row, snapshot, serializePageToMarkdown(page, tags), p.sourcePath, p.canonicalRoot);+ const target = await connectorFileTarget(engine, row, snapshot, serializePageToMarkdown(page, tags), p.sourcePath, p.canonicalRoot);+ // Google pages hold private mail: derived here from the stored connector, never submitted, so request ids are unchanged.+ const file = target && p.connector === 'google' ? { ...target, publishMode: 0o600 } : target;if (file && (file.path !== p.filePath || file.expectedBeforeHash !== p.fileBeforeHash)) throw new OperationError('source_changed', 'The connector canonical file changed during preparation.');return { observedRevision: ready.observedRevision, sourceExclusive: true,validate: async tx => { await validate(tx); await ready.validate(tx); },diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 6f5d2f8ed6..16d7763ea2 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -2,7 +2,7 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, unlinkSync, oimport { dirname } from 'node:path';import type { BrainEngine } from '../engine.ts';import { OperationError } from '../ops/contract.ts';-import { atomicWriteFileSync } from '../atomic-write.ts';+import { atomicWriteFileSync, mkdirPrivate } from '../atomic-write.ts';import { isWriteTargetContained } from '../path-confine.ts';import { sha256 } from './digest.ts';import { authorizeStoredRequest } from './authority.ts';@@ -39,8 +39,10 @@ interface PreparedMutationBase {apply(tx: BrainEngine): Promise<Record<string, unknown>>;validate?(tx: BrainEngine): Promise<void>;}+/** A page file target; `publishMode` (Google pages) is the exact mode it publishes with, and its created directories get 0700. */+export type PageMutationFile = MutationFile & { publishMode?: number };export type PreparedMutation = PreparedMutationBase & (- | { target?: 'page'; file?: MutationFile; files?: never }+ | { target?: 'page'; file?: PageMutationFile; files?: never }| { target: 'skill_bundle'; file?: never; files: MutationFile[]; validate(tx: BrainEngine): Promise<void> });export interface PublicationHooks {@@ -61,19 +63,21 @@ function flushDirectory(path: string): void {if (!(process.platform === 'win32' && ['EISDIR','EPERM','EINVAL','ENOTSUP'].includes(code ?? ''))) throw error;} finally { if (fd !== undefined) closeSync(fd); }}-function publishFile(file: NonNullable<PreparedMutation['file']>, stagingPath?: string, afterStagingFlush?: () => void, mode?: number | null): void {+function publishFile(file: PageMutationFile, stagingPath?: string, afterStagingFlush?: () => void, mode?: number | null): void {if (!isWriteTargetContained(file.path, file.root)) throw new OperationError('storage_error', 'Canonical file target escapes its source root.');- mkdirSync(dirname(file.path), { recursive: true });+ if (file.publishMode === undefined) mkdirSync(dirname(file.path), { recursive: true });+ else mkdirPrivate(dirname(file.path), file.root);if (!isWriteTargetContained(file.path, file.root)) throw new OperationError('storage_error', 'Canonical parent path changed during publication.');+ const openMode = mode ?? file.publishMode;if (file.content === null) {try { unlinkSync(file.path); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }- } else atomicWriteFileSync(file.path, file.content, { durable: true, stagingPath, afterStagingFlush: () => {+ } else atomicWriteFileSync(file.path, file.content, { durable: true, stagingPath, ...(openMode === undefined ? {} : { mode: openMode }), afterStagingFlush: () => {+ afterStagingFlush?.();if (mode !== undefined && mode !== null && stagingPath) {chmodSync(stagingPath, mode);const fd = openSync(stagingPath, 'r');try { fsyncSync(fd); } finally { closeSync(fd); }}- afterStagingFlush?.();} });flushDirectory(file.path);}@@ -358,7 +362,8 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostIdstageBundleFile(file, restored);if (file.content !== null) hooks.fileBoundary?.('restoration_staging_flushed', current, index);publishStagedBundleFile(restored, phase => hooks.fileBoundary?.(`restoration_${phase}`, current, index));- } else publishFile(file, record.staging?.restoration?.path, undefined, record.mode);+ } else publishFile(file, record.staging?.restoration?.path,+ () => hooks.fileBoundary?.('restoration_staging_flushed', current, index), record.mode);});}hooks.fileBoundary?.('after_restore', current, index);diff --git a/src/core/post-upgrade-reembed.ts b/src/core/post-upgrade-reembed.tsindex db5ec6241f..8fe59c5590 100644--- a/src/core/post-upgrade-reembed.ts+++ b/src/core/post-upgrade-reembed.ts@@ -7,10 +7,10 @@* pennies; on a 100K-page brain it's tens of dollars. Surprise OpenAI bills* are how trust breaks.*- * Per D3=B: print a stderr line with the real-data estimate before the- * sweep starts, give the operator 10 seconds to Ctrl-C, then proceed.- *- * TTY-only wait so non-TTY upgrades (CI, cron-driven, headless) don't hang.+ * Print a stderr line with the real-data estimate, then re-embed only on an+ * affirmative answer: a TTY operator must type `y`; a non-TTY upgrade (CI,+ * cron, an agent) never spends and prints the commands to run instead+ * (security wave ENG-3: no paid work without consent).** Codex C3 corrections in place:* - Real SQL queries against `pages.chunker_version < N AND page_kind = 'markdown'`@@ -80,7 +80,7 @@ export async function computeReembedEstimate(* Format the operator-facing stderr line. Pure function so tests can pin* the exact wording.*/-export function formatReembedPrompt(est: ReembedEstimate, graceSeconds: number): string {+export function formatReembedPrompt(est: ReembedEstimate): string {if (est.pendingCount === 0) {return `[chunker-bump] No pending markdown pages. Skipping re-embed.`;}@@ -97,36 +97,41 @@ export function formatReembedPrompt(est: ReembedEstimate, graceSeconds: number):`title before embedding (Anthropic's published method).`;if (est.pricingKnown && est.estimatedCostUsd !== null) {const dollars = est.estimatedCostUsd.toFixed(2);- return `[chunker-bump] Will re-embed ~${est.pendingCount} markdown pages via ${est.modelString}, est. ~$${dollars}, ~${minEst}min. Press Ctrl-C within ${graceSeconds}s to abort.${crNote}`;+ return `[chunker-bump] Re-embedding ~${est.pendingCount} markdown pages via ${est.modelString} would cost est. ~$${dollars}, ~${minEst}min.${crNote}`;}- return `[chunker-bump] Will re-embed ~${est.pendingCount} markdown pages via ${est.modelString}; pricing estimate unavailable for this provider. Press Ctrl-C within ${graceSeconds}s to abort.${crNote}`;+ return `[chunker-bump] Re-embedding ~${est.pendingCount} markdown pages via ${est.modelString} has a cost; pricing estimate unavailable for this provider.${crNote}`;}export interface PromptResult {proceeded: boolean;- reason: 'no_pending' | 'bypassed_no_reembed' | 'tty_proceeded' | 'non_tty_proceeded';+ reason: 'no_pending' | 'bypassed_no_reembed' | 'consent_required' | 'tty_declined' | 'tty_consented';estimate: ReembedEstimate;}+/** What to run instead when the operator has not agreed to re-embed now. */+export const REEMBED_DEFERRED_HINT = '[chunker-bump] Not re-embedding without your consent. When ready: `gbrain reindex --markdown` '+ + '(re-embeds), or `gbrain repair safe-chunks --apply --no-embed` to re-chunk without provider calls, then `gbrain embed --stale`.';++async function askYesNo(question: string): Promise<boolean> {+ const { createInterface } = await import('readline');+ return new Promise<boolean>(resolveAnswer => {+ const rl = createInterface({ input: process.stdin, output: process.stderr });+ let answered = false;+ rl.question(question, answer => {+ answered = true;+ resolveAnswer(/^y(es)?$/i.test(answer.trim()));+ rl.close();+ });+ rl.on('close', () => { if (!answered) resolveAnswer(false); });+ });+}+/**- * Run the post-upgrade chunker-bump prompt + grace window. Returns whether- * the caller should proceed to invoke `gbrain reindex --markdown`.- *- * Env overrides (codex C3 + D3=B):- * - GBRAIN_NO_REEMBED=1 → bail out entirely (writes a doctor warning marker).- * - GBRAIN_REEMBED_GRACE_SECONDS=0 → skip wait (proceed immediately).- * - Non-TTY (CI / cron) → skip wait, proceed.- *- * v0.41.13.0 T13 retrofit relationship: this prompt is a pre-flight gate- * for `gbrain reindex --markdown` (which is a separate site we retrofitted- * onto the progressive-batch primitive — see T11 in reindex.ts). The- * underlying reindex sweep now writes progressive-batch audit JSONL +- * cost-cap gating; this prompt remains as the operator-facing cost- * estimate before that work starts. The `GBRAIN_NO_REEMBED=1` env var- * remains the authoritative bail-out at THIS layer; the- * `GBRAIN_PROGRESSIVE_BATCH_DISABLED=1` env var at the reindex layer- * is a different toggle (skips ramp within reindex but doesn't bail- * out the whole cycle).+ * Run the post-upgrade chunker-bump prompt. Returns whether the caller should+ * proceed to invoke `gbrain reindex --markdown`, which calls the embedding+ * provider. It proceeds only when a TTY operator answers yes; the default,+ * a non-TTY run and an unanswered prompt all decline and print+ * REEMBED_DEFERRED_HINT. `GBRAIN_NO_REEMBED=1` skips the prompt entirely.*/export async function runPostUpgradeReembedPrompt(engine: BrainEngine,@@ -134,8 +139,8 @@ export async function runPostUpgradeReembedPrompt(opts: {/** Override for tests: pretend stdin is/isn't a TTY. */isTTY?: boolean;- /** Override for tests: how long the wait window is. */- graceSeconds?: number;+ /** Override for tests: the yes/no answer source. Defaults to a readline prompt on stdin. */+ confirm?: (question: string) => Promise<boolean>;/** Override for tests: env-var bag. Defaults to process.env. */env?: Record<string, string | undefined>;/** Override for tests: where to write. Defaults to process.stderr. */@@ -155,23 +160,18 @@ export async function runPostUpgradeReembedPrompt(return { proceeded: false, reason: 'bypassed_no_reembed', estimate };}- const grace = typeof opts.graceSeconds === 'number'- ? opts.graceSeconds- : (() => {- const n = parseInt(env.GBRAIN_REEMBED_GRACE_SECONDS ?? '', 10);- return Number.isFinite(n) && n >= 0 ? n : 10;- })();-- writeFn(formatReembedPrompt(estimate, grace));+ writeFn(formatReembedPrompt(estimate));- const isTTY = typeof opts.isTTY === 'boolean'- ? opts.isTTY- : Boolean(process.stdin.isTTY);-- if (!isTTY || grace === 0) {- return { proceeded: true, reason: isTTY ? 'tty_proceeded' : 'non_tty_proceeded', estimate };+ const isTTY = typeof opts.isTTY === 'boolean' ? opts.isTTY : Boolean(process.stdin.isTTY);+ if (!isTTY) {+ writeFn(REEMBED_DEFERRED_HINT);+ return { proceeded: false, reason: 'consent_required', estimate };}- await new Promise<void>(resolveSleep => setTimeout(resolveSleep, grace * 1000));- return { proceeded: true, reason: 'tty_proceeded', estimate };+ const consented = await (opts.confirm ?? askYesNo)('[chunker-bump] Re-embed now? [y/N] ');+ if (!consented) {+ writeFn(REEMBED_DEFERRED_HINT);+ return { proceeded: false, reason: 'tty_declined', estimate };+ }+ return { proceeded: true, reason: 'tty_consented', estimate };}diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex a27020ce52..79ec677b0a 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -23,7 +23,7 @@ import { getWriteRequest } from '../persistence/journal.ts';import { initializeLocalPersistence, requestPrincipalForContext } from '../persistence/page-mutations.ts';import { lookupEmbeddingPrice, estimateCostFromChars } from '../embedding-pricing.ts';-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects', 'stale-atoms', 'extractor-facts'] as const;+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects', 'google-file-modes', 'stale-atoms', 'extractor-facts'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }diff --git a/src/core/repair/google-file-modes.ts b/src/core/repair/google-file-modes.tsnew file mode 100644index 0000000000..7405ff56db--- /dev/null+++ b/src/core/repair/google-file-modes.ts@@ -0,0 +1,34 @@+/**+ * `gbrain repair google-file-modes` (security fix wave): clear the group and+ * other bits of files and directories gbrain wrote under a Google source+ * directory outside `~/.gbrain` (see `src/core/google/file-modes.ts` for what+ * counts as gbrain's own layout). Never the user-chosen root, never through a+ * symlink, never another user's file. Filesystem only: no journal admission.+ * Each run re-scans, so a rerun after `--limit` or an interruption picks up+ * exactly the entries that are still loose.+ */+import { scanGoogleFileModes, tightenGoogleEntry } from '../google/file-modes.ts';+import type { RepairHandler, RepairItem } from './core.ts';++export const googleFileModesRepair: RepairHandler = {+ kind: 'google-file-modes',+ publication: 'projection',+ embeds: false,+ async plan(engine, scope) {+ const scans = await scanGoogleFileModes(engine, { sourceIds: scope.source_ids });+ const items: RepairItem[] = scans.flatMap((scan, phase) => scan.loose.map((entry, index) => ({+ cursor: { phase, id: index + 1 }, source_id: scan.sourceId, slug: entry.rel, chars: 0, action: `tighten_${entry.kind}`,+ change: { from: JSON.stringify({ root: scan.dir, rel: entry.rel, kind: entry.kind, mode: entry.mode.toString(8) }), to: (entry.mode & ~0o077).toString(8) },+ })));+ const residuals: Record<string, number> = {};+ for (const scan of scans) for (const [reason, count] of Object.entries(scan.skipped)) {+ if (count) residuals[`skipped_${reason}`] = (residuals[`skipped_${reason}`] ?? 0) + count;+ }+ return { items, residuals };+ },+ async apply(_ctx, item) {+ const { root, rel, kind } = JSON.parse(item.change!.from!) as { root: string; rel: string; kind: 'file' | 'dir' };+ const result = tightenGoogleEntry(root, { rel, kind });+ return { applied: result.outcome === 'tightened', outcome: result.outcome, ...(result.reason ? { reason: result.reason } : {}) };+ },+};diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex f85c51f811..0db950fd6c 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -31,6 +31,7 @@ import { requestIndexesRepair } from './request-indexes.ts';import { connectorFencesRepair } from './connector-fences.ts';import { orphanBindingsRepair } from './orphan-bindings.ts';import { embeddingEffectsRepair } from './embedding-effects.ts';+import { googleFileModesRepair } from './google-file-modes.ts';import { staleAtomsRepair } from './stale-atoms.ts';import { extractorFactsRepair } from './extractor-facts.ts';import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';@@ -95,6 +96,12 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'Each effect is reconciled (current vectors pass the effect verifier), superseded (page deleted, or a newer revision owns its own effect), '+ 'retry_queued for its owner (paid; a consumed retry allowance gets one new bounded cycle per explicit run) or blocked with the reason. Never drops an obligation.',},+ 'google-file-modes': {+ handler: googleFileModesRepair, embeds: 'none', checks: ['google_file_modes'], explicit_only: true,+ summary: 'Clear group and other permission bits on files and directories gbrain wrote under a Google source directory outside ~/.gbrain '+ + '(cursor state, mail/calendar/contact pages and the subdirectories gbrain laid out), written before this release with the default umask. '+ + 'Never the directory you chose, never through a symlink, never another user\'s file. Filesystem only; runs only when named (`gbrain repair google-file-modes`).',+ },'stale-atoms': {handler: staleAtomsRepair, embeds: 'none', checks: ['atom_provenance_drift'], explicit_only: true,summary: 'Retire, by soft delete, page-bound atoms whose source page is gone, or whose source page changed after its current text was already extracted (#5770). 'diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex a4d3590a61..3879d88fb8 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -189,6 +189,7 @@ import { v185 } from './v185-decide-calibrations.ts';import { v186 } from './v186-decide-proposals.ts';import { v187 } from './v187-fact-relink-attempts.ts';import { v188 } from './v188-facts-ontology-stint-dedup.ts';+import { v189 } from './v189-pages-credential-projection-pending.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -376,4 +377,5 @@ export const MIGRATIONS: Migration[] = [v186,v187,v188,+ v189,];diff --git a/src/core/schema-migrations/v189-pages-credential-projection-pending.ts b/src/core/schema-migrations/v189-pages-credential-projection-pending.tsnew file mode 100644index 0000000000..18ebd94c14--- /dev/null+++ b/src/core/schema-migrations/v189-pages-credential-projection-pending.ts@@ -0,0 +1,31 @@+import type { Migration } from './types.ts';++// Security wave ENG-2: chunks built before the credential-safe projection+// (src/core/credential-projection.ts) can hold private-key fragments with no+// fence, which no output scan can recognize. Only pages whose canonical body+// carries a private-key marker are affected, so only they are unsealed here:+// every retrieval path, local and remote, reads chunks through the current+// text-projection seal, so their old chunks are withheld from this statement+// on. Each page is queued for the keyless projection rebuild (reason+// 'credential_projection'); the v0.60.31 orchestrated migration re-chunks them+// with no provider calls. The chunker and safe-fence versions do not change.+// The marker literal is frozen as shipped; see page-state/credential-reseal.ts.+export const v189: Migration = {+ version: 189,+ name: 'pages_credential_projection_pending',+ idempotent: true,+ sql: `+ WITH marked AS (+ UPDATE pages p SET text_projection_revision = NULL+ WHERE p.deleted_at IS NULL AND p.page_kind IN ('markdown', 'code')+ AND (p.compiled_truth ~ '-----(BEGIN|END) [A-Z ]*PRIVATE KEY-----'+ OR COALESCE(p.timeline, '') ~ '-----(BEGIN|END) [A-Z ]*PRIVATE KEY-----')+ RETURNING p.source_id, p.slug, p.knowledge_revision+ )+ INSERT INTO page_projection_jobs(source_incarnation, slug, revision, reason)+ SELECT s.incarnation, marked.slug, marked.knowledge_revision, 'credential_projection'+ FROM marked JOIN sources s ON s.id = marked.source_id+ ON CONFLICT(source_incarnation, slug) DO UPDATE+ SET revision = EXCLUDED.revision, reason = EXCLUDED.reason, updated_at = now();+ `,+};diff --git a/src/core/search/evidence-delivery.ts b/src/core/search/evidence-delivery.tsindex 4fbdfebe41..8cfd4cbdcb 100644--- a/src/core/search/evidence-delivery.ts+++ b/src/core/search/evidence-delivery.ts@@ -31,6 +31,7 @@ import { currentTextProjectionFilter, safeChunksFilter, requiresSafeChunks } froimport { resolveExcludePrivatePages } from './private-visibility.ts';import { safeSplitIndex } from '../text-safe.ts';import { sanitizeRemoteBody } from '../remote-body.ts';+import { credentialSafeProjection } from '../credential-projection.ts';import { stripChunkHeader } from '../chunkers/code.ts';import { OperationError } from '../ops/contract.ts';@@ -516,12 +517,14 @@ function fallbackBlock(hit: SearchResult, hits: SearchResult[], reason: string):* The page text evidence is cut from: the complete stored body, sanitized* with the strict protected-body boundary BEFORE any slicing (Takes, non-world* and withdrawn Facts rows, malformed protected tails, materialized markers),- * compiled truth and timeline each sanitized whole and joined the way- * serializeMarkdown joins them. Frontmatter is not part of it.+ * compiled truth and timeline each sanitized whole, run through the same+ * credential-safe projection the chunkers cut from (private-key spans become+ * newline-padded tokens), and joined the way serializeMarkdown joins them.+ * Frontmatter is not part of it.*/export function pageEvidenceText(page: { compiled_truth: string; timeline: string }, includeTimeline: boolean): { text: string; timelineAt: number } {- const truth = sanitizeRemoteBody(page.compiled_truth ?? '');- const timeline = includeTimeline ? sanitizeRemoteBody(page.timeline ?? '') : '';+ const truth = credentialSafeProjection(sanitizeRemoteBody(page.compiled_truth ?? ''));+ const timeline = includeTimeline ? credentialSafeProjection(sanitizeRemoteBody(page.timeline ?? '')) : '';if (!timeline.trim()) return { text: truth, timelineAt: -1 };return { text: truth + TIMELINE_SEPARATOR + timeline, timelineAt: truth.length + TIMELINE_SEPARATOR.length };}diff --git a/src/core/search/output-redaction.ts b/src/core/search/output-redaction.tsindex 1b71fedbbd..e8ce86d72b 100644--- a/src/core/search/output-redaction.ts+++ b/src/core/search/output-redaction.ts@@ -1,5 +1,6 @@import { applyRedaction, planRedaction, type RedactionPlan } from '../secret-scan.ts';import { DEGRADED_REASONS, DEGRADED_STAGES } from '../types.ts';+import type { Operation } from '../ops/contract.ts';export const OUTPUT_REDACTION_MAX_FIELD_CHARS = 64 * 1024;export const OUTPUT_REDACTION_MAX_TOTAL_CHARS = 1024 * 1024;@@ -8,27 +9,43 @@ export const OUTPUT_REDACTION_LIMIT = '<REDACTED:output_limit>';const IDENTITY_FIELDS = new Set(['id', 'slug', 'source_id', 'page_id', 'chunk_id', 'message_id', 'thread_id','graph_session_prefix', 'relational_seed', 'relational_path', 'superseded_by',+ 'fact_id', 'entity_slug',]);const MAX_DEPTH = 24;const MAX_TEXT_FIELDS = 8192;const DEGRADED_STAGE_CODES = new Set<string>(DEGRADED_STAGES);const DEGRADED_REASON_CODES = new Set<string>(DEGRADED_REASONS);-export function redactRetrievalOutput<T, M>(results: T[], meta: M): { results: T[]; meta: M } {+export interface RetrievalRedactionOpts {+ /**+ * Scan every text field whole: no per-field, response or field-count+ * replacement with `<REDACTED:output_limit>`. One echo dictionary still+ * spans the response and every field is planned before any write.+ */+ uncapped?: boolean;+ /** Keys of each top-level result object copied verbatim, unscanned. */+ verbatim?: readonly string[];+}++export function redactRetrievalOutput<T, M>(results: T[], meta: M, opts: RetrievalRedactionOpts = {}): { results: T[]; meta: M } {const echoValues = new Map<string, string>();const plans = new Map<string, RedactionPlan>();const writes: Array<() => void> = [];+ const verbatim = new Set(opts.verbatim ?? []);let remaining = OUTPUT_REDACTION_MAX_TOTAL_CHARS;let fields = 0;function copy(value: unknown, depth: number, path: Array<string | number>): unknown {if (typeof value !== 'object' || value === null) return value;+ if (value instanceof Date) return new Date(value.getTime());if (depth > MAX_DEPTH) return OUTPUT_REDACTION_LIMIT;const entries = Array.isArray(value) ? value.entries() : Object.entries(value);const out: Record<string, unknown> | unknown[] = Array.isArray(value) ? [] : {};for (const [key, item] of entries) {let next: unknown;- if (IDENTITY_FIELDS.has(String(key)) && (typeof item !== 'object' || item === null ||+ if (path.length === 2 && path[0] === 'results' && verbatim.has(String(key))) {+ next = item;+ } else if (IDENTITY_FIELDS.has(String(key)) && (typeof item !== 'object' || item === null ||(Array.isArray(item) && item.every(part => typeof part === 'string')))) {next = Array.isArray(item) ? [...item] : item;} else if (typeof item === 'string' && path[0] === 'meta' && (@@ -40,12 +57,12 @@ export function redactRetrievalOutput<T, M>(results: T[], meta: M): { results: Tnext = item;} else if (typeof item === 'string') {let plan = plans.get(item);- if (item.length > OUTPUT_REDACTION_MAX_FIELD_CHARS || item.length > remaining || ++fields > MAX_TEXT_FIELDS) {+ if (!opts.uncapped && (item.length > OUTPUT_REDACTION_MAX_FIELD_CHARS || item.length > remaining || ++fields > MAX_TEXT_FIELDS)) {next = OUTPUT_REDACTION_LIMIT;} else {remaining -= item.length;if (!plan) {- plan = planRedaction(item, { echoValues });+ plan = planRedaction(item, { echoValues, highEntropy: true });plans.set(item, plan);}const planned = plan;@@ -65,3 +82,19 @@ export function redactRetrievalOutput<T, M>(results: T[], meta: M): { results: Tfor (const write of writes) write();return output;}++/**+ * The registration-time wrapper behind `Operation.outputRedaction`: a+ * retrieval op's whole response (early returns included) passes through the+ * uncapped redactor; `localVerbatim` keys stay raw for the trusted local CLI.+ * Every other policy returns the handler unchanged.+ */+export function withOutputRedaction(op: Pick<Operation, 'handler' | 'outputRedaction'>): Operation['handler'] {+ const { handler, outputRedaction: policy } = op;+ if (policy !== 'retrieval' && !(typeof policy === 'object' && 'retrieval' in policy)) return handler;+ const localVerbatim = policy === 'retrieval' ? [] : policy.retrieval.localVerbatim;+ return async (ctx, params) => {+ const result = await handler(ctx, params);+ return redactRetrievalOutput([result], {}, { uncapped: true, verbatim: ctx.remote === false ? localVerbatim : [] }).results[0];+ };+}diff --git a/src/core/search/two-pass.ts b/src/core/search/two-pass.tsindex 050fb84473..cec572e392 100644--- a/src/core/search/two-pass.ts+++ b/src/core/search/two-pass.ts@@ -23,6 +23,7 @@import type { BrainEngine } from '../engine.ts';import type { SearchResult } from '../types.ts';+import { currentTextProjectionFilter } from './safe-chunks.ts';const MAX_WALK_DEPTH = 2;const NEIGHBOR_CAP_PER_HOP = 50;@@ -198,7 +199,7 @@ export async function hydrateChunks(cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_sourceFROM content_chunks ccJOIN pages p ON p.id = cc.page_id- WHERE cc.id = ANY($1::int[])`,+ WHERE cc.id = ANY($1::int[]) AND ${currentTextProjectionFilter('p')}`,[chunkIds],);return rows.map((r) => ({diff --git a/src/core/secret-scan.ts b/src/core/secret-scan.tsindex a06e14be76..ca8c9eab49 100644--- a/src/core/secret-scan.ts+++ b/src/core/secret-scan.ts@@ -48,6 +48,18 @@ export interface SecretFinding {fingerprint: string;/** Set by scanFiles: the path the finding came from (as given by the caller). */file?: string;+ /**+ * The gbrain version that added or last changed this finding's rule+ * (`patternSince`); absent for rules unchanged since before it was tracked.+ */+ since?: string;+ /**+ * private_key_pem findings whose claim now covers key body after a BEGIN+ * fence with no END in view: the fingerprint the pre-wave scanner reported+ * for the same key (header only). An allowlist entry carrying it no longer+ * matches; a refusal can name the replacement line.+ */+ legacyFingerprint?: string;}export interface ScanOpts {@@ -77,9 +89,9 @@ export const SCAN_ALLOW_FILENAME = '.gbrain-scan-allow';// an account SID, a connection string carrying its password) are matched on// their WIRE SHAPE. Fixed-length shapes carry a trailing negative lookahead so// a longer alphanumeric run (a digest, an identifier) is not cut into a-// false "key". The two CATCH-ALLS (`bearer`, `db_url_credentials`) are-// appended LAST on purpose: the per-line claimed-span dedupe is first-wins-// for ATTRIBUTION, so `Bearer <vendor key>` keeps its vendor attribution and+// false "key". The CATCH-ALLS (`bearer`, `db_url_credentials`,+// `url_credentials`, `basic_auth`) are appended LAST on purpose: the per-line+// claimed-span dedupe is first-wins for ATTRIBUTION, so `Bearer <vendor key>` keeps its vendor attribution and// a JWT used as a URL password is reported as `jwt` once — while COVERAGE is// the union: whatever part of the later catch-all span the earlier claim did// not cover (the userinfo around that JWT) is still claimed by the catch-all@@ -87,11 +99,13 @@ export const SCAN_ALLOW_FILENAME = '.gbrain-scan-allow';interface CompiledPattern {name: string;- re: RegExp; // 'g' flags; group 1 = boundary, group 2 = the secret value+ re: RegExp; // 'g' or 'gi'; group 1 = boundary/anchor, group 2 = the secret value/** When true, a match must also pass the Shannon-entropy gate. */entropyGated?: boolean;/** See CorePattern.precheck. */precheck?: (line: string) => boolean;+ /** See CorePattern.validate. */+ validate?: (value: string) => boolean;}interface CorePattern {@@ -104,6 +118,8 @@ interface CorePattern {* literal keyword (e.g. `Bearer `) that must NOT be part of the value.*/prebuilt?: boolean;+ /** RegExp flags. Default `'g'`; a case-insensitive shape uses `'gi'`. */+ flags?: string;/*** Cheap substring gate run BEFORE the regex on every line: when it returns* false the line cannot contain a match and the regex is skipped. Used by@@ -111,8 +127,62 @@ interface CorePattern {* shapes here and whose anchor (`earer`, `@`) is a one-call `includes`.*/precheck?: (line: string) => boolean;+ /**+ * Post-match check on the WHOLE matched value (group 2), run before the+ * claim and before any union split. False drops the match; the regex has+ * already consumed it, so a rejected value is never re-tried from inside.+ * Must be O(value).+ */+ validate?: (value: string) => boolean;+ /**+ * The gbrain version that added or last changed this rule. Copied onto+ * every finding of the pattern (`SecretFinding.since`) so a refusal can say+ * which upgrade started blocking it.+ */+ since?: string;}+/**+ * `since` for the rules added or changed by the security fix wave+ * (`digitalocean`, `url_credentials`, `basic_auth`, truncated/split+ * `private_key_pem` bodies).+ */+const SECURITY_WAVE_SINCE = '0.60.31.0';++/**+ * Placeholder passwords in documentation URLs: `<password>`, `${VAR}`,+ * `$VAR`, all-`*` and all-`x` masks. Never a live credential, so+ * `url_credentials` leaves them alone.+ */+const URL_PASSWORD_PLACEHOLDER_RE = /^(?:<[^<>]*>|\$\{[^{}]*\}|\$[A-Za-z_][A-Za-z0-9_]*|\*+|[xX]+)$/;++/** `url_credentials` validate: the password segment is not a placeholder. */+function urlPasswordIsReal(value: string): boolean {+ const schemeEnd = value.indexOf('://') + 3;+ const colon = value.indexOf(':', schemeEnd);+ return !URL_PASSWORD_PLACEHOLDER_RE.test(value.slice(colon + 1, -1));+}++/**+ * `basic_auth` validate: the value base64-decodes to printable ASCII that+ * contains a `:` (the user-pass separator). Prose after the word `Basic`+ * decodes to binary noise and is rejected. The value class is bounded at+ * 2048 chars, so the decode is constant work per match.+ */+function basicValueDecodesToUserPass(value: string): boolean {+ const bytes = Buffer.from(value, 'base64');+ if (bytes.length < 3) return false;+ let colon = false;+ for (const b of bytes) {+ if (b < 0x20 || b > 0x7e) return false;+ if (b === 0x3a) colon = true;+ }+ return colon;+}++/** `basic_auth` precheck: the lowercase-insensitive word, no allocation. */+const BASIC_PRECHECK_RE = /basic/i;+const CORE_PATTERNS: ReadonlyArray<CorePattern> = [{ name: 'anthropic', source: 'sk-ant-[A-Za-z0-9_-]{16,}' },// Prefixed OpenAI forms (sk-proj-/sk-svcacct-/sk-None-) allow `_`/`-` in the@@ -145,6 +215,9 @@ const CORE_PATTERNS: ReadonlyArray<CorePattern> = [{ name: 'supabase_key', source: 'sbp_[a-f0-9]{40}(?![0-9A-Za-z])' },{ name: 'npm_token', source: 'npm_[A-Za-z0-9]{36}(?![A-Za-z0-9])' },{ name: 'huggingface', source: 'hf_[A-Za-z0-9]{30,}' },+ // DigitalOcean personal access (dop_), OAuth (doo_) and refresh (dor_)+ // tokens: v1 + 64 lowercase hex, hard right edge.+ { name: 'digitalocean', source: 'do[opr]_v1_[a-f0-9]{64}(?![A-Za-z0-9])', since: SECURITY_WAVE_SINCE },// gbrain's own tokens: generateToken (core/utils.ts) mints 'gbrain_' plus an// optional OAuth infix (at_ access / rt_ refresh / cs_ client secret /// code_ auth code) plus 32 random bytes hex. Without this entry the scanner@@ -224,36 +297,285 @@ const CORE_PATTERNS: ReadonlyArray<CorePattern> = ['[^\\s:/@"\']{0,128}:[^\\s@"\']{1,256}@',precheck: (line) => line.includes('@'),},+ // http(s) userinfo carrying a password: a sibling of db_url_credentials,+ // NOT folded into it, because the password class differs. The value is the+ // same span shape (scheme, user, `:`, password, `@`; host and path kept).+ // The scheme matches case-insensitively. User 0-128 stopping at `:` and+ // `/`; password 1-256 stopping at whitespace, `@`, `"`, `'` and also `/`,+ // `?`, `#` — RFC 3986 requires those percent-encoded in userinfo, and+ // admitting them would read a dev-server or registry path whose segment+ // starts with `@` (after a `host:port` authority) as a credential. A+ // password carrying a literal `/`, `?` or `#` is the accepted miss. A user+ // with no password never fires. Placeholder passwords are rejected by+ // `validate` (URL_PASSWORD_PLACEHOLDER_RE).+ {+ name: 'url_credentials',+ source: 'https?:\\/\\/[^\\s:/@"\']{0,128}:[^\\s@"\'/?#]{1,256}@',+ flags: 'gi',+ precheck: (line) => line.includes('@'),+ validate: urlPasswordIsReal,+ since: SECURITY_WAVE_SINCE,+ },+ // HTTP Basic credentials. Two prebuilt two-group forms share the name: the+ // header form (`Authorization:` then `Basic`, value 4+ chars, so the short+ // `u:p` encoding fires) and the bare `Basic <value>` form (16+ chars). Both+ // words match case-insensitively (HTTP/2 lowercase headers, `curl -H`).+ // The value is bounded at 2048 with a hard right edge (a longer base64 run+ // is not a Basic credential — the accepted miss) and must pass `validate`:+ // it decodes to printable ASCII containing `:`. NOT in the bearer family:+ // it joins neither the echo dictionary nor the `secret:bearer` sensitivity+ // family.+ {+ name: 'basic_auth',+ source: '((?:^|[^A-Za-z0-9_])authorization\\s{0,16}:\\s{0,16}basic\\s{1,16})([A-Za-z0-9+/=]{4,2048})(?![A-Za-z0-9+/=])',+ prebuilt: true,+ flags: 'gi',+ precheck: (line) => BASIC_PRECHECK_RE.test(line),+ validate: basicValueDecodesToUserPass,+ since: SECURITY_WAVE_SINCE,+ },+ {+ name: 'basic_auth',+ source: '((?:^|[^A-Za-z0-9_])basic\\s{1,16})([A-Za-z0-9+/=]{16,2048})(?![A-Za-z0-9+/=])',+ prebuilt: true,+ flags: 'gi',+ precheck: (line) => BASIC_PRECHECK_RE.test(line),+ validate: basicValueDecodesToUserPass,+ since: SECURITY_WAVE_SINCE,+ },// NOTE: private_key_pem is NOT here — a PEM key spans multiple lines and the// per-line scanner below cannot see the base64 body. It is matched over the- // WHOLE text by PEM_BLOCK_RE (see scanPemBlocks) so redaction covers the+ // WHOLE text by pemClaims (see scanPemBlocks) so redaction covers the// body+footer, not just the header line.];/**- * Whole-block PEM private key: header + (optional) base64 body + (optional)- * footer, matched multiline. The header-only pattern used to leave the base64- * body in the redacted corpus (the redaction replaced only the header line);- * matching the whole span means the key body is scrubbed. The body+footer are- * OPTIONAL so a lone/truncated header (a body-only leak, or a header with no- * END) still fires the push-block gate — value is then just the header. The- * lazy body stops at the first END marker so two adjacent keys don't collapse- * into one span. `-----BEGIN CERTIFICATE-----` never matches (the literal- * `PRIVATE KEY` is required).+ * Private-key claims over the WHOLE text (a PEM key spans lines, so the+ * per-line scanner cannot see its body). One source of truth for the scanner+ * and for `privateKeySpans` (retrieval projection). Three claim kinds:+ *+ * - BLOCK: a `BEGIN … PRIVATE KEY` fence whose next fence is an END fence+ * within PEM_BODY_MAX_CHARS. The claim is header through END, whatever lies+ * between (unchanged from the whole-block regex, except that a block never+ * swallows a later BEGIN: a truncated key followed by a complete one is two+ * claims, and the prose between them survives).+ * - FORWARD (BEGIN with no END in view: a snippet cap or excerpt cut the key+ * off): the header plus the body lines that follow it.+ * - BACKWARD (END with no BEGIN in view: a chunk that starts mid-key): the+ * body lines before the END fence plus the fence. An END fence with no body+ * line before it (a marker quoted in prose) is no claim at all.*- * The body is BOUNDED at 16384 chars (PEM_BODY_MAX_CHARS). The unbounded lazy- * `[\s\S]*?` scanned from every header to the end of the text when no END- * followed — quadratic on header-without-END texts (2000 header-only mentions- * ahead of a 1 MB tail took ~4 s). With the bound a header does constant- * work; a real key is far smaller (an RSA-4096 PEM is ~3.3 KB, RSA-16384- * ~12.5 KB). A body longer than the bound degrades to the header-only match —- * the gate still fires, the body is the accepted miss.+ * A BODY LINE is a whole-line run of base64 characters (`A-Za-z0-9+/=`),+ * optionally indented by up to PEM_INDENT_MAX spaces/tabs and followed by up+ * to that much trailing whitespace. Line ends are `\n`, `\r\n`, or the+ * literal two-character `\n` / four-character `\r\n` escapes of a+ * JSON-serialized key. Interior lines are PEM_LINE_MIN..PEM_LINE_MAX chars;+ * the line adjacent to a fence and a partial line at a cut (the end of the+ * text going forward, the start of the text going backward) may be+ * 1..PEM_LINE_MAX. A line holding anything else after its indentation+ * (prose, a space inside the run) ends the body, and so does a run longer+ * than PEM_LINE_MAX (not claimed). Going forward, optional RFC 1421 header+ * lines (`Proc-Type:`, `DEK-Info:`) and one blank line may follow the BEGIN+ * line. A header followed by no body line (a marker quoted in prose, or text+ * on the header's own line) is claimed alone, as before.+ *+ * Total claimed body stays within PEM_BODY_MAX_CHARS (an RSA-4096 PEM is+ * ~3.3 KB, RSA-16384 ~12.5 KB); past it the remainder is the accepted miss.+ * Accepted misses: body on the header's own line, space-joined single-line+ * keys, blockquoted (`> `) keys, and runs over PEM_LINE_MAX chars.+ *+ * LINEAR TIME. The fences are found by two global regex passes and merged in+ * text order; each walk stops at the neighbouring fence or at the end of the+ * previous claim, so walks never overlap and every character is visited a+ * bounded number of times (20k unterminated BEGIN fences, 20k END-only+ * fences and 1 MB of base64 lines are pinned in+ * test/secret-scan-perf.test.ts). There is no forward regex that starts at+ * every base64 line.*/export const PEM_BODY_MAX_CHARS = 16384;-export const PEM_BLOCK_RE = new RegExp(- `-----BEGIN [A-Z ]*PRIVATE KEY-----(?:[\\s\\S]{0,${PEM_BODY_MAX_CHARS}}?-----END [A-Z ]*PRIVATE KEY-----)?`,- 'g',-);+const PEM_LINE_MAX = 128;+const PEM_LINE_MIN = 16;+const PEM_INDENT_MAX = 16;+const PEM_RFC1421_LINE_MAX = 256;+const PEM_BEGIN_RE = /-----BEGIN [A-Z ]*PRIVATE KEY-----/g;+const PEM_END_RE = /-----END [A-Z ]*PRIVATE KEY-----/g;++type PemClaimKind = 'block' | 'forward' | 'backward';++interface PemClaim {+ start: number;+ end: number;+ kind: PemClaimKind;+ /** End of the BEGIN fence (block/forward): the pre-wave header-only value ends here. */+ headerEnd: number;+}++function isBase64Code(c: number): boolean {+ return (+ (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || (c >= 48 && c <= 57) || c === 43 || c === 47 || c === 61+ );+}++function isIndentCode(c: number): boolean {+ return c === 32 || c === 9;+}++/** Index just past a line end starting at `i`, or -1. */+function lineEndAt(t: string, i: number): number {+ const c = t.charCodeAt(i);+ if (c === 10) return i + 1;+ if (c === 13 && t.charCodeAt(i + 1) === 10) return i + 2;+ if (c === 92) {+ const d = t.charCodeAt(i + 1);+ if (d === 110) return i + 2;+ if (d === 114 && t.charCodeAt(i + 2) === 92 && t.charCodeAt(i + 3) === 110) return i + 4;+ }+ return -1;+}++/** Skip up to PEM_INDENT_MAX trailing spaces/tabs from `i`, then a line end: index past it, or -1. */+function lineEndAfter(t: string, i: number): number {+ let p = i;+ while (p - i < PEM_INDENT_MAX && isIndentCode(t.charCodeAt(p))) p++;+ return lineEndAt(t, p);+}++/** Start of a line end that ends exactly at `p` (never below `floor`), or -1. */+function lineEndBefore(t: string, p: number, floor: number): number {+ if (p - 1 < floor) return -1;+ const c = t.charCodeAt(p - 1);+ if (c === 10) return p - 2 >= floor && t.charCodeAt(p - 2) === 13 ? p - 2 : p - 1;+ if (c === 110 && p - 2 >= floor && t.charCodeAt(p - 2) === 92) {+ return p - 4 >= floor && t.charCodeAt(p - 4) === 92 && t.charCodeAt(p - 3) === 114 ? p - 4 : p - 2;+ }+ return -1;+}++/**+ * True when nothing but trailing whitespace and the start of a line end (`\r`,+ * or a JSON escape cut after its backslash) follows `i`: the text was cut+ * there, so the run before it is a partial last line.+ */+function atCut(t: string, i: number): boolean {+ let p = i;+ while (p - i < PEM_INDENT_MAX && isIndentCode(t.charCodeAt(p))) p++;+ const rest = t.length - p;+ return rest === 0 || (rest <= 3 && ['\r', '\\', '\\r', '\\r\\'].includes(t.slice(p)));+}++/** FORWARD claim end for a BEGIN fence ending at `headerEnd` (== headerEnd when no body line follows). */+function pemForwardEnd(t: string, headerEnd: number): number {+ const n = t.length;+ const cap = headerEnd + PEM_BODY_MAX_CHARS;+ let pos = lineEndAfter(t, headerEnd);+ if (pos < 0) return headerEnd;+ for (let k = 0; k < 4 && (t.startsWith('Proc-Type:', pos) || t.startsWith('DEK-Info:', pos)); k++) {+ let next = -1;+ for (let j = pos; j < n && j - pos <= PEM_RFC1421_LINE_MAX && next < 0; j++) next = lineEndAt(t, j);+ if (next < 0) return headerEnd;+ pos = next;+ }+ const blank = lineEndAfter(t, pos);+ if (blank >= 0) pos = blank;+ let end = headerEnd;+ for (let first = true; pos < n; first = false) {+ let p = pos;+ while (p - pos < PEM_INDENT_MAX && isIndentCode(t.charCodeAt(p))) p++;+ let q = p;+ while (q < n && q - p <= PEM_LINE_MAX && isBase64Code(t.charCodeAt(q))) q++;+ const len = q - p;+ if (len === 0 || len > PEM_LINE_MAX || q > cap) break;+ if (atCut(t, q)) return q;+ const next = lineEndAfter(t, q);+ if (next < 0) break;+ if (len < PEM_LINE_MIN && !first && next < n) break;+ end = q;+ pos = next;+ }+ return end;+}++/** BACKWARD claim start for an END fence at `endStart`, never below `floor`; -1 when no body line precedes it. */+function pemBackwardStart(t: string, endStart: number, floor: number): number {+ let p = endStart;+ while (endStart - p < PEM_INDENT_MAX && p > floor && isIndentCode(t.charCodeAt(p - 1))) p--;+ let le = lineEndBefore(t, p, floor);+ let start = -1;+ for (let adjacent = true; le >= 0; adjacent = false) {+ let q = le;+ while (le - q < PEM_INDENT_MAX && q > floor && isIndentCode(t.charCodeAt(q - 1))) q--;+ let r = q;+ while (r > floor && q - r <= PEM_LINE_MAX + 1 && isBase64Code(t.charCodeAt(r - 1))) r--;+ // A run that starts with the `n` of a JSON `\n` escape: the escape is the line end.+ if (r < q && r > floor && t.charCodeAt(r) === 110 && t.charCodeAt(r - 1) === 92) r++;+ const len = q - r;+ if (len === 0 || len > PEM_LINE_MAX || endStart - r > PEM_BODY_MAX_CHARS) break;+ let s = r;+ while (r - s < PEM_INDENT_MAX && s > floor && isIndentCode(t.charCodeAt(s - 1))) s--;+ const atTextStart = s === 0;+ const prev = atTextStart ? -1 : lineEndBefore(t, s, floor);+ if (!atTextStart && prev < 0) break;+ if (len < PEM_LINE_MIN && !adjacent && !atTextStart) break;+ start = r;+ le = prev;+ }+ return start;+}++function pemFences(t: string): Array<{ begin: boolean; start: number; end: number }> {+ const begins = [...t.matchAll(PEM_BEGIN_RE)];+ const ends = [...t.matchAll(PEM_END_RE)];+ const out: Array<{ begin: boolean; start: number; end: number }> = [];+ for (let i = 0, j = 0; i < begins.length || j < ends.length; ) {+ const b = begins[i];+ const e = ends[j];+ if (b && (!e || b.index <= e.index)) {+ out.push({ begin: true, start: b.index, end: b.index + b[0].length });+ i++;+ } else {+ out.push({ begin: false, start: e!.index, end: e!.index + e![0].length });+ j++;+ }+ }+ return out;+}++/** Every private-key claim in `t`, sorted and non-overlapping (see the section comment). */+function pemClaims(t: string): PemClaim[] {+ if (!t.includes('PRIVATE KEY-----')) return [];+ const fences = pemFences(t);+ const claims: PemClaim[] = [];+ let floor = 0;+ for (let i = 0; i < fences.length; i++) {+ const f = fences[i]!;+ if (f.start < floor) continue;+ if (f.begin) {+ const next = fences[i + 1];+ if (next && !next.begin && next.start - f.end <= PEM_BODY_MAX_CHARS) {+ claims.push({ start: f.start, end: next.end, kind: 'block', headerEnd: f.end });+ floor = next.end;+ i++;+ continue;+ }+ floor = pemForwardEnd(t, f.end);+ claims.push({ start: f.start, end: floor, kind: 'forward', headerEnd: f.end });+ continue;+ }+ const start = pemBackwardStart(t, f.start, floor);+ if (start >= 0) claims.push({ start, end: f.end, kind: 'backward', headerEnd: -1 });+ floor = f.end;+ }+ return claims;+}++/**+ * Absolute character spans of every private-key claim in `text` — exactly+ * what the scanner reports as `private_key_pem` (BLOCK, FORWARD and BACKWARD+ * rules above). Sorted, non-overlapping, linear time.+ */+export function privateKeySpans(text: string): Array<{ start: number; end: number }> {+ return pemClaims(text).map((c) => ({ start: c.start, end: c.end }));+}// Opt-in: `secret|token|password|api key`-shaped assignment whose value has// high Shannon entropy. Keyword-anchored (compiled inline below so the group@@ -297,25 +619,67 @@ export const PEM_BLOCK_RE = new RegExp(const HIGH_ENTROPY_MIN_BITS_PER_CHAR = 3.5;const HIGH_ENTROPY_REQUIRES_DIGIT_RE = /[0-9]/;+// PUNCTUATED VALUES. The rule is two compiled patterns sharing the name and+// the group-2-is-value contract. QUOTED: after an opening `"` or `'`, the+// value is any run of non-quote, non-whitespace characters (a password like+// `ab!#%…<…` is one value). UNQUOTED: the legacy class plus the password+// punctuation `!#$%*@^~.?<>` — not `&` (it would swallow sibling query+// parameters), not `()[]{}` (so `token = getToken(x)` never matches), not `:`,+// and not `,` / `;` (the false-positive measurement found SQL `SET` lists+// such as `execution_token=NULL,claim_expires_at=NULL,error_code=$3` read as+// one value; a password carrying them is matched only when quoted) — and the+// last character excludes `.?!`, so `TOKEN=<tok>.` claims the token without+// the sentence's full stop and its bare echoes still scrub.+// Both keep the 12-4096 bounds and the digit + entropy gates.+const ASSIGNMENT_KEY =+ '(?:^|[^A-Za-z0-9])(?:secret|token|passwd|password|passphrase|credential|api[_-]?key|apikey)[A-Za-z0-9_-]{0,64}["\']?\\s*[:=]\\s*';+const ASSIGNMENT_QUOTED_SOURCE = `(${ASSIGNMENT_KEY}["'])([^"'\\s]{12,4096})`;+const ASSIGNMENT_UNQUOTED_SOURCE =+ `(${ASSIGNMENT_KEY})([A-Za-z0-9+/_=\\-!#$%*@^~.?<>]{11,4095}[A-Za-z0-9+/_=\\-#$%*@^~<>])`;+/** The legacy (pre-punctuation) value class, whole-value form. */+const LEGACY_ASSIGNMENT_VALUE_RE = /^[A-Za-z0-9+/_=-]+$/;+/** A dotted member path in code (`process.env.DB_PASSWORD_2`): every segment an identifier. */+const DOTTED_IDENTIFIER_RE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/;++/**+ * Assignment-value validate: reject values that are references, not secrets+ * — a URL (`scheme://`), a relative or home path (`./`, `~/`), a shell+ * expansion (`${`, `$(`), an already-redacted token, an absolute path (`/`+ * plus a character outside the legacy class, such as the `.` of a file+ * name), and a dotted member path whose every segment is an identifier+ * (`process.env.X`, `config.secrets.key2`: the `.` admitted for passwords+ * would otherwise turn code into a value). A leading `/` on a pure base64+ * value still fires: one random base64 secret in 64 starts with `/`, and the+ * legacy rule redacted those. A dotted password whose every segment starts+ * with a letter is the accepted miss.+ */+function assignmentValueIsSecretShaped(value: string): boolean {+ if (/^[A-Za-z][A-Za-z0-9+.-]{0,31}:\/\//.test(value)) return false;+ if (value.startsWith('./') || value.startsWith('~/') || value.startsWith('${') || value.startsWith('$(')) return false;+ if (value.startsWith('<REDACTED:') || DOTTED_IDENTIFIER_RE.test(value)) return false;+ return !(value.startsWith('/') && !LEGACY_ASSIGNMENT_VALUE_RE.test(value));+}+function compilePatterns(opts: ScanOpts): CompiledPattern[] {const out: CompiledPattern[] = CORE_PATTERNS.map((p) => ({name: p.name,// nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- p.source is a compile-time literal from CORE_PATTERNS (never caller input); every pattern uses bounded quantifiers, pinned by test/secret-scan-perf.test.ts- re: new RegExp(p.prebuilt ? p.source : `(^|[^A-Za-z0-9_])(${p.source})`, 'g'),+ re: new RegExp(p.prebuilt ? p.source : `(^|[^A-Za-z0-9_])(${p.source})`, p.flags ?? 'g'),...(p.precheck ? { precheck: p.precheck } : {}),+ ...(p.validate ? { validate: p.validate } : {}),}));if (opts.highEntropy) {- // Group layout matches the core shape: group 1 = boundary (empty here,- // the keyword anchor plays that role), group 2 = value. We wrap the- // keyword part into group 1 so span math stays uniform.- out.push({- name: 'high_entropy_assignment',- re: new RegExp(- `((?:^|[^A-Za-z0-9])(?:secret|token|passwd|password|passphrase|credential|api[_-]?key|apikey)[A-Za-z0-9_-]{0,64}["']?\\s*[:=]\\s*["']?)([A-Za-z0-9+/_=-]{12,4096})`,- 'gi',- ),- entropyGated: true,- });+ // Group layout matches the core shape: group 1 = the keyword anchor+ // through the `=`/`:` (and opening quote), group 2 = value.+ for (const source of [ASSIGNMENT_QUOTED_SOURCE, ASSIGNMENT_UNQUOTED_SOURCE]) {+ out.push({+ name: 'high_entropy_assignment',+ // 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(source, 'gi'),+ entropyGated: true,+ validate: assignmentValueIsSecretShaped,+ });+ }}return out;}@@ -469,21 +833,27 @@ interface RawHit extends LineSpan {abs: number;lineText: string;spans: LineSpans;+ /**+ * private_key_pem FORWARD claims only: the header-only value the pre-wave+ * scanner reported for the same key (its fingerprint was the allowlist key).+ */+ legacyValue?: string;}/**- * Whole-text PEM private-key pass. Runs over the FULL text (not per-line) so- * the base64 body between header and footer is part of the matched value and+ * Whole-text PEM private-key pass over pemClaims. Runs over the FULL text+ * (not per-line) so the base64 body is part of the claimed value and* therefore gets redacted, never left behind. `lineText` is set to the whole- * matched block so buildPreview renders the entire span as one- * `<REDACTED:private_key_pem>` token.+ * claim so buildPreview renders the entire span as one+ * `<REDACTED:private_key_pem>` token. A finding's line is the line of the+ * first claimed character (for a BACKWARD claim, its first body line).*- * The 1-based header line is counted INCREMENTALLY: the position of the NEXT- * `\n` is carried as state across hits (global exec yields them in ascending- * index order). Each `indexOf` resumes where the previous one stopped and a- * -1 (no newline left in the text) is sticky, so the newline search touches- * every character at most once and the pass is O(text) however the newlines- * are distributed. Two earlier forms were O(hits × text): recomputing+ * The 1-based line is counted INCREMENTALLY: the position of the NEXT `\n`+ * is carried as state across claims (they come in ascending order). Each+ * `indexOf` resumes where the previous one stopped and a -1 (no newline left+ * in the text) is sticky, so the newline search touches every character at+ * most once and the pass is O(text) however the newlines are distributed.+ * Two earlier forms were O(hits × text): recomputing* `text.slice(0, m.index).split('\n')` per hit, and a cursor that re-ran* `text.indexOf('\n', cursor)` per hit — when no `\n` follows the cursor that* call rescans to the end of the text and returns -1 once PER HIT (20000@@ -491,41 +861,51 @@ interface RawHit extends LineSpan {* ~30 s with a 23 MB tail, inside SCAN_MAX_FILE_BYTES). Pinned in* test/secret-scan-perf.test.ts.*/-function scanPemBlocks(text: string): RawHit[] {+function scanPemBlocks(text: string, claims: PemClaim[]): RawHit[] {const hits: RawHit[] = [];- PEM_BLOCK_RE.lastIndex = 0;let line = 1;let nextNl = text.indexOf('\n');- let m: RegExpExecArray | null;- while ((m = PEM_BLOCK_RE.exec(text)) !== null) {- const value = m[0];- if (value.length === 0) {- PEM_BLOCK_RE.lastIndex++; // zero-width safety- continue;- }- while (nextNl !== -1 && nextNl < m.index) {+ for (const c of claims) {+ while (nextNl !== -1 && nextNl < c.start) {line++;nextNl = text.indexOf('\n', nextNl + 1);}+ const value = text.slice(c.start, c.end);const span: LineSpan = { pattern: 'private_key_pem', value, start: 0 };- hits.push({ ...span, line, abs: m.index, lineText: value, spans: { all: [span] } });+ const hit: RawHit = { ...span, line, abs: c.start, lineText: value, spans: { all: [span] } };+ if (c.kind === 'forward' && c.end > c.headerEnd) hit.legacyValue = text.slice(c.start, c.headerEnd);+ hits.push(hit);}return hits;}+/** True when [start, end) lies entirely inside one claim (claims sorted, disjoint). */+function insideClaim(claims: PemClaim[], start: number, end: number): boolean {+ let lo = 0;+ let hi = claims.length;+ while (lo < hi) {+ const mid = (lo + hi) >> 1;+ if (claims[mid]!.end <= start) lo = mid + 1;+ else hi = mid;+ }+ const c = claims[lo];+ return c !== undefined && c.start <= start && end <= c.end;+}+function scanInternal(text: string, opts: ScanOpts): RawHit[] {const patterns = compilePatterns(opts);// PEM blocks first: their full-span value must be redacted before any// per-line replacement can touch the region (base64 bodies never match the// named patterns, so order is a belt-and-suspenders guarantee).- const hits: RawHit[] = scanPemBlocks(text);+ const pem = pemClaims(text);+ const hits: RawHit[] = scanPemBlocks(text, pem);const lines = text.split('\n');// No per-line length cap, deliberately: a secret on a 1 MB minified line// must still be found and redacted, so long lines are scanned in full.// What keeps that bounded is (a) every pattern doing constant work per// candidate occurrence — the shapes whose value class could otherwise run// to end-of-line and backtrack (db_url_credentials, jwt,- // high_entropy_assignment, and PEM_BLOCK_RE over the whole text) carry+ // high_entropy_assignment, and the PEM walks over the whole text) carry// bounded quantifiers, and jwt's boundary excludes `-` so a `-` run is// never a fresh start — and (b) each catch-all's `precheck`, a substring// test that skips its regex on lines without the anchor. The overlap check@@ -545,6 +925,9 @@ function scanInternal(text: string, opts: ScanOpts): RawHit[] {const lineStart = offset;offset += line.length + 1;if (line.length < 8) 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;const spans: LineSpans = { all: [] };// Claimed-character bitmap behind the first-wins dedupe: allocated on the// line's FIRST hit only (most lines have none), then O(value) to test and@@ -552,6 +935,10 @@ function scanInternal(text: string, opts: ScanOpts): RawHit[] {let taken: Uint8Array | null = null;const claim = (pattern: string, value: string, start: number): void => {taken!.fill(1, start, start + value.length);+ // A hit entirely inside a private-key claim (a vendor-shaped run in a+ // key body on a line the claim only partly covers) still takes its+ // characters for the first-wins dedupe but is not reported.+ if (pem.length > 0 && insideClaim(pem, lineStart + start, lineStart + start + value.length)) return;spans.all.push({ pattern, value, start });hits.push({ pattern, value, start, abs: lineStart + start, line: i + 1, lineText: line, spans });};@@ -569,6 +956,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)) continue;if (p.entropyGated && shannonEntropy(value) < HIGH_ENTROPY_MIN_BITS_PER_CHAR) continue;+ if (p.validate && !p.validate(value)) continue;if (!taken) {taken = new Uint8Array(line.length);} else if (anyTaken(taken, start, end)) {@@ -681,14 +1069,32 @@ function sha256Hex(value: string): string {return createHash('sha256').update(value).digest('hex');}+const PATTERN_SINCE: ReadonlyMap<string, string> = new Map([+ ...CORE_PATTERNS.flatMap((p): Array<[string, string]> => (p.since ? [[p.name, p.since]] : [])),+ ['private_key_pem', SECURITY_WAVE_SINCE],+]);++/** The gbrain version that added or last changed `pattern`'s rule, if tracked. */+export function patternSince(pattern: string): string | undefined {+ return PATTERN_SINCE.get(pattern);+}++function fingerprintOf(fullHex: string): string {+ return `sha256:${fullHex.slice(0, 16)}`;+}+/** `file` is stamped by scanFiles on the way out, not here. */function toFinding(hit: RawHit, fullHex: string): SecretFinding {- return {+ const finding: SecretFinding = {pattern: hit.pattern,line: hit.line,redactedPreview: buildPreview(hit),- fingerprint: `sha256:${fullHex.slice(0, 16)}`,+ fingerprint: fingerprintOf(fullHex),};+ const since = PATTERN_SINCE.get(hit.pattern);+ if (since) finding.since = since;+ if (hit.legacyValue !== undefined) finding.legacyFingerprint = fingerprintOf(sha256Hex(hit.legacyValue));+ return finding;}/**diff --git a/src/core/sources-ops.ts b/src/core/sources-ops.tsindex 609d095dd5..3a3bef0bd2 100644--- a/src/core/sources-ops.ts+++ b/src/core/sources-ops.ts@@ -41,6 +41,7 @@ import { managedPersistenceEnabled } from './persistence/ownership.ts';import { existsSync, mkdirSync, renameSync, rmSync, lstatSync, realpathSync } from 'fs';import { join, dirname, basename, resolve as resolvePath } from 'path';import { isPathContained, msysToNativePath } from './path-confine.ts';+import { mkdirPrivate } from './atomic-write.ts';import { randomBytes } from 'crypto';import type { BrainEngine } from './engine.ts';import {@@ -650,7 +651,7 @@ export async function addSource(// vault; config carries only the account POINTER (mirrors gh_token_env// storing an env NAME — check:source-config-leak stays trivially green).const finalPath = opts.google.dir;- mkdirSync(finalPath, { recursive: true });+ mkdirPrivate(finalPath);const config: Record<string, unknown> = {kind: 'google',g_account: opts.google.account,diff --git a/src/core/transcripts.ts b/src/core/transcripts.tsindex fb0f2a8ad4..61dacaa155 100644--- a/src/core/transcripts.ts+++ b/src/core/transcripts.ts@@ -17,6 +17,7 @@ import { readFileSync, readdirSync, statSync } from 'node:fs';import { join, basename } from 'node:path';import type { BrainEngine } from './engine.ts';import { isDreamOutput } from './cycle/transcript-discovery.ts';+import { redactFindings } from './secret-scan.ts';export interface RecentTranscriptOpts {/** Window in days. Default 7. */@@ -114,12 +115,14 @@ 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;out.push({path: name,date: dateMatch ? dateMatch[1] : null,mtime: new Date(c.mtimeMs).toISOString(),length: c.size,- summary: summary ? buildSummary(raw) : raw.slice(0, FULL_READ_CAP),+ summary: summary ? buildSummary(text) : text.slice(0, FULL_READ_CAP),});}return out;diff --git a/src/core/verbs.ts b/src/core/verbs.tsindex 95d25dadfb..7f57864d6f 100644--- a/src/core/verbs.ts+++ b/src/core/verbs.ts@@ -60,6 +60,7 @@ const PROVENANCE_MAX = 500;const remember: Operation = {name: 'remember',+ outputRedaction: 'no_stored_text',description:'MEMORY VERB (v1): save one fact to durable agent memory — the protocol write verb. ' +'provenance is REQUIRED (free text, e.g. "conversation 2026-06-12", "user said in chat", "import: notes.md"). ' +@@ -170,6 +171,7 @@ const remember: Operation = {const entity: Operation = {name: 'entity',+ outputRedaction: 'retrieval',description:'MEMORY VERB (v1): inspect ONE known person/company/project card — zero LLM calls, sub-100ms. ' +'Resolution: alias > exact title > slug-suffix; ties break on most-recently-touched. ' +@@ -224,6 +226,7 @@ const SYNTHESIS_FAILURE_CODES: Record<string, string> = {const synthesize: Operation = {name: 'synthesize',+ outputRedaction: 'retrieval',description:'[EXPENSIVE / SLOW — makes LLM calls, seconds-to-minutes latency, costs money] ' +'MEMORY VERB (v1): answer a broad question using cross-page LLM reasoning with citations and gap analysis. ' +@@ -346,6 +349,7 @@ const synthesize: Operation = {const forget: Operation = {name: 'forget',+ outputRedaction: 'no_stored_text',description:'MEMORY VERB (v1): expire a remembered fact by id — the protocol delete verb. ' +'`id` is the opaque string id returned by remember and recall (facts[].fact_id) — never a page slug. ' +diff --git a/src/core/workspace-push.ts b/src/core/workspace-push.tsindex 1e001f1bf8..c1696c89e4 100644--- a/src/core/workspace-push.ts+++ b/src/core/workspace-push.ts@@ -55,7 +55,7 @@ import { OperationError } from './ops/contract.ts';import {existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync,} from 'fs';-import { dirname, join } from 'path';+import { dirname, join, resolve } from 'path';import { createHash, randomBytes } from 'crypto';import { execFileSync } from 'child_process';import { GIT_ENV, GIT_ENV_AUTH, GIT_SSRF_SUBCOMMAND_FLAGS, detectDefaultBranch, divergenceSafePull } from './git-remote.ts';@@ -70,10 +70,11 @@ import {} from './repo-visibility.ts';import { isProcessAlive } from './pglite-lock.ts';import {- loadWorkspaceAllowlist, matchesGlob, pathAllowlisted, scanText,+ ALLOWLIST_FINGERPRINT_MIN_HEX, loadWorkspaceAllowlist, matchesGlob, pathAllowlisted, scanText,SCAN_ALLOW_FILENAME, SCAN_MAX_FILE_BYTES,type SecretFinding,} from './secret-scan.ts';+import { shellQuote } from './mcp-registration.ts';// ── Types ───────────────────────────────────────────────────────────────────@@ -103,11 +104,45 @@ export interface WorkspacePushResult {denyMatches?: string[];/** Untracked deny-glob matches excluded from staging (kept on disk). */excludedUntracked?: string[];- findings?: SecretFinding[];+ findings?: PushSecretFinding[];/** Staged paths the secret scan could not read (fail-closed block reason). */unscannable?: string[];}+/** Troubleshooting section for push refusals (DX-8 in docs/guides/write-refusals.md). */+export const SECRET_SCAN_REFUSAL_DOCS =+ 'https://github.com/garrytan/gbrain/blob/master/docs/guides/write-refusals.md#secret-scan-refusals-and-redaction';++/**+ * An allowlist line that suppressed a private key's header-only value before+ * the scanner claimed the key body too. The line no longer matches; the+ * finding's current fingerprint is the reviewed replacement.+ */+export interface StaleAllowlistEntry {+ entry: string;+ replacement: string;+}++/**+ * A blocking finding plus everything needed to act on it from any working+ * directory (DX-3/ENG-11). The guidance rides here, not in `reason`, because+ * `reason` is clipped to 140 chars by `sanitizePushReason` on every status+ * surface.+ */+export interface PushSecretFinding extends SecretFinding {+ file: string;+ /** The gbrain version that added or changed the rule, when the scanner reports one. */+ since?: string;+ /** Absolute path of the `.gbrain-scan-allow` file the gate reads. */+ allowlistPath: string;+ /** Shell command appending this finding's fingerprint to the allowlist. */+ allowCommand: string;+ /** Shell command re-running this push, runnable from any directory. */+ retryCommand: string;+ docs: string;+ staleAllowlistEntry?: StaleAllowlistEntry;+}+export interface WorkspacePushOpts {/** Any directory inside the repo; the root is resolved via rev-parse [CX2-3]. */dir: string;@@ -472,6 +507,107 @@ export function sanitizePushReason(reason: string | undefined): string {return reason.replace(/[^\x20-\x7E]/g, ' ').replace(/[`$\\]/g, "'").slice(0, 140);}+const PUSH_REASON_MAX_CHARS = 140;++/**+ * The `blocked_secrets` reason: a summary that `sanitizePushReason` passes+ * through unclipped, so hook and doctor surfaces show the count, the first+ * location and where the fix steps are. The location keeps its tail (file+ * name and line) when the budget is short.+ */+export function blockedSecretsReason(findings: readonly PushSecretFinding[]): string {+ const first = findings[0]!;+ const head = `${findings.length} secret finding(s), first `;+ const tail = ` [${first.pattern}]; nothing committed. Run gbrain sources push for fix steps`;+ const budget = PUSH_REASON_MAX_CHARS - head.length - tail.length;+ const loc = `${first.file}:${first.line}`;+ const shown = loc.length <= budget ? loc : `...${loc.slice(-Math.max(1, budget - 3))}`;+ return `${head}${shown}${tail}`.slice(0, PUSH_REASON_MAX_CHARS);+}++/**+ * DX-4: before the scanner learned truncated key bodies, a private key with+ * no END fence in view was claimed header-only, so an allowlist line could+ * hold the fingerprint of the bare BEGIN header. The scanner reports that+ * pre-wave fingerprint as `legacyFingerprint`; return the allowlist entry it+ * matches, if any.+ */+function staleHeaderOnlyEntry(legacyFingerprint: string | undefined, allowlist: readonly string[]): string | undefined {+ if (!legacyFingerprint) return undefined;+ const legacyHex = legacyFingerprint.slice('sha256:'.length);+ return allowlist.find((entry) => {+ if (!entry.startsWith('sha256:')) return false;+ const prefix = entry.slice('sha256:'.length).toLowerCase();+ return prefix.length >= ALLOWLIST_FINGERPRINT_MIN_HEX && prefix.startsWith(legacyHex);+ });+}++/** The exact `gbrain sources push` invocation that re-runs this push from any directory. */+function pushRetryCommand(opts: WorkspacePushOpts): string {+ return [+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- display only: the printed retry command names the caller's own workspace dir; nothing is read or written here.+ 'gbrain sources push --path', shellQuote(resolve(opts.dir)),+ ...(opts.branch ? ['--branch', shellQuote(opts.branch)] : []),+ ...(opts.allowUnverifiedRemote ? ['--allow-unverified-remote'] : []),+ ].join(' ');+}++/** Attach the DX-3 refusal guidance to one file's findings; no value ever reaches the output. */+export function buildPushFindings(input: {+ file: string;+ findings: readonly SecretFinding[];+ allowlist: readonly string[];+ allowlistPath: string;+ retryCommand: string;+}): PushSecretFinding[] {+ return input.findings.map(({ legacyFingerprint, ...f }) => {+ const out: PushSecretFinding = {+ ...f,+ file: input.file,+ allowlistPath: input.allowlistPath,+ allowCommand: `printf '\\n%s\\n' ${f.fingerprint} >> ${shellQuote(input.allowlistPath)}`,+ retryCommand: input.retryCommand,+ docs: SECRET_SCAN_REFUSAL_DOCS,+ };+ const entry = staleHeaderOnlyEntry(legacyFingerprint, input.allowlist);+ if (entry) out.staleAllowlistEntry = { entry, replacement: f.fingerprint };+ return out;+ });+}++/**+ * Human rendering of a `blocked_secrets` result for `gbrain sources push`.+ * Every line comes from the structured findings, so the CLI text and the+ * `--json` output carry the same commands.+ */+export function formatBlockedSecrets(findings: readonly PushSecretFinding[]): string[] {+ const version = (since: string) => `gbrain v${since.replace(/^v/, '')}`;+ const lines = ['PUSH BLOCKED — secret scan findings (nothing committed):'];+ for (const f of findings) {+ lines.push(` ${f.file}:${f.line} [${f.pattern}] ${f.redactedPreview}`);+ lines.push(` fingerprint: ${f.fingerprint}`);+ if (f.since) lines.push(` rule [${f.pattern}] blocks pushes since ${version(f.since)}`);+ if (f.staleAllowlistEntry) {+ const { entry, replacement } = f.staleAllowlistEntry;+ lines.push(+ ` stale allowlist entry: ${entry} matched only this key's BEGIN header ` ++ `${f.since ? `before ${version(f.since)}` : 'before this version'}; the fingerprint now covers the key body.`,+ );+ lines.push(` if the key is a reviewed false positive, replace that line in ${shellQuote(f.allowlistPath)} with: ${replacement}`);+ }+ lines.push(` allow this finding: ${f.allowCommand}`);+ }+ const first = findings[0];+ if (!first) return lines;+ lines.push(+ 'Remove a real credential from the file (and rotate it) first. Allowlist only a reviewed false positive',+ `with the "allow this finding" command above (it appends to ${shellQuote(first.allowlistPath)}), then retry:`,+ ` ${first.retryCommand}`,+ `Docs: ${first.docs}`,+ );+ return lines;+}+export function summarizePushStatuses(entries: PushStatusEntry[]): {failing: PushStatusEntry[];stalestTs: number | null;@@ -659,7 +795,10 @@ export async function workspacePush(opts: WorkspacePushOpts): Promise<WorkspacePstagedDeletions = new Set();}const allowlist = loadWorkspaceAllowlist(root);- const findings: SecretFinding[] = [];+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- fixed filename under the resolved workspace root (same path loadWorkspaceAllowlist reads); used only in printed guidance.+ const allowlistPath = join(root, SCAN_ALLOW_FILENAME);+ const retryCommand = pushRetryCommand(opts);+ const findings: PushSecretFinding[] = [];const unscannable: string[] = [];for (const rel of stagedForScan) {if (pathAllowlisted(rel, allowlist)) continue; // user-declared safe path@@ -683,22 +822,18 @@ export async function workspacePush(opts: WorkspacePushOpts): Promise<WorkspaceP// 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.- for (const f of scanText(blob.toString('utf-8'), { allowlist })) {- findings.push({ ...f, file: rel });+ 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);}}if (findings.length > 0) {// Restore the index to HEAD (disk files untouched) — a blocked push// leaves nothing staged and nothing committed, same as before.tryGit(root, ['reset', '-q']);- const summary = findings- .slice(0, 10)- .map((f) => `${f.file}:${f.line} [${f.pattern}]`)- .join(', ');- const reason =- `secret scan found ${findings.length} finding(s): ${summary}` +- `${findings.length > 10 ? ', …' : ''} — nothing committed. ` +- `Add a fingerprint or glob line to ${SCAN_ALLOW_FILENAME} to override a false positive.`;+ const reason = blockedSecretsReason(findings);log(`PUSH BLOCKED: ${reason}`);return finish({ok: false, status: 'blocked_secrets', repoRoot: root, branch, findings, reason,diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex ff7444e13b..b5405dc60d 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.60.30.0 -->+<!-- gbrain-template-stamp: 0.60.31.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/apply-migrations.test.ts b/test/apply-migrations.test.tsindex 2744d66d5f..eea8106c8e 100644--- a/test/apply-migrations.test.ts+++ b/test/apply-migrations.test.ts@@ -108,7 +108,7 @@ describe('buildPlan — diff against completed + installed VERSION', () => {// autopilot cooperative, v0.16.0 = subagent runtime, v0.18.0 = multi-// source brains, v0.18.1 = RLS hardening, v0.21.0 = Cathedral II// (renumbered from v0.20.0 after master shipped v0.20.x in parallel).- expect(plan.skippedFuture.map(m => m.version)).toEqual(['0.12.0', '0.12.2', '0.13.0', '0.13.1', '0.14.0', '0.16.0', '0.18.0', '0.18.1', '0.21.0', '0.22.4', '0.28.0', '0.29.1', '0.31.0', '0.32.2', '0.43.0', '0.46.3', '0.53.0']);+ expect(plan.skippedFuture.map(m => m.version)).toEqual(['0.12.0', '0.12.2', '0.13.0', '0.13.1', '0.14.0', '0.16.0', '0.18.0', '0.18.1', '0.21.0', '0.22.4', '0.28.0', '0.29.1', '0.31.0', '0.32.2', '0.43.0', '0.46.3', '0.53.0', '0.60.31']);});test('already applied → v0.11.0 lands in `applied` bucket, not pending', () => {@@ -148,7 +148,7 @@ describe('buildPlan — diff against completed + installed VERSION', () => {// v0.22.4, v0.28.0, v0.29.1, v0.31.0 were added later; installed=0.12.0// means they belong in skippedFuture, not pending. v0.11.0 and v0.12.0// stay pending despite being ≤ installed — that is the H9 invariant.- expect(plan.skippedFuture.map(m => m.version)).toEqual(['0.12.2', '0.13.0', '0.13.1', '0.14.0', '0.16.0', '0.18.0', '0.18.1', '0.21.0', '0.22.4', '0.28.0', '0.29.1', '0.31.0', '0.32.2', '0.43.0', '0.46.3', '0.53.0']);+ expect(plan.skippedFuture.map(m => m.version)).toEqual(['0.12.2', '0.13.0', '0.13.1', '0.14.0', '0.16.0', '0.18.0', '0.18.1', '0.21.0', '0.22.4', '0.28.0', '0.29.1', '0.31.0', '0.32.2', '0.43.0', '0.46.3', '0.53.0', '0.60.31']);});test('--migration filter narrows to one version', () => {diff --git a/test/bootstrap-repo.test.ts b/test/bootstrap-repo.test.tsindex e9fadd6c22..bfe7e06ddc 100644--- a/test/bootstrap-repo.test.ts+++ b/test/bootstrap-repo.test.ts@@ -209,6 +209,9 @@ describe('createPrivateRepo', () => {const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home }));expect(err.code).toBe('SECRET_SCAN_BLOCKED');expect(err.message).not.toContain('sk-A1b2C3d4'); // value never surfaces+ expect(err.message).toMatch(/leak\.md:1 \[openai\] sha256:[0-9a-f]{16}/);+ expect(err.message).toContain(`appending its fingerprint to ${join(ws, '.gbrain-scan-allow')}`);+ expect(err.message).toContain('write-refusals.md#secret-scan-refusals-and-redaction');expect(calls.some((c) => c.join(' ').includes('commit -m'))).toBe(false);expect(calls.some((c) => c.join(' ').includes('push -u origin'))).toBe(false);});diff --git a/test/bootstrap-verify.serial.test.ts b/test/bootstrap-verify.serial.test.tsindex cb90a7e6ca..7fd1c79f7c 100644--- a/test/bootstrap-verify.serial.test.ts+++ b/test/bootstrap-verify.serial.test.ts@@ -275,6 +275,8 @@ describe('verifyWorkspace — keyless pass', () => {const scan = check(res.checks, 'secret_scan')[0];expect(scan.ok).toBe(false);expect(scan.detail).toContain('openai');+ expect(scan.detail).toContain(`allowlist only a reviewed false positive by appending its fingerprint to ${join(ws, '.gbrain-scan-allow')}`);+ expect(scan.detail).toContain('write-refusals.md#secret-scan-refusals-and-redaction');// Redaction discipline: the finding detail NEVER carries the secret value.expect(scan.detail).not.toContain('sk-AAAAAAAAAAAAAAAAAAAAAAAA');diff --git a/test/brain-resolver.test.ts b/test/brain-resolver.test.tsindex aeea7847fc..091be86e26 100644--- a/test/brain-resolver.test.ts+++ b/test/brain-resolver.test.ts@@ -6,7 +6,7 @@ import { resolveBrainId, __testing } from '../src/core/brain-resolver.ts';import { HOST_BRAIN_ID, type MountEntry } from '../src/core/brain-registry.ts';const toCleanup: string[] = [];-const originalEnv = { ...process.env };+const originalBrainId = process.env.GBRAIN_BRAIN_ID;function mktmp(prefix = 'brain-resolver-'): string {const dir = mkdtempSync(join(tmpdir(), prefix));@@ -20,7 +20,8 @@ beforeEach(() => {});afterEach(() => {- process.env = { ...originalEnv };+ if (originalBrainId === undefined) delete process.env.GBRAIN_BRAIN_ID;+ else process.env.GBRAIN_BRAIN_ID = originalBrainId;while (toCleanup.length > 0) {const p = toCleanup.pop();if (!p) continue;diff --git a/test/check-pg-url-redaction.test.ts b/test/check-pg-url-redaction.test.tsnew file mode 100644index 0000000000..4b71b1e5f4--- /dev/null+++ b/test/check-pg-url-redaction.test.ts@@ -0,0 +1,132 @@+/**+ * scripts/check-pg-url-redaction.sh CI gate self-test (widened to every+ * db_url_credentials scheme, per TODOS.md: "the guard greps src/ for+ * postgres(ql) URL literals with userinfo only; comments could still spell a+ * mysql/mongodb/redis URL with userinfo").+ *+ * Same positive/negative structure as test/check-system-of-record.test.ts:+ * - Positive: the real repo's src/ tree must stay clean (exit 0).+ * - Negative: a synthetic mini-repo with a credential-bearing URL of a+ * newly-covered scheme (mysql / mongodb+srv) must trip the gate+ * (exit 1, names the file) — this is the regression guard that would+ * have failed before the widening (only postgres(ql) tripped it).+ * - The already-redacted `***@` form of a new scheme must still pass,+ * confirming the widened pattern didn't turn into a blanket ban on+ * the scheme name itself.+ *+ * Fixture URLs are assembled at runtime from parts so this file never spells+ * a credential-bearing URL literal (gitleaks and pre-push scanners stay quiet).+ */+import { describe, test, expect } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync, cpSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++const SCRIPT_PATH = join(import.meta.dir, '..', 'scripts', 'check-pg-url-redaction.sh');++function dbUrl(scheme: string, userinfo: string, hostPath: string): string {+ return [scheme, ':/', '/', userinfo, '@', hostPath].join('');+}++function credentials(user: string): string {+ return [user, 'GSTACK_EXAMPLE_NONCE'].join(':');+}++function runGate(scriptPath: string): { code: number; stdout: string; stderr: string } {+ const r = spawnSync('bash', [scriptPath], { encoding: 'utf-8', timeout: 30_000 });+ return { code: r.status ?? -1, stdout: r.stdout ?? '', stderr: r.stderr ?? '' };+}++describe('check-pg-url-redaction.sh — positive case (real repo)', () => {+ test('exits 0 on the current repo state', () => {+ const r = runGate(SCRIPT_PATH);+ expect(r.code).toBe(0);+ });+});++describe('check-pg-url-redaction.sh — negative case (newly-covered schemes)', () => {+ function withFakeRepo(fn: (fakeRepo: string, fakeScript: string) => void): void {+ const fakeRepo = mkdtempSync(join(tmpdir(), 'pg-url-redaction-gate-test-'));+ try {+ const fakeScripts = join(fakeRepo, 'scripts');+ mkdirSync(fakeScripts, { recursive: true });+ const fakeScript = join(fakeScripts, 'check-pg-url-redaction.sh');+ cpSync(SCRIPT_PATH, fakeScript);+ mkdirSync(join(fakeRepo, 'src'), { recursive: true });+ fn(fakeRepo, fakeScript);+ } finally {+ rmSync(fakeRepo, { recursive: true, force: true });+ }+ }++ test('a bare mysql:// URL with userinfo trips the gate (pre-widening this scheme was invisible to it)', () => {+ withFakeRepo((fakeRepo, fakeScript) => {+ writeFileSync(+ join(fakeRepo, 'src', 'violator.ts'),+ `console.log('connecting: ${dbUrl('mysql', credentials('admin'), 'db.internal:3306/app')}');\n`,+ 'utf-8',+ );+ const r = runGate(fakeScript);+ expect(r.code).toBe(1);+ expect(r.stdout).toContain('violator.ts');+ expect(r.stdout).toContain('unredacted database URL');+ });+ });++ test('a bare mongodb+srv:// URL with userinfo also trips the gate', () => {+ withFakeRepo((fakeRepo, fakeScript) => {+ writeFileSync(+ join(fakeRepo, 'src', 'violator2.ts'),+ `console.error(\`failed: ${dbUrl('mongodb+srv', credentials('svc'), 'cluster0.example.net/app')}\`);\n`,+ 'utf-8',+ );+ const r = runGate(fakeScript);+ expect(r.code).toBe(1);+ expect(r.stdout).toContain('violator2.ts');+ });+ });++ test('an already-redacted `***@` mysql URL does NOT trip the gate', () => {+ withFakeRepo((fakeRepo, fakeScript) => {+ writeFileSync(+ join(fakeRepo, 'src', 'clean.ts'),+ `console.log('connecting: ${dbUrl('mysql', '***', 'db.internal:3306/app')}');\n`,+ 'utf-8',+ );+ const r = runGate(fakeScript);+ expect(r.code).toBe(0);+ });+ });++ test('a bare postgresql:// URL still trips the gate (pre-existing coverage unaffected)', () => {+ withFakeRepo((fakeRepo, fakeScript) => {+ writeFileSync(+ join(fakeRepo, 'src', 'violator3.ts'),+ `console.log('connecting: ${dbUrl('postgresql', credentials('admin'), 'db.internal:5432/app')}');\n`,+ 'utf-8',+ );+ const r = runGate(fakeScript);+ expect(r.code).toBe(1);+ expect(r.stdout).toContain('violator3.ts');+ });+ });++ // The remaining three db_url_credentials schemes not covered by the+ // dedicated tests above — each gets its own fake source file so a single+ // failure names exactly which scheme's alternation broke.+ for (const scheme of ['redis', 'rediss', 'amqp', 'mssql']) {+ test(`a bare ${scheme}:// URL with userinfo trips the gate`, () => {+ withFakeRepo((fakeRepo, fakeScript) => {+ writeFileSync(+ join(fakeRepo, 'src', `violator-${scheme}.ts`),+ `console.log('connecting: ${dbUrl(scheme, credentials('admin'), 'db.internal/app')}');\n`,+ 'utf-8',+ );+ const r = runGate(fakeScript);+ expect(r.code).toBe(1);+ expect(r.stdout).toContain(`violator-${scheme}.ts`);+ });+ });+ }+});diff --git a/test/context-engine-checkpoint.serial.test.ts b/test/context-engine-checkpoint.serial.test.tsindex 2f9b12bec6..f06bdf5730 100644--- a/test/context-engine-checkpoint.serial.test.ts+++ b/test/context-engine-checkpoint.serial.test.ts@@ -486,6 +486,26 @@ describe('memorable receipts from compact() (openclaw lane)', () => {expect(body).toContain('record --session oc-mem');});+ it('MR4: a high-entropy hit refuses the relay with one content-free heartbeat line; the checkpoint is unaffected (DX-7)', async () => {+ tmpDir = makeWorkspace();+ const marker = await optIn();+ const value = require('node:crypto').randomBytes(18).toString('base64url').replace(/[-_]/g, 'q') + '7';+ const sessionFile = join(home!, 'oc-mem.jsonl');+ wf(sessionFile, [sessionLine, msg(`deploy with password=${value} later`, 'exec')].join('\n') + '\n');+ const engine = createGBrainContextEngine({ workspaceDir: tmpDir });+ const result = await engine.compact({ sessionId: 'oc-mem', sessionFile });+ expect(result.ok).toBe(true);+ expect(await receipts()).toEqual([]);+ expect(existsSync(marker)).toBe(false);+ const { heartbeatPath } = await import('../src/core/context/hook-heartbeat.ts');+ const raw = readFileSync(await heartbeatPath(), 'utf8');+ expect(raw).not.toContain(value);+ const line = raw.trim().split('\n').map((l) => JSON.parse(l)).find((e) => e.event === 'relay');+ expect(line).toMatchObject({ outcome: 'degraded', reason: 'secret_scan_refused', pattern: 'high_entropy_assignment' });+ expect(line.fingerprint).toMatch(/^sha256:[0-9a-f]{16}$/);+ expect(line.hint).toContain('next window');+ });+it('MR3: enabled flag WITHOUT the disclosure stamp (out-of-band write) ⇒ no receipt, no spawn', async () => {tmpDir = makeWorkspace();await optIn();diff --git a/test/credential-projection.test.ts b/test/credential-projection.test.tsnew file mode 100644index 0000000000..3af2db75c4--- /dev/null+++ b/test/credential-projection.test.ts@@ -0,0 +1,164 @@+/**+ * Credential-safe retrieval projection (security wave ENG-1 / CEO-19).+ *+ * Protects: no fragment of a stored private key reaches chunks (and so the+ * embedding provider) or any retrieval op output, including chunks that+ * contain neither key fence, and evidence delivered in window/section/page+ * units is cut from the same projected text so anchors still locate.+ * Regression it catches: a chunker or evidence path that slices the raw body+ * before the private-key pass (master split a 4096-bit key into chunks whose+ * middle part carried 42 body lines and no fence, and the output redactor+ * could not recognise them). Existing coverage scans only finished output,+ * per chunk. No seams: real chunkers, real ops on PGLite.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { generateKeyPairSync } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations, type OperationContext } from '../src/core/operations.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { credentialSafeProjection, PRIVATE_KEY_PROJECTION_TOKEN } from '../src/core/credential-projection.ts';+import { chunkText } from '../src/core/chunkers/recursive.ts';+import { prepareMarkdownChunks } from '../src/core/markdown-chunks.ts';+import { prepareCodeChunks } from '../src/core/code-chunks.ts';+import { pageEvidenceText } from '../src/core/search/evidence-delivery.ts';+import type { SearchResult } from '../src/core/types.ts';++function ephemeralKey(bits = 4096): string {+ return generateKeyPairSync('rsa', {+ modulusLength: bits,+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },+ publicKeyEncoding: { type: 'spki', format: 'pem' },+ }).privateKey;+}++const KEY = ephemeralKey();+const KEY_LINES = KEY.split('\n').filter(line => /^[A-Za-z0-9+/=]{16,}$/.test(line));++/** 24-char windows of every body line: any one of them in output is a leaked fragment. */+const FRAGMENTS = KEY_LINES.flatMap(line => {+ const out: string[] = [];+ for (let i = 0; i + 24 <= line.length; i += 8) out.push(line.slice(i, i + 24));+ return out;+});++function leakedFragments(payload: unknown): string[] {+ const text = typeof payload === 'string' ? payload : JSON.stringify(payload);+ return FRAGMENTS.filter(fragment => text.includes(fragment));+}++const words = (n: number, tag: string) => Array.from({ length: n }, (_, i) => `${tag}${i} word`).join(' ');++/** Prose around the key so the default chunker splits through the key body. */+const PAGE_BODY = `## Deploy notes\n\n${words(140, 'alpha')}\n\nThe deploy service key:\n\n${KEY}\n## Rotation\n\n${words(140, 'omega')}\n`;++describe('credentialSafeProjection', () => {+ test('replaces the key with one token, keeps every line offset, and is idempotent', () => {+ const projected = credentialSafeProjection(PAGE_BODY);+ expect(leakedFragments(projected)).toEqual([]);+ expect(projected).toContain(PRIVATE_KEY_PROJECTION_TOKEN);+ expect(projected.includes('PRIVATE KEY-----')).toBe(false);+ expect(projected.split('\n').length).toBe(PAGE_BODY.split('\n').length);+ const original = PAGE_BODY.split('\n');+ const after = projected.split('\n');+ const rotationLine = original.indexOf('## Rotation');+ expect(after[rotationLine]).toBe('## Rotation');+ expect(credentialSafeProjection(projected)).toBe(projected);+ });++ test('a key cut off before its END fence is still replaced', () => {+ const truncated = `Notes before.\n${KEY.split('\n').slice(0, 12).join('\n')}`;+ const projected = credentialSafeProjection(truncated);+ expect(leakedFragments(projected)).toEqual([]);+ expect(projected.split('\n').length).toBe(truncated.split('\n').length);+ });++ test('text without a key marker is returned unchanged', () => {+ const plain = `${words(40, 'plain')}\n\nNo key material here.`;+ expect(credentialSafeProjection(plain)).toBe(plain);+ });+});++describe('chunkers cut from the projection', () => {+ test('markdown chunker at the default and a 512-token budget', () => {+ for (const opts of [undefined, { maxTokens: 512 }]) {+ const chunks = chunkText(PAGE_BODY, opts);+ expect(chunks.length).toBeGreaterThan(1);+ expect(leakedFragments(chunks.map(c => c.text))).toEqual([]);+ }+ });++ test('a key inside a recognized fenced code block', async () => {+ const body = `## Config\n\n${words(30, 'cfg')}\n\n\`\`\`yaml\nservice:\n name: deploy\n key: |\n${KEY.split('\n').map(l => ` ${l}`).join('\n')}\n\`\`\`\n\n${words(30, 'tail')}\n`;+ const chunks = await prepareMarkdownChunks({ compiled_truth: body, timeline: '' });+ expect(chunks.some(c => c.chunk_source === 'fenced_code')).toBe(true);+ expect(leakedFragments(chunks.map(c => c.chunk_text))).toEqual([]);+ });++ test('code chunker keeps symbol line numbers after the key', async () => {+ const source = `export const DEPLOY_KEY = \`\n${KEY}\`;\n\nexport function rotateDeployKey(input: number): number {\n const next = input + 1;\n return next * 2;\n}\n`;+ const prepared = await prepareCodeChunks({ compiled_truth: source }, 'src/deploy-keys.ts');+ expect(leakedFragments(prepared.chunks.map(c => c.chunk_text))).toEqual([]);+ const fn = prepared.chunks.find(c => c.symbol_name === 'rotateDeployKey');+ expect(fn?.start_line).toBe(source.split('\n').findIndex(l => l.startsWith('export function rotateDeployKey')) + 1);+ });++ test('evidence page text is the same projection', () => {+ const { text } = pageEvidenceText({ compiled_truth: PAGE_BODY, timeline: '' }, false);+ expect(leakedFragments(text)).toEqual([]);+ expect(text).toBe(credentialSafeProjection(PAGE_BODY));+ });+});++describe('retrieval ops over a stored key (PGLite)', () => {+ let engine: PGLiteEngine;+ const op = (name: string) => operations.find(o => o.name === name)!;+ const meta: Array<{ key: string; value: unknown }> = [];+ const ctxOf = (remote: boolean): OperationContext => ({+ engine: engine as never, config: {} as never, logger: console as never, dryRun: false, remote, sourceId: 'default',+ emitResponseMeta: (key: string, value: unknown) => { meta.push({ key, value }); },+ } as OperationContext);+ // A token from the middle of the key body, so ranking reaches chunks that hold neither fence.+ const bodyToken = KEY_LINES[Math.floor(KEY_LINES.length / 2)].slice(0, 40).replace(/[+/=]/g, ' ').trim().split(' ')[0];++ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.setConfig('search.mcp_keyword_only', 'true');+ const imported = await importFromContent(engine, 'notes/deploy-runbook', `---\ntitle: Deploy runbook\ntype: note\n---\n\n${PAGE_BODY}`, { noEmbed: true });+ expect(imported.status).toBe('imported');+ }, 120_000);++ afterAll(async () => {+ await engine.disconnect();+ });++ test('stored chunks hold no fragment', async () => {+ const chunks = await engine.getChunks('notes/deploy-runbook', { sourceId: 'default', includeUnsealed: true });+ expect(chunks.length).toBeGreaterThan(1);+ expect(leakedFragments(chunks.map(c => c.chunk_text))).toEqual([]);+ });++ for (const remote of [false, true]) {+ test(`search, query and recall return no fragment (remote=${remote})`, async () => {+ for (const query of ['alpha3 deploy', 'omega7 rotation', bodyToken]) {+ const outputs = [+ await op('search').handler(ctxOf(remote), { query }),+ await op('query').handler(ctxOf(remote), { query, expand: false }),+ await op('recall').handler(ctxOf(remote), { query }),+ ];+ expect(leakedFragments(outputs), `query ${query}`).toEqual([]);+ }+ });++ test(`evidence delivery in every unit with a tight budget (remote=${remote})`, async () => {+ for (const unit of ['window', 'section', 'page'] as const) {+ for (const query of ['alpha3 deploy', 'omega7 rotation', bodyToken]) {+ const rows = await op('search').handler(ctxOf(remote), { query, return_unit: unit, return_window: 1, token_budget: 400 }) as Array<SearchResult & { delivered?: { unit: string; fallback_reason?: string } }>;+ expect(leakedFragments(rows), `${unit} ${query}`).toEqual([]);+ for (const row of rows) expect(row.delivered?.fallback_reason, `${unit} ${query}`).not.toBe('anchor_not_located');+ }+ }+ });+ }+});diff --git a/test/e2e/credential-projection-repair.test.ts b/test/e2e/credential-projection-repair.test.tsnew file mode 100644index 0000000000..23aaf50d4c--- /dev/null+++ b/test/e2e/credential-projection-repair.test.ts@@ -0,0 +1,177 @@+/**+ * Existing-brain repair for the credential-safe projection (security wave+ * ENG-2 / DX-9), on PGLite and (with DATABASE_URL) Postgres.+ *+ * Protects: chunks stored before the projection, including a middle chunk that+ * holds private-key body lines and no fence, never reach a local or remote+ * search/query/recall/evidence caller once the upgrade's schema migration has+ * run: not before the re-chunk completes, not after an interrupted re-chunk,+ * not after it. The re-chunk runs with no provider calls, leaves pages without+ * a key untouched, and doctor reports what is still pending. The chunker and+ * safe-fence versions stay pinned, so no brain-wide re-chunk is triggered.+ * Regression it catches: a global fence bump, a pending set that a retrieval+ * path ignores, or a repair that re-embeds without consent.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { generateKeyPairSync } from 'node:crypto';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { ChunkInput, SearchResult } from '../../src/core/types.ts';+import { operations, type OperationContext } from '../../src/core/operations.ts';+import { runMigrations } from '../../src/core/migrate.ts';+import { MARKDOWN_CHUNKER_VERSION } from '../../src/core/chunkers/recursive.ts';+import { SAFE_FENCE_CHUNKER_VERSION } from '../../src/core/search/safe-chunks.ts';+import { resealSafeChunks } from '../../src/core/page-state/projections.ts';+import { hydrateChunks } from '../../src/core/search/two-pass.ts';+import { credentialProjectionPendingCheck } from '../../src/commands/doctor/checks/credential-projection.ts';+import { v0_60_31, __setTestEngineOverride } from '../../src/commands/migrations/v0_60_31.ts';+import * as gateway from '../../src/core/ai/gateway.ts';+import { LEGACY_EMBEDDING_CONFIG } from '../helpers/legacy-embedding-config.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';+import { installFixtureChunks } from '../helpers/page-projection.ts';+import { getFtsLanguage } from '../../src/core/fts-language.ts';+import { readContentChunksEmbeddingDim } from '../../src/core/embedding-dim-check.ts';++const SOURCE = 'credential-reseal-fixture';++const KEY = generateKeyPairSync('rsa', {+ modulusLength: 2048,+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },+ publicKeyEncoding: { type: 'spki', format: 'pem' },+}).privateKey;+const KEY_LINES = KEY.split('\n').filter(line => /^[A-Za-z0-9+/=]{16,}$/.test(line));+const FRAGMENTS = KEY_LINES.flatMap(line => {+ const out: string[] = [];+ for (let i = 0; i + 24 <= line.length; i += 8) out.push(line.slice(i, i + 24));+ return out;+});+const leaked = (payload: unknown) => FRAGMENTS.filter(fragment => JSON.stringify(payload).includes(fragment));++const words = (n: number, tag: string) => Array.from({ length: n }, (_, i) => `${tag}${i} word`).join(' ');+const keyPage = (tag: string) => `## ${tag} deploy notes\n\n${words(60, tag)}\n\nThe service key:\n\n${KEY}\n## Rotation\n\n${words(60, `${tag}tail`)}\n`;+const CONTROL_BODY = `## Kestrel notes\n\n${words(60, 'kestrel')}\n`;++/** Chunks as the pre-projection chunker cut them: the middle one is key body only, with no fence. */+function legacyChunks(body: string, dims: number): ChunkInput[] {+ const lines = body.split('\n');+ const begin = lines.findIndex(l => l.startsWith('-----BEGIN'));+ const end = lines.findIndex(l => l.startsWith('-----END'));+ const vector = () => new Float32Array(dims).fill(0.01);+ return [lines.slice(0, begin + 4), lines.slice(begin + 4, end - 3), lines.slice(end - 3)].map((part, i) => ({+ chunk_index: i, chunk_text: part.join('\n').trim(), chunk_source: 'compiled_truth', embedding: vector(),+ }));+}++for (const kind of ['pglite', 'postgres'] as const) {+ const suite = kind === 'postgres' && !process.env.DATABASE_URL ? describe.skip : describe;+ suite(`${kind}: credential-safe re-chunk of existing pages`, () => {+ let engine: BrainEngine;+ /** A search term only the fenceless middle chunk holds, as the keyword index tokenizes it. */+ let BODY_TOKEN = '';+ const op = (name: string) => operations.find(o => o.name === name)!;+ const ctxOf = (remote: boolean): OperationContext => ({+ engine: engine as never, config: {} as never, logger: console as never, dryRun: false, remote, sourceId: SOURCE,+ emitResponseMeta: () => {},+ } as OperationContext);++ async function retrieve(remote: boolean, query: string): Promise<unknown[]> {+ return [+ await op('search').handler(ctxOf(remote), { query }),+ await op('query').handler(ctxOf(remote), { query, expand: false }),+ await op('recall').handler(ctxOf(remote), { query }),+ await op('search').handler(ctxOf(remote), { query, return_unit: 'window', return_window: 1, token_budget: 400 }),+ await op('search').handler(ctxOf(remote), { query, return_unit: 'page', token_budget: 2000 }),+ ];+ }++ async function expectNoFragment(stage: string): Promise<void> {+ for (const remote of [false, true]) {+ for (const query of [BODY_TOKEN, 'alpha3 deploy', 'beta3 deploy']) {+ expect(leaked(await retrieve(remote, query)), `${stage} remote=${remote} ${query}`).toEqual([]);+ }+ }+ }++ const slugsFound = async (query: string) =>+ ((await op('search').handler(ctxOf(false), { query })) as SearchResult[]).map(r => r.slug);++ beforeAll(async () => {+ gateway.configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+ engine = kind === 'postgres' ? new PostgresEngine() : new PGLiteEngine();+ if (kind === 'postgres') assertSafeE2eDatabaseUrl(process.env.DATABASE_URL!);+ await engine.connect(kind === 'postgres' ? { database_url: process.env.DATABASE_URL! } : {});+ await engine.initSchema();+ await engine.executeRaw('DELETE FROM pages WHERE source_id = $1', [SOURCE]);+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SOURCE]);+ await engine.setConfig('search.mcp_keyword_only', 'true');+ const dims = (await readContentChunksEmbeddingDim(engine)).dims ?? LEGACY_EMBEDDING_CONFIG.embedding_dimensions;+ for (const [slug, body] of [['notes/alpha-key', keyPage('alpha')], ['notes/beta-key', keyPage('beta')], ['notes/kestrel', CONTROL_BODY]] as const) {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: body, timeline: '', frontmatter: {} }, { sourceId: SOURCE });+ await installFixtureChunks(engine, slug, body === CONTROL_BODY+ ? [{ chunk_index: 0, chunk_text: body.trim(), chunk_source: 'compiled_truth' }]+ : legacyChunks(body, dims), { sourceId: SOURCE });+ }+ const [token] = await engine.executeRaw<{ lexeme: string }>(`SELECT t.lexeme FROM unnest(to_tsvector('${getFtsLanguage()}', $1::text)) t+ WHERE t.lexeme ~ '^[a-z0-9]{12,}$' AND t.lexeme ~ '[0-9]' ORDER BY length(t.lexeme) DESC, t.lexeme LIMIT 1`, [legacyChunks(keyPage('alpha'), dims)[1].chunk_text]);+ BODY_TOKEN = token.lexeme;+ }, 180_000);++ afterAll(async () => {+ __setTestEngineOverride(null);+ if (engine) {+ await engine.executeRaw('DELETE FROM pages WHERE source_id = $1', [SOURCE]);+ await engine.executeRaw('DELETE FROM sources WHERE id = $1', [SOURCE]);+ await engine.disconnect();+ }+ gateway.resetGateway();+ }, 60_000);++ test('chunker and safe-fence versions are pinned (no brain-wide re-chunk)', () => {+ expect(MARKDOWN_CHUNKER_VERSION).toBe(4);+ expect(SAFE_FENCE_CHUNKER_VERSION).toBe(4);+ });++ test('the seeded legacy brain leaks a fenceless fragment before the upgrade', async () => {+ expect(leaked(await op('search').handler(ctxOf(false), { query: BODY_TOKEN })).length).toBeGreaterThan(0);+ });++ test('after the schema migration, before the re-chunk: withheld for every caller, doctor reports it', async () => {+ await engine.setConfig('version', '186');+ await runMigrations(engine);+ await expectNoFragment('pending');+ expect(await slugsFound('kestrel3')).toContain('notes/kestrel');+ const legacyIds = (await engine.getChunks('notes/alpha-key', { sourceId: SOURCE, includeUnsealed: true })).map(c => c.id);+ expect(await hydrateChunks(engine, legacyIds), 'local code-walk hydration').toEqual([]);+ const check = await credentialProjectionPendingCheck(engine, [SOURCE]);+ expect(check.status).toBe('warn');+ expect(check.details).toMatchObject({ pages_pending: 2, kept_pages: 0 });+ expect(check.message).toContain('gbrain apply-migrations --yes');+ });++ test('after an interrupted re-chunk: the finished page is clean and visible, the rest stay withheld', async () => {+ expect(await resealSafeChunks(engine, 'notes/alpha-key', SOURCE)).not.toBeNull();+ await expectNoFragment('interrupted');+ expect(await slugsFound('alpha3')).toContain('notes/alpha-key');+ expect(await slugsFound('beta3')).not.toContain('notes/beta-key');+ expect((await credentialProjectionPendingCheck(engine, [SOURCE])).details).toMatchObject({ pages_pending: 1 });+ });++ test('the orchestrated migration finishes provider-free and is idempotent', async () => {+ __setTestEngineOverride(engine);+ const result = await v0_60_31.orchestrator({ yes: true, dryRun: false, noAutopilotInstall: true });+ expect(result.status).toBe('complete');+ expect(result.phases[0]).toMatchObject({ name: 'credential_projection', status: 'complete' });+ expect(result.phases[0].detail).toContain('1 page(s) re-chunked without provider calls');+ await expectNoFragment('repaired');+ expect(await slugsFound('beta3')).toContain('notes/beta-key');+ expect(await slugsFound('kestrel3')).toContain('notes/kestrel');+ const chunks = await engine.getChunks('notes/beta-key', { sourceId: SOURCE, includeUnsealed: true });+ expect(leaked(chunks.map(c => c.chunk_text))).toEqual([]);+ expect(chunks.some(c => c.embedded_at === null)).toBe(true);+ expect((await credentialProjectionPendingCheck(engine, [SOURCE])).status).toBe('ok');+ const rerun = await v0_60_31.orchestrator({ yes: true, dryRun: false, noAutopilotInstall: true });+ expect(rerun.phases[0].detail).toContain('0 page(s) re-chunked');+ });+ });+}diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.tsindex be41dbbea3..6552fe9a2b 100644--- a/test/fix-wave-5-integration.test.ts+++ b/test/fix-wave-5-integration.test.ts@@ -191,7 +191,7 @@ for (const backend of testBackends()) {const liveAtoms = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pages WHERE type='atom' AND deleted_at IS NULL"))[0].n;const activeFacts = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE source_markdown_slug='conversations/expired' AND expired_at IS NULL"))[0].n;const untouched = async () => { expect(await liveAtoms()).toBe(30); expect(await activeFacts()).toBe(0); };- const previews = { 'stale-atoms': 'gbrain repair stale-atoms', 'extractor-facts': 'gbrain repair extractor-facts' };+ const previews = { 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'extractor-facts': 'gbrain repair extractor-facts' };// The post-upgrade banner names both findings with the kind's read-only preview.const banner = await postUpgradeRecoveryBanner(engine, 'host');diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex f0d4c92a69..95f3ecb7cd 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -381,7 +381,7 @@},{"category": "meta",- "message": "Version 188 (latest: 188)",+ "message": "Version 189 (latest: 189)","name": "schema_version","status": "ok"},@@ -506,6 +506,18 @@"name": "safe_index_pending","status": "ok"},+ {+ "category": "brain",+ "details": {+ "count": "exact",+ "kept_pages": 0,+ "pages_pending": 0,+ "truncated": false+ },+ "message": "No page waits for the credential-safe re-chunk.",+ "name": "credential_projection_pending",+ "status": "ok"+ },{"category": "brain","details": {@@ -683,6 +695,18 @@"name": "stale_embedding_effects","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/google-connect.md",+ "repair": "google-file-modes",+ "sources": []+ },+ "message": "No group- or world-readable gbrain files under Google source directories outside ~/.gbrain.",+ "name": "google_file_modes",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 527e804b40..5e51eb5d56 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -381,7 +381,7 @@},{"category": "meta",- "message": "Version 188 (latest: 188)",+ "message": "Version 189 (latest: 189)","name": "schema_version","status": "ok"},@@ -506,6 +506,18 @@"name": "safe_index_pending","status": "ok"},+ {+ "category": "brain",+ "details": {+ "count": "exact",+ "kept_pages": 0,+ "pages_pending": 0,+ "truncated": false+ },+ "message": "No page waits for the credential-safe re-chunk.",+ "name": "credential_projection_pending",+ "status": "ok"+ },{"category": "brain","details": {@@ -683,6 +695,18 @@"name": "stale_embedding_effects","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/google-connect.md",+ "repair": "google-file-modes",+ "sources": []+ },+ "message": "No group- or world-readable gbrain files under Google source directories outside ~/.gbrain.",+ "name": "google_file_modes",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex aacb98fb53..331e21e9d5 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -387,7 +387,7 @@},{"category": "meta",- "message": "Version 188 (latest: 188)",+ "message": "Version 189 (latest: 189)","name": "schema_version","status": "ok"},@@ -512,6 +512,18 @@"name": "safe_index_pending","status": "ok"},+ {+ "category": "brain",+ "details": {+ "count": "exact",+ "kept_pages": 0,+ "pages_pending": 0,+ "truncated": false+ },+ "message": "No page waits for the credential-safe re-chunk.",+ "name": "credential_projection_pending",+ "status": "ok"+ },{"category": "brain","details": {@@ -693,6 +705,18 @@"name": "stale_embedding_effects","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/google-connect.md",+ "repair": "google-file-modes",+ "sources": []+ },+ "message": "No group- or world-readable gbrain files under Google source directories outside ~/.gbrain.",+ "name": "google_file_modes",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex 6634028c4a..b40fae8128 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -337,6 +337,10 @@"category": "brain","name": "safe_index_pending"},+ {+ "category": "brain",+ "name": "credential_projection_pending"+ },{"category": "brain","name": "connector_checkpoints"@@ -377,6 +381,10 @@"category": "ops","name": "stale_embedding_effects"},+ {+ "category": "ops",+ "name": "google_file_modes"+ },{"category": "brain","name": "extractor_facts_expired"diff --git a/test/fixtures/goldens/doctor/registry-report-remote.json b/test/fixtures/goldens/doctor/registry-report-remote.jsonindex 19ae30ea72..04d2d22070 100644--- a/test/fixtures/goldens/doctor/registry-report-remote.json+++ b/test/fixtures/goldens/doctor/registry-report-remote.json@@ -201,6 +201,10 @@"category": "brain","name": "safe_index_pending"},+ {+ "category": "brain",+ "name": "credential_projection_pending"+ },{"category": "brain","name": "connector_checkpoints"diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 81bb5ba40d..2bafcead62 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -5359,6 +5359,7 @@"localOnly?: boolean | undefined","mutating?: boolean | undefined","name: string",+ "outputRedaction: OutputRedactionPolicy","params: Record<string, ParamDef>","publishGateKey?: \"mcp.publish_skills\" | \"mcp.publish_advisor\" | undefined","requiredScopes?: readonly string[] | undefined",diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 5222124254..0f6cbcd7e6 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 183,+ "count": 184,"gaps": [17,18,@@ -27,7 +27,7 @@"slugifyPath": "401dbca23580865d8b168dd8d84db4a6c708c6610d7cb61abafc7d0ee9809063","verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"},- "latest": 188,+ "latest": 189,"records": [{"handler": {@@ -2787,6 +2787,19 @@"transaction": "absent","verify": "absent","version": 188+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "pages_credential_projection_pending",+ "sql": {+ "length": 757,+ "sha256": "8aa1667978e6e6f065afd4e0344cf0547bc03665a549ed7a5a8fdcd984cb14f5"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 189}],"versions": [@@ -2972,7 +2985,8 @@185,186,187,- 188+ 188,+ 189]},"normalizer": "migrations-record-v1"diff --git a/test/google-file-modes-repair.test.ts b/test/google-file-modes-repair.test.tsnew file mode 100644index 0000000000..dc2ba46b2f--- /dev/null+++ b/test/google-file-modes-repair.test.ts@@ -0,0 +1,168 @@+/**+ * Legacy Google file repair (security fix wave, user challenge UC1): files+ * gbrain wrote under a Google source directory outside `~/.gbrain` before+ * this release keep their 0644 modes. `gbrain doctor` reports them+ * (`google_file_modes`), the v0.60.31 migration prints a one-time notice, and+ * `gbrain repair google-file-modes` previews by default and tightens only with+ * `--apply`: only gbrain's own layout, never the chosen root, never through a+ * symlink, never another user's file. POSIX modes only: skipped on win32.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { chmodSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';+import { resolveRepairScope } from '../src/core/repair/core.ts';+import { repairRunner } from '../src/core/repair/registry.ts';+import { checkGoogleFileModes } from '../src/commands/doctor/checks/google-file-modes.ts';+import { googleFileModesNoticePhase } from '../src/commands/migrations/v0_60_31-google-file-modes.ts';++let engine: PGLiteEngine;+const scratch = mkdtempSync(join(tmpdir(), 'gbrain-google-repair-'));+const home = join(scratch, 'home');+let root: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+ rmSync(scratch, { recursive: true, force: true });+});++beforeEach(async () => {+ await resetPgliteState(engine);+ root = mkdtempSync(join(scratch, 'custom-'));+ chmodSync(root, 0o755);+});++const mode = (path: string) => lstatSync(path).mode & 0o7777;+const config = (dir: string) => JSON.stringify({ kind: 'google', g_account: '[email protected]', g_services: 'gmail', g_dir: dir });+const PAGES = ['emails/2026/09/2026-09-01-roadmap-aa11.md', 'calendar/2026/09/2026-09-02-sync-bb22.md', 'people/alice-example.md'];++/** A pre-release custom-dir layout: everything 0644/0755, as the default umask left it. */+async function legacySource(id = 'gmail', dir = root) {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)', [id, dir, config(dir)]);+ for (const rel of PAGES) {+ mkdirSync(dirname(join(dir, rel)), { recursive: true });+ writeFileSync(join(dir, rel), `page ${rel}\n`);+ chmodSync(join(dir, rel), 0o644);+ await engine.putPage(rel.replace(/\.md$/, ''), { type: 'note', title: rel, compiled_truth: rel, timeline: '', frontmatter: {} }, { sourceId: id });+ await engine.executeRaw('UPDATE pages SET source_path=$1 WHERE source_id=$2 AND slug=$3', [rel, id, rel.replace(/\.md$/, '')]);+ }+ for (const d of ['emails', 'emails/2026', 'emails/2026/09', 'calendar', 'calendar/2026', 'calendar/2026/09', 'people']) chmodSync(join(dir, d), 0o755);+ writeFileSync(join(dir, '.google-source.json'), '{}');+ chmodSync(join(dir, '.google-source.json'), 0o644);+ writeFileSync(join(dir, 'my-own-notes.md'), 'not gbrain');+ chmodSync(join(dir, 'my-own-notes.md'), 0o644);+}++const repair = (apply: boolean, source?: string) => withEnv({ GBRAIN_HOME: home }, async () => {+ const runner = await repairRunner(engine, { apply, logger: { info() {}, warn() {}, error() {} } });+ return runner.run('google-file-modes', await resolveRepairScope(engine, source), { sourceFlag: source, explicit: true });+});++describe.skipIf(process.platform === 'win32')('gbrain repair google-file-modes', () => {+ test('preview lists gbrain-written loose entries and changes nothing', async () => {+ await legacySource();+ const result = await repair(false, 'gmail');+ expect(result.mode).toBe('dry_run');+ // 3 pages + state file + 7 layout directories; never the root or the user's own file.+ expect(result.affected).toBe(11);+ expect(result.sample).toContain('gmail:.google-source.json');+ expect(result.sample.some(item => item.includes('my-own-notes'))).toBe(false);+ expect(result.apply_command).toBe('gbrain repair google-file-modes --source gmail --apply');+ expect(mode(join(root, PAGES[0]))).toBe(0o644);+ expect(mode(join(root, 'emails'))).toBe(0o755);+ });++ test('apply tightens files 0600 and layout directories 0700, leaving the root, other files and content untouched', async () => {+ await legacySource();+ const before = PAGES.map(rel => readFileSync(join(root, rel), 'utf8'));+ const result = await repair(true, 'gmail');+ expect(result).toMatchObject({ applied: 11, skipped: 0, complete: true });+ for (const rel of [...PAGES, '.google-source.json']) expect([rel, mode(join(root, rel))]).toEqual([rel, 0o600]);+ for (const d of ['emails', 'emails/2026', 'emails/2026/09', 'calendar', 'people']) expect([d, mode(join(root, d))]).toEqual([d, 0o700]);+ expect(mode(root)).toBe(0o755);+ expect(mode(join(root, 'my-own-notes.md'))).toBe(0o644);+ expect(PAGES.map(rel => readFileSync(join(root, rel), 'utf8'))).toEqual(before);+ expect((await repair(false, 'gmail')).affected).toBe(0);+ });++ test('never follows a symlinked page or a symlinked layout directory', async () => {+ await legacySource();+ const outside = join(scratch, `outside-${Date.now()}`);+ mkdirSync(join(outside, '2026', '09'), { recursive: true });+ writeFileSync(join(outside, 'target.md'), 'outside');+ chmodSync(join(outside, 'target.md'), 0o644);+ writeFileSync(join(outside, '2026', '09', '2026-09-02-sync-bb22.md'), 'outside');+ chmodSync(join(outside, '2026', '09', '2026-09-02-sync-bb22.md'), 0o644);+ rmSync(join(root, 'people/alice-example.md'));+ symlinkSync(join(outside, 'target.md'), join(root, 'people/alice-example.md'));+ rmSync(join(root, 'calendar'), { recursive: true });+ symlinkSync(outside, join(root, 'calendar'));+ const preview = await repair(false, 'gmail');+ expect(preview.residuals.skipped_symlink).toBeGreaterThanOrEqual(2);+ expect(preview.sample.some(item => item.includes('calendar') || item.includes('alice'))).toBe(false);+ await repair(true, 'gmail');+ expect(mode(join(outside, 'target.md'))).toBe(0o644);+ expect(mode(join(outside, '2026', '09', '2026-09-02-sync-bb22.md'))).toBe(0o644);+ expect(mode(join(root, PAGES[0]))).toBe(0o600);+ });++ test("another user's files are counted and left alone", async () => {+ await legacySource();+ const getuid = process.getuid!;+ const real = getuid.call(process);+ process.getuid = () => real + 1;+ let preview;+ try { preview = await repair(false, 'gmail'); } finally { process.getuid = getuid; }+ expect(preview.affected).toBe(0);+ expect(preview.residuals.skipped_foreign_owner).toBeGreaterThan(0);+ expect(mode(join(root, PAGES[0]))).toBe(0o644);+ });++ test('a Google source inside ~/.gbrain is out of scope', async () => {+ const inside = join(home, '.gbrain', 'clones', 'gmail-google');+ mkdirSync(inside, { recursive: true });+ await legacySource('gmail', inside);+ expect((await repair(false, 'gmail')).affected).toBe(0);+ });+});++describe.skipIf(process.platform === 'win32')('detection: doctor and the one-time upgrade notice', () => {+ test('doctor warns per directory with counts and the exact preview and apply commands, without file names', async () => {+ await legacySource();+ const check = await withEnv({ GBRAIN_HOME: home }, () => checkGoogleFileModes(engine));+ expect(check.status).toBe('warn');+ expect(check.message).toContain(`Google source gmail: 4 file(s) and 7 directories gbrain wrote under ${root}`);+ expect(check.message).toContain('Preview: gbrain repair google-file-modes --source gmail');+ expect(check.message).toContain('apply after the user agrees: gbrain repair google-file-modes --source gmail --apply');+ expect(check.message).not.toContain('roadmap');+ await repair(true, 'gmail');+ expect((await withEnv({ GBRAIN_HOME: home }, () => checkGoogleFileModes(engine))).status).toBe('ok');+ });++ test('the migration notice names each custom-dir source once and skips default-dir sources', async () => {+ await legacySource('custom');+ const inside = join(home, '.gbrain', 'clones', 'default-google');+ mkdirSync(inside, { recursive: true });+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)', ['inside-home', inside, config(inside)]);+ const printed: string[] = [];+ const run = () => withEnv({ GBRAIN_HOME: home }, () => googleFileModesNoticePhase(engine, { dryRun: false, print: line => printed.push(line) }));+ expect((await run()).status).toBe('complete');+ expect(printed).toHaveLength(1);+ expect(printed[0]).toContain(`Google source custom keeps its files in ${root}, outside ~/.gbrain`);+ expect(printed[0]).toContain('(11 found now)');+ expect(printed[0]).toContain('gbrain repair google-file-modes --source custom --apply');+ expect(printed[0]).not.toContain('roadmap');+ expect(mode(join(root, PAGES[0]))).toBe(0o644);+ expect(await run()).toMatchObject({ status: 'skipped', detail: 'already_shown' });+ expect(printed).toHaveLength(1);+ });+});diff --git a/test/google-file-modes.test.ts b/test/google-file-modes.test.tsnew file mode 100644index 0000000000..5d4f2512c1--- /dev/null+++ b/test/google-file-modes.test.ts@@ -0,0 +1,135 @@+/**+ * Google connector file privacy (security fix wave). Custom `--dir` Google+ * sources live outside the 0700 `~/.gbrain`, so the files gbrain writes there+ * must be private by themselves: the cursor state file, its corrupt-file+ * quarantine and every materialized page are 0600, and directories gbrain+ * creates are 0700. A directory the user chose is never chmod-ed.+ *+ * Every mode assertion runs in a child process under umask 0000+ * (test/helpers/google-file-modes-child.ts), where an unspecified mode is+ * world-readable, so a writer that forgets its mode fails here. POSIX modes+ * only: skipped on win32.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync, existsSync, lstatSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { googleStateFile, readGoogleState } from '../src/core/google/google-source.ts';++const posix = process.platform !== 'win32';+const base = mkdtempSync(join(tmpdir(), 'gbrain-file-modes-'));+afterAll(() => rmSync(base, { recursive: true, force: true }));++async function child(scenario: string, dir: string, extra: Record<string, unknown> = {}) {+ const env: Record<string, string | undefined> = { ...process.env, GBRAIN_HOME: join(base, 'home'), FILE_MODES_TOKEN: 'synthetic-local-fixture',+ GBRAIN_TEST_FILE_MODES: JSON.stringify({ scenario, base: dir, ...extra }) };+ delete env.DATABASE_URL;+ delete env.GBRAIN_DATABASE_URL;+ const proc = Bun.spawn([process.execPath, 'run', join(import.meta.dir, 'helpers/google-file-modes-child.ts')], { env, stdout: 'pipe', stderr: 'pipe' });+ const timer = setTimeout(() => proc.kill('SIGKILL'), 100_000);+ try {+ const [stdout, stderr, exit] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);+ const line = stdout.split('\n').find(l => l.startsWith('FILE_MODES {'));+ return { stdout, stderr, exit, result: line ? JSON.parse(line.slice('FILE_MODES '.length)) : null };+ } finally { clearTimeout(timer); if (proc.exitCode === null) proc.kill('SIGKILL'); await proc.exited; }+}++describe.skipIf(!posix)('Google files written under umask 0000', () => {+ let legacy: any;+ let managed: any;+ beforeAll(async () => {+ const legacyDir = join(base, 'legacy');+ const managedDir = join(base, 'managed');+ mkdirSync(legacyDir);+ mkdirSync(managedDir);+ const [l, m] = await Promise.all([child('legacy', legacyDir), child('managed', managedDir)]);+ expect(l.result, l.stderr).not.toBeNull();+ expect(m.result, m.stderr).not.toBeNull();+ legacy = l.result;+ managed = m.result;+ }, 120_000);++ test('atomicWriteFileSync opens and fchmods a requested mode; an omitted mode keeps the existing behavior', () => {+ expect(legacy.atomic).toEqual({ requested: 0o600, legacy: 0o600, omitted: 0o644, preserved: 0o640 });+ });++ test('sources add --kind google creates only the leaf 0700 and leaves a chosen directory alone', () => {+ expect(legacy.sourcesAdd).toEqual({ parent: 0o777, added: 0o700, chosen: 0o755 });+ });++ test('a fresh sweep writes the state file and every page 0600 and lays out 0700 directories under an untouched root', () => {+ expect(legacy.fresh.status).not.toBe('partial');+ expect(legacy.fresh.root).toBe(0o755);+ const files = Object.entries(legacy.fresh.files);+ expect(files.map(([path]) => path)).toEqual(expect.arrayContaining(['.google-source.json']));+ expect(files.filter(([path]) => path.endsWith('.md')).map(([path]) => path.split('/')[0]).sort()).toEqual(['calendar', 'emails', 'people']);+ for (const [path, mode] of files) expect([path, mode]).toEqual([path, 0o600]);+ expect(Object.keys(legacy.fresh.dirs).length).toBeGreaterThan(3);+ for (const [path, mode] of Object.entries(legacy.fresh.dirs)) expect([path, mode]).toEqual([path, 0o700]);+ });++ test('a delta sweep over legacy 0644 files reasserts 0600 and replaces a stale 0644 temp file', () => {+ expect(legacy.delta).toMatchObject({ pageMode: 0o600, state: 0o600, staleTmp: false });+ expect(legacy.delta.status).not.toBe('partial');+ });++ test('a stale temp path that is a directory fails that thread with an error naming the path', () => {+ expect(legacy.staleDir.status).toBe('partial');+ expect(legacy.staleDir.stderr).toContain(`Stale temporary path ${legacy.staleDir.tmpPath} is a directory`);+ });++ test('a corrupt state file is quarantined 0600 and the sync continues with empty state', () => {+ expect(legacy.quarantine).toEqual({ mode: 0o600, emptyState: true });+ });++ test('managed coordinator publication with publishMode lands 0600 files and 0700 created directories, and reasserts on rewrite', () => {+ expect(managed.coordinatorNew).toMatchObject({ state: 'committed', file: 0o600, root: 0o755,+ dirs: { emails: 0o700, 'emails/2026': 0o700, 'emails/2026/09': 0o700 } });+ expect(managed.coordinatorRewrite).toEqual({ state: 'committed', file: 0o600 });+ });++ test('managed Google import and receipts rewrite publish 0600 without changing the submitted intent', () => {+ expect(managed.googleImport).toMatchObject({ file: 0o600, root: 0o755, dirs: { emails: 0o700, 'emails/2026': 0o700, 'emails/2026/09': 0o700 } });+ expect(managed.googleImport.intentText).not.toContain('publishMode');+ expect(managed.googleImport.intentText).not.toContain('"mode"');+ // Request ids derive from this intent (minus its authority); the key set is the pre-wave set, so ids are unchanged across the upgrade.+ expect(managed.googleImport.intentKeys).toEqual(['canonicalRoot', 'checkpointBefore', 'checkpointKey', 'configHash', 'connector', 'content',+ 'expected_revision', 'fileBeforeHash', 'filePath', 'kind', 'noEmbed', 'noSchemaPack', 'ownerEpoch', 'sourcePath', 'sourceRoot', 'syncAuthority']);+ expect(managed.googleReceipts).toEqual({ status: 'complete', file: 0o600 });+ });+});++describe.skipIf(!posix)('managed restoration after a crash', () => {+ test('restoring a deleted private page stages it 0600 from the first byte, then restores it 0600', async () => {+ const dir = join(base, 'restore-case');+ mkdirSync(dir);+ const crashed = await child('restore-crash', dir);+ expect(crashed.stdout, crashed.stderr).toContain('FILE_MODES_CRASH');+ expect(crashed.result.before).toBe(0o600);+ expect(existsSync(crashed.result.file)).toBe(false);+ const observed = await child('restore-observe', dir, { requestId: crashed.result.requestId });+ expect(observed.result, observed.stderr).not.toBeNull();+ expect(observed.exit).not.toBe(0);+ expect(observed.result.stageMode).toBe(0o600);+ expect(lstatSync(observed.result.stage).mode & 0o777).toBe(0o600);+ const finished = await child('restore-finish', dir, { requestId: crashed.result.requestId });+ expect(finished.result, finished.stderr).toMatchObject({ recovery: null, file: 0o600 });+ }, 120_000);+});++describe('corrupt state quarantine that cannot be secured', () => {+ test('names the path, the failed step, the exposure and the fix, and still returns empty state', () => {+ const dir = join(base, 'unsecured');+ mkdirSync(join(dir, '.google-source.json.corrupt', 'occupied'), { recursive: true });+ writeFileSync(googleStateFile(dir), '{ not json');+ const lines: string[] = [];+ const write = process.stderr.write.bind(process.stderr);+ process.stderr.write = ((chunk: string | Uint8Array) => { lines.push(String(chunk)); return true; }) as typeof process.stderr.write;+ let state;+ try { state = readGoogleState(dir); } finally { process.stderr.write = write; }+ expect(state.gmail_history_id).toBeNull();+ const file = googleStateFile(dir);+ expect(lines.join('')).toContain(`[google] could not secure the quarantined state file ${file}: rename failed`);+ expect(lines.join('')).toContain(`It may be readable by other local users; run chmod 600 ${file} or delete it.`);+ });+});diff --git a/test/helpers/google-file-modes-child.ts b/test/helpers/google-file-modes-child.tsnew file mode 100644index 0000000000..3ae8e19612--- /dev/null+++ b/test/helpers/google-file-modes-child.ts@@ -0,0 +1,266 @@+/**+ * Child process for test/google-file-modes.test.ts. File-mode assertions need+ * umask 0000, which is process-global, so every scenario runs here instead of+ * in the test process. The scenario writes one `FILE_MODES <json>` line with+ * the observed modes; the parent asserts on it.+ *+ * Synthetic data only: example.invalid addresses, hex thread ids.+ */+import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs';+import { dirname, join, relative } from 'node:path';+import { randomUUID } from 'node:crypto';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { atomicWriteFileSync } from '../../src/core/atomic-write.ts';+import { addSource } from '../../src/core/sources-ops.ts';+import { googleStateFile, parseGoogleSourceConfig, readGoogleState, runGoogleAttachmentBackfill, runGoogleSync } from '../../src/core/google/google-source.ts';+import { withConnectorSync } from '../../src/core/persistence/connector-sync.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { localHostId, registerLocalWriter } from '../../src/core/persistence/identity.ts';+import { submissionAuthority } from '../../src/core/persistence/authority.ts';+import { admitWrite, claimNextWrite } from '../../src/core/persistence/journal.ts';+import { publishMutation, recoverPublication } from '../../src/core/persistence/coordinator.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import type { WriteRequest } from '../../src/core/persistence/model.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { withGoogleAccount } from './connector-fixture.ts';++process.umask(0);+const input = JSON.parse(process.env.GBRAIN_TEST_FILE_MODES!) as { scenario: string; base: string; requestId?: string };+const base = input.base;+const mode = (path: string) => lstatSync(path).mode & 0o7777;+const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });+const report = (value: unknown) => process.stdout.write(`FILE_MODES ${JSON.stringify(value)}\n`);+const ACCOUNT = '[email protected]';+const googleConfig = (services: string) => ({ kind: 'google', g_account: ACCOUNT, g_services: services, g_history_days: 90, g_access: 'env', g_token_env: 'FILE_MODES_TOKEN' });++function tree(root: string): { files: Record<string, number>; dirs: Record<string, number> } {+ const files: Record<string, number> = {};+ const dirs: Record<string, number> = {};+ const walk = (dir: string) => {+ for (const name of readdirSync(dir)) {+ const path = join(dir, name);+ if (lstatSync(path).isDirectory()) { dirs[relative(root, path)] = mode(path); walk(path); }+ else files[relative(root, path)] = mode(path);+ }+ };+ walk(root);+ return { files, dirs };+}++const T_A = '17aa00000000a001';+const NOW = Math.floor(Date.now() / 1000) * 1000;+const message = (id: string, ms: number, body: string) => ({+ id, threadId: T_A, labelIds: [], internalDate: String(ms),+ payload: { mimeType: 'text/plain', headers: [{ name: 'From', value: 'Charlie Example <[email protected]>' },+ { name: 'To', value: ACCOUNT }, { name: 'Subject', value: 'Zephyr roadmap' }], body: { data: Buffer.from(body).toString('base64url') } },+});++function googleFetch(fx: { messages: ReturnType<typeof message>[]; history: string[][] }) {+ return withGoogleAccount(async (url: string) => {+ const u = new URL(url);+ if (u.pathname.endsWith('/settings/sendAs')) return json({ sendAs: [] });+ if (u.pathname.endsWith('/users/me/profile')) return json({ emailAddress: ACCOUNT, historyId: '1000' });+ if (u.pathname.endsWith('/users/me/messages')) return json({ messages: fx.messages.map(m => ({ id: m.id, threadId: m.threadId })) });+ if (u.pathname.endsWith('/users/me/history')) return json({ historyId: '1001', history: fx.history.map(ids => ({ messages: ids.map(threadId => ({ threadId })) })) });+ if (u.pathname.endsWith(`/users/me/threads/${T_A}`)) return json({ id: T_A, messages: fx.messages });+ if (/\/calendars\/[^/]+\/events/.test(u.pathname)) return json({ items: [{ id: 'evt00000000000001', status: 'confirmed', summary: 'Zephyr sync',+ start: { dateTime: new Date(NOW - 86_400_000).toISOString() }, end: { dateTime: new Date(NOW - 82_800_000).toISOString() },+ organizer: { email: ACCOUNT } }], nextSyncToken: 'cal-1' });+ if (u.pathname.includes('/people/me/connections')) return json({ connections: [{ resourceName: 'people/c000000001',+ names: [{ displayName: 'Alice Example' }], emailAddresses: [{ value: '[email protected]' }] }], nextSyncToken: 'ppl-1' });+ return json({ error: { message: `unhandled ${u.pathname}` } }, 400);+ }, ACCOUNT);+}++async function legacy(engine: BrainEngine) {+ const out: Record<string, unknown> = {};++ const atomicDir = join(base, 'atomic');+ mkdirSync(atomicDir);+ atomicWriteFileSync(join(atomicDir, 'requested'), 'x', { mode: 0o600 });+ writeFileSync(join(atomicDir, 'legacy'), 'x');+ chmodSync(join(atomicDir, 'legacy'), 0o644);+ atomicWriteFileSync(join(atomicDir, 'legacy'), 'y', { mode: 0o600 });+ atomicWriteFileSync(join(atomicDir, 'omitted'), 'x');+ writeFileSync(join(atomicDir, 'preserved'), 'x');+ chmodSync(join(atomicDir, 'preserved'), 0o640);+ atomicWriteFileSync(join(atomicDir, 'preserved'), 'y');+ out.atomic = tree(atomicDir).files;++ const added = join(base, 'missing-parent', 'added');+ await addSource(engine, { id: 'gadded', google: { account: ACCOUNT, services: ['contacts'], historyDays: 90, dir: added, access: 'env', tokenEnv: 'FILE_MODES_TOKEN' } });+ const chosen = join(base, 'chosen');+ mkdirSync(chosen);+ chmodSync(chosen, 0o755);+ await addSource(engine, { id: 'gchosen', google: { account: ACCOUNT, services: ['contacts'], historyDays: 90, dir: chosen, access: 'env', tokenEnv: 'FILE_MODES_TOKEN' } });+ out.sourcesAdd = { parent: mode(dirname(added)), added: mode(added), chosen: mode(chosen) };++ const root = join(base, 'custom-dir');+ mkdirSync(root);+ chmodSync(root, 0o755);+ const config = googleConfig('gmail,calendar,contacts');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)', ['gsrc', root, JSON.stringify(config)]);+ const cfg = parseGoogleSourceConfig(config, root);+ const fx = { messages: [message('18c2f4a9b3d21e01', NOW - 2 * 86_400_000, 'Sharing the zephyr roadmap draft.')], history: [] as string[][] };+ const sync = () => runGoogleSync(engine, 'gsrc', cfg, { sourceId: 'gsrc', noEmbed: true, noExtract: true }, googleFetch(fx));+ const fresh = await sync();+ out.fresh = { status: fresh.status, root: mode(root), ...tree(root) };++ const page = Object.keys(tree(root).files).find(path => path.startsWith('emails/'))!;+ for (const path of Object.keys(tree(root).files)) chmodSync(join(root, path), 0o644);+ writeFileSync(join(root, `${page}.tmp`), 'stale bytes from a crashed sweep');+ chmodSync(join(root, `${page}.tmp`), 0o644);+ fx.messages.push(message('18c2f4a9b3d21e02', NOW - 86_400_000, 'Following up on the roadmap.'));+ fx.history = [[T_A]];+ const delta = await sync();+ out.delta = { status: delta.status, page, pageMode: mode(join(root, page)), state: mode(googleStateFile(root)), staleTmp: existsSync(join(root, `${page}.tmp`)) };++ mkdirSync(join(root, `${page}.tmp`));+ const stderr: string[] = [];+ const write = process.stderr.write.bind(process.stderr);+ process.stderr.write = ((chunk: string | Uint8Array) => { stderr.push(String(chunk)); return true; }) as typeof process.stderr.write;+ let staleDir;+ try { staleDir = await sync(); } finally { process.stderr.write = write; }+ out.staleDir = { status: staleDir.status, stderr: stderr.join(''), tmpPath: join(root, `${page}.tmp`) };++ writeFileSync(googleStateFile(root), '{ not json');+ chmodSync(googleStateFile(root), 0o644);+ const state = readGoogleState(root);+ out.quarantine = { mode: mode(`${googleStateFile(root)}.corrupt`), emptyState: state.gmail_history_id === null && state.contacts_sync_token === null };+ return out;+}++async function enablePersistence(engine: BrainEngine, enabled: boolean) {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=$1 WHERE singleton=1', [enabled]);+}++/** A worktree-bound source; managed persistence stays off unless `managed` (direct coordinator fixtures write pages themselves). */+async function boundSource(engine: BrainEngine, root: string, config: Record<string, unknown> | null, managed: boolean) {+ await disposePersistenceConsumer(engine);+ await enablePersistence(engine, false);+ const id = `modes-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)', [id, root, JSON.stringify(config ?? {})]);+ const binding = await claimWorktree(engine, id, root);+ if (managed) await enablePersistence(engine, true);+ return { id, binding };+}++const context = (engine: BrainEngine, sourceId: string): OperationContext =>+ ({ engine, config: { engine: 'pglite', embedding_disabled: true }, remote: false, dryRun: false, sourceId, logger: { info() {}, warn() {}, error() {} } } as OperationContext);++async function coordinatedRequest(engine: BrainEngine, sourceId: string, binding: Awaited<ReturnType<typeof claimWorktree>>, slug: string) {+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;+ const authority = await submissionAuthority(context(engine, sourceId), 'put_page', sourceId, binding.source_incarnation, slug);+ const admitted = await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId,+ sourceIncarnation: binding.source_incarnation, slug, pageId: snapshot.page.id, requestId: randomUUID(),+ callerIntent: { content: 'fixture' }, intent: { content: 'fixture' }, worktreeId: binding.worktree_id, topologyGeneration: binding.topology_generation });+ const row = (await claimNextWrite(engine, localHostId()))!;+ if (row.id !== admitted.id) throw new Error('fixture claimed an unexpected request');+ return { row, snapshot };+}++const page = (body: string) => ({ type: 'note' as const, title: 'Fixture', compiled_truth: body, timeline: '', frontmatter: {} });++async function managed(engine: BrainEngine) {+ const out: Record<string, unknown> = {};+ await registerLocalWriter(engine, 'cli');++ const root = join(base, 'coordinator');+ mkdirSync(root);+ chmodSync(root, 0o755);+ const { id, binding } = await boundSource(engine, root, null, false);+ const slug = 'emails/2026/09/fixture';+ await engine.putPage(slug, page('Before'), { sourceId: id });+ const file = join(root, `${slug}.md`);+ const created = await coordinatedRequest(engine, id, binding, slug);+ const publish = (row: WriteRequest, observedRevision: string, content: string) => publishMutation(engine, row, { observedRevision,+ file: { path: file, root, content, publishMode: 0o600 },+ apply: async tx => { await tx.putPage(slug, page(content), { sourceId: id }); return {}; } });+ const first = await publish(created.row, created.snapshot.revision, 'Created');+ out.coordinatorNew = { state: first.state, file: mode(file), root: mode(root), ...tree(root) };+ chmodSync(file, 0o644);+ const rewrite = await coordinatedRequest(engine, id, binding, slug);+ const second = await publish(rewrite.row, rewrite.snapshot.revision, 'Rewritten');+ out.coordinatorRewrite = { state: second.state, file: mode(file) };++ const groot = join(base, 'google-bound');+ mkdirSync(groot);+ chmodSync(groot, 0o755);+ const gconfig = googleConfig('gmail');+ const g = await boundSource(engine, groot, gconfig, true);+ const cfg = parseGoogleSourceConfig(gconfig, groot);+ const gslug = 'emails/2026/09/thread-1';+ const content = `---\ntype: email\ntitle: Synthetic thread\nthread_id: thread1\naccount: ${ACCOUNT}\nmessage_ids: [message0000000001]\nvisibility: private\n---\nSynthetic body.\n`;+ await withConnectorSync(engine, g.id, 'google', cfg, { noEmbed: true, noExtract: true, noSchemaPack: true }, async session => {+ await session!.importMarkdown(`${gslug}.md`, content);+ });+ const gfile = join(groot, `${gslug}.md`);+ const [importRow] = await engine.executeRaw<WriteRequest>(+ "SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='connector_v2_import' ORDER BY sequence LIMIT 1", [g.id]);+ out.googleImport = { file: mode(gfile), root: mode(groot), ...tree(groot), intentKeys: Object.keys(importRow.intent!).sort(),+ intentText: JSON.stringify(importRow.intent) };+ chmodSync(gfile, 0o644);+ await disposePersistenceConsumer(engine);+ const backfill = await runGoogleAttachmentBackfill(engine, g.id, cfg, {}, async (url: string) => {+ if (url.includes('/profile')) return json({ emailAddress: ACCOUNT, historyId: '100' });+ return json({ id: 'thread1', messages: [{ id: 'message0000000001', payload: { mimeType: 'multipart/mixed', parts: [+ { partId: '1', filename: 'fixture.pdf', mimeType: 'application/pdf', body: { attachmentId: 'opaque', size: 17 } }] } }] });+ });+ out.googleReceipts = { status: backfill.status, file: mode(gfile) };+ await disposePersistenceConsumer(engine);+ return out;+}++async function restoreCrash(engine: BrainEngine) {+ await registerLocalWriter(engine, 'cli');+ const root = join(base, 'restore');+ mkdirSync(root);+ const { id, binding } = await boundSource(engine, root, null, false);+ const slug = 'emails/2026/09/private';+ await engine.putPage(slug, page('Private'), { sourceId: id });+ const file = join(root, `${slug}.md`);+ const created = await coordinatedRequest(engine, id, binding, slug);+ await publishMutation(engine, created.row, { observedRevision: created.snapshot.revision, file: { path: file, root, content: 'Private', publishMode: 0o600 },+ apply: async () => ({}) });+ const before = mode(file);+ const deletion = await coordinatedRequest(engine, id, binding, slug);+ report({ requestId: deletion.row.id, root, file, before });+ await publishMutation(engine, deletion.row, { observedRevision: deletion.snapshot.revision, file: { path: file, root, content: null },+ apply: async () => ({}) }, localHostId(), { boundary: async name => {+ if (name === 'after_publication') { process.stdout.write('FILE_MODES_CRASH\n'); process.kill(process.pid, 'SIGKILL'); await new Promise(() => {}); }+ } });+}++async function restoreObserve(engine: BrainEngine) {+ const [row] = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid', [input.requestId]);+ const stage = (row.recovery as { staging?: { restoration?: { path: string } } }).staging?.restoration?.path;+ await recoverPublication(engine, row.id, localHostId(), false, undefined, false, { fileBoundary: name => {+ if (name !== 'restoration_staging_flushed' || !stage) return;+ report({ stage, stageMode: mode(stage) });+ process.kill(process.pid, 'SIGKILL');+ } });+}++async function restoreFinish(engine: BrainEngine) {+ const [row] = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid', [input.requestId]);+ const file = (row.recovery as { path: string }).path;+ const after = await recoverPublication(engine, row.id, localHostId());+ report({ state: after.state, recovery: after.recovery, file: existsSync(file) ? mode(file) : null });+}++const disk = input.scenario.startsWith('restore');+const engine = new PGLiteEngine();+await engine.connect(disk ? { database_path: join(base, 'database') } : {});+await engine.initSchema();+try {+ if (input.scenario === 'legacy') report(await legacy(engine));+ else if (input.scenario === 'managed') report(await managed(engine));+ else if (input.scenario === 'restore-crash') await restoreCrash(engine);+ else if (input.scenario === 'restore-observe') await restoreObserve(engine);+ else if (input.scenario === 'restore-finish') await restoreFinish(engine);+ else throw new Error(`unknown scenario ${input.scenario}`);+} finally {+ await disposePersistenceConsumer(engine);+ await engine.disconnect();+}diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsindex 8856d80715..a42e5f6229 100644--- a/test/repair-explicit-only.test.ts+++ b/test/repair-explicit-only.test.ts@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';import { withEnv } from './helpers/with-env.ts';-const EXPLICIT: RepairKind[] = ['stale-atoms', 'extractor-facts'];+const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts'];let engine: PGLiteEngine;const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));@@ -62,7 +62,7 @@ function withExplicitCheck<T>(run: (spec: WaveCheckSpec) => T): T {}describe('registry', () => {- test('stale-atoms and extractor-facts are registered explicit-only and excluded from the --all set', () => {+ test('google-file-modes, stale-atoms and extractor-facts are registered explicit-only and excluded from the --all set', () => {expect(EXPLICIT_REPAIR_REGISTRY.map(spec => spec.kind)).toEqual(EXPLICIT);for (const kind of EXPLICIT) expect(REPAIR_REGISTRY.map(spec => spec.kind)).toContain(kind);expect(AUTO_REPAIR_REGISTRY.some(spec => spec.explicit_only)).toBe(false);@@ -109,7 +109,7 @@ describe('surfaces that list instead of run', () => {expect(out.explicit_kinds).toEqual(EXPLICIT.map(kind => ({ kind, code: 'explicit_kind_required', preview_command: `gbrain repair ${kind}`,docs: 'docs/guides/repair.md#explicit-only-repair-kinds' })));}- expect(await captured(['--all'])).toContain('Explicit-only kinds (not run without their name; preview each): gbrain repair stale-atoms; gbrain repair extractor-facts');+ expect(await captured(['--all'])).toContain('Explicit-only kinds (not run without their name; preview each): gbrain repair google-file-modes; gbrain repair stale-atoms; gbrain repair extractor-facts');});test('gbrain repair --all --apply exits 0 when explicit kinds are the only ones left', async () => {diff --git a/test/retrieval-op-redaction.test.ts b/test/retrieval-op-redaction.test.tsnew file mode 100644index 0000000000..3bf5a9027a--- /dev/null+++ b/test/retrieval-op-redaction.test.ts@@ -0,0 +1,360 @@+/**+ * ENG-4 / CEO-1 / ENG-5 / ENG-17 — every op's output-redaction policy, driven+ * through the real MCP dispatch path (`dispatchToolCall`, remote = true).+ *+ * Contract: an op classified 'retrieval' never hands a stored credential to a+ * caller (early returns included); an op classified 'no_stored_text' returns+ * no stored text at all; an exempt op names its reason. The seeded fixture+ * plants a random vendor token next to a plain marker word in every stored+ * text surface (titles, bodies, timeline, frontmatter, link context, facts,+ * takes, events, ontology values, ingest log, raw data). A retrieval op must+ * show the marker (anti-vacuity: it really returned stored text) but never+ * the token; a no_stored_text op must show neither.+ *+ * Regressions it catches: a new or edited read op that returns stored text+ * without the registration wrapper, a mis-classified op, a handler-level+ * redaction that skips the facts arm or the rendered text, and budgets or+ * delta cursors computed from text other than what is delivered.+ *+ * Every credential fixture is assembled at runtime from random parts (CEO-10).+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { randomBytes, randomUUID } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import { operations, operationsByName, type Operation, type OperationContext } from '../src/core/operations.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { estimateTokens } from '../src/core/search/token-budget.ts';++const ALNUM = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';+function rand(n: number): string {+ let out = '';+ for (const b of randomBytes(n)) out += ALNUM[b % ALNUM.length];+ return out;+}+const vendorToken = () => ['gh', 'p_'].join('') + rand(36);+const openaiKey = () => ['sk', rand(40)].join('-');++const TOKEN = vendorToken();+const MARK = 'PLANTMARK';+const planted = (label: string) => `${MARK} ${label} ${TOKEN} end`;+const TODAY = new Date().toISOString().slice(0, 10);+const SRC = 'default';+const CONFIG = { engine: 'pglite' } as OperationContext['config'];++let engine: PGLiteEngine;++async function call(name: string, args: Record<string, unknown>, remote = true): Promise<{ text: string; isError: boolean }> {+ const res = await dispatchToolCall(engine, name, args, { remote, transport: 'stdio', sourceId: SRC, config: CONFIG });+ return { text: res.content.map(c => c.text).join('\n'), isError: res.isError === true };+}++function localCtx(): OperationContext {+ return {+ engine, config: CONFIG, remote: false, dryRun: false, sourceId: SRC, transport: 'stdio',+ logger: { info() {}, warn() {}, error() {}, debug() {} },+ } as unknown as OperationContext;+}++const isRetrieval = (op: Operation) =>+ op.outputRedaction === 'retrieval' || (typeof op.outputRedaction === 'object' && 'retrieval' in op.outputRedaction);++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.setConfig('schema_pack', 'gbrain-base');+ await engine.putPage('people/alice-example', {+ type: 'person', title: planted('person'), compiled_truth: planted('person body'),+ timeline: `- ${TODAY}: ${planted('timeline')}`, frontmatter: { summary: planted('summary') },+ }, { sourceId: SRC });+ await engine.putPage('notes/n1', {+ type: 'note', title: planted('note'), compiled_truth: `${planted('note body')}\nGITHUB_TOKEN=${rand(31)}7`,+ timeline: `- ${TODAY}: ${planted('note timeline')}`, frontmatter: {},+ }, { sourceId: SRC });+ await engine.putPage('misc/orphan', { type: 'note', title: planted('orphan'), compiled_truth: planted('orphan body'), frontmatter: {} }, { sourceId: SRC });+ await engine.executeRaw(`UPDATE pages SET type = '' WHERE slug = 'misc/orphan'`);+ await engine.putPage('stubs/s1', {+ type: 'person', title: planted('stub'), compiled_truth: planted('stub body'),+ frontmatter: { provenance: 'auto-extracted', status: 'unverified' },+ }, { sourceId: SRC });+ await engine.addTag('notes/n1', 'topic', { sourceId: SRC });+ await engine.addLink('notes/n1', 'people/alice-example', planted('link'), 'mentions', 'markdown', undefined, undefined, { fromSourceId: SRC, toSourceId: SRC });+ await engine.createVersion('notes/n1', { sourceId: SRC });+ await engine.putRawData('notes/n1', 'crm', { owner: planted('raw') }, { sourceId: SRC });+ await engine.logIngest({ source_id: SRC, source_type: 'test', source_ref: 'ref-1', pages_updated: ['notes/n1'], summary: planted('ingest') });+ await engine.insertFact({ fact: planted('fact'), entity_slug: 'people/alice-example', source: planted('fact source'), visibility: 'world', embedding: null, context: planted('fact context') } as never, { source_id: SRC });+ await engine.mergeOntologyFact({ entitySlug: 'people/alice-example', dimension: 'employer', value: planted('ontology'), confidence: 0.9, source: 'test:x', sourceId: SRC, visibility: 'world' } as never);+ await engine.upsertEventProjection({ depthSlug: 'people/alice-example', eventSlug: 'notes/n1', date: TODAY, summary: planted('event'), sourceId: SRC });+ const page = await engine.getPage('notes/n1', { sourceId: SRC });+ await engine.addTakesBatch([{ page_id: (page as { id: number }).id, row_num: 1, claim: planted('take'), kind: 'view', holder: 'world', weight: 0.8 }] as never);+ for (const slug of ['people/alice-example', 'notes/n1', 'misc/orphan', 'stubs/s1']) {+ const p = await engine.getPage(slug, { sourceId: SRC });+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: p!.compiled_truth, chunk_source: 'compiled_truth', token_count: 8 }], { sourceId: SRC });+ }+}, 120_000);++afterAll(async () => {+ await engine.disconnect();+}, 60_000);++describe('policy classification (ENG-4)', () => {+ test('every op declares a policy; exempt ops carry a reason; the plan-named ops are classified as stated', () => {+ for (const op of operations) {+ const p = op.outputRedaction;+ const valid = p === 'retrieval' || p === 'no_stored_text' ||+ (typeof p === 'object' && ('exempt' in p ? p.exempt.length >= 20 : Array.isArray(p.retrieval.localVerbatim)));+ expect(valid, op.name).toBe(true);+ }+ for (const name of ['get_page', 'fetch', 'get_chunks', 'get_raw_data']) {+ expect(typeof operationsByName[name]!.outputRedaction === 'object' && 'exempt' in (operationsByName[name]!.outputRedaction as object), name).toBe(true);+ }+ for (const name of ['takes_list', 'takes_search', 'search_by_image', 'volunteer_context', 'get_recent_transcripts', 'entity', 'search', 'query']) {+ expect(operationsByName[name]!.outputRedaction, name).toBe('retrieval');+ }+ for (const name of ['recall', 'context_pack', 'delta']) {+ expect(operationsByName[name]!.outputRedaction, name).toEqual({ retrieval: { localVerbatim: ['facts'] } });+ }+ });++ test('an op without a policy does not typecheck', () => {+ // @ts-expect-error outputRedaction is required on every Operation.+ const unclassified: Operation = { name: 'x', description: 'x', params: {}, handler: async () => null };+ expect(unclassified.name).toBe('x');+ });+});++// ─── Seeded sweep: every 'retrieval' and 'no_stored_text' op ───────────────+// `content: false` marks a retrieval op the fixture cannot make return stored+// text (its no-token assertion still runs). Every op not run here is a SKIP+// with its reason, so the table covers the two classes exactly.+type Row = { args: Record<string, unknown>; content?: false; remote?: false } | { skip: string };+const SWEEP: Record<string, Row> = {+ // retrieval — read+ entity: { args: { name: 'people/alice-example' } },+ synthesize: { skip: 'LLM-backed; keyless test env returns no composition. Wrapper coverage is the registration test below.' },+ list_pages: { args: { limit: 100 } },+ search: { args: { query: 'PLANTMARK note body', limit: 20 } },+ query: { args: { query: 'PLANTMARK note body', limit: 20 } },+ assemble_evidence: { args: { hits: [{ source_id: SRC, slug: 'notes/n1', chunk_id: 0 }], return_unit: 'page' } },+ search_by_image: { skip: 'needs image-embedding infra; cross-modal suites own it. Wrapper coverage is the registration test below.' },+ get_links: { args: { slug: 'notes/n1' } },+ get_backlinks: { args: { slug: 'people/alice-example' } },+ traverse_graph: { args: { slug: 'notes/n1', depth: 2 } },+ get_timeline: { args: { slug: 'people/alice-example' } },+ advisor: { skip: 'aggregate advisory over the installed skill stack; advisor suites own it' },+ get_ingest_log: { args: { limit: 50 } },+ find_orphans: { args: {} },+ get_calibration_profile: { args: {}, content: false },+ takes_list: { args: { limit: 50 } },+ takes_search: { args: { query: 'PLANTMARK', limit: 20 } },+ think: { skip: 'LLM-backed; keyless test env. Wrapper coverage is the registration test below.' },+ get_recent_salience: { args: { limit: 50 } },+ find_anomalies: { args: {}, content: false },+ get_recent_transcripts: { skip: 'local-only file walk; covered by test/transcripts-redaction.test.ts' },+ chronicle_day: { args: { date: TODAY } },+ chronicle_on_this_day: { args: { date: TODAY }, content: false },+ chronicle_since: { args: { date: TODAY } },+ chronicle_last_seen: { args: { entity: 'people/alice-example' }, content: false },+ ontology_get: { args: { entity: 'people/alice-example', include_quarantined: true } },+ ontology_conflicts: { args: {}, content: false },+ volunteer_chronicle: { args: { days: 30, limit: 50 } },+ volunteer_context: { args: { window: 'What do we know about people/alice-example?' }, content: false },+ extraction_pending: { args: { limit: 50 } },+ recall: { args: { query: 'PLANTMARK note body', entity: 'people/alice-example' } },+ context_pack: { args: { entities: 'people/alice-example', session_id: randomUUID() } },+ delta: { args: { since: '2000-01-01T00:00:00Z' } },+ find_contradictions: { args: {}, content: false },+ find_experts: { args: { topic: 'PLANTMARK', limit: 10 } },+ find_trajectory: { args: { entity_slug: 'people/alice-example' } },+ code_callers: { skip: 'code-index fixture pipeline; code-intel suites own it' },+ code_callees: { skip: 'code-index fixture pipeline; code-intel suites own it' },+ code_def: { skip: 'code-index fixture pipeline; code-intel suites own it' },+ code_refs: { skip: 'code-index fixture pipeline; code-intel suites own it' },+ code_blast: { skip: 'code-index fixture pipeline; code-intel suites own it' },+ code_flow: { skip: 'code-index fixture pipeline; code-intel suites own it' },+ open_loops: { args: {}, content: false },+ // retrieval — write/admin/agent (add_timeline_entry echoes the stored entry in its receipt)+ add_timeline_entry: { args: { slug: 'notes/n1', date: TODAY, summary: planted('new timeline'), request_id: randomUUID() } },+ ontology_propose: { skip: 'write op; returns the merged ontology row, covered by the wrapper registration test' },+ extract_entities: { skip: 'write op over the extraction pipeline; covered by the wrapper registration test' },+ quarantine_list: { args: {}, content: false },+ get_agent_job: { skip: 'agent-scope job poll needs a submitted agent job; covered by the wrapper registration test' },+ // no_stored_text — read+ search_modes: { args: {} },+ get_tags: { args: { slug: 'notes/n1' } },+ list_link_sources: { args: {} },+ get_brain_identity: { args: {} },+ list_skills: { skip: 'bundled skills catalog from the install tree (throws outside an installed skills dir)' },+ join_brain: { skip: 'shared-skills enrollment needs an explicit member grant; returns membership ids' },+ leave_brain: { skip: 'shared-skills membership op; returns membership ids' },+ resolve_slugs: { args: { partial: 'n1' } },+ takes_scorecard: { args: {} },+ takes_calibration: { args: {} },+ whoami: { args: {} },+ sources_list: { args: {} },+ sources_status: { args: { id: SRC } },+ sources_inspect: { skip: 'local-only inspection of a committed Git repository directory; returns repo metadata, owned by the sources suites' },+ request_tools: { args: { tools: ['get_page'] } },+ connectors_status: { args: {}, remote: false },+ ontology_dimensions: { args: {} },+ entity_identity_list: { args: {} },+ get_active_schema_pack: { args: {} },+ list_schema_packs: { args: {} },+ schema_stats: { args: {} },+ schema_lint: { args: {} },+ schema_graph: { args: {} },+ schema_explain_type: { args: { type: 'note' } },+ schema_review_orphans: { args: { limit: 50 } },+ // no_stored_text — write receipts (the planted content is the caller's own+ // input here; the receipt must not echo it)+ remember: { args: { fact: planted('remembered'), provenance: 'test:sweep', request_id: randomUUID() } },+ put_page: { args: { slug: 'notes/sweep-put', content: `---\ntitle: sweep\n---\n${planted('put body')}`, request_id: randomUUID() } },+ capture: { args: { content: planted('captured'), request_id: randomUUID() } },+ log_ingest: { args: { source_type: 'test', source_ref: 'sweep', pages_updated: ['notes/n1'], summary: planted('logged') } },+ add_tag: { args: { slug: 'notes/n1', tag: 'sweep-tag', request_id: randomUUID() } },+ remove_tag: { args: { slug: 'notes/n1', tag: 'sweep-tag', request_id: randomUUID() } },+ // no_stored_text — admin counters+ search_stats: { args: {} },+ cache_stats: { args: {} },+ get_stats: { args: {} },+ get_usage: { args: {} },+ get_job_stats: { args: {} },+};++const RECEIPT_SKIP = 'mutating write/admin receipt op (ids, status, counts); not run in the read sweep — its receipt shape is pinned by its own suite';++describe('seeded sweep through MCP dispatch (remote = true)', () => {+ test('the sweep table covers every retrieval and no_stored_text op exactly', () => {+ const classes = operations.filter(op => isRetrieval(op) || op.outputRedaction === 'no_stored_text').map(o => o.name).sort();+ const unlisted = classes.filter(n => !(n in SWEEP) && !(operationsByName[n]!.outputRedaction === 'no_stored_text' && operationsByName[n]!.scope !== 'read'));+ expect(unlisted).toEqual([]);+ expect(Object.keys(SWEEP).filter(n => !classes.includes(n))).toEqual([]);+ });++ for (const op of operations.filter(o => isRetrieval(o) || o.outputRedaction === 'no_stored_text')) {+ const row = SWEEP[op.name];+ if (!row) {+ test(`SKIP ${op.name} — ${RECEIPT_SKIP}`, () => {+ expect(op.scope).not.toBe('read');+ });+ continue;+ }+ if ('skip' in row) {+ test(`SKIP ${op.name} — ${row.skip}`, () => {+ expect(row.skip.length).toBeGreaterThan(20);+ });+ continue;+ }+ test(`${isRetrieval(op) ? 'RETRIEVAL' : 'NO_STORED_TEXT'} ${op.name}`, async () => {+ const { text, isError } = await call(op.name, row.args, row.remote ?? true);+ expect(isError, text.slice(0, 300)).toBe(false);+ expect(text.includes(TOKEN), `${op.name} returned the planted token`).toBe(false);+ if (!isRetrieval(op)) {+ if (op.scope === 'read') expect(text.includes(MARK), `${op.name} returned stored text`).toBe(false);+ } else if (row.content !== false) {+ expect(text.includes(MARK), `${op.name}: VACUOUS — no stored text came back`).toBe(true);+ }+ });+ }+});++// ─── Memory verbs (CEO-1, DX-15, ENG-5, ENG-9) ──────────────────────────────++describe('memory verbs redact query-arm text for everyone and facts for remote callers', () => {+ const pageToken = vendorToken();+ const assigned = `${rand(29)}4`;+ const factKey = openaiKey();++ beforeAll(async () => {+ await engine.putPage('notes/verb-page', {+ type: 'note', title: 'verb page', compiled_truth: `verbmark rollout notes ${pageToken}\nGITHUB_TOKEN=${assigned}`, frontmatter: {},+ }, { sourceId: SRC });+ const p = await engine.getPage('notes/verb-page', { sourceId: SRC });+ await installFixtureChunks(engine, 'notes/verb-page', [{ chunk_index: 0, chunk_text: p!.compiled_truth, chunk_source: 'compiled_truth', token_count: 12 }], { sourceId: SRC });+ await engine.insertFact({ fact: `verbfact key ${factKey}`, entity_slug: 'companies/acme-example', source: `test:${factKey}`, visibility: 'world', embedding: null } as never, { source_id: SRC });+ });++ test('recall over MCP: no page token, assignment value or fact key; identities byte-identical', async () => {+ const { text } = await call('recall', { query: 'verbmark rollout', entity: 'companies/acme-example' });+ for (const secret of [pageToken, assigned, factKey]) expect(text.includes(secret)).toBe(false);+ const body = JSON.parse(text);+ const hit = body.results.find((r: { slug: string }) => r.slug === 'notes/verb-page');+ expect(hit.provenance).toBe('notes/verb-page');+ expect(hit.chunk).toContain('<REDACTED:github_token>');+ expect(hit.chunk).toContain('GITHUB_TOKEN=<REDACTED:high_entropy_assignment>');+ const fact = body.facts.find((f: { entity_slug: string }) => f.entity_slug === 'companies/acme-example');+ expect(fact.fact).toBe('verbfact key <REDACTED:openai>');+ expect(fact.provenance).toBe('test:<REDACTED:openai>');+ expect(fact.fact_id).toBe(String(fact.id));+ });++ test('recall from the trusted local CLI: facts raw, query-arm results still redacted', async () => {+ const body = await operationsByName.recall!.handler(localCtx(), { query: 'verbmark rollout', entity: 'companies/acme-example' }) as {+ facts: Array<{ fact: string; source: string; entity_slug: string }>; results: Array<{ chunk: string }>;+ };+ const fact = body.facts.find(f => f.entity_slug === 'companies/acme-example')!;+ expect(fact.fact).toBe(`verbfact key ${factKey}`);+ expect(fact.source).toBe(`test:${factKey}`);+ const out = JSON.stringify(body.results);+ expect(out.includes(pageToken) || out.includes(assigned)).toBe(false);+ });++ test('context_pack and delta over MCP return no fact key; the local CLI gets facts raw but redacted text', async () => {+ for (const [name, args] of [['context_pack', { entities: 'companies/acme-example', session_id: randomUUID() }], ['delta', { since: '2000-01-01T00:00:00Z' }]] as const) {+ const { text } = await call(name, args);+ expect(text.includes(factKey), name).toBe(false);+ expect(text, name).toContain('verbfact key <REDACTED:openai>');+ const local = await operationsByName[name]!.handler(localCtx(), args) as { facts: Array<{ fact: string }>; text: string };+ expect(local.facts.some(f => f.fact === `verbfact key ${factKey}`), name).toBe(true);+ expect(local.text.includes(factKey), name).toBe(false);+ }+ });+});++describe('budgets and the delta cursor are computed from delivered (redacted) text (ENG-5)', () => {+ // 15 distinct characters + a digit: clears the assignment rule's entropy gate every run.+ const distinct = () => [...ALNUM].sort(() => randomBytes(1)[0]! - 128).slice(0, 15).join('') + '3';+ const shortSecrets = Array.from({ length: 30 }, distinct);++ beforeAll(async () => {+ for (const [i, s] of shortSecrets.entries()) {+ await engine.insertFact({ fact: `budgetmark ${i} password=${s}`, entity_slug: 'projects/budget-example', source: 'test:budget', visibility: 'world', embedding: null } as never, { source_id: SRC });+ await engine.putPage(`notes/budget-${String(i).padStart(2, '0')}`, { type: 'note', title: `budget ${i} password=${s}`, compiled_truth: 'b', frontmatter: {} }, { sourceId: SRC });+ }+ });++ test('context_pack: budget_used is the delivered text and stays within the allocation', async () => {+ for (const budget of [60, 90, 140]) {+ const body = JSON.parse((await call('context_pack', { entities: 'projects/budget-example', budget_tokens: budget, session_id: randomUUID() })).text);+ for (const s of shortSecrets) expect(body.text.includes(s)).toBe(false);+ expect(body.budget_used).toBe(estimateTokens(body.text));+ expect(body.budget_used).toBeLessThanOrEqual(budget);+ expect(body.dropped_count).toBeGreaterThan(0);+ }+ });++ test('delta: budget_used is the delivered text and the cursor never passes an undelivered page', async () => {+ const body = JSON.parse((await call('delta', { since: '2000-01-01T00:00:00Z', budget_tokens: 200 })).text);+ for (const s of shortSecrets) expect(JSON.stringify(body).includes(s)).toBe(false);+ expect(body.budget_used).toBe(estimateTokens(body.text));+ expect(body.budget_used).toBeLessThanOrEqual(200);+ expect(body.has_more).toBe(true);+ expect(body.pages.length).toBeGreaterThan(0);+ const last = body.pages[body.pages.length - 1];+ expect(body.next_cursor).toEqual({ since: last.updated_at, slug: last.slug });+ for (const p of body.pages) expect(body.text).toContain(`\`${p.slug}\``);+ });++ test('context_pack text over 64 KiB is redacted in full, never replaced with output_limit', async () => {+ const big = vendorToken();+ for (let i = 0; i < 40; i++) {+ await engine.insertFact({ fact: `bigmark ${i} ${big} ${'lorem ipsum dolor '.repeat(500)}`, entity_slug: 'projects/big-example', source: 'test:big', visibility: 'world', embedding: null } as never, { source_id: SRC });+ }+ const body = JSON.parse((await call('context_pack', { entities: 'projects/big-example', session_id: randomUUID() })).text);+ expect(body.text.length).toBeGreaterThan(64 * 1024);+ expect(body.text.includes(big)).toBe(false);+ expect(body.text).toContain('<REDACTED:github_token>');+ expect(body.text).not.toContain('<REDACTED:output_limit>');+ });+});diff --git a/test/search/output-redaction.test.ts b/test/search/output-redaction.test.tsindex 68b00b7e06..3d5be478d1 100644--- a/test/search/output-redaction.test.ts+++ b/test/search/output-redaction.test.ts@@ -1,8 +1,10 @@import { describe, expect, test } from 'bun:test';+import { randomBytes } from 'node:crypto';import {- redactRetrievalOutput, OUTPUT_REDACTION_MAX_FIELD_CHARS,+ redactRetrievalOutput, withOutputRedaction, OUTPUT_REDACTION_MAX_FIELD_CHARS,OUTPUT_REDACTION_MAX_TOTAL_CHARS, OUTPUT_REDACTION_LIMIT,} from '../../src/core/search/output-redaction.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';import { encodeDeepResearchId } from '../../src/core/deep-research-id.ts';const key = 'sk-proj-' + 'syntheticfixture19'.repeat(3);@@ -116,3 +118,272 @@ describe('bounded retrieval display redaction', () => {expect(output.meta.__proto__.text).toBe('<REDACTED:openai>');});});++// ── #5348 shape port (B2, CEO-15) ───────────────────────────────────────────+// Every credential-shaped fixture is assembled at runtime from random parts+// (CEO-10): no literal token, key body or userinfo URL lives in this file.++const ALNUM = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';+function rand(n: number, alphabet = ALNUM): string {+ let out = '';+ for (const b of randomBytes(n)) out += alphabet[b % alphabet.length];+ return out;+}+/** Random alnum with at least one digit (the assignment rule's entropy gate). */+const secretValue = (n: number) => rand(n - 1) + String(randomBytes(1)[0]! % 10);+const hex = (n: number) => rand(n, '0123456789abcdef');+const b64Line = (n: number) => randomBytes(n).toString('base64').slice(0, n);+const fence = '-'.repeat(5);+const keyLabel = ['PRIVATE', 'KEY'].join(' ');+const begin = (label = keyLabel) => `${fence}BEGIN ${label}${fence}`;+const end = (label = keyLabel) => `${fence}END ${label}${fence}`;+const redact = (text: string) => redactRetrievalOutput([{ chunk_text: text }], {}).results[0]!.chunk_text;++describe('retrieval output: assignment rule and #5348 shapes (B1/B2)', () => {+ test('KEY=value assignments reach the caller redacted, with no fragment of the value', () => {+ for (const keyName of ['GITHUB_TOKEN=', 'API_KEY=', 'client_secret: ', 'password = ', 'DB_PASSWORD="']) {+ const value = secretValue(32);+ const out = redact(`config ${keyName}${value}${keyName.endsWith('"') ? '"' : ''} end`);+ expect(out, keyName).not.toContain(value.slice(0, 12));+ expect(out, keyName).not.toContain(value.slice(-12));+ expect(out, keyName).toContain('<REDACTED:high_entropy_assignment>');+ }+ });++ test('an assigned value echoed bare in another field is scrubbed there too, trailing period included', () => {+ const value = secretValue(28);+ const [row] = redactRetrievalOutput([{ chunk_text: `set TOKEN=${value}. then retry`, title: `rotate ${value} today` }], {}).results;+ expect(JSON.stringify(row)).not.toContain(value);+ expect(row!.chunk_text).toBe('set TOKEN=<REDACTED:high_entropy_assignment>. then retry');+ expect(row!.title).toBe('rotate <REDACTED:high_entropy_assignment> today');+ });++ test('values longer than any old cap are redacted with no surviving tail', () => {+ const longAssigned = secretValue(300);+ expect(redact(`API_KEY=${longAssigned}`)).not.toContain(longAssigned.slice(-40));+ const longBearer = rand(300);+ expect(redact(`Authorization: Bearer ${longBearer}`)).not.toContain(longBearer.slice(-40));+ const longGithub = ['gh', 'p_'].join('') + rand(300);+ expect(redact(longGithub)).not.toContain(longGithub.slice(-40));+ });++ test('vendor-prefixed tokens, JWTs, bearer headers and complete private keys are redacted', () => {+ const pemBody = Array.from({ length: 6 }, () => b64Line(64)).join('\n');+ const shapes = [+ ['gh', 'p_'].join('') + rand(36),+ ['github', 'pat', rand(22), rand(59)].join('_'),+ ['sk', 'proj', rand(48)].join('-'),+ ['sk', 'ant', 'api03', rand(48)].join('-'),+ ['xoxb', String(100000000000 + (randomBytes(4).readUInt32BE() % 1e9)), rand(24)].join('-'),+ ['AK', 'IA'].join('') + rand(16, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),+ ['AI', 'za'].join('') + rand(35),+ ['sk', 'live', rand(32)].join('_'),+ ['SG', rand(22), rand(43)].join('.'),+ ['eyJ' + rand(18), 'eyJ' + rand(24), rand(32)].join('.'),+ `Authorization: Bearer ${rand(40)}`,+ [begin(), pemBody, end()].join('\n'),+ ];+ for (const credential of shapes) {+ const out = redact(`prefix ${credential} suffix`);+ expect(out).toContain('<REDACTED:');+ expect(out.startsWith('prefix ')).toBe(true);+ expect(out.endsWith(' suffix')).toBe(true);+ for (const part of credential.split(/[\s\n]+/).filter(p => p.length >= 16)) expect(out).not.toContain(part);+ }+ });++ test('every occurrence in one field is redacted, and redaction is idempotent', () => {+ const token = ['gh', 'p_'].join('') + rand(36);+ const assigned = `password=${secretValue(24)}`;+ const once = redactRetrievalOutput([{ chunk_text: `${token} and ${token}; ${assigned}` }], {});+ expect(once.results[0]!.chunk_text.match(/<REDACTED:github_token>/g)).toHaveLength(2);+ expect(redactRetrievalOutput(once.results, once.meta)).toEqual(once);+ for (const marked of ['password="<REDACTED:high_entropy_assignment>"', 'x <REDACTED:high_entropy_assignment> y <REDACTED:google_api_key> z']) {+ expect(redact(marked)).toBe(marked);+ }+ });++ test('prose, placeholders, hashes, ids, public keys and non-credential URLs stay byte-identical', () => {+ const guards = [+ 'see Basic concepts in the docs',+ 'Basic responsibilities include on-call',+ 'basic internationalization support',+ 'Authorization: Basic auth is deprecated',+ 'Bearer of bad news',+ 'the SG. prefix is SendGrid',+ 'export GITHUB_TOKEN=',+ 'password: ****',+ 'api_key = TODO',+ 'set SECRET to whatever the vault returns',+ 'the token is stored in the keychain, not in the repo',+ 'rotate the api key quarterly and record the date',+ ['gh', 'p_test_fixture'].join(''),+ hex(40),+ '550e8400-e29b-41d4-a716-446655440000',+ `ssh-ed25519 ${b64Line(68)} me@host`,+ 'token_url: "https://accounts.example/o/oauth2/token"',+ 'credentials_path: "/home/alice-example/.config/gcloud/creds.json"',+ 'https://[email protected]/path',+ 'https://host.example/a@b',+ 'http://localhost:5173/@vite/client',+ 'https://registry.example/@scope/pkg',+ 'https://host.example:443/@user',+ `id: dop_v1_${hex(65)}`,+ `To find leaks, search for ${end()} in your repo, then rotate.`,+ ];+ for (const safe of guards) expect(redact(safe), safe).toBe(safe);+ });++ test('a document that quotes the BEGIN marker keeps its surrounding prose', () => {+ const out = redact(`To find leaks, search for the string ${begin()} in your repo, then rotate.`);+ expect(out.startsWith('To find leaks, search for the string ')).toBe(true);+ expect(out.endsWith(' in your repo, then rotate.')).toBe(true);+ });++ test('a base64 run longer than 128 chars after a header stays the documented accepted miss', () => {+ const run = b64Line(200);+ const out = redact(`${begin()}\n${run}`);+ expect(out).toContain('<REDACTED:private_key_pem>');+ expect(out).toContain(run);+ });++ test('20k unterminated fences and END-only fences scan in linear time when uncapped', () => {+ for (const input of [`${begin('PUBLIC KEY')}\n`.repeat(20_000), `${begin()}\n`.repeat(20_000), `${end()}\n`.repeat(20_000)]) {+ const t0 = performance.now();+ redactRetrievalOutput([{ chunk_text: input }], {}, { uncapped: true });+ expect(performance.now() - t0).toBeLessThan(2000);+ }+ });+});++// Expected RED until lane S1 (src/core/secret-scan.ts A1-A5) merges: these+// shapes need the new url_credentials / basic_auth / digitalocean patterns,+// truncated/split private-key body claims and punctuated assignment values.+describe('retrieval output: shapes that need the S1 scanner patterns', () => {+ test('assigned passwords may start with or contain punctuation', () => {+ for (const value of [`!${rand(20)}9`, `$${rand(20)}7`, `${rand(10)}!#%${rand(20)}3`]) {+ const out = redact(`password=${value} tail`);+ expect(out).not.toContain(value.slice(-12));+ expect(out).toContain('<REDACTED:high_entropy_assignment>');+ expect(out.endsWith(' tail')).toBe(true);+ }+ const quoted = `ab!#%${rand(16)}<${rand(12)}5`;+ expect(redact(`DB_PASSWORD="${quoted}"`)).not.toContain(quoted.slice(-12));+ });++ test('http(s) userinfo credentials are redacted while host and path stay', () => {+ const pass = rand(24);+ const url = ['https', '://user:', pass, '@example.invalid/path'].join('');+ expect(redact(`clone ${url} now`)).toBe('clone <REDACTED:url_credentials>example.invalid/path now');+ const tok = ['gh', 'p_'].join('') + rand(36);+ const clone = ['https', '://x-access-token:', tok, '@github.com/acme-example/repo.git'].join('');+ expect(redact(clone)).not.toContain(tok);+ });++ test('Authorization: Basic is redacted in header and bare forms, any case, short values included', () => {+ const cred = Buffer.from(`${rand(8)}:${rand(16)}`).toString('base64');+ for (const header of [`Authorization: Basic ${cred}`, `authorization: basic ${cred}`, `AUTHORIZATION: BASIC ${cred}`, `Basic ${cred}`]) {+ const out = redact(header);+ expect(out, header).not.toContain(cred);+ expect(out, header).toContain('<REDACTED:basic_auth>');+ }+ const short = Buffer.from('u:p').toString('base64');+ expect(redact(`Authorization: Basic ${short}`)).not.toContain(short);+ });++ test('DigitalOcean tokens are redacted', () => {+ for (const kind of ['dop', 'doo', 'dor']) {+ const token = `${kind}_v1_${hex(64)}`;+ const out = redact(`token ${token} end`);+ expect(out).not.toContain(token);+ expect(out).toContain('<REDACTED:digitalocean>');+ }+ });++ test('a private key cut before its END fence loses its body, and preceding prose survives', () => {+ const lines = [b64Line(64), b64Line(64), b64Line(40)];+ const out = redact(`deploy notes:\n${begin('RSA PRIVATE KEY')}\n${lines.join('\n')}`);+ expect(out.startsWith('deploy notes:\n')).toBe(true);+ for (const l of lines) expect(out).not.toContain(l);+ });++ test('a chunk that starts mid-key loses the body before its END fence', () => {+ const lines = [b64Line(30), b64Line(64), b64Line(64)];+ const out = redact(`${lines.join('\n')}\n${end()}\nafter the key`);+ for (const l of lines) expect(out).not.toContain(l);+ expect(out.endsWith('after the key')).toBe(true);+ });++ test('JSON-escaped, indented, CRLF and RFC 1421 key bodies are redacted', () => {+ const body = [b64Line(64), b64Line(64)];+ const cases = [+ `{"private_key":"${begin()}\\n${body.join('\\n')}\\n${end()}\\n"}`,+ `key: |\n ${begin()}\n ${body.join('\n ')}`,+ `${begin()}\r\n${body.join('\r\n')}`,+ [begin('RSA PRIVATE KEY'), 'Proc-Type: 4,ENCRYPTED', `DEK-Info: AES-128-CBC,${hex(32).toUpperCase()}`, '', ...body].join('\n'),+ ];+ for (const text of cases) {+ const out = redact(`notes\n${text}`);+ for (const l of body) expect(out, text.slice(0, 40)).not.toContain(l);+ expect(out.startsWith('notes\n')).toBe(true);+ }+ });+});++describe('retrieval output: identity fields, dates and options', () => {+ test('fact_id and entity_slug stay byte-identical; dates survive the copy', () => {+ const value = secretValue(30);+ const when = new Date('2026-08-01T00:00:00Z');+ const [row] = redactRetrievalOutput([{ fact_id: `password=${value}`, entity_slug: `people/password=${value}`, fact: `password=${value}`, valid_from: when }], {}).results;+ expect(row!.fact_id).toBe(`password=${value}`);+ expect(row!.entity_slug).toBe(`people/password=${value}`);+ expect(row!.fact).toBe('password=<REDACTED:high_entropy_assignment>');+ expect(row!.valid_from).toBeInstanceOf(Date);+ expect(row!.valid_from.getTime()).toBe(when.getTime());+ });++ test('uncapped scans an oversized field whole instead of withholding it', () => {+ const token = ['gh', 'p_'].join('') + rand(36);+ const text = 'x'.repeat(OUTPUT_REDACTION_MAX_FIELD_CHARS) + ` ${token} tail`;+ const [row] = redactRetrievalOutput([{ text }], {}, { uncapped: true }).results;+ expect(row!.text.endsWith(' <REDACTED:github_token> tail')).toBe(true);+ expect(row!.text.length).toBeGreaterThan(OUTPUT_REDACTION_MAX_FIELD_CHARS);+ });++ test('verbatim keys of each top-level result are returned unscanned, nested keys are not', () => {+ const token = ['gh', 'p_'].join('') + rand(36);+ const [row] = redactRetrievalOutput([{ facts: [{ fact: token }], text: token, nested: { facts: token } }], {}, { verbatim: ['facts'] }).results;+ expect(row!.facts[0]!.fact).toBe(token);+ expect(row!.text).toBe('<REDACTED:github_token>');+ expect(row!.nested.facts).toBe('<REDACTED:github_token>');+ });+});++describe('withOutputRedaction (ENG-4 registration wrapper)', () => {+ const token = () => ['gh', 'p_'].join('') + rand(36);+ const ctx = (remote: boolean) => ({ remote }) as unknown as OperationContext;++ test('a retrieval op is redacted on every return path, including an early return', async () => {+ const secret = token();+ const handler = async (_ctx: OperationContext, p: Record<string, unknown>) =>+ p.early ? { text: `early ${secret}` } : { results: [{ chunk: secret, slug: 'notes/a' }] };+ const wrapped = withOutputRedaction({ handler, outputRedaction: 'retrieval' });+ expect(await wrapped(ctx(false), { early: true })).toEqual({ text: 'early <REDACTED:github_token>' });+ expect(await wrapped(ctx(true), {})).toEqual({ results: [{ chunk: '<REDACTED:github_token>', slug: 'notes/a' }] });+ });++ test('localVerbatim keys stay raw only for the trusted local caller', async () => {+ const secret = token();+ const handler = async () => ({ facts: [{ fact: secret }], text: secret });+ const wrapped = withOutputRedaction({ handler, outputRedaction: { retrieval: { localVerbatim: ['facts'] } } });+ expect(await wrapped(ctx(false), {})).toEqual({ facts: [{ fact: secret }], text: '<REDACTED:github_token>' });+ expect(await wrapped(ctx(true), {})).toEqual({ facts: [{ fact: '<REDACTED:github_token>' }], text: '<REDACTED:github_token>' });+ expect(await wrapped({ remote: undefined } as unknown as OperationContext, {})).toEqual({ facts: [{ fact: '<REDACTED:github_token>' }], text: '<REDACTED:github_token>' });+ });++ test('exempt and no_stored_text ops keep their handler untouched', () => {+ const handler = async () => ({});+ expect(withOutputRedaction({ handler, outputRedaction: { exempt: 'page read' } })).toBe(handler);+ expect(withOutputRedaction({ handler, outputRedaction: 'no_stored_text' })).toBe(handler);+ });+});diff --git a/test/secret-scan-credential-shapes.test.ts b/test/secret-scan-credential-shapes.test.tsnew file mode 100644index 0000000000..d22d3730d2--- /dev/null+++ b/test/secret-scan-credential-shapes.test.ts@@ -0,0 +1,294 @@+/**+ * secret-scan credential shapes added or widened by the security fix wave:+ * A2 `url_credentials` (http/https userinfo with a password, ENG-14+ * placeholders, CEO-12b miss), A3 `basic_auth` (decode-to-`user:pass`+ * validate, ENG-15 bounds), A4 `digitalocean` (DX-5 name, hard right edge),+ * A5 punctuated assignment values (two compiled variants, ENG-13 rejections,+ * regex-expressed trailing trim, idempotence), CEO-12 ordering and the DX-5+ * `since` field, CRLF across every new line pattern (ENG-17).+ *+ * Every credential-shaped value is random and assembled at runtime from+ * parts (CEO-10): no literal secret, no literal URL with userinfo.+ */+import { describe, expect, test } from 'bun:test';+import { randomBytes } from 'crypto';+import { patternSince, redactFindings, scanText } from '../src/core/secret-scan.ts';++const ALNUM = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';+/** Random alphanumeric string that always carries a digit (entropy rule input). */+function rand(n: number): string {+ const bytes = randomBytes(n);+ let s = '';+ for (let i = 0; i < n; i++) s += ALNUM[bytes[i]! % ALNUM.length];+ return s.slice(0, n - 1) + String(bytes[0]! % 10);+}+const hex = (n: number) => randomBytes(Math.ceil(n / 2)).toString('hex').slice(0, n);+const PLACEHOLDER_NONCE = 'GSTACK_EXAMPLE_NONCE';+const SCHEME_SEP = ':' + '//';+/** `scheme://user:password@host/path`, assembled from parts. */+const userinfoUrl = (scheme: string, user: string, password: string, rest = 'host.example/path') =>+ [scheme, SCHEME_SEP, user, ':', password, '@', rest].join('');+const basic = (userPass: string) => Buffer.from(userPass).toString('base64');+const REDACTED = (p: string) => `<REDACTED:${p}>`;++describe('A2 url_credentials: http(s) userinfo carrying a password', () => {+ test('fires on http and https in any case; the value is the userinfo span, host and path kept', () => {+ const pw = rand(24);+ for (const scheme of ['https', 'http', 'HTTPS', 'Http']) {+ const url = userinfoUrl(scheme, 'x-access-token', pw);+ const findings = scanText(`git clone ${url}.git`);+ expect(findings.map((f) => f.pattern)).toEqual(['url_credentials']);+ expect(JSON.stringify(findings).includes(pw)).toBe(false);+ expect(redactFindings(`git clone ${url}.git`).text).toBe(`git clone ${REDACTED('url_credentials')}host.example/path.git`);+ }+ });++ test('the design reversal: a short user:pw pair on an https URL now fires', () => {+ expect(scanText(userinfoUrl('https', 'user', 'pw')).map((f) => f.pattern)).toEqual(['url_credentials']);+ });++ test('a password made of the approved placeholder nonce still fires (it is not a placeholder SHAPE)', () => {+ expect(scanText(userinfoUrl('https', 'alice-example', PLACEHOLDER_NONCE)).map((f) => f.pattern)).toEqual(['url_credentials']);+ });++ test('URLs without a password, or with an @ in the path, stay untouched', () => {+ const at = '@';+ for (const s of [+ ['https', SCHEME_SEP, 'user', at, 'host'].join(''),+ ['https', SCHEME_SEP, 'host/a', at, 'b'].join(''),+ ['http', SCHEME_SEP, 'localhost:5173/', at, 'vite/client'].join(''),+ ['https', SCHEME_SEP, 'registry.example/', at, 'scope/pkg'].join(''),+ ['https', SCHEME_SEP, 'host:443/', at, 'user'].join(''),+ ]) {+ expect(scanText(s)).toEqual([]);+ expect(redactFindings(s, { highEntropy: true }).text).toBe(s);+ }+ });++ test('ENG-14: placeholder-shaped passwords do not fire', () => {+ for (const pw of ['<password>', '<PASSWORD>', '${DB_PASSWORD}', '$PASSWORD', '****', 'xxxxxxxx', 'XXXX']) {+ expect(scanText(userinfoUrl('https', 'user', pw))).toEqual([]);+ }+ });++ test('CEO-12b: a password carrying a literal `/`, `?` or `#` is the accepted miss', () => {+ for (const sep of ['/', '?', '#']) {+ expect(scanText(userinfoUrl('https', 'user', `${rand(8)}${sep}${rand(8)}`))).toEqual([]);+ }+ });++ test('bounds: user 0-128, password 1-256', () => {+ expect(scanText(userinfoUrl('https', '', rand(16))).map((f) => f.pattern)).toEqual(['url_credentials']);+ expect(scanText(userinfoUrl('https', 'u', rand(256))).map((f) => f.pattern)).toEqual(['url_credentials']);+ expect(scanText(userinfoUrl('https', 'u', rand(257)))).toEqual([]);+ expect(scanText(userinfoUrl('https', 'u'.repeat(129), rand(12)))).toEqual([]);+ });++ test('a vendor token used as the password keeps its vendor attribution; the userinfo around it is still covered', () => {+ const ghp = ['ghp', rand(36)].join('_');+ const { text, redactions } = redactFindings(userinfoUrl('https', 'x-access-token', ghp, 'github.com/org/repo'));+ expect(text.includes(ghp)).toBe(false);+ expect(text.includes('x-access-token')).toBe(false);+ expect(redactions.map((r) => r.pattern)).toContain('github_token');+ expect(text.endsWith('github.com/org/repo')).toBe(true);+ });+});++describe('A3 basic_auth: a Basic credential that decodes to user:pass', () => {+ test('header form, any case, including the short u:p encoding', () => {+ const short = basic('u:p');+ expect(short.length).toBe(4);+ const long = basic(`alice-example:${rand(20)}`);+ for (const line of [+ `Authorization: Basic ${short}`,+ `authorization: basic ${short}`,+ `AUTHORIZATION:BASIC ${long}`,+ `Proxy-Authorization: Basic ${long}`,+ `curl -H "Authorization: Basic ${long}" https://api.example`,+ ]) {+ const { text, redactions } = redactFindings(line);+ expect(redactions.map((r) => r.pattern)).toEqual(['basic_auth']);+ expect(text.includes(short) || text.includes(long)).toBe(false);+ }+ expect(redactFindings(`Authorization: Basic ${short}`).text).toBe(`Authorization: Basic ${REDACTED('basic_auth')}`);+ });++ test('bare form needs 16+ chars', () => {+ const v = basic(`svc:${rand(14)}`);+ expect(v.length).toBeGreaterThanOrEqual(16);+ expect(scanText(`use Basic ${v} for the proxy`).map((f) => f.pattern)).toEqual(['basic_auth']);+ expect(scanText(`use Basic ${basic('u:p')} for the proxy`)).toEqual([]);+ });++ test('prose after the word Basic stays untouched', () => {+ for (const s of [+ 'Basic responsibilities include on-call',+ 'basic internationalization support',+ 'Authorization: Basic auth is deprecated',+ 'see Basic concepts in the docs',+ 'Basic AAAAAAAAAAAAAAAAAAAAAAAA', // decodes to NUL bytes+ ]) {+ expect(scanText(s)).toEqual([]);+ expect(redactFindings(s, { highEntropy: true }).text).toBe(s);+ }+ });++ test('ENG-15: the value is bounded 4-2048 with a hard right edge; a longer run is not claimed', () => {+ const at2048 = basic(`u:${'a'.repeat(1534)}`);+ expect(at2048.length).toBe(2048);+ expect(scanText(`Authorization: Basic ${at2048}`).map((f) => f.pattern)).toEqual(['basic_auth']);+ const over = basic(`u:${'a'.repeat(1540)}`);+ expect(over.length).toBeGreaterThan(2048);+ expect(scanText(`Authorization: Basic ${over}`)).toEqual([]);+ });++ test('basic_auth is not in the bearer echo family: a bare echo of the value is not scrubbed', () => {+ const v = basic(`alice-example:${rand(20)}`);+ const { text, echoValues } = redactFindings(`Authorization: Basic ${v}\nlater: ${v}`);+ expect(echoValues.size).toBe(0);+ expect(text.split('\n')[1]).toBe(`later: ${v}`);+ });+});++describe('A4 digitalocean', () => {+ test('dop_/doo_/dor_ v1 tokens fire as digitalocean', () => {+ for (const p of ['dop', 'doo', 'dor']) {+ const tok = [p, 'v1', hex(64)].join('_');+ const findings = scanText(`DO token ${tok} end`);+ expect(findings.map((f) => f.pattern)).toEqual(['digitalocean']);+ expect(redactFindings(`t ${tok}`).text).toBe(`t ${REDACTED('digitalocean')}`);+ }+ });++ test('hard right edge and exact hex body: 65 hex, 63 hex, uppercase hex and an embedded prefix do not fire', () => {+ for (const s of [+ ['dop', 'v1', hex(64) + 'a'].join('_'),+ ['dop', 'v1', hex(63)].join('_'),+ ['dop', 'v1', hex(64).toUpperCase().replace(/[0-9]/g, 'A')].join('_'),+ 'x' + ['dop', 'v1', hex(64)].join('_'),+ ]) {+ expect(scanText(s)).toEqual([]);+ }+ });+});++describe('A5 high_entropy_assignment: punctuated values', () => {+ const he = (s: string) => redactFindings(s, { highEntropy: true });+ const T = REDACTED('high_entropy_assignment');++ test('unquoted values with password punctuation are claimed whole', () => {+ for (const v of [`!${rand(14)}`, `${rand(10)}!#%${rand(10)}`, `${rand(8)}$*@^~${rand(8)}`, `${rand(8)}.?<>${rand(8)}`]) {+ expect(he(`password=${v}`).text).toBe(`password=${T}`);+ expect(he(`DB_PASSWORD: ${v}`).text).toBe(`DB_PASSWORD: ${T}`);+ }+ });++ test('quoted values are any run of non-quote, non-whitespace characters', () => {+ const v = `${rand(10)}!#%&()<${rand(10)}`;+ expect(he(`DB_PASSWORD="${v}"`).text).toBe(`DB_PASSWORD="${T}"`);+ expect(he(`{"api_key": '${v}'}`).text).toBe(`{"api_key": '${T}'}`);+ });++ test('`&`, `,`, `;` and brackets end an unquoted value: query parameters, SQL SET lists and code calls survive', () => {+ const tok = rand(24);+ expect(he(`?token=${tok}&page=2`).text).toBe(`?token=${T}&page=2`);+ expect(he('token = getToken(x1, y2, zz3)').text).toBe('token = getToken(x1, y2, zz3)');+ expect(he('password = process.env.DB_PASSWORD_2').text).toBe('password = process.env.DB_PASSWORD_2');+ const sql = 'SET execution_token=NULL,claim_expires_at=NULL,error_code=$3,updated_at=now()';+ expect(he(sql).text).toBe(sql);+ expect(he(`cookie: session_token=${tok}; path=/`).text).toBe(`cookie: session_token=${T}; path=/`);+ });++ test('trailing sentence punctuation is not part of an unquoted value, and the bare echo still scrubs', () => {+ const tok = rand(24);+ for (const tail of ['.', ',', ';', '?', '!', '...', '.)']) {+ expect(he(`TOKEN=${tok}${tail}`).text).toBe(`TOKEN=${T}${tail}`);+ }+ expect(he(`set TOKEN=${tok}. Then later the agent printed ${tok} again`).text)+ .toBe(`set TOKEN=${T}. Then later the agent printed ${T} again`);+ });++ test('a vendor token at the start of a punctuated value keeps its attribution; the tail is still covered', () => {+ const ghp = ['ghp', rand(36)].join('_');+ const tail = `!tail-${rand(16)}`;+ const { text } = he(`password=${ghp}${tail}`);+ expect(text.includes(ghp)).toBe(false);+ expect(text.includes(tail)).toBe(false);+ });++ test('ENG-13: URLs, paths and shell expansions are not secrets', () => {+ for (const s of [+ `token_url: "https://oauth2.example.com/token?v=${rand(6)}"`,+ `credentials_path: "/home/alice-example/.config/app${rand(4)}/creds.json"`,+ `credentials_path: /home/alice-example/.config/app${rand(4)}/creds.json`,+ `secret_file = ./secrets/prod${rand(6)}.env.json`,+ `api_key_file: ~/keys/${rand(10)}.txt`,+ `password: "\${{ secrets.DB_PASSWORD_${rand(6)} }}"`,+ `TOKEN=$(cat /run/secrets/token${rand(6)})`,+ ]) {+ expect(he(s).text).toBe(s);+ }+ });++ test('a pure base64 value that starts with `/` still fires (one random secret in 64 does)', () => {+ const v = `/${rand(20)}+${rand(10)}/${rand(8)}`;+ expect(he(`aws_secret_access_key = ${v}`).text).toBe(`aws_secret_access_key = ${T}`);+ });++ test('idempotence: redacting redacted output changes nothing', () => {+ const v = `${rand(10)}!#%<${rand(10)}`;+ const once = he(`password="${v}" and TOKEN=${rand(20)}. done`).text;+ expect(once).toBe(`password="${T}" and TOKEN=${T}. done`);+ expect(he(once).text).toBe(once);+ expect(he(once).redactions).toEqual([]);+ });++ test('prose and placeholder assignments stay byte-identical', () => {+ for (const s of [+ 'export GITHUB_TOKEN=',+ 'password: ****',+ 'api_key = TODO',+ 'the token is stored in the keychain, not in the repo',+ `password=${PLACEHOLDER_NONCE}`,+ 'password=<your-password-here>',+ ]) {+ expect(he(s).text).toBe(s);+ }+ });+});++describe('CEO-12 ordering and DX-5 since', () => {+ test('vendor shapes win attribution over the appended catch-alls', () => {+ const tok = ['dop', 'v1', hex(64)].join('_');+ expect(scanText(`Authorization: Bearer ${tok}`).map((f) => f.pattern)).toEqual(['digitalocean']);+ });++ test('every new or changed rule carries since; unchanged rules do not', () => {+ const since = patternSince('url_credentials');+ expect(since).toMatch(/^\d+\.\d+\.\d+\.\d+$/);+ for (const p of ['basic_auth', 'digitalocean', 'private_key_pem']) expect(patternSince(p)).toBe(since);+ for (const p of ['openai', 'bearer', 'db_url_credentials', 'high_entropy_assignment']) expect(patternSince(p)).toBeUndefined();+ const [f] = scanText(`t ${['dop', 'v1', hex(64)].join('_')}`);+ expect(f!.since).toBe(since);+ const [g] = scanText(`k ${['ghp', rand(36)].join('_')}`);+ expect(g!.since).toBeUndefined();+ });+});++describe('ENG-17: CRLF line ends behave like LF for every new line pattern', () => {+ test('the same findings and the same redacted bytes before the line end', () => {+ const lines = [+ `clone ${userinfoUrl('https', 'u', rand(20))}`,+ `Authorization: Basic ${basic(`alice-example:${rand(12)}`)}`,+ `do ${['dop', 'v1', hex(64)].join('_')}`,+ `password=${rand(10)}!#%${rand(6)}`,+ `token="${rand(10)}<${rand(6)}"`,+ `TOKEN=${rand(20)}.`,+ ];+ const lf = redactFindings(lines.join('\n') + '\n', { highEntropy: true });+ const crlf = redactFindings(lines.join('\r\n') + '\r\n', { highEntropy: true });+ expect(crlf.redactions.map((r) => r.pattern)).toEqual(lf.redactions.map((r) => r.pattern));+ expect(crlf.redactions.length).toBe(lines.length);+ expect(crlf.text).toBe(lf.text.replace(/\n/g, '\r\n'));+ });+});diff --git a/test/secret-scan-fp-budget.test.ts b/test/secret-scan-fp-budget.test.tsnew file mode 100644index 0000000000..1ff833b208--- /dev/null+++ b/test/secret-scan-fp-budget.test.ts@@ -0,0 +1,49 @@+/**+ * Secret-scan false-positive budget on the synthetic brain-like fixture+ * (security fix wave CEO-18 thresholds). The fixture comes from+ * scripts/secret-scan-fp-budget.ts, which also measures NEW hits against a+ * base git ref over this repo's src/, docs/ and skills/ (a maintainer tool;+ * the base ref is not available in every CI checkout). Here the thresholds+ * are enforced against the current scanner alone:+ * - the non-secret part gains no finding in either mode (so no push block,+ * no dropped context entry, no refused relay, no redaction);+ * - the secret-bearing part is fully redacted.+ */+import { describe, expect, test } from 'bun:test';+import { buildSyntheticBrainCorpus, newFindings } from '../scripts/secret-scan-fp-budget.ts';+import { redactFindings, scanText } from '../src/core/secret-scan.ts';++const corpus = buildSyntheticBrainCorpus();++describe('synthetic brain-like fixture: the non-secret part', () => {+ for (const doc of corpus.filter((d) => d.kind === 'clean')) {+ test(`${doc.id}: no finding with or without highEntropy, text byte-identical after redaction`, () => {+ expect(scanText(doc.text)).toEqual([]);+ expect(scanText(doc.text, { highEntropy: true })).toEqual([]);+ expect(redactFindings(doc.text, { highEntropy: true }).text).toBe(doc.text);+ });+ }+});++describe('synthetic brain-like fixture: the secret-bearing part', () => {+ for (const doc of corpus.filter((d) => d.kind === 'secret')) {+ test(`${doc.id}: every planted value is redacted`, () => {+ const withEntropy = redactFindings(doc.text, { highEntropy: true }).text;+ const without = redactFindings(doc.text).text;+ for (const v of doc.secrets ?? []) {+ expect(withEntropy.includes(v)).toBe(false);+ expect(without.includes(v)).toBe(false);+ }+ for (const v of doc.assignmentSecrets ?? []) expect(withEntropy.includes(v)).toBe(false);+ });+ }+});++describe('newFindings (the measurement diff)', () => {+ test('a multiset difference on (pattern, fingerprint)', () => {+ const f = (pattern: string, fingerprint: string) => ({ pattern, fingerprint, line: 1 });+ const before = [f('a', '1'), f('a', '1'), f('b', '2')];+ const after = [f('a', '1'), f('a', '1'), f('a', '1'), f('b', '3')];+ expect(newFindings(before, after)).toEqual([f('a', '1'), f('b', '3')]);+ });+});diff --git a/test/secret-scan-perf.test.ts b/test/secret-scan-perf.test.tsindex 353237329c..cd10898921 100644--- a/test/secret-scan-perf.test.ts+++ b/test/secret-scan-perf.test.ts@@ -20,7 +20,7 @@*/import { describe, expect, test } from 'bun:test';import { createHash } from 'crypto';-import { ECHO_MAX_UNIQUE, ECHO_MAX_VALUE_CHARS, redactFindings, scanText } from '../src/core/secret-scan.ts';+import { ECHO_MAX_UNIQUE, ECHO_MAX_VALUE_CHARS, privateKeySpans, redactFindings, scanText } from '../src/core/secret-scan.ts';function elapsedMs(fn: () => void): number {const t0 = performance.now();@@ -208,7 +208,7 @@ describe('jwt + high_entropy_assignment are linear on adversarial `-`/`_` runs',});});-describe('PEM_BLOCK_RE is linear in headers and text', () => {+describe('private-key claims are linear in headers and text', () => {const MB_TAIL = 'x'.repeat(1024 * 1024);const PEM_BODY_LINE = ['MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSj', 'AgEAAoIBAQC7VJTUt9Us8cKj'].join('');// Header/footer joined from fragments so the committed source never carries a whole PEM block (gitleaks private-key rule).@@ -414,3 +414,84 @@ describe('redactFindings is linear in unique values (span-splice, not replaceAllexpect(ms).toBeLessThan(200);});});++describe('security fix wave shapes are linear (A1 walks, A2, A3, A5; ENG-15, ENG-17)', () => {+ // Fences and values are joined from fragments; measured timings on the+ // dev box were 2-90 ms for every input below.+ const DASHES = '-'.repeat(5);+ const BEGIN = [DASHES, 'BEGIN RSA ', 'PRIVATE KEY', DASHES].join('');+ const END = [DASHES, 'END RSA ', 'PRIVATE KEY', DASHES].join('');+ const bodyLine = (i: number) => ['MIIEvQIBADANBgkqhkiG9w0BAQEF', 'AASCBKcwggSj', i.toString(36).padStart(24, 'Q')].join('');+ const MB_OF_BODY_LINES = Array.from({ length: 16_000 }, (_, i) => bodyLine(i)).join('\n');+ const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#%<>';+ const entropic = (n: number, salt: number) =>+ Array.from({ length: n }, (_, k) => ALPHABET[(k * 7 + salt) % ALPHABET.length]).join('');++ test('20000 unterminated BEGIN fences, each with a body line: 20000 claims, < 400ms', () => {+ const text = Array.from({ length: 20_000 }, (_, i) => `${BEGIN}\n${bodyLine(i)}`).join('\n');+ let findings: ReturnType<typeof scanText> = [];+ const ms = elapsedMs(() => { findings = scanText(text); });+ expect(findings.length).toBe(20_000);+ expect(JSON.stringify(findings).includes(bodyLine(7))).toBe(false);+ expect(ms).toBeLessThan(400);+ });++ test('20000 END-only fences (each walk stops at the previous fence): 0 findings, < 300ms; on ONE line ahead of an 8 MB tail, < 1500ms', () => {+ let ms = elapsedMs(() => { expect(scanText(`${END}\n`.repeat(20_000))).toEqual([]); });+ expect(ms).toBeLessThan(300);+ ms = elapsedMs(() => { expect(scanText(`${END} `.repeat(20_000) + 'x'.repeat(8 << 20))).toEqual([]); });+ expect(ms).toBeLessThan(1500);+ });++ test('20000 END fences each preceded by a body line: 20000 backward claims, < 400ms', () => {+ const text = Array.from({ length: 20_000 }, (_, i) => `${bodyLine(i)}\n${END}`).join('\n');+ const ms = elapsedMs(() => { expect(privateKeySpans(text).length).toBe(20_000); });+ expect(ms).toBeLessThan(400);+ });++ test('1 MB of base64 lines with no fence, after a BEGIN, before an END, and with a fence every 10 lines: each < 300ms', () => {+ for (const text of [+ MB_OF_BODY_LINES,+ `${BEGIN}\n${MB_OF_BODY_LINES}`,+ `${MB_OF_BODY_LINES}\n${END}`,+ MB_OF_BODY_LINES.split('\n').map((l, i) => (i % 10 === 9 ? END : l)).join('\n'),+ MB_OF_BODY_LINES.split('\n').map((l, i) => (i % 10 === 9 ? BEGIN : l)).join('\n'),+ ]) {+ const ms = elapsedMs(() => { scanText(text); });+ expect(ms).toBeLessThan(300);+ }+ });++ test('url_credentials: 160k of repeated scheme + user + colon and a lone @, and 8000 credential-less https URLs with an email: < 200ms', () => {+ const sep = ':' + '//';+ let ms = elapsedMs(() => { expect(scanText(['https', sep, 'a:'].join('').repeat(16_000) + '@')).toEqual([]); });+ expect(ms).toBeLessThan(200);+ const json = '[' + Array.from({ length: 8000 }, (_, i) => `{"u":"${['https', sep, `host${i}.example:8443/x`].join('')}"}`).join(',') + ',{"e":"[email protected]"}]';+ ms = elapsedMs(() => { expect(scanText(json)).toEqual([]); });+ expect(ms).toBeLessThan(200);+ });++ test('basic_auth: a 1 MB run of `Basic ` / `Authorization: Basic `, `Basic` + 1 MB of base64, and 500 valid 2048-char values: < 300ms', () => {+ for (const text of ['Basic '.repeat(180_000), 'Authorization: Basic '.repeat(50_000), 'Basic ' + 'A'.repeat(1 << 20)]) {+ const ms = elapsedMs(() => { expect(scanText(text)).toEqual([]); });+ expect(ms).toBeLessThan(300);+ }+ const value = Buffer.from(['u', ':', 'a'.repeat(1534)].join('')).toString('base64');+ const ms = elapsedMs(() => { expect(scanText(`Basic ${value} `.repeat(500)).length).toBe(500); });+ expect(ms).toBeLessThan(300);+ });++ test('high_entropy_assignment: 250 quoted and 250 unquoted 4096-char values on one line, and 4100-char runs of trailing punctuation: < 300ms', () => {+ const quoted = Array.from({ length: 250 }, (_, i) => `password="${entropic(4096, i)}"`).join(' ');+ let result!: ReturnType<typeof redactFindings>;+ let ms = elapsedMs(() => { result = redactFindings(quoted, { highEntropy: true }); });+ expect(result.redactions.length).toBe(250);+ expect(ms).toBeLessThan(300);+ const unquoted = Array.from({ length: 250 }, (_, i) => `token=${entropic(4096, i).replace(/[<>]/g, '.')}`).join(' ');+ ms = elapsedMs(() => { result = redactFindings(unquoted, { highEntropy: true }); });+ expect(result.redactions.length).toBe(250);+ expect(ms).toBeLessThan(300);+ ms = elapsedMs(() => { expect(scanText(`token=${'.'.repeat(4100)} `.repeat(250), { highEntropy: true })).toEqual([]); });+ expect(ms).toBeLessThan(300);+ });+});diff --git a/test/secret-scan-private-key-spans.test.ts b/test/secret-scan-private-key-spans.test.tsnew file mode 100644index 0000000000..5ac653bc65--- /dev/null+++ b/test/secret-scan-private-key-spans.test.ts@@ -0,0 +1,277 @@+/**+ * secret-scan private-key claims (security fix wave A1, ENG-12, CEO-15,+ * DX-4 support): truncated keys (BEGIN with no END in view) claim the body+ * that follows; split keys (END with no BEGIN in view) claim the body before+ * the fence; quoted markers stay marker-only (BEGIN) or unclaimed (END);+ * `privateKeySpans` is the same claim set the scanner reports.+ *+ * Key material is generated at runtime (ephemeral keys, random base64) and+ * every fence is joined from fragments, so the committed source carries no+ * key block (gitleaks private-key rule, CEO-10).+ */+import { describe, expect, test } from 'bun:test';+import { createHash, generateKeyPairSync, randomBytes } from 'crypto';+import {+ PEM_BODY_MAX_CHARS,+ patternSince,+ privateKeySpans,+ redactFindings,+ scanText,+} from '../src/core/secret-scan.ts';++const DASHES = '-'.repeat(5);+const begin = (kind = 'RSA ') => [DASHES, 'BEGIN ', kind, 'PRIVATE KEY', DASHES].join('');+const end = (kind = 'RSA ') => [DASHES, 'END ', kind, 'PRIVATE KEY', DASHES].join('');++/** One random base64 body line of `n` chars. */+function b64Line(n = 64): string {+ let s = '';+ while (s.length < n) s += randomBytes(n).toString('base64').replace(/=/g, '');+ return s.slice(0, n);+}++const TOKEN = '<REDACTED:private_key_pem>';++/** No run of 8+ base64 chars survives outside the redaction tokens. */+function noKeyMaterial(out: string): boolean {+ return !/[A-Za-z0-9+/=]{8,}/.test(out.split(TOKEN).join(' '));+}++const RSA_PEM = generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();+const EC_PEM = generateKeyPairSync('ec', { namedCurve: 'P-256' }).privateKey.export({ type: 'sec1', format: 'pem' }).toString();++describe('FORWARD: a BEGIN fence with no END in view claims the body after it', () => {+ test('a key cut off mid-line: header, every whole line and the partial last line are claimed', () => {+ const lines = [b64Line(), b64Line(), b64Line()];+ const partial = b64Line(23);+ const text = `notes:\n${begin()}\n${lines.join('\n')}\n${partial}`;+ const { text: out, redactions } = redactFindings(text);+ expect(out).toBe(`notes:\n${TOKEN}`);+ expect(redactions.map((r) => [r.pattern, r.line])).toEqual([['private_key_pem', 2]]);+ expect(JSON.stringify(redactions).includes(partial)).toBe(false);+ });++ test('a key cut at a line end keeps the prose that follows the body', () => {+ const body = [b64Line(), b64Line(), b64Line(20)].join('\n');+ const text = `${begin('')}\n${body}\n\nMore notes about the server follow here.\n`;+ expect(redactFindings(text).text).toBe(`${TOKEN}\n\nMore notes about the server follow here.\n`);+ });++ test('a short final line followed by a cut is claimed; a short interior word after the body is not', () => {+ const tail = b64Line(5);+ expect(redactFindings(`${begin()}\n${b64Line()}\n${tail}\n`).text).toBe(`${TOKEN}\n`);+ expect(redactFindings(`${begin()}\n${b64Line()}\nThanks\nsee you`).text).toBe(`${TOKEN}\nThanks\nsee you`);+ });++ test('RFC 1421 encrypted headers and one blank line may follow BEGIN', () => {+ const text = [+ 'notes',+ begin(),+ 'Proc-Type: 4,ENCRYPTED',+ `DEK-Info: AES-128-CBC,${randomBytes(16).toString('hex').toUpperCase()}`,+ '',+ b64Line(),+ b64Line(),+ ].join('\n');+ const { text: out } = redactFindings(text);+ expect(out).toBe(`notes\n${TOKEN}`);+ });++ test('indented (YAML block scalar) and CRLF bodies are claimed', () => {+ const lines = [b64Line(), b64Line(), b64Line(31)];+ const yaml = `tls:\n key: |\n ${begin('EC ')}\n${lines.map((l) => ` ${l}`).join('\n')}\nother: value\n`;+ expect(redactFindings(yaml).text).toBe(`tls:\n key: |\n ${TOKEN}\nother: value\n`);+ const crlf = `a\r\n${begin()}\r\n${lines.join('\r\n')}\r\nb text here\r\n`;+ expect(redactFindings(crlf).text).toBe(`a\r\n${TOKEN}\r\nb text here\r\n`);+ });++ test('a JSON \\n-escaped key: truncated, complete, and cut inside an escape', () => {+ const lines = [b64Line(), b64Line(), b64Line(17)];+ const truncated = `{"private_key":"${begin('')}\\n${lines.join('\\n')}`;+ expect(redactFindings(truncated).text).toBe(`{"private_key":"${TOKEN}`);+ const complete = `{"private_key":"${begin('')}\\n${lines.join('\\n')}\\n${end('')}\\n","id":"x"}`;+ expect(redactFindings(complete).text).toBe(`{"private_key":"${TOKEN}\\n","id":"x"}`);+ const cutInEscape = `{"k":"${begin('')}\\n${lines[0]}\\n${lines[1]}\\`;+ expect(redactFindings(cutInEscape).text).toBe(`{"k":"${TOKEN}\\`);+ });++ test('a quoted marker in prose stays marker-only and the next prose line survives', () => {+ const marker = begin('');+ const inline = `To find leaks, search for the string ${marker} in your repo, then rotate.`;+ expect(redactFindings(inline).text).toBe(`To find leaks, search for the string ${TOKEN} in your repo, then rotate.`);+ const ownLine = `Search for this line:\n${marker}\nThen rotate every key you find.\n`;+ expect(redactFindings(ownLine).text).toBe(`Search for this line:\n${TOKEN}\nThen rotate every key you find.\n`);+ });++ test('a base64 run longer than 128 chars ends the body and is not claimed', () => {+ const long = b64Line(129);+ const out = redactFindings(`${begin()}\n${b64Line()}\n${long}\n`).text;+ expect(out).toBe(`${TOKEN}\n${long}\n`);+ });++ test(`the forward claim stops at PEM_BODY_MAX_CHARS (${PEM_BODY_MAX_CHARS}); the remainder is the accepted miss`, () => {+ const lines = Array.from({ length: 400 }, () => b64Line());+ const text = `${begin()}\n${lines.join('\n')}`;+ const [span] = privateKeySpans(text);+ const header = begin().length;+ expect(span!.start).toBe(0);+ expect(span!.end - header).toBeLessThanOrEqual(PEM_BODY_MAX_CHARS);+ expect(span!.end - header).toBeGreaterThan(PEM_BODY_MAX_CHARS - 70);+ });+});++describe('BACKWARD: an END fence with no BEGIN in view claims the body before it', () => {+ test('a chunk that starts mid-key (partial first line): body and fence claimed, prose after survives', () => {+ const partial = b64Line(9);+ const text = `${partial}\n${b64Line()}\n${b64Line()}\n${b64Line(12)}\n${end()}\nafter the key\n`;+ const { text: out, redactions } = redactFindings(text);+ expect(out).toBe(`${TOKEN}\nafter the key\n`);+ expect(redactions.map((r) => [r.pattern, r.line])).toEqual([['private_key_pem', 1]]);+ });++ test("a finding's line is the line of its first claimed character", () => {+ const text = `intro prose line\n\n${b64Line()}\n${b64Line()}\n${end('')}`;+ expect(scanText(text).map((f) => f.line)).toEqual([3]);+ expect(redactFindings(text).text).toBe(`intro prose line\n\n${TOKEN}`);+ });++ test('a quoted END marker with no body line before it produces no finding', () => {+ for (const text of [+ `Keys end with ${end('')} and nothing else.`,+ `Keys end with this line:\n${end('')}\n`,+ `${end('')}\n`,+ ]) {+ expect(scanText(text)).toEqual([]);+ expect(privateKeySpans(text)).toEqual([]);+ }+ });++ test('CRLF, indented and JSON-escaped bodies before END are claimed', () => {+ const lines = [b64Line(), b64Line(), b64Line(30)];+ expect(redactFindings(`${lines.join('\r\n')}\r\n${end()}\r\nz\r\n`).text).toBe(`${TOKEN}\r\nz\r\n`);+ expect(redactFindings(`key: |\n${lines.map((l) => ` ${l}`).join('\n')}\n ${end()}\nnext: 1\n`).text)+ .toBe(`key: |\n ${TOKEN}\nnext: 1\n`);+ expect(redactFindings(`${lines.join('\\n')}\\n${end('')}\\n"}`).text).toBe(`${TOKEN}\\n"}`);+ });++ test('a short interior line or a prose line stops the walk; the over-128 run is not claimed', () => {+ const keep = 'a prose line with spaces';+ expect(redactFindings(`${keep}\n${b64Line()}\n${b64Line()}\n${end()}`).text).toBe(`${keep}\n${TOKEN}`);+ const long = b64Line(129);+ expect(redactFindings(`x y\n${long}\n${b64Line()}\n${end()}`).text).toBe(`x y\n${long}\n${TOKEN}`);+ expect(redactFindings(`x y\nAbc\n${b64Line()}\n${end()}`).text).toBe(`x y\nAbc\n${TOKEN}`);+ });+});++describe('fences in combination', () => {+ test('a truncated key followed within 16 KB by a complete key: two claims, the prose between survives', () => {+ const prose = 'Second key below, rotated last week.';+ const text = `${begin()}\n${b64Line()}\n${b64Line(40)}\n\n${prose}\n${begin('EC ')}\n${b64Line()}\n${end('EC ')}\n`;+ const { text: out, redactions } = redactFindings(text);+ expect(out).toBe(`${TOKEN}\n\n${prose}\n${TOKEN}\n`);+ expect(redactions.map((r) => r.line)).toEqual([1, 6]);+ });++ test('BEGIN-only, END-only and complete keys in one text: spans are sorted, disjoint and equal to the redacted spans', () => {+ const text = [+ `${b64Line(7)}\n${b64Line()}\n${end()}`,+ 'between one',+ `${begin()}\n${b64Line()}\n${end()}`,+ 'between two',+ `${begin()}\n${b64Line()}\n${b64Line(11)}`,+ ].join('\n');+ const spans = privateKeySpans(text);+ expect(spans.length).toBe(3);+ for (let i = 1; i < spans.length; i++) expect(spans[i]!.start).toBeGreaterThanOrEqual(spans[i - 1]!.end);+ let rebuilt = '';+ let at = 0;+ for (const s of spans) {+ rebuilt += text.slice(at, s.start) + TOKEN;+ at = s.end;+ }+ rebuilt += text.slice(at);+ expect(redactFindings(text).text).toBe(rebuilt);+ expect(rebuilt).toBe(`${TOKEN}\nbetween one\n${TOKEN}\nbetween two\n${TOKEN}`);+ });++ test('text without a private-key fence has no spans', () => {+ expect(privateKeySpans('')).toEqual([]);+ expect(privateKeySpans(`${b64Line()}\n${b64Line()}\n`)).toEqual([]);+ expect(privateKeySpans([DASHES, 'BEGIN CERTIFICATE', DASHES].join('') + `\n${b64Line()}\n`)).toEqual([]);+ });+});++describe('generated keys split at every cut point leave no key material in either half', () => {+ const encodings: Array<[string, string]> = [+ ['LF', RSA_PEM],+ ['CRLF', RSA_PEM.replace(/\n/g, '\r\n')],+ ['indented', RSA_PEM.trimEnd().split('\n').map((l) => ` ${l}`).join('\n')],+ ['JSON-escaped', JSON.stringify({ private_key: RSA_PEM })],+ ['EC sec1', EC_PEM],+ ];+ for (const [label, pem] of encodings) {+ test(`${label}`, () => {+ const text = `notes: the deploy key\n${pem}\ndone`;+ const keyStart = text.indexOf(DASHES);+ const keyEnd = text.lastIndexOf(DASHES) + DASHES.length;+ for (let cut = keyStart; cut <= keyEnd; cut += 5) {+ const head = redactFindings(text.slice(0, cut)).text;+ const tail = redactFindings(text.slice(cut)).text;+ if (!noKeyMaterial(head) || !noKeyMaterial(tail)) {+ throw new Error(`${label}: key material survived a cut at ${cut - keyStart}`);+ }+ }+ });+ }+});++describe('ENG-12: one key, one finding', () => {+ test('a vendor-shaped line inside a key body is not reported on its own', () => {+ const aws = ['AKIA', 'Q7RZ2X9KLM4N8P3T'].join('');+ for (const text of [+ `${begin()}\n${b64Line()}\n${aws}\n${b64Line()}\n${end()}`,+ `${begin()}\n${b64Line()}\n${aws}\n${b64Line()}`,+ `${b64Line()}\n${aws}\n${b64Line()}\n${end()}`,+ ]) {+ expect(scanText(text).map((f) => f.pattern)).toEqual(['private_key_pem']);+ expect(redactFindings(text).text).toBe(TOKEN);+ }+ });++ test('a hit outside the key on the same text is still reported', () => {+ const aws = ['AKIA', 'Q7RZ2X9KLM4N8P3T'].join('');+ const text = `id ${aws}\n${begin()}\n${b64Line()}\n${end()}`;+ expect(scanText(text).map((f) => f.pattern).sort()).toEqual(['aws_access_key', 'private_key_pem']);+ });+});++describe('fingerprints and since (A6, DX-4, DX-5)', () => {+ const sha16 = (v: string) => `sha256:${createHash('sha256').update(v).digest('hex').slice(0, 16)}`;++ test('a truncated key carries the pre-wave header-only fingerprint as legacyFingerprint', () => {+ const header = begin();+ const [f] = scanText(`${header}\n${b64Line()}\n${b64Line(10)}`);+ expect(f!.legacyFingerprint).toBe(sha16(header));+ expect(f!.fingerprint).not.toBe(sha16(header));+ expect(f!.since).toBe(patternSince('private_key_pem'));+ });++ test('a complete block and a marker-only claim keep their pre-wave fingerprint (no legacyFingerprint)', () => {+ const header = begin();+ const [marker] = scanText(`see ${header} here`);+ expect(marker!.fingerprint).toBe(sha16(header));+ expect(marker!.legacyFingerprint).toBeUndefined();+ const block = `${header}\n${b64Line()}\n${end()}`;+ const [full] = scanText(block);+ expect(full!.fingerprint).toBe(sha16(block));+ expect(full!.legacyFingerprint).toBeUndefined();+ });++ test('the header-only allowlist entry from before the wave no longer suppresses a truncated key', () => {+ const header = begin();+ const text = `${header}\n${b64Line()}\n${b64Line(10)}`;+ expect(scanText(text, { allowlist: [sha16(header)] }).length).toBe(1);+ const [f] = scanText(text);+ expect(scanText(text, { allowlist: [f!.fingerprint] })).toEqual([]);+ });+});diff --git a/test/secret-scan.test.ts b/test/secret-scan.test.tsindex 741d71922c..b7dd11bf44 100644--- a/test/secret-scan.test.ts+++ b/test/secret-scan.test.ts@@ -607,10 +607,12 @@ describe('format-based detectors — negatives (identifiers and public shapes stexpect(scanText(`sha256: ${digest}`)).toEqual([]);});- test('URLs with userinfo but no password, or non-database schemes, do not fire', () => {+ test('URLs with userinfo but no password, or no credentials at all, do not fire', () => {+ // Design reversal (security fix wave): an http(s) URL whose userinfo+ // carries a password used to be listed here as "not a database scheme";+ // it now fires as url_credentials (see the url_credentials describe).for (const s of ['https://[email protected]/path',- 'https://user:[email protected]/path', // not a database scheme — by design'postgres://db.internal:5432/app', // no credentials'[email protected]:org/repo.git',]) {diff --git a/test/sensitivity-scan.test.ts b/test/sensitivity-scan.test.tsindex a69c8ba49b..4ea8a06670 100644--- a/test/sensitivity-scan.test.ts+++ b/test/sensitivity-scan.test.ts@@ -12,6 +12,7 @@ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs';import { join } from 'path';import { tmpdir } from 'os';import {+ formatSensitivityDrop,loadSensitivityConfig,scanSensitive,SensitivityScanConfigError,@@ -288,3 +289,18 @@ describe('secret-scan owns the jwt/bearer shapes — no double report with the Pexpect(findings.map((f) => f.family)).toEqual(['pii:bearer']);});});++describe('DX-7: a dropped entry gets one content-free diagnostic line', () => {+ test('names reason, pattern, fingerprint and the allowlist recovery, never the value', () => {+ const token = ['gh', 'p_'].join('') + 'Q7'.repeat(18);+ const [finding] = scanSensitive(`notes ${token} end`, loadSensitivityConfig({ blocklist: '' }));+ const line = formatSensitivityDrop({ slug: 'concepts/leaky', ...finding! }, '/work/space');+ expect(line).toContain('concepts/leaky');+ expect(line).toContain('reason: sensitivity_scan');+ expect(line).toContain('pattern: secret:github_token');+ expect(line).toContain(`fingerprint: ${finding!.fingerprint}`);+ expect(line).toContain(`add the line "${finding!.fingerprint}" to ${join('/work/space', SCAN_ALLOW_FILENAME)}`);+ expect(line).not.toContain(token);+ expect(line).not.toContain('\n');+ });+});diff --git a/test/sources-push-cli.serial.test.ts b/test/sources-push-cli.serial.test.tsindex f85251a4a6..83509d700d 100644--- a/test/sources-push-cli.serial.test.ts+++ b/test/sources-push-cli.serial.test.ts@@ -19,7 +19,7 @@ import { describe, test, expect, beforeEach, afterEach } from 'bun:test';import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { tmpdir } from 'node:os';-import { execFileSync } from 'node:child_process';+import { execFileSync, spawnSync } from 'node:child_process';import { runSources } from '../src/commands/sources.ts';import { acquirePushLock, resolveWorkspaceRoot } from '../src/core/workspace-push.ts';@@ -308,3 +308,63 @@ describe('--json output', () => {expect(r.stderr.join('\n')).not.toContain('allow this finding:');}, T);});++// ── refusal guidance (security wave DX-3/ENG-11/CEO-21) ─────────────────────++describe('blocked_secrets guidance — runnable from outside the source dir', () => {+ function cloneAt(dir: string): void {+ execFileSync('git', ['-c', 'protocol.file.allow=always', 'clone', '-q', bare, dir], {+ stdio: 'ignore', env: process.env,+ });+ git(dir, 'config', 'user.email', '[email protected]');+ git(dir, 'config', 'user.name', 'tester');+ try { git(dir, 'remote', 'set-head', 'origin', 'main'); } catch { /* */ }+ }++ async function inDir<T>(dir: string, fn: () => Promise<T>): Promise<T> {+ const prev = process.cwd();+ process.chdir(dir);+ try { return await fn(); } finally { process.chdir(prev); }+ }++ test('a source path with spaces: absolute quoted allowlist path, append + retry commands, docs; JSON parity; the printed commands work', async () => {+ const name = 'my brain dir';+ const spaced = join(root, name);+ cloneAt(spaced);+ writeFileSync(join(spaced, 'notes.md'), `my key: ${OPENAI}\n`);+ const quotedAllowlist = `'${join(spaced, SCAN_ALLOW_FILENAME)}'`;+ const quotedDir = `'${spaced}'`;++ const human = await inDir(root, () => runPushCli(untouchableEngine, ['--path', name, '--allow-unverified-remote']));+ expect(human.exitCode).toBe(5);+ const err = human.stderr.join('\n');+ expect(err.includes(OPENAI)).toBe(false);+ const allowLine = human.stderr.find((l) => l.includes('allow this finding:'))!.trim();+ const allowCommand = allowLine.slice('allow this finding: '.length);+ expect(allowCommand).toMatch(new RegExp(`^printf '\\\\n%s\\\\n' sha256:[0-9a-f]{16} >> `));+ expect(allowCommand).toEndWith(` >> ${quotedAllowlist}`);+ expect(err).toContain('fingerprint: sha256:');+ expect(err).toContain(`(it appends to ${quotedAllowlist})`);+ expect(err).toContain(` gbrain sources push --path ${quotedDir} --allow-unverified-remote`);+ expect(err).toContain('Remove a real credential from the file (and rotate it) first. Allowlist only a reviewed false positive');+ expect(err).toContain('Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/write-refusals.md#secret-scan-refusals-and-redaction');++ const json = await inDir(root, () => runPushCli(untouchableEngine, ['--path', name, '--allow-unverified-remote', '--json']));+ expect(json.exitCode).toBe(5);+ const res = JSON.parse(json.stdout[0]);+ expect(json.stdout[0].includes(OPENAI)).toBe(false);+ expect(res.reason.length).toBeLessThanOrEqual(140);+ const f = res.findings[0];+ expect(f.allowCommand).toBe(allowCommand);+ expect(f.allowlistPath).toBe(join(spaced, SCAN_ALLOW_FILENAME));+ expect(f.retryCommand).toBe(`gbrain sources push --path ${quotedDir} --allow-unverified-remote`);+ expect(err).toContain(`fingerprint: ${f.fingerprint}`);+ expect(f.docs).toBe('https://github.com/garrytan/gbrain/blob/master/docs/guides/write-refusals.md#secret-scan-refusals-and-redaction');++ const appended = spawnSync('bash', ['-c', allowCommand], { cwd: tmpdir(), encoding: 'utf-8' });+ expect(appended.status).toBe(0);+ const retried = await inDir(tmpdir(), () => runPushCli(untouchableEngine, ['--path', spaced, '--allow-unverified-remote']));+ expect(retried.exitCode).toBe(0);+ expect(originHead(bare)).toBe(git(spaced, 'rev-parse', 'HEAD'));+ }, T);+});diff --git a/test/transcripts-redaction.test.ts b/test/transcripts-redaction.test.tsnew file mode 100644index 0000000000..495284bf99--- /dev/null+++ b/test/transcripts-redaction.test.ts@@ -0,0 +1,90 @@+/**+ * ENG-8 — handlers that clip, collapse or summarize stored text redact the+ * whole source field FIRST. A credential cut by a summary cap (or a key whose+ * lines are collapsed onto one line) no longer matches the scanner, so a+ * clip-then-redact order leaks the fragment that survives the cut.+ *+ * Covers `listRecentTranscripts` (250-char summary head and 100 KB full-read+ * cap, the `get_recent_transcripts` op) and `safeSynopsis` (160-char+ * `clip(collapse(...))`, the entity-card / reflex pointer summary).+ * Fixtures are assembled at runtime from random parts (CEO-10).+ */+import { describe, expect, test, beforeAll, afterAll } from 'bun:test';+import { randomBytes } from 'node:crypto';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { listRecentTranscripts } from '../src/core/transcripts.ts';+import { safeSynopsis, type PageRow } from '../src/core/context/retrieval-reflex.ts';++const ALNUM = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';+function rand(n: number): string {+ let out = '';+ for (const b of randomBytes(n)) out += ALNUM[b % ALNUM.length];+ return out;+}+const vendorToken = () => ['gh', 'p_'].join('') + rand(36);++let dir: string;+const fakeEngine = {+ async getConfig(key: string): Promise<string | null> {+ return key === 'dream.synthesize.session_corpus_dir' ? dir : null;+ },+} as unknown as Parameters<typeof listRecentTranscripts>[0];++beforeAll(() => {+ dir = mkdtempSync(join(tmpdir(), 'gbrain-transcripts-redaction-'));+});++afterAll(() => {+ rmSync(dir, { recursive: true, force: true });+});++/** Write one transcript into a fresh corpus dir and read it back. */+async function transcript(name: string, content: string, summary: boolean) {+ rmSync(dir, { recursive: true, force: true });+ dir = mkdtempSync(join(tmpdir(), 'gbrain-transcripts-redaction-'));+ writeFileSync(join(dir, name), content);+ const [t] = await listRecentTranscripts(fakeEngine, { days: 3650, summary });+ expect(t!.path).toBe(name);+ return t!;+}++describe('transcripts redact before the summary and full-read caps cut', () => {+ test('a token crossing the 250-char summary boundary leaves no fragment', async () => {+ const token = vendorToken();+ // The token starts 20 chars before the cap, so a clip-first summary keeps+ // `ghp_` plus 16 random chars: too short to match, still a real fragment.+ const t = await transcript('2026-09-30-summary.txt', `Session notes\n${'x'.repeat(229)} ${token} trailing words\n`, true);+ expect(t.summary).toContain('Session notes');+ expect(t.summary.includes(token.slice(4, 16))).toBe(false);+ });++ test('a token crossing the 100 KB full-read cap leaves no fragment', async () => {+ const token = vendorToken();+ const t = await transcript('2026-09-30-full.txt', `Session notes\n${'y'.repeat(100 * 1024 - 14 - 21)} ${token} tail\n`, false);+ expect(t.summary.length).toBeGreaterThan(100 * 1024 - 64);+ expect(t.summary.includes(token.slice(4, 16))).toBe(false);+ });+});++describe('safeSynopsis redacts the whole source field before collapse and clip', () => {+ const row = (frontmatter: Record<string, unknown> | null, compiled_truth: string): PageRow =>+ ({ slug: 'people/alice-example', source_id: 'default', title: 'Alice', type: 'person', frontmatter, compiled_truth });++ test('a multiline private key in a frontmatter summary leaves no body fragment', () => {+ const fence = '-'.repeat(5);+ const label = ['PRIVATE', 'KEY'].join(' ');+ const body = Array.from({ length: 4 }, () => randomBytes(48).toString('base64'));+ const summary = [`${fence}BEGIN ${label}${fence}`, ...body, `${fence}END ${label}${fence}`].join('\n');+ const out = safeSynopsis(row({ summary }, ''), { maxLen: 600 });+ for (const line of body) expect(out.includes(line.slice(0, 16))).toBe(false);+ expect(out).toContain('<REDACTED:private_key_pem>');+ });++ test('a token crossing the 160-char clip in the first prose line leaves no fragment', () => {+ const token = vendorToken();+ const out = safeSynopsis(row(null, `# Alice\n\n${'z'.repeat(139)} ${token} more prose.`));+ expect(out.includes(token.slice(4, 16))).toBe(false);+ });+});diff --git a/test/upgrade-reembed-prompt.test.ts b/test/upgrade-reembed-prompt.test.tsindex d03077a5e3..6539e4f9a0 100644--- a/test/upgrade-reembed-prompt.test.ts+++ b/test/upgrade-reembed-prompt.test.ts@@ -1,8 +1,9 @@/*** v0.32.7 CJK wave — post-upgrade chunker-bump cost prompt tests.*- * Asserts the prompt fires with real-data estimates, honors the non-TTY- * skip-wait + GBRAIN_NO_REEMBED env overrides, and falls back to an+ * Asserts the prompt fires with real-data estimates, re-embeds only on an+ * explicit TTY yes (security wave ENG-3: non-TTY and declined runs never+ * call the provider), honors GBRAIN_NO_REEMBED, and falls back to an* "estimate unavailable" message for unknown embedding providers.*/@@ -12,6 +13,7 @@ import {computeReembedEstimate,formatReembedPrompt,runPostUpgradeReembedPrompt,+ REEMBED_DEFERRED_HINT,} from '../src/core/post-upgrade-reembed.ts';import { MARKDOWN_CHUNKER_VERSION } from '../src/core/chunkers/recursive.ts';@@ -70,18 +72,16 @@ describe('formatReembedPrompt (v0.32.7)', () => {test('known provider includes dollar figure', () => {const line = formatReembedPrompt({ pendingCount: 100, pendingChars: 100000, estimatedTokens: 28571, estimatedCostUsd: 0.034, modelString: 'openai:text-embedding-3-large', pricingKnown: true },- 10,);expect(line).toContain('100 markdown pages');expect(line).toContain('openai:text-embedding-3-large');expect(line).toContain('$0.03');- expect(line).toContain('Ctrl-C within 10s');+ expect(line).not.toContain('Ctrl-C');});test('unknown provider says "estimate unavailable"', () => {const line = formatReembedPrompt({ pendingCount: 50, pendingChars: 50000, estimatedTokens: 14286, estimatedCostUsd: null, modelString: 'hunyuan:hunyuan-embedding-v1', pricingKnown: false },- 10,);expect(line).toContain('estimate unavailable');expect(line).toContain('hunyuan:hunyuan-embedding-v1');@@ -90,7 +90,6 @@ describe('formatReembedPrompt (v0.32.7)', () => {test('no pending → "Skipping re-embed"', () => {const line = formatReembedPrompt({ pendingCount: 0, pendingChars: 0, estimatedTokens: 0, estimatedCostUsd: 0, modelString: 'openai:text-embedding-3-large', pricingKnown: true },- 10,);expect(line).toContain('No pending markdown pages');});@@ -110,19 +109,21 @@ describe('runPostUpgradeReembedPrompt (v0.32.7)', () => {expect(writes.length).toBe(0);});- test('non-TTY proceeds without wait', async () => {+ test('non-TTY never proceeds and prints the deferred commands', async () => {await seedPage('a', 'body');const writes: string[] = [];+ const asked: string[] = [];const result = await runPostUpgradeReembedPrompt(engine, 'openai:text-embedding-3-large', {isTTY: false,env: {},write: (l) => writes.push(l),- graceSeconds: 99, // would block forever if respected+ confirm: async (q) => { asked.push(q); return true; },});- expect(result.proceeded).toBe(true);- expect(result.reason).toBe('non_tty_proceeded');- expect(writes.length).toBe(1);- expect(writes[0]).toContain('Ctrl-C');+ expect(result.proceeded).toBe(false);+ expect(result.reason).toBe('consent_required');+ expect(asked).toEqual([]);+ expect(writes).toHaveLength(2);+ expect(writes[1]).toBe(REEMBED_DEFERRED_HINT);});test('GBRAIN_NO_REEMBED=1 bails out with doctor-warning marker', async () => {@@ -132,28 +133,42 @@ describe('runPostUpgradeReembedPrompt (v0.32.7)', () => {isTTY: true,env: { GBRAIN_NO_REEMBED: '1' },write: (l) => writes.push(l),- graceSeconds: 99,+ confirm: async () => { throw new Error('must not ask'); },});expect(result.proceeded).toBe(false);expect(result.reason).toBe('bypassed_no_reembed');expect(writes.some(w => w.includes('GBRAIN_NO_REEMBED=1'))).toBe(true);});- test('GBRAIN_REEMBED_GRACE_SECONDS=0 skips wait on TTY', async () => {+ test('TTY proceeds only on an explicit yes', async () => {+ await seedPage('a', 'body');+ const asked: string[] = [];+ const result = await runPostUpgradeReembedPrompt(engine, 'openai:text-embedding-3-large', {+ isTTY: true,+ env: {},+ write: () => {},+ confirm: async (q) => { asked.push(q); return true; },+ });+ expect(asked).toEqual(['[chunker-bump] Re-embed now? [y/N] ']);+ expect(result.proceeded).toBe(true);+ expect(result.reason).toBe('tty_consented');+ });++ test('TTY default answer (Enter, EOF, no) declines', async () => {await seedPage('a', 'body');const writes: string[] = [];- const t0 = Date.now();const result = await runPostUpgradeReembedPrompt(engine, 'openai:text-embedding-3-large', {isTTY: true,- env: { GBRAIN_REEMBED_GRACE_SECONDS: '0' },+ env: {},write: (l) => writes.push(l),+ confirm: async () => false,});- expect(result.proceeded).toBe(true);- expect(result.reason).toBe('tty_proceeded');- expect(Date.now() - t0).toBeLessThan(1000); // didn't actually wait+ expect(result.proceeded).toBe(false);+ expect(result.reason).toBe('tty_declined');+ expect(writes.at(-1)).toBe(REEMBED_DEFERRED_HINT);});- test('unknown provider still prompts + proceeds (degrades to "estimate unavailable")', async () => {+ test('unknown provider still prints the estimate line (degrades to "estimate unavailable")', async () => {await seedPage('a', 'body');const writes: string[] = [];const result = await runPostUpgradeReembedPrompt(engine, 'hunyuan:hunyuan-embedding-v1', {@@ -161,7 +176,7 @@ describe('runPostUpgradeReembedPrompt (v0.32.7)', () => {env: {},write: (l) => writes.push(l),});- expect(result.proceeded).toBe(true);+ expect(result.proceeded).toBe(false);expect(writes[0]).toContain('estimate unavailable');});});diff --git a/test/upgrade-zero-provider-calls.serial.test.ts b/test/upgrade-zero-provider-calls.serial.test.tsnew file mode 100644index 0000000000..90dc273fb1--- /dev/null+++ b/test/upgrade-zero-provider-calls.serial.test.ts@@ -0,0 +1,138 @@+/**+ * `gbrain post-upgrade` makes zero embedding-provider calls without+ * affirmative consent (security wave ENG-3), in non-TTY and TTY runs.+ *+ * Protects: an upgrade on a brain with an embedding provider configured, with+ * markdown pages below the chunker version and a page holding a private key,+ * completes this release's migrations (the credential-safe re-chunk) without+ * sending anything to the provider. Regression it catches: the chunker-bump+ * re-embed that proceeded on its own (immediately without a TTY, after a 10s+ * Ctrl-C window with one), or a migration that embeds. Existing coverage+ * pinned the old auto-proceed. Serial: spawns the real CLI against a disk+ * PGLite brain and a local fake provider.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { generateKeyPairSync } from 'node:crypto';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { migrations } from '../src/commands/migrations/index.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import { keylessBrainEnv } from './helpers/provider-env.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';++const REPO = resolve(import.meta.dir, '..');+const KEY = generateKeyPairSync('rsa', {+ modulusLength: 2048,+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },+ publicKeyEncoding: { type: 'spki', format: 'pem' },+}).privateKey;+const words = (n: number, tag: string) => Array.from({ length: n }, (_, i) => `${tag}${i} word`).join(' ');+const hasScript = process.platform === 'linux' && existsSync('/usr/bin/script');++let provider: ReturnType<typeof Bun.serve>;+const embeddingCalls: string[] = [];++/** A brain upgraded from the previous release: schema one behind, every older orchestrator recorded complete. */+async function seedBrain(home: string): Promise<void> {+ const dir = join(home, '.gbrain');+ mkdirSync(join(dir, 'migrations'), { recursive: true });+ const databasePath = join(home, 'brain.pglite');+ writeFileSync(join(dir, 'config.json'), JSON.stringify({ engine: 'pglite', database_path: databasePath, ...LEGACY_EMBEDDING_CONFIG }));+ writeFileSync(join(dir, 'migrations', 'completed.jsonl'), migrations.filter(m => m.version !== '0.60.31')+ .map(m => JSON.stringify({ version: m.version, status: 'complete' })).join('\n') + '\n');+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: databasePath });+ try {+ await engine.initSchema();+ await engine.setConfig('mcp.publish_skills_prompted', 'true');+ for (const [slug, body] of [['notes/old-chunker', `## Old\n\n${words(40, 'legacy')}\n`], ['notes/deploy-key', `## Deploy\n\n${words(40, 'deploy')}\n\n${KEY}\n${words(20, 'after')}\n`]] as const) {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: body, timeline: '', frontmatter: {} });+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: body.trim(), chunk_source: 'compiled_truth' }]);+ }+ await engine.executeRaw(`UPDATE pages SET chunker_version = 3 WHERE slug = 'notes/old-chunker'`);+ await engine.setConfig('version', '186');+ } finally {+ await engine.disconnect();+ }+}++async function postUpgrade(home: string, tty: boolean): Promise<{ exitCode: number; out: string }> {+ const env = keylessBrainEnv(process.env, home, {+ OPENAI_API_KEY: ['fixture', 'not', 'a', 'key'].join('-'),+ OPENAI_BASE_URL: `http://127.0.0.1:${provider.port}/v1`,+ GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_SKIP_REFERENCE_SWEEP: '1', GBRAIN_NO_AUTOPILOT_INSTALL: '1',+ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,+ });+ const cli = [process.execPath, '--no-env-file', join(REPO, 'src/cli.ts'), 'post-upgrade', '--no-autopilot-install'];+ const cmd = tty ? ['/usr/bin/script', '-qec', cli.map(a => `'${a.replace(/'/g, `'\\''`)}'`).join(' '), '/dev/null'] : cli;+ const proc = Bun.spawn({ cmd, env, cwd: home, stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });+ // Every prompt gets the default answer (Enter); the stream stays open until the run ends.+ const answers = setInterval(() => { try { proc.stdin.write('\n'); proc.stdin.flush(); } catch { /* exited */ } }, 500);+ const kill = setTimeout(() => proc.kill(9), 170_000);+ try {+ const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);+ return { exitCode, out: stdout + stderr };+ } finally {+ clearInterval(answers);+ clearTimeout(kill);+ try { proc.stdin.end(); } catch { /* closed */ }+ }+}++describe('post-upgrade with a configured embedding provider', () => {+ const homes: string[] = [];++ beforeAll(() => {+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+ provider = Bun.serve({+ port: 0,+ hostname: '127.0.0.1',+ async fetch(req) {+ const path = new URL(req.url).pathname;+ if (!path.endsWith('/embeddings')) return new Response('not found', { status: 404 });+ embeddingCalls.push(path);+ const body = await req.json() as { input: string[] | string };+ const inputs = Array.isArray(body.input) ? body.input : [body.input];+ return Response.json({+ object: 'list', model: 'text-embedding-3-large', usage: { prompt_tokens: 1, total_tokens: 1 },+ data: inputs.map((_, index) => ({ object: 'embedding', index, embedding: Array.from({ length: LEGACY_EMBEDDING_CONFIG.embedding_dimensions }, () => 0.01) })),+ });+ },+ });+ });++ afterAll(() => {+ provider?.stop(true);+ resetGateway();+ for (const home of homes) rmSync(home, { recursive: true, force: true });+ });++ for (const tty of [false, true]) {+ test.skipIf(tty && !hasScript)(`${tty ? 'TTY (default answer)' : 'non-TTY'}: migrations finish, nothing is sent to the provider`, async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-upgrade-zero-provider-'));+ homes.push(home);+ await seedBrain(home);+ embeddingCalls.length = 0;+ const run = await postUpgrade(home, tty);+ expect(run.exitCode, run.out).toBe(0);+ expect(embeddingCalls, run.out).toEqual([]);+ expect(run.out).toContain('Not re-embedding without your consent');+ if (tty) expect(run.out).toContain('Re-embed now? [y/N]');+ const ledger = readFileSync(join(home, '.gbrain', 'migrations', 'completed.jsonl'), 'utf8');+ expect(ledger).toContain('"version":"0.60.31"');+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: join(home, 'brain.pglite') });+ try {+ const [page] = await engine.executeRaw<{ sealed: boolean }>(`SELECT (text_projection_revision = knowledge_revision) IS TRUE AS sealed FROM pages WHERE slug = 'notes/deploy-key'`);+ expect(page.sealed).toBe(true);+ const chunks = await engine.getChunks('notes/deploy-key', { sourceId: 'default' });+ expect(chunks.map(c => c.chunk_text).join('\n')).not.toContain('PRIVATE KEY-----');+ } finally {+ await engine.disconnect();+ }+ }, 180_000);+ }+});diff --git a/test/workspace-push-guidance.test.ts b/test/workspace-push-guidance.test.tsnew file mode 100644index 0000000000..96041e8d28--- /dev/null+++ b/test/workspace-push-guidance.test.ts@@ -0,0 +1,199 @@+/**+ * Push-refusal guidance (security wave DX-3/ENG-11/CEO-21/DX-4): the+ * per-finding fix steps that ride `findings[]`, the short `reason` that has to+ * survive `sanitizePushReason`, and the stale header-only private-key+ * allowlist hint. Pure functions: no git, no engine, no env mutation.+ *+ * Credential-shaped fixtures (key fences, key bodies) are assembled at+ * runtime from parts; key bodies are random bytes, never a real key.+ */+import { describe, test, expect } from 'bun:test';+import { createHash, randomBytes } from 'node:crypto';+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { spawnSync } from 'node:child_process';+import {+ blockedSecretsReason, buildPushFindings, formatBlockedSecrets, sanitizePushReason, SECRET_SCAN_REFUSAL_DOCS,+ type PushSecretFinding,+} from '../src/core/workspace-push.ts';+import { loadWorkspaceAllowlist, scanText, SCAN_ALLOW_FILENAME, type SecretFinding } from '../src/core/secret-scan.ts';++const KEY_LABEL = ['PRIVATE', 'KEY'].join(' ');+const BEGIN = `${'-'.repeat(5)}BEGIN RSA ${KEY_LABEL}${'-'.repeat(5)}`;+const END = `${'-'.repeat(5)}END RSA ${KEY_LABEL}${'-'.repeat(5)}`;++function bodyLines(n: number): string[] {+ return Array.from({ length: n }, () => randomBytes(48).toString('base64'));+}++function fp(value: string): string {+ return `sha256:${createHash('sha256').update(value).digest('hex').slice(0, 16)}`;+}++function finding(over: Partial<SecretFinding & { since: string }> = {}): SecretFinding {+ return {+ pattern: 'private_key_pem',+ line: 2,+ redactedPreview: '<REDACTED:private_key_pem>',+ fingerprint: 'sha256:0123456789abcdef',+ ...over,+ };+}++function build(findings: SecretFinding[], allowlist: string[] = []): PushSecretFinding[] {+ return buildPushFindings({+ file: 'notes/key.md',+ findings,+ allowlist,+ allowlistPath: '/ws/.gbrain-scan-allow',+ retryCommand: 'gbrain sources push --path /ws',+ });+}++describe('blockedSecretsReason (ENG-11: reason survives sanitizePushReason)', () => {+ test('a long path and long pattern name stay within 140 chars, unclipped and readable', () => {+ const file = `${'deeply/nested/'.repeat(12)}meeting-notes.md`;+ const reason = blockedSecretsReason([+ { ...build([finding({ pattern: 'high_entropy_assignment', line: 1234 })])[0]!, file },+ { ...build([finding()])[0]!, file: 'b.md' },+ ]);+ expect(reason.length).toBeLessThanOrEqual(140);+ expect(sanitizePushReason(reason)).toBe(reason);+ expect(reason).toStartWith('2 secret finding(s), first ...');+ expect(reason).toContain('/meeting-notes.md:1234 [high_entropy_assignment]');+ expect(reason).toContain('nothing committed');+ expect(reason).toContain('gbrain sources push');+ });++ test('a short location is shown whole', () => {+ const reason = blockedSecretsReason(build([finding({ pattern: 'openai', line: 3 })]));+ expect(reason).toBe('1 secret finding(s), first notes/key.md:3 [openai]; nothing committed. Run gbrain sources push for fix steps');+ expect(sanitizePushReason(reason)).toBe(reason);+ });+});++describe('buildPushFindings (DX-3: per-finding guidance)', () => {+ test('carries the fingerprint, allowlist path, append + retry commands and docs anchor', () => {+ const [f] = build([finding({ pattern: 'openai', fingerprint: 'sha256:aaaabbbbccccdddd' })]);+ expect(f!.file).toBe('notes/key.md');+ expect(f!.fingerprint).toBe('sha256:aaaabbbbccccdddd');+ expect(f!.allowlistPath).toBe('/ws/.gbrain-scan-allow');+ expect(f!.allowCommand).toBe("printf '\\n%s\\n' sha256:aaaabbbbccccdddd >> /ws/.gbrain-scan-allow");+ expect(f!.retryCommand).toBe('gbrain sources push --path /ws');+ expect(f!.docs).toBe(SECRET_SCAN_REFUSAL_DOCS);+ expect(f!.docs).toEndWith('write-refusals.md#secret-scan-refusals-and-redaction');+ expect(f!.since).toBeUndefined();+ expect(f!.staleAllowlistEntry).toBeUndefined();+ });++ test("CEO-21: the finding's since version rides through when the scanner reports one", () => {+ const [f] = build([finding({ pattern: 'basic_auth', since: '0.60.31.0' } as Partial<SecretFinding>)]);+ expect(f!.since).toBe('0.60.31.0');+ });++ test('the append command works verbatim on a path with spaces and quotes, from any cwd', () => {+ const root = mkdtempSync(join(tmpdir(), 'wspg-'));+ try {+ const ws = join(root, "my brain's dir");+ mkdirSync(ws);+ const allowlistPath = join(ws, SCAN_ALLOW_FILENAME);+ writeFileSync(allowlistPath, '# reviewed\nnotes/*.tmp');+ const [f] = buildPushFindings({+ file: 'a.md', allowlist: [], allowlistPath, retryCommand: 'x',+ findings: [finding({ pattern: 'openai', fingerprint: 'sha256:1111222233334444' })],+ });+ const r = spawnSync('bash', ['-c', f!.allowCommand], { cwd: tmpdir(), encoding: 'utf-8' });+ expect(r.status).toBe(0);+ expect(loadWorkspaceAllowlist(ws)).toEqual(['notes/*.tmp', 'sha256:1111222233334444']);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });+});++describe('stale header-only private-key allowlist hint (DX-4)', () => {+ const truncated = ['intro prose', BEGIN, ...bodyLines(6)].join('\n');+ const headerOnly = fp(BEGIN);+ const bodyFp = 'sha256:fedcba9876543210';++ test('a header-only allowlist entry is named with the replacement fingerprint', () => {+ const [f] = build([finding({ fingerprint: bodyFp, legacyFingerprint: headerOnly })], ['notes/*.tmp', headerOnly]);+ expect(f!.staleAllowlistEntry).toEqual({ entry: headerOnly, replacement: bodyFp });+ expect(f).not.toHaveProperty('legacyFingerprint');+ });++ test('no hint without a legacy fingerprint, or without a matching entry', () => {+ expect(build([finding({ fingerprint: bodyFp })], [headerOnly])[0]!.staleAllowlistEntry).toBeUndefined();+ expect(build([finding({ legacyFingerprint: headerOnly })], ['sha256:9999999999999999'])[0]!.staleAllowlistEntry).toBeUndefined();+ });++ test('a short (< 16 hex) prefix of the header fingerprint does not count as a match', () => {+ const [f] = build([finding({ fingerprint: bodyFp, legacyFingerprint: headerOnly })], [headerOnly.slice(0, 'sha256:'.length + 12)]);+ expect(f!.staleAllowlistEntry).toBeUndefined();+ });++ test('with the real scanner, the old entry yields a body finding plus the hint', () => {+ const allowlist = [headerOnly];+ const findings = scanText(truncated, { allowlist });+ expect(findings.length).toBe(1);+ expect(findings[0]!.fingerprint).not.toBe(headerOnly);+ const [f] = build(findings, allowlist);+ expect(f!.staleAllowlistEntry).toEqual({ entry: headerOnly, replacement: findings[0]!.fingerprint });+ });++ test('with the real scanner, a complete block (END in view) gets no hint', () => {+ const complete = ['intro', BEGIN, ...bodyLines(6), END].join('\n');+ const findings = scanText(complete, { allowlist: [headerOnly] });+ expect(build(findings, [headerOnly])[0]!.staleAllowlistEntry).toBeUndefined();+ });+});++describe('formatBlockedSecrets (CLI rendering of the structured findings)', () => {+ const allowlistPath = "/home/u/my brain/.gbrain-scan-allow";+ function one(over: Partial<SecretFinding & { since: string }>, allowlist: string[] = []): PushSecretFinding[] {+ return buildPushFindings({+ file: 'k.md', findings: [finding(over)], allowlist, allowlistPath,+ retryCommand: "gbrain sources push --path '/home/u/my brain'",+ });+ }++ test('fingerprint, append command, remove-first advice, retry and docs; no since line without since', () => {+ const lines = formatBlockedSecrets(one({ pattern: 'openai', line: 4, fingerprint: 'sha256:aaaabbbbccccdddd' }));+ expect(lines).toEqual([+ 'PUSH BLOCKED — secret scan findings (nothing committed):',+ ' k.md:4 [openai] <REDACTED:private_key_pem>',+ ' fingerprint: sha256:aaaabbbbccccdddd',+ " allow this finding: printf '\\n%s\\n' sha256:aaaabbbbccccdddd >> '/home/u/my brain/.gbrain-scan-allow'",+ 'Remove a real credential from the file (and rotate it) first. Allowlist only a reviewed false positive',+ "with the \"allow this finding\" command above (it appends to '/home/u/my brain/.gbrain-scan-allow'), then retry:",+ " gbrain sources push --path '/home/u/my brain'",+ `Docs: ${SECRET_SCAN_REFUSAL_DOCS}`,+ ]);+ });++ test("CEO-21: a finding's since version names the gbrain version that made the shape blocking", () => {+ for (const [pattern, since] of [['url_credentials', '0.60.31.0'], ['basic_auth', 'v0.60.31.0'], ['digitalocean', '0.60.31.0']]) {+ const out = formatBlockedSecrets(one({ pattern, since } as Partial<SecretFinding>)).join('\n');+ expect(out).toContain(` rule [${pattern}] blocks pushes since gbrain v0.60.31.0`);+ }+ });++ test('DX-4: the stale header-only entry is named with the replacement line', () => {+ const headerOnly = fp(BEGIN);+ const out = formatBlockedSecrets(one(+ { line: 1, fingerprint: 'sha256:fedcba9876543210', since: '0.60.31.0', legacyFingerprint: headerOnly },+ [headerOnly],+ )).join('\n');+ expect(out).toContain(+ ` stale allowlist entry: ${headerOnly} matched only this key's BEGIN header before gbrain v0.60.31.0; the fingerprint now covers the key body.`,+ );+ expect(out).toContain(+ " if the key is a reviewed false positive, replace that line in '/home/u/my brain/.gbrain-scan-allow' with: sha256:fedcba9876543210",+ );+ });++ test('an empty finding list renders only the header', () => {+ expect(formatBlockedSecrets([])).toEqual(['PUSH BLOCKED — secret scan findings (nothing committed):']);+ });+});diff --git a/test/workspace-push.serial.test.ts b/test/workspace-push.serial.test.tsindex 90b923e19d..5c7eb88a8e 100644--- a/test/workspace-push.serial.test.ts+++ b/test/workspace-push.serial.test.ts@@ -19,6 +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,} from '../src/core/workspace-push.ts';import { SCAN_ALLOW_FILENAME } from '../src/core/secret-scan.ts';import { visibilityCachePath } from '../src/core/repo-visibility.ts';@@ -267,6 +268,31 @@ describe('secret-scan gate', () => {}, T);});+describe('secret-scan refusal guidance (DX-3/ENG-11)', () => {+ test('the status-file reason survives sanitizePushReason; fix steps ride findings[]', async () => {+ const deep = join(work, ...Array.from({ length: 10 }, (_, i) => `folder-level-${i}`));+ mkdirSync(deep, { recursive: true });+ writeFileSync(join(deep, 'notes.md'), `ok\nmy key: ${OPENAI}\n`);+ writeFileSync(join(work, 'other.md'), `again: ${OPENAI}\n`);+ const r = await push();+ expect(r.status).toBe('blocked_secrets');+ expect(r.findings?.length).toBe(2);+ const status = readPushStatuses()[0]!;+ expect(status.reason).toBe(r.reason);+ expect(r.reason!.length).toBeLessThanOrEqual(140);+ expect(sanitizePushReason(status.reason)).toBe(status.reason!);+ expect(status.reason).toMatch(/^2 secret finding\(s\), first .*notes\.md:2 \[openai\]; nothing committed/);+ const repoRoot = git(work, 'rev-parse', '--show-toplevel');+ for (const f of r.findings!) {+ expect(f.allowlistPath).toBe(join(repoRoot, SCAN_ALLOW_FILENAME));+ expect(f.allowCommand).toContain(f.fingerprint);+ expect(f.retryCommand).toBe(`gbrain sources push --path ${work} --branch main --allow-unverified-remote`);+ expect(f.docs).toBe(SECRET_SCAN_REFUSAL_DOCS);+ }+ expect(JSON.stringify(r).includes(OPENAI)).toBe(false);+ }, T);+});+describe('secret-scan gate — fails CLOSED on unscannable staged blobs', () => {test('a staged blob that fails cat-file (non-deletion) BLOCKS the push', async () => {// A gitlink to a nested repo whose commit is not in the parent object db: