Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.46.30.0 fix(privacy): registry-driven remote privacy sweep + world-only filters for list-style read ops (#4572)

Garry Tan872c3d6ae407
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 8dfa600566..c6c29c645a 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "gbrain",
- "version": "0.46.29.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.",
+ "version": "0.46.30.0",
+ "description": "Personal knowledge brain for your coding agent \u2014 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",
"url": "https://github.com/garrytan"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 1253a2f078..3872afdc8c 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "gbrain",
- "version": "0.46.29.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.",
+ "version": "0.46.30.0",
+ "description": "Personal knowledge brain for your coding agent \u2014 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",
"url": "https://github.com/garrytan"
@@ -23,7 +23,7 @@
"interface": {
"displayName": "GBrain",
"shortDescription": "Give your agent a persistent brain: search, synthesis, memory",
- "longDescription": "GBrain wires a personal knowledge brain into every session: hybrid keyword+vector search, entity graph traversal, synthesis, and memory your agent writes itself — served on the starter MCP surface (the seven memory verbs plus the daily-driver brain ops). Bundles the curated brain-first skill set: setup (walks install + gbrain init), cold-start day-one brain filling, ingest, query, briefing, upgrade, and more. Requires the gbrain CLI (bun install -g github:garrytan/gbrain#latest-stable) and a brain (gbrain init); the bundled setup skill walks the rest. Unix (macOS/Linux) only.",
+ "longDescription": "GBrain wires a personal knowledge brain into every session: hybrid keyword+vector search, entity graph traversal, synthesis, and memory your agent writes itself \u2014 served on the starter MCP surface (the seven memory verbs plus the daily-driver brain ops). Bundles the curated brain-first skill set: setup (walks install + gbrain init), cold-start day-one brain filling, ingest, query, briefing, upgrade, and more. Requires the gbrain CLI (bun install -g github:garrytan/gbrain#latest-stable) and a brain (gbrain init); the bundled setup skill walks the rest. Unix (macOS/Linux) only.",
"developerName": "Garry Tan",
"category": "Productivity",
"capabilities": [
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index d84f4d77c5..b962aeb349 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.46.29.0 -->
+<!-- gbrain-runbook-stamp: 0.46.30.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 11e460188f..f81cd2cf96 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,46 @@
All notable changes to GBrain will be documented in this file.
+## [0.46.30.0] - 2026-08-25
+
+Privacy hardening pass: the read-side privacy boundary is now guarded by a
+registry-driven sweep, so the whole class of "a new remote surface forgets
+the world-only filter" fails the build instead of shipping.
+
+### Added
+- **Remote privacy sweep** (`test/remote-privacy-sweep.test.ts`): every
+ remote-callable operation — including ones added in the future — is
+ dispatched against a seeded private corpus in both the single-source and
+ federated caller shapes, and the full response envelope (structured
+ fields, rendered text, error messages, and the hot-memory `_meta`
+ channel) is asserted free of private content. Fail-closed by design: a
+ new operation breaks the suite until it is classified, local-only
+ operations must be denied over non-local transports, and publish-gated
+ operations must deny with their gate named. Companion curated probes
+ landed in the trust-boundary suite (its static sibling).
+
+### Fixed
+- Several list-style read operations now honor page visibility for remote
+ callers the same way page reads and ambient-recall deltas already do
+ (same fix family as the v0.46.29.0 privacy work; found by the new sweep
+ on its first runs). Published aggregate counts and derived statistics
+ are adjusted with the filtered rows — and re-sorted — so remote
+ responses stay self-consistent and reveal nothing about what was
+ filtered; soft-deleted pages and mid-read deletions are handled
+ fail-closed. Trusted local callers are unaffected.
+- `find_anomalies` no longer clamps large-cohort counts to the display cap
+ of its page list when filtering, and `find_orphans`' totals stay
+ coherent for the thin-client doctor's orphan-ratio check.
+
+### To take advantage of v0.46.30.0
+```bash
+gbrain upgrade # no migration needed — handler + test changes only
+gbrain doctor # confirms the upgrade; remote surfaces re-verified
+```
+Remote MCP callers may see slightly fewer rows from list operations on
+brains with private pages — that is the fix working, not data loss; local
+CLI reads are unchanged.
+
## [0.46.29.0] - 2026-08-24
The community wave: 38 contributor PRs landed (37 authors credited below) plus
diff --git a/TODOS.md b/TODOS.md
index 2ac095d733..da8f13f51d 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -7711,3 +7711,52 @@ covers DEAD logs; go-forward capture beyond Claude Code is deliberately absent.
like the main keyword arm; (c) the chat-usage sink is a registry stack with
deregister-on-disconnect (records route to the top LIVE entry), so a
multi-engine process no longer loses its ledger to a closed engine.
+
+## Privacy-sweep follow-ups (filed from the remote-privacy-sweep branch)
+
+- [ ] **P2 — write-side privacy sweep (put_page round-trip class).** The
+ read-side sweep (`test/remote-privacy-sweep.test.ts`) covers what remote
+ callers can READ; it deliberately does not cover the erase-on-write hazard
+ class (#2044 family: a remote get_page → edit → put_page round-trip
+ silently erasing rows the caller never saw) NOR the write-triggered
+ restoration ECHO class (a remote put_page INTO a fence-bearing page whose
+ response envelope echoes #2044-restored private rows — the sweep's phase W
+ targets fresh slugs only, by design, so an echo requires a dedicated
+ harness). Build: put_page round-trips over seeded private corpora with
+ response-echo assertions, anchored on `src/core/import-file.ts`'s
+ restoration mechanism. **Why now-ish:** the read-side sweep found 4 live
+ read leaks on its first runs; the write side has had zero equivalent
+ sweep pressure. Effort: M. Depends on: nothing (read-side sweep already
+ landed as the pattern to copy).
+- [ ] **P2 — source-scope + row-grain hardening for the salience/anomaly/expert
+ arms.** Four classes surfaced by the read-side sweep's review and deferred
+ from the leak PR because each is a family-wide semantics change: (a)
+ `get_recent_salience`/`find_anomalies` never thread `sourceScopeOpts(ctx)`
+ into the engine reads (pre-existing v0.34.1 source-isolation class — a
+ source-bound remote client sees every source's world rows); (b) the whole
+ `findPrivateOnlySlugs` family is slug-grain, so a slug world-in-source-A /
+ private-in-source-B serves the PRIVATE row's own title through row-grain
+ arms (rows carry source_id — a composite-key filter fixes it, but must land
+ family-wide or semantics diverge across ops); (c) the private post-filters
+ run AFTER the engine's LIMIT, so remote callers can get fewer than `limit`
+ rows while world rows exist below the cutoff (push the
+ `privatePagesFilterFragment` predicate into the engine reads, or over-fetch);
+ (d) the two unscoped private-visibility probes are slug-only queries
+ with no slug-leading index (`pages_source_slug_key` leads on source_id) —
+ add a `pages(slug)` btree index when (a)-(c) land; (e) `find_anomalies`
+ baselines (`baseline_mean`/`baseline_stddev`) are computed private-inclusive
+ in both engines, so a mixed cohort's baseline discloses aggregate private
+ activity volume AND a genuinely-anomalous world spike can be suppressed when
+ concurrent private activity inflated the baseline — world-only cohort
+ aggregation belongs in the same engine pass as (a). Effort: M-L. Depends on:
+ nothing, but coordinate with the P3 chokepoint below rather than duplicating.
+- [ ] **P3 — runtime chokepoint for world-only filtering.** Privacy is
+ enforced per-arm/per-column at N call sites (get_page/fetch strip, delta
+ page arm, find_orphans/get_recent_salience/find_anomalies post-filters,
+ context_pack/delta include_private gating); each new remote surface leaks
+ until someone notices — the class has now recurred five times. Move the
+ world-only filter to a single dispatch-layer interceptor (or an
+ engine-level read-scope wrapper) so new ops are world-only BY DEFAULT.
+ High blast radius: touches every read op; do NOT attempt until both
+ sweeps (read-side, landed; write-side, P2 above) are in place as safety
+ nets. Effort: L. Depends on: the P2 write-side sweep.
diff --git a/VERSION b/VERSION
index 600f7521e8..27c784795d 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.46.29.0
\ No newline at end of file
+0.46.30.0
diff --git a/docs/TESTING.md b/docs/TESTING.md
index f05a31ea26..3664b47f84 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -529,6 +529,7 @@ Unit tests and what they cover:
- `test/oauth.test.ts` — OAuth 2.1 provider: register, getClient, `client_credentials` grant exchange, `authorization_code` flow with PKCE challenge/verifier, refresh token rotation, `verifyAccessToken` with both OAuth + legacy `access_tokens` fallback, `revokeToken`, `sweepExpiredTokens`; contract test asserting `scope` + `localOnly` annotations on all operations; `coerceTimestamp` unit cases (null/undefined/string/number/throw-on-NaN); NULL-`expires_at`-as-expired contract for both refresh + access token paths; cascade-delete contract asserting `revoke-client` purges `oauth_tokens` + `oauth_codes` via FK CASCADE; cross-client isolation (wrong-client attempt MUST reject AND rightful owner MUST still succeed atomically afterward); empty-string `redirect_uri` bypass guard; PKCE DCR public-client gate (`token_endpoint_auth_method: "none"` returns no `client_secret`, default `client_secret_post` clients get the one-time-reveal secret, `getClient` NULL→undefined normalization, full PKCE `/authorize` → `/token` round-trip against a public client).
- `test/mcp-dispatch-summarize.test.ts` — `summarizeMcpParams` invariants: declared-keys allow-list intersection, attacker-key-name leak guard (unknown keys counted not named), 1KB byte bucketing for size-probe defense, missing op falls through to fully-redacted shape, declared-keys sorted for deterministic output.
- `test/trust-boundary-contract.test.ts` — fail-closed trust semantics under cast bypass: `ctx.remote === undefined` treated as remote/untrusted at every flipped call site; `as any` and `Partial<>` spreads can't downgrade trust by accident.
+- `test/remote-privacy-sweep.test.ts` — registry-driven remote privacy sweep: every non-localOnly op dispatched remote-shaped through `dispatchToolCall` against a corpus seeded with high-entropy private sentinels, in both scalar and federated caller shapes; the full response envelope (structured fields, rendered text, errors, `_meta.brain_hot_memory`) asserted sentinel-free. Fail-closed maintenance contract: a new op fails the suite until classified in `EXPECTED_OUTCOME` (+ `PARAM_FACTORY` if it can return corpus data); localOnly ops asserted denied over non-stdio transports; publish-gated ops must deny naming their gate. Curated static sibling: `test/operations-trust-boundary.test.ts`.
- `test/check-resolvable-cli.test.ts` — CLI wrapper: exit codes, JSON envelope shape, AGENTS.md fallback chain.
- `test/regression-v0_16_4.test.ts` — `findRepoRoot` regression guard, hermetic startDir parameterization.
- `test/repo-root.test.ts` — `findRepoRoot` walk semantics + default-arg parity; the 4-tier `autoDetectSkillsDir` fallback chain (`$OPENCLAW_WORKSPACE` → `~/.openclaw/workspace` → repo-root → `./skills`); RESOLVER.md/AGENTS.md filename precedence; explicit-env-wins-over-repo-root; tier-0 `$GBRAIN_SKILLS_DIR` valid/invalid/precedence-over-`OPENCLAW_WORKSPACE`; the install-path walk in `autoDetectSkillsDirReadOnly`; no-drift on primary success; `AUTO_DETECT_HINT` + `AUTO_DETECT_HINT_READ_ONLY` content; regression guard asserting the shared `autoDetectSkillsDir` MUST NEVER return `'install_path'` source (how the read-path/write-path split stays safe).
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 5042b303b7..14c012aa7d 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -97,7 +97,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/search/title-match.ts` — pure, zero-I/O title-phrase matcher shared by the production title boost AND NamedThingBench (no drift). `isTitlePhraseMatch(query, title)` returns true when the normalized query is a contiguous token run inside the title with `>= MIN_CONTENT_TOKENS=2` non-stopword tokens, OR an exact full-title match (covers deliberate 1-word chosen names like "Helios"). Token-boundary matching (never raw substring, so "art" doesn't match "Bartholomew"); small conservative English stopword set excluded from the content-token floor (guards against promoting generic pages on stopword-y queries); NFKC normalize so CJK / width variants converge. Exports `tokenizeTitle` + `__test__` internals.
- `src/core/search/alias-normalize.ts` — ONE normalizer shared by the WRITE path (ingest projects frontmatter `aliases:` into `page_aliases`) and the READ path (search matches query against `page_aliases`), so stored aliases can't silently fail to match queries via divergent normalization (same single-source posture as `cjk.ts`). `normalizeAlias(raw)` does NFKC + lowercase + whitespace-collapse + trim + strip one layer of wrapping quotes/brackets; returns `''` for empty (callers MUST skip empty aliases). `normalizeAliasList(value)` coerces a frontmatter scalar / array / comma-list / garbage into a deduped list of normalized non-empty aliases — used by both the ingest projection and the `reindex --aliases` backfill.
- `src/core/search/evidence.ts` — the agent-facing why-it-matched contract (closes the root behavior where an agent read one blended score, decided "no strong match, safe to create", and wrote a duplicate over a fully-developed page). `classifyEvidence(r, opts?)` names the strongest signal (precedence: `alias_hit` > `exact_title_match` > `high_vector_match` (real query↔chunk cosine `SearchResult.cosine` ≥ `DEFAULT_HIGH_COSINE_FLOOR=0.8`, overridable via `EvidenceOpts.cosineFloor` / config `search.evidence_cosine_floor` — never the blended score, so a keyword+boost pile-up can't earn the label; keyless/hermetic runs have no cosine and degrade to keyword-based labels; legacy `HIGH_MATCH_FLOOR=0.85` stays exported for back-compat only) > `keyword_exact` (base ≥ `SOLID_MATCH_FLOOR=0.6`) > `weak_semantic`). `createSafetyFor(evidence)` derives the don't-duplicate hint (`exists`/`probable`/`unknown`) the agent keys off INSTEAD of a raw threshold (a blended RRF/cosine score is not a calibrated probability). `stampEvidence(results, opts?)` stamps `evidence` + `create_safety` in place once at pipeline end (after the alias hop, before slice); idempotent.
-- `src/core/search/private-visibility.ts` (#4352) — page-level `visibility: private` enforcement for untrusted callers; the single trust+config resolver for every remote read surface (search arms, recall's query arm, entity cards, context_pack, get_page/fetch/list_pages, get_chunks/get_versions/get_timeline/get_raw_data, resolve_slugs, get_links/get_backlinks/traverse_graph). Resolution: `ctx.remote === false` → see everything (trusted local CLI); `GBRAIN_REMOTE_PRIVATE_PAGES=1` env or config `search.remote_private_pages` ∈ {visible,true,1} → operator opt-out; otherwise private pages are excluded, FAIL-CLOSED default — a private page reads exactly like a missing one (no existence oracle). `privatePagesFilterFragment(pageAlias)` is the one SQL predicate (`COALESCE(frontmatter->>'visibility','world') <> 'private'`; consumed by `buildVisibilityClause` in sql-ranking.ts behind `SearchOpts.excludePrivate`, both engines' listPages, the relational-arm hydrate, get_page's fuzzy-candidate filter); `isPrivatePage(frontmatter)` is the row-side twin for already-fetched rows; `findPrivateOnlySlugs(engine, slugs, scope)` returns slugs an untrusted caller must not see enumerated (every in-scope page row private; a slug with at least one non-private in-scope page stays visible; dangling endpoints pass through). Visibility posture folds into the query-cache key (knobs_hash) so remote/local results can't cross-contaminate the cache. Runbook: `docs/operations/mcp-surface-runbook.md`.
+- `src/core/search/private-visibility.ts` (#4352) — page-level `visibility: private` enforcement for untrusted callers; the single trust+config resolver for every remote read surface (search arms, recall's query arm, entity cards, context_pack, get_page/fetch/list_pages, get_chunks/get_versions/get_timeline/get_raw_data, resolve_slugs, get_links/get_backlinks/traverse_graph, and the list-style analytics ops find_orphans/get_recent_salience/find_experts/find_anomalies). Resolution: `ctx.remote === false` → see everything (trusted local CLI); `GBRAIN_REMOTE_PRIVATE_PAGES=1` env or config `search.remote_private_pages` ∈ {visible,true,1} → operator opt-out; otherwise private pages are excluded, FAIL-CLOSED default — a private page reads exactly like a missing one (no existence oracle). `privatePagesFilterFragment(pageAlias)` is the one SQL predicate (`COALESCE(frontmatter->>'visibility','world') <> 'private'`; consumed by `buildVisibilityClause` in sql-ranking.ts behind `SearchOpts.excludePrivate`, both engines' listPages, the relational-arm hydrate, get_page's fuzzy-candidate filter); `isPrivatePage(frontmatter)` is the row-side twin for already-fetched rows; `findPrivateOnlySlugs(engine, slugs, scope)` returns slugs an untrusted caller must not see enumerated (every in-scope page row private; a slug with at least one non-private in-scope page stays visible; dangling endpoints pass through). `findWorldVisibleSlugs(engine, slugs, scope)` is the KEEP-list inverse: of the given slugs, which have at least one world-visible page row — deleted rows considered, so a soft-deleted private page still counts as private-only for callers whose raw queries carry no `deleted_at` predicate; fail-closed by construction, since a slug with NO page row at all (hard-purged between a caller's list read and the probe) is simply absent from the keep-set and gets dropped instead of served. `dropPrivateOnlyRows(engine, remote, rows, slugOf, scope)` is the shared post-filter for list-shaped read ops — one gate read + one batched keep-list probe, keeping only rows whose slug has a world-visible page; consumed by `find_orphans` (which also shrinks `total_orphans`/`total_pages`/`total_linkable` with the hidden rows, leaving `excluded` alone so there's no count oracle), `get_recent_salience`, and `find_experts`. `find_anomalies` composes `resolveExcludePrivatePages` + `findWorldVisibleSlugs` directly: private slugs are filtered out of `page_slugs`, rows whose visible slugs empty out are dropped (an empty-but-present row is a hidden-activity oracle), `count` is adjusted by the slugs actually removed and `sigma_observed` recomputed with the engine's own formula, sub-threshold survivors are dropped, and rows re-sort by the published sigma — accepted residuals for >50-page display-capped cohorts are documented at the call site in `src/core/ops/salience.ts`. Visibility posture folds into the query-cache key (knobs_hash) so remote/local results can't cross-contaminate the cache. Runbook: `docs/operations/mcp-surface-runbook.md`.
- `src/commands/search-diagnose.ts` — `gbrain search diagnose "<query>" --target <slug> [--json] [--source <id>]`: Phase-0 retrieval diagnostic. Traces WHERE a target page surfaces (or fails to) across keyword / vector (per-page max-pool) / alias / hybrid layers and names the layer responsible for an incident, so an operator can pin whether the fix is max-pool/innerLimit (vector) vs title/alias. The verdict names the layer that DOES surface the target (or "none"). Pinned by `test/search/search-diagnose.test.ts`.
- `src/commands/reindex-aliases.ts` — `gbrain reindex --aliases [--limit N] [--dry-run] [--json] [--source <id>]`: backfills the free-text alias layer for EXISTING pages whose frontmatter `aliases:` predate the alias table (the import-time projection covers new + changed pages). Reads each page's frontmatter `aliases:`, writes via `engine.setPageAliases`. Idempotent + convergent (setPageAliases replaces a page's alias set) so no op-checkpoint needed; walks `listAllPageRefs` (cheap cross-source enumeration), `--source` narrows. Pinned by `test/search/reindex-aliases.test.ts`.
- `src/eval/retrieval-quality/harness.ts` + `src/commands/eval-retrieval-quality.ts` + `test/fixtures/retrieval-quality/namedthing.jsonl` — NamedThingBench, the retrieval-quality eval that makes the named-thing-miss incident impossible to reintroduce silently. Seven query families, each a distinct failure class: `title-substring` (the direct regression), `generic-to-named` (tourist label → named thing), `alias-synonym` (declared alias / romanization → canonical), `multi-chunk-dilution` (one strong chunk among many weak — stresses max-pool), `short-vs-rich`, `graph-relationship` (guardrail), `hard-negative` (precision guard, must NOT return a page). `gbrain eval retrieval-quality <fixture.jsonl>` runs it with hard gates (e.g. title-substring Hit@1 ≥ 0.95, alias Hit@1 ≥ 0.98, multi-chunk-dilution Hit@3 = 1.0). Pure: caller injects a `SearchFn` (CLI uses `hybridSearch`, tests stub) so it's engine-agnostic. Metric glossary entries (`hit@1`/`hit@3`) added to `src/core/eval/metric-glossary.ts`. Pinned by `test/eval-retrieval-quality.test.ts` + `test/retrieval-quality-harness.test.ts`.
@@ -247,7 +247,8 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/migrate.ts` — schema-migration runner. Owns the `MIGRATIONS` array (source of truth for schema DDL). `Migration` interface carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; mirror in pglite-schema.ts + schema.sql + bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (#1941, opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (#2073, idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — NULL never matched a scoped `AND source_id = …` filter so scoped `code-callers`/`code-callees` returned 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (#4152, additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes). The dedup-index self-heal (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) is NOT version-gated: `runMigrations` invokes `repairTimelineDedupIndex` on every pass (including the no-pending early-return path) because a merge-renumbered migration can leave the version counter past the index change while the index stays the old shape. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice).
- `src/cli.ts` — no-DB fallbacks announce themselves on stderr instead of degrading silently. `dream` dispatch binds the caught engine-connect error and emits `[dream] WARNING: could not connect to DB (...)` before falling through to filesystem-only phases; the `runDream(null, ...)` no-DB fallback is preserved (pinned by `test/cli-dream-engine-warn.test.ts`, 2 subprocess cases against good + bad DATABASE_URL). `doctor` dispatch does the same: when `connectEngine` OR the DB-backed `runDoctor` run throws, it emits `[doctor] DB-backed doctor run failed (...) — falling back to filesystem-only checks`, scrubbing the error message through BOTH `url-redact.ts:redactUrlsInText` and `redact-connection-info.ts:redactConnectionInfo` first, because doctor output is exactly what users paste into issues and CI logs (pinned by the fallback case in `test/doctor-minions-check.test.ts`: stderr note present, credentials absent, stdout stays parseable `--json`).
- `skills/conventions/brain-routing.md` — agent-facing convention skill documenting the canonical 6-tier source resolution chain (flag → env → dotfile → local_path → brain_default → seed_default) with paste-ready decision tables. Linked from CLAUDE.md's "Two organizational axes" section and from `gbrain sources current`'s hint output.
-- `test/operations-trust-boundary.test.ts` + `scripts/check-operations-filter-bypass.sh` — operations trust-boundary contract coverage. Pure assertions over all 74 ops (every op has a scope annotation; every mutating op has a non-read scope; `localOnly: true` ops are excluded from `operations.filter(op => !op.localOnly)`; the seven historically-sensitive localOnly ops snapshot-pinned by name) plus targeted handler-invocation regressions for the two historically-broken HTTP-callable classes: `submit_job` with `name='shell'` + `ctx.remote=true` MUST reject (the HTTP MCP shell-job RCE class), and `search_by_image` with `image_path` + `ctx.remote=true` MUST reject (the P0 image-leak class). `file_upload` and `sync_brain` omitted from handler-invocation tests because they're `localOnly: true` (that path would test an impossible production scenario). The shell guard greps `src/` for any module importing the `operations` value outside the canonical filter site at `src/commands/serve-http.ts` (three import shapes: destructured, aliased, namespace), with an explicit 10-entry allow-list + a literal-string check that `serve-http.ts` still contains `operations.filter(op => !op.localOnly)`. Wired into `bun run verify`.
+- `test/operations-trust-boundary.test.ts` + `scripts/check-operations-filter-bypass.sh` — operations trust-boundary contract coverage. Pure assertions over all 74 ops (every op has a scope annotation; every mutating op has a non-read scope; `localOnly: true` ops are excluded from `operations.filter(op => !op.localOnly)`; the seven historically-sensitive localOnly ops snapshot-pinned by name) plus targeted handler-invocation regressions for the historically-broken HTTP-callable classes: `submit_job` with `name='shell'` + `ctx.remote=true` MUST reject (the HTTP MCP shell-job RCE class); `search_by_image` with `image_path` + `ctx.remote=true` MUST reject (the P0 image-leak class); and the list-op read-leak class — `find_orphans`/`get_recent_salience`/`find_anomalies`/`find_experts` invoked with `ctx.remote=true` over a seeded `visibility: private` page MUST NOT return its slug/title, with a local positive control proving the assertions non-vacuous, count self-consistency assertions pinning the no-count-oracle posture (both orphan denominators shrink with hidden rows; `excluded` untouched; anomaly `count` mirrors the visible slug list), and a soft-delete re-probe pinning the includeDeleted fail-closed path. `file_upload` and `sync_brain` omitted from handler-invocation tests because they're `localOnly: true` (that path would test an impossible production scenario). The shell guard greps `src/` for any module importing the `operations` value outside the canonical filter site at `src/commands/serve-http.ts` (three import shapes: destructured, aliased, namespace), with an explicit 10-entry allow-list + a literal-string check that `serve-http.ts` still contains `operations.filter(op => !op.localOnly)`. Wired into `bun run verify`. Dynamic sibling: `test/remote-privacy-sweep.test.ts` (next entry) — same doctrine, corpus-seeded, catches leaks in ops neither curated list has heard of yet.
+- `test/remote-privacy-sweep.test.ts` — registry-driven, corpus-seeded leak detection across the ENTIRE dispatch surface (closes the read-leak class where a new remote surface forgets the world-only filter). Seeds a hermetic PGLite corpus carrying high-entropy PRIVATE sentinels (private page title/body, a private fact, a non-world take, fence-row content — never slugs, which are legitimately echoed in "Page not found" errors and would false-positive on correct behavior) plus WORLD markers as positive controls; enumerates every non-localOnly op from the registry; dispatches each one remote-shaped through `dispatchToolCall` (the exact layer both MCP transports share) in BOTH caller shapes — scalar source-scoped (like stdio) and federated with an auth-array read grant; and asserts no private sentinel appears anywhere in the serialized response envelope: structured fields, rendered text, error messages, and the `_meta.brain_hot_memory` channel alike. Fail-closed maintenance contract: `EXPECTED_OUTCOME`'s key set must be set-equal to the enumerated registry, so a NEW op FAILS the suite until classified (`data` = must prove corpus contact via a WORLD marker / `ok` / `error` — envelope still sentinel-checked / `denied` = publish-gated, must error naming its `mcp.*` gate; plus a `PARAM_FACTORY` entry if it can return corpus data — the failure message prints exactly what to add). A separate arm asserts every `localOnly` op is denied fail-closed over non-stdio transports; `KNOWN_EXPOSED` op-wide exemptions must stay empty absent written justification + review. Phase W covers mutating ops against fresh slugs (destructive ops last, corpus-intact re-checks between phases). Honest scope: covers the dispatch surface for transport-floor callers; does NOT cover the IPC context-pack handler (`src/mcp/context-pack-handler.ts` bypasses `dispatchToolCall`) or write-triggered restoration echoes — the write-side sweep is a filed TODO. Static siblings: `test/operations-trust-boundary.test.ts` (previous entry) + `scripts/check-operations-filter-bypass.sh`.
- `src/core/content-sanity.ts` — pure assessor for the content-sanity defense. `assessContent(content, opts): SanityVerdict` returns one of `ok | warn_oversize | hard_block_junk_pattern | soft_block_oversize` with `{reason, bytes, matched_pattern_name?}`. Six built-in junk patterns (Cloudflare challenge dumps, CAPTCHAs, 403 dumps, bare error-page titles) compiled at module load; operator literal substrings via `loadOperatorLiterals()` from `src/core/content-sanity-literals.ts`. `ContentSanityBlockError` tagged class is the typed throw shape every wrapper site (`gbrain import`, `put_page` MCP op, `gbrain sync`, `/ingest` webhook) catches via the existing exception flow. The bytes-parity contract pins `Buffer.byteLength(content, 'utf8')` against the embedder's actual byte count so a 499K-byte page can't be soft-blocked on assessment then overflow on embed. Knob resolution chain env > file (`~/.gbrain/config.json`) > DB > defaults. Four knobs: `content_sanity.bytes_warn` (50_000), `content_sanity.bytes_block` (500_000), `content_sanity.junk_patterns_enabled` (true), `content_sanity.disabled` (false; `GBRAIN_NO_SANITY=1` is the loud-stderr kill-switch). New `assessContentSanity(opts): SanityAssessment` returns the three-tier disposition (`shouldQuarantine` / `shouldFlag` + reason/detail) consumed by `importFromContent` and `gbrain quarantine scan`; adds the fuzzy prose-vs-markup ratio pass (markup chars / total above `max_markup_ratio`; code pages exempt; gated by `prose_check_enabled`) on top of the byte + junk-pattern passes. Three more knobs: `content_sanity.junk_disposition` (`quarantine` default | `reject`; no env override — a destructive flip belongs in explicit config), `content_sanity.max_markup_ratio` (0.85, env `GBRAIN_MAX_MARKUP_RATIO`, clamped `(0,1]`), `content_sanity.prose_check_enabled` (true). Pinned by `test/content-sanity.test.ts`. new `assessContentSanity(opts): SanityAssessment` returns the three-tier disposition (`shouldQuarantine` / `shouldFlag` + reason/detail) consumed by `importFromContent` and `gbrain quarantine scan`. Adds the fuzzy prose-vs-markup ratio pass (markup chars / total chars above `max_markup_ratio`, default 0.85; code pages exempt; gated by `prose_check_enabled`, default true) on top of the byte + junk-pattern passes. Three config knobs: `content_sanity.junk_disposition` (`quarantine` default | `reject`; no env override), `content_sanity.max_markup_ratio` (0.85, env `GBRAIN_MAX_MARKUP_RATIO`, clamped `(0,1]`), `content_sanity.prose_check_enabled` (true). Same env > file > DB > defaults resolution chain. Pinned by `test/content-sanity.test.ts`.
- `src/core/content-sanity-literals.ts` — operator literal-substring loader. Reads `~/.gbrain/junk-substrings.txt`, one literal per non-comment non-blank line; optional `# name=<id>` header pairs an identifier with the following literal so audit JSONL groups by site (`linkedin_auth_wall`, `reddit_blocked`, etc.). Fail-soft on ENOENT (missing file = empty array). Loaded on every ingest. Deliberately literal substrings (NOT regex) to defeat ReDoS. Pinned by `test/content-sanity-literals.test.ts`.
- `src/core/embed-skip.ts` — 5-site shared predicate for the soft-block embed-skip filter. Exports `shouldSkipEmbedding(frontmatter): boolean` (JS predicate for callers holding the page in memory), `EMBED_SKIP_SQL_FRAGMENT` (parameterized SQL clause shared by Postgres + PGLite via `executeRaw`), and `buildEmbedSkipMarker(reason: string)` (writes `frontmatter.embed_skip = {at: ISO_TIMESTAMP, reason}` so the JSONB shape stays uniform). The 5 sites: `embed.ts --stale`, `embed.ts --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks`. Single source of truth so the filter cannot drift. Pinned by `test/embed-skip.test.ts` (cross-site invariant + JSONB shape).
@@ -333,10 +334,10 @@ v0.46: the `sync` handler forwards `job.data.github_item` ({repo, number, kind})
- `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 no longer 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 the `MIGRATIONS` array in `src/core/migrate.ts`. `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 (running in-process removes the spawn that died 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` — ZeroEntropy sunset notice migration, detect-and-notify ONLY. Detects the HOST brain's exposure via `src/core/ze-exposure.ts` (read-only); when exposed — or when exposure is UNKNOWN, fail-safe — prints the ACTION REQUIRED banner and appends one idempotent entry to `~/.gbrain/migrations/pending-host-work.jsonl` pointing the host agent at `skills/migrations/v0.46.3.0.md`. Performs NO config writes, NO pinning, and never invokes `migrate embeddings` (the migration costs money and needs a target key — that decision belongs to the user/agent via the playbook). UNKNOWN returns `complete` with an `exposure_unknown` detail rather than `partial` (three consecutive partials would wedge the whole migration chain behind `--force-retry`); the stage-2 upgrade banner and `gbrain doctor` carry the ongoing nag instead. Host-scoped (apply-migrations runs once per host with a global completed.jsonl); mounted/team brains are covered by the per-brain stage-2 banner (`ze_sunset_notice_v2_shown` in each brain's own DB config) + doctor gates.
- `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` (pre-subagent-era brains), 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. Fixes the double-encode bug on Postgres; PGLite no-ops. Idempotent. Pinned by `test/repair-jsonb.test.ts` + `test/doctor.test.ts`.
-- `src/commands/orphans.ts` — `gbrain orphans [--json] [--count] [--include-pseudo] [--source <id>] [--mode islanded|inbound]`: surfaces disconnected pages, grouped by domain (auto-generated/raw/pseudo filtered by default). The DEFAULT definition is `islanded` — no live inbound AND no live outbound link — matching `get_health.orphan_pages` so doctor, health, and this command agree by construction; `--mode inbound` restores the legacy no-inbound-only view (pages that link out but are never linked TO). Also exposed as `find_orphans` MCP op (same `mode` param; an unknown mode is rejected loudly, never silently coerced to the default). `findOrphans`/`getOrphansData` (the canonical pure fn shared with doctor's `orphan_ratio`) takes `{ sourceId?, sourceIds?, mode? }`; `BrainEngine.findOrphanPages(opts?)` (both engines) scopes ONLY the candidate side (`p.source_id = $1` scalar, or `= ANY($1::text[])` federated) while still counting inbound links from ANY source — a page in source X linked FROM source Y is reachable, so NOT an orphan of X (deliberate definition; the stricter intra-source-only reading is rejected). `--source` is an explicit raw-flag parse (NOT `resolveSourceWithTier`, which would scope bare invocations to a default). The `total_linkable` denominator enumerates ALL live pages (scoped) and subtracts every excluded-by-slug page (templates/, scratch/, etc.) so excluded NON-orphan pages with inbound links don't inflate it and suppress warnings. The `find_orphans` MCP op threads `sourceScopeOpts(ctx)` so a source-bound OAuth client doesn't see brain-wide orphans. `gbrain doctor --source <id>` scopes `orphan_ratio` and, under explicit `--source` below 100 entity pages, reports the ratio with a low-scale caveat (thin-client `doctor --source` orphan_ratio remains brain-wide — TODO). Pinned by `test/orphans-source-scope.test.ts` (PGLite) + `test/orphans-mode-islanded.test.ts` (islanded-default + mode contract) + `test/e2e/engine-parity.test.ts` (Postgres↔PGLite scalar + federated parity). Contributed by @knee5.
+- `src/commands/orphans.ts` — `gbrain orphans [--json] [--count] [--include-pseudo] [--source <id>] [--mode islanded|inbound]`: surfaces disconnected pages, grouped by domain (auto-generated/raw/pseudo filtered by default). The DEFAULT definition is `islanded` — no live inbound AND no live outbound link — matching `get_health.orphan_pages` so doctor, health, and this command agree by construction; `--mode inbound` restores the legacy no-inbound-only view (pages that link out but are never linked TO). Also exposed as `find_orphans` MCP op (same `mode` param; an unknown mode is rejected loudly, never silently coerced to the default). `findOrphans`/`getOrphansData` (the canonical pure fn shared with doctor's `orphan_ratio`) takes `{ sourceId?, sourceIds?, mode? }`; `BrainEngine.findOrphanPages(opts?)` (both engines) scopes ONLY the candidate side (`p.source_id = $1` scalar, or `= ANY($1::text[])` federated) while still counting inbound links from ANY source — a page in source X linked FROM source Y is reachable, so NOT an orphan of X (deliberate definition; the stricter intra-source-only reading is rejected). `--source` is an explicit raw-flag parse (NOT `resolveSourceWithTier`, which would scope bare invocations to a default). The `total_linkable` denominator enumerates ALL live pages (scoped) and subtracts every excluded-by-slug page (templates/, scratch/, etc.) so excluded NON-orphan pages with inbound links don't inflate it and suppress warnings. The `find_orphans` MCP op threads `sourceScopeOpts(ctx)` so a source-bound OAuth client doesn't see brain-wide orphans, and for remote callers post-filters `visibility: private` pages via `dropPrivateOnlyRows` (`src/core/search/private-visibility.ts`): hidden orphans vanish from every published counter — `total_orphans`, `total_pages`, and `total_linkable` all shrink with them while `excluded` is untouched (folding them into `excluded` would be a one-call private-orphan-count oracle, since with `include_pseudo:true` the unfiltered op guarantees `excluded === 0`), keeping doctor-remote's orphan ratio and the `excluded === total_pages - total_linkable` invariant coherent over the world-visible universe. `gbrain doctor --source <id>` scopes `orphan_ratio` and, under explicit `--source` below 100 entity pages, reports the ratio with a low-scale caveat (thin-client `doctor --source` orphan_ratio remains brain-wide — TODO). Pinned by `test/orphans-source-scope.test.ts` (PGLite) + `test/orphans-mode-islanded.test.ts` (islanded-default + mode contract) + `test/e2e/engine-parity.test.ts` (Postgres↔PGLite scalar + federated parity). Contributed by @knee5.
- `src/commands/salience.ts` — `gbrain salience [--days N] [--limit N] [--kind PREFIX] [--json]`: pages ranked by emotional + activity salience over a recency window. Mirrors orphans.ts shape (pure data fn + JSON formatter + human formatter). Calls `engine.getRecentSalience(opts)`. Score formula: `(emotional_weight × 5) + ln(1 + active_take_count) + 1/(1 + days_since_update)`.
- `src/commands/anomalies.ts` — `gbrain anomalies [--since YYYY-MM-DD] [--lookback-days N] [--sigma N] [--json]`: cohort-level activity outliers. Calls `engine.findAnomalies(opts)`. Two cohort kinds: tag, type.
-- `src/commands/whoknows.ts` — `gbrain whoknows <topic> [--explain] [--limit N] [--json]`: expertise + relationship-proximity routing. Mirrors salience/anomalies shape (pure `rankCandidates()` + `findExperts()` orchestrator + `runWhoknows()` CLI dispatch + thin-client routing). MCP op = `find_experts` (scope: read, localOnly: false). Ranking formula: `score = log(1 + raw_match) × max(0.1, exp(-days/180)) × (0.5 + 0.5 × salience)` where `raw_match` is hybridSearch's RRF+source-boost score. Filters at SQL via `SearchOpts.types: ['person', 'company']` (no post-filter waste); hybridSearch's internal salience+recency boosts are intentionally disabled so the locked formula applies on a clean signal. Floors prevent multiplicative-zero edge cases (cold-start people stay visible); ties break alphabetically by slug for determinism. 16 unit tests in `test/whoknows.test.ts` pin the math. with `src/core/operations.ts:find_experts`: T1.5 wiring sites. Pack-aware via `expertTypesFromPack(pack.manifest)` from `best-effort.ts`. Pack-load failure → EMPTY filter (NOT hardcoded `['person', 'company']` defaults). A `researcher` type declared `--expert` now surfaces in `whoknows` results.
+- `src/commands/whoknows.ts` — `gbrain whoknows <topic> [--explain] [--limit N] [--json]`: expertise + relationship-proximity routing. Mirrors salience/anomalies shape (pure `rankCandidates()` + `findExperts()` orchestrator + `runWhoknows()` CLI dispatch + thin-client routing). MCP op = `find_experts` (scope: read, localOnly: false); for remote callers it post-filters `visibility: private` pages from the rankings via `dropPrivateOnlyRows` (a private page's slug/title/scores never reach untrusted readers; trusted local CLI sees the unfiltered view). Ranking formula: `score = log(1 + raw_match) × max(0.1, exp(-days/180)) × (0.5 + 0.5 × salience)` where `raw_match` is hybridSearch's RRF+source-boost score. Filters at SQL via `SearchOpts.types: ['person', 'company']` (no post-filter waste); hybridSearch's internal salience+recency boosts are intentionally disabled so the locked formula applies on a clean signal. Floors prevent multiplicative-zero edge cases (cold-start people stay visible); ties break alphabetically by slug for determinism. 16 unit tests in `test/whoknows.test.ts` pin the math. with `src/core/operations.ts:find_experts`: T1.5 wiring sites. Pack-aware via `expertTypesFromPack(pack.manifest)` from `best-effort.ts`. Pack-load failure → EMPTY filter (NOT hardcoded `['person', 'company']` defaults). A `researcher` type declared `--expert` now surfaces in `whoknows` results.
- `src/commands/eval-whoknows.ts` — `gbrain eval whoknows <fixture.jsonl> [--json] [--skip-replay]`: two-layer eval gate. Layer 1 quality (hand-labeled fixture, top-3 hit rate ≥ 0.8). Layer 2 regression (`eval_candidates` replay set-Jaccard@3 ≥ 0.4). Sparseness fallback: < 20 replay-eligible rows → Layer 2 auto-skips with stderr warning. Stable JSON envelope with `schema_version: 1`; exit 0/1/2 for pass/fail/usage. `WhoknowsFn` callable abstraction makes the gates impl-agnostic; `runEvalWhoknows(engine: BrainEngine | null, args)` picks the impl at entry — thin-client mode (`isThinClient(cfg)`) routes per-query through `callRemoteTool(cfg, 'find_experts', {topic, limit})`, local mode calls `findExperts(engine, ...)` directly. cli.ts adds a thin-client bypass before `connectEngine` (dispatch shape under `src/commands/eval.ts`); the regression gate auto-skips in thin-client mode (no DB access to `eval_candidates`). Public exports `jaccardAtK`, `topKHit`, `readFixture`, `WhoknowsFn`, threshold constants pinned by `test/eval-whoknows.test.ts` (25 cases incl. null-engine signature contract).
- `test/fixtures/whoknows-eval.jsonl` — 10-row synthetic placeholder demonstrating the eval-fixture schema (`{query, expected_top_3_slugs, notes?}` JSONL). End users replace with their own real queries; placeholder uses obviously-example slugs (`wiki/people/example-alice`). Drives `test/e2e/whoknows.test.ts` (seeds a matching synthetic brain, asserts the >=80% gate) and the `whoknows_health` doctor check.
- `src/core/skillopt/` + `src/commands/skillopt.ts` + `skills/skill-optimizer/` — self-evolving skill optimization grounded in the SkillOpt paper (arXiv 2605.23904). `gbrain skillopt <skill>` treats `SKILL.md` as trainable parameters of a frozen agent: validation-gated (median-of-3 + epsilon=0.05), budget-capped (preflight estimator), per-skill DB-locked (`tryAcquireDbLock('skillopt:<name>', 60min)`), atomic-versioned (history-intent-first 5-step commit), body-only mutations (frontmatter forbidden). Rollouts use `gateway.toolLoop` directly with no-op persistence callbacks (zero `subagent_messages` pollution) + a read-only tool allowlist derived from `BRAIN_TOOL_ALLOWLIST` minus `put_page`/`submit_job`/`file_upload`. Two reflect calls per step; rejected-edit buffer LRU-bounded to 100; bundled-skill gate; bootstrap workflow (sentinel + `--bootstrap-reviewed`); D_sel floor (>=5 with `--split` override); audit JSONL via `audit-writer.ts`. Added to `ALL_PHASES` after `patterns` (default OFF; opt-in via `gbrain config set cycle.skillopt.enabled true`); cycle phase wrapper at `src/core/skillopt/cycle-phase.ts` walks stale skills with per-skill ($0.50) + brain-wide ($2.00) caps. Added to `PROTECTED_JOB_NAMES`. Surface: dream-cycle phase wrapper; `--all` batch mode (`src/core/skillopt/batch.ts:runBatchAll`); `--target-models` fleet (`runFleet` parallel per-model receipts under `skillopt/fleet/<slug>/`); MCP op `run_skillopt` (admin scope + per-skill `skillopt.allowed_skills` allowlist, NOT localOnly, validates `skill_name` kebab-only + confines caller-supplied benchmark/held-out paths to skillsDir for remote callers); Minion `skillopt` handler + `--background` with `allowProtectedSubmit: true`; write-flavored optimization via `src/core/skillopt/write-capture.ts:buildWriteCaptureRegistry` (virtual `put_page`/`submit_job`/`file_upload` captured in-memory; `--write-capture` flag); held-out real-user test set via `src/core/skillopt/held-out.ts` (capture infra at `~/.gbrain/skillopt-captures/<skill>/<run>.jsonl`, `--held-out <path>` flag, `runHeldOutGate` candidate >= baseline). Hermetic via DI seams (`opts.chatFn` for optimizer + judge; `opts.toolLoopFn` for rollouts; no `mock.module`). `--bootstrap-from-skill` → `runBootstrapFromSkill` in `src/core/skillopt/bootstrap-benchmark.ts`: reads `SKILL.md` directly (no `routing-eval.jsonl`), makes ONE LLM call emitting a full starter benchmark (tasks + rule judges) as JSONL, parsed line-by-line with skip-bad-line salvage and a min-2-valid-checks-per-task drop; provider/transport errors PROPAGATE (not collapsed to `bootstrap_empty`). `--bootstrap-tasks N` (default 15, capped 50); `maxTokens` scales `min(8000, max(4000, N*220))`. The stderr REVIEW line prints the literal `gbrain skillopt <name> --bootstrap-reviewed --split 1:1:1` — load-bearing because the default `4:1:5` split makes a 15-task starter's `D_sel = floor(15/10) = 1`, below the `>=5` floor, so a 15-task benchmark needs `--split 1:1:1`. Both bootstrap generators share `assertBenchmarkAbsent` + `readSkillBodyOrThrow`; `--bootstrap-from-skill` is mutually exclusive with `--bootstrap-from-routing`/`--benchmark`/`--all`/`--target-models`/`--resume`. Generated rule judges are explicitly WEAK DRAFTS to be strengthened during the review gate. The F11 held-out gate is wired: `--held-out <path>` is parsed and threaded through every caller (CLI main + `--background` `held_out_path` + batch/fleet `heldOutPath` + the `run_skillopt` `held_out_path` param), running at CHECKPOINT ACCEPTANCE so no-mutate/fleet paths can't promote a held-out-failing candidate. `assertBundledMutationHeldOut` in bundled-skill-gate.ts: bundled + `--allow-mutate-bundled` requires a NON-EMPTY held-out (`MIN_HELD_OUT_SIZE = D_SEL_MIN_SIZE` = 5, derived so they can't desync) or hard-refuses (exit 2), for ALL callers (they funnel through `runSkillOpt`); held-out must be task_id-DISJOINT from the benchmark (overlap rejected — can't catch overfitting). `receipt.baseline_sel_score` populated + a real final-test eval (`test_score` + `baseline_test_score`) scoring best + baseline on `split.test`; shared `scoreSkillOnTasks` primitive (validate-gate.ts) backs baseline/final-test/held-out scoring. `--no-mutate` writes proposed.md via `writeProposed` in version-store.ts. `maxRuntimeMin` ENFORCED (wall-clock deadline between steps → `skillopt_runtime_exceeded` → outcome aborted). Three eval-internal ablation opts on `SkillOptOpts` (NOT on CLI): `reflectMode` (`'both'`/`'failure-only'`), `disableValidationGate` (greedy-accept), `optimizerMode` (`'reflect'`/`'one-shot-rewrite'`), recorded in `RunReceipt` + audit `run_start` for replayability; `ROLLOUT_SUCCESS_THRESHOLD = 0.5` named constant for the partition; one-shot fence-strip is anchored (`^```...```$`) so an embedded code sample isn't truncated. Budget no-pricing fix: Claude Haiku 4.5's dateless canonical id `claude-haiku-4-5` is in `src/core/anthropic-pricing.ts` (a `BudgetTracker`-capped run on Haiku otherwise threw `no_pricing` on the FIRST `chat()` of every rollout); `runValidationGate` (validate-gate.ts) scans settled results for `isMustAbortError(error)` (from `worker-pool.ts`; `BUDGET_EXHAUSTED` is in `MUST_ABORT_ERROR_TAGS`) and re-throws so the caller aborts loudly instead of recording a hollow `selScore:0` — ordinary non-abort rollout errors still fail-open to `score:0` (judge-hiccup posture preserved). Pinned by 152 tests across 18 files (foundation + adversarial + v2 surface + E2E PGLite serial), `test/skillopt/bootstrap-from-skill.test.ts` (20 cases), `test/skillopt/rollout.test.ts`, `test/skillopt/validate-gate-abort.test.ts` (3 cases), held-out ENFORCE + one-shot-rewrite unit cases, and e2e (F11 block/allow, bundled no-mutate, runtime deadline, receipt honesty, held-out disjointness, no-DB-pollution). Drives the Track B SkillOpt benchmark suite in the sibling `gbrain-evals` repo.
diff --git a/docs/operations/mcp-surface-runbook.md b/docs/operations/mcp-surface-runbook.md
index e0fe70ab6e..a44967c735 100644
--- a/docs/operations/mcp-surface-runbook.md
+++ b/docs/operations/mcp-surface-runbook.md
@@ -138,8 +138,12 @@ remote/untrusted read path by default (fail-closed; trusted local CLI —
`ctx.remote === false` — always sees everything). The gate covers search +
recall's query arm, entity cards / context_pack / delta, and the page read
ops: `get_page` / `fetch` / `list_pages`, `get_chunks` / `get_versions` /
-`get_timeline` / `get_raw_data`, `resolve_slugs`, and
-`get_links` / `get_backlinks` / `traverse_graph`. A gated page reads exactly
+`get_timeline` / `get_raw_data`, `resolve_slugs`,
+`get_links` / `get_backlinks` / `traverse_graph`, and the list-style
+analytics ops `find_orphans` / `get_recent_salience` / `find_anomalies` /
+`find_experts` (published counts and derived statistics are adjusted with
+the filtered rows, so remote responses stay self-consistent and reveal
+nothing about what was filtered). A gated page reads exactly
like a missing one (no existence oracle), and link/graph output never
enumerates private slugs.
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index a6509dff15..b6b8b0b642 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.46.29.0",
+ "version": "0.46.30.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"configSchema": {
diff --git a/package.json b/package.json
index da6261bc54..50c99a6c7f 100644
--- a/package.json
+++ b/package.json
@@ -171,7 +171,7 @@
"bun": ">=1.3.10"
},
"license": "MIT",
- "version": "0.46.29.0",
+ "version": "0.46.30.0",
"overrides": {
"@hono/node-server": "^2.0.5",
"fast-uri": "^3.1.5",
diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index 0fa902f2e7..2bb923e9f6 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.46.29.0",
+ "version": "0.46.30.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 — 18 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index be44980c77..17fec60257 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.46.29.0",
+ "version": "0.46.30.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 — 18 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.md
index 740728e562..4a5424afc7 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.46.29.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.46.30.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-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index 3ee39299c3..ea6c214c68 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.46.29.0",
+ "version": "0.46.30.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 — 17 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index dc61c9fb13..ed05319f78 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.46.29.0",
+ "version": "0.46.30.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 — 17 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.md
index b8d59119c2..6060077718 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.46.29.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.46.30.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.md
index 88ead63c75..972858d5d5 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.46.29.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.46.30.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/src/core/ops/insights.ts b/src/core/ops/insights.ts
index 73e95dee90..ba2f9dfe37 100644
--- a/src/core/ops/insights.ts
+++ b/src/core/ops/insights.ts
@@ -17,6 +17,7 @@ import {
FIND_CONTRADICTIONS_DESCRIPTION,
FIND_TRAJECTORY_DESCRIPTION,
} from '../operations-descriptions.ts';
+import { dropPrivateOnlyRows } from '../search/private-visibility.ts';
// --- v0.43 (#2095): push-based context — the brain volunteers pages ---
@@ -152,13 +153,18 @@ const find_experts: Operation = {
const { loadActivePackBestEffort, expertTypesFromPack } = await import('../schema-pack/index.ts');
const pack = await loadActivePackBestEffort(ctx);
const types = pack ? expertTypesFromPack(pack.manifest) : [];
- return findExperts(ctx.engine, {
+ const scope = sourceScopeOpts(ctx);
+ const experts = await findExperts(ctx.engine, {
topic,
limit: typeof p.limit === 'number' ? p.limit : undefined,
explain: p.explain === true,
types: types as never,
- ...sourceScopeOpts(ctx),
+ ...scope,
});
+ // A `visibility: private` page's slug/title/scores must not reach remote
+ // readers through the expertise rankings (same read-leak class as the
+ // delta page arm / find_orphans / get_recent_salience).
+ return dropPrivateOnlyRows(ctx.engine, ctx.remote, experts, e => e.slug, scope);
},
// hidden: 'whoknows' is in CLI_ONLY (src/cli.ts) — runWhoknows owns the CLI
// surface (ranked table + per-factor explain + thin-client routing) and was
diff --git a/src/core/ops/orphans.ts b/src/core/ops/orphans.ts
index 13e24993b9..2efc7d74d1 100644
--- a/src/core/ops/orphans.ts
+++ b/src/core/ops/orphans.ts
@@ -7,6 +7,7 @@
import type { Operation } from './contract.ts';
import { sourceScopeOpts } from './context.ts';
+import { dropPrivateOnlyRows } from '../search/private-visibility.ts';
// --- Orphans ---
@@ -38,11 +39,33 @@ const find_orphans: Operation = {
// source-bound OAuth client's scope — a read leak in the v0.34.1
// source-isolation class. Local CLI callers route through `gbrain
// orphans --source` instead (ctx.remote === false → empty scope here).
- return findOrphans(ctx.engine, {
+ const scope = sourceScopeOpts(ctx);
+ const result = await findOrphans(ctx.engine, {
includePseudo: (p.include_pseudo as boolean) || false,
...(mode ? { mode } : {}),
- ...sourceScopeOpts(ctx),
+ ...scope,
});
+ // An orphaned `visibility: private` page's slug + title must not reach
+ // remote readers (same read-leak class as the delta page arm; same
+ // helper family as the get_page/resolve_slugs gates). Hidden orphans
+ // VANISH from every published counter — total_pages and total_linkable
+ // shrink with them and `excluded` is left alone. Folding them into
+ // `excluded` instead would relocate the count, not hide it: with
+ // include_pseudo:true the unfiltered op guarantees excluded === 0, so a
+ // non-zero value would be an exact one-call private-orphan-count oracle.
+ // Subtracting from both denominators keeps doctor-remote's
+ // total_orphans/total_linkable ratio and the excluded ===
+ // total_pages - total_linkable invariant coherent over the
+ // world-visible universe.
+ const kept = await dropPrivateOnlyRows(ctx.engine, ctx.remote, result.orphans, o => o.slug, scope);
+ const hiddenCount = result.orphans.length - kept.length;
+ if (hiddenCount > 0) {
+ result.orphans = kept;
+ result.total_orphans = kept.length;
+ result.total_pages -= hiddenCount;
+ result.total_linkable -= hiddenCount;
+ }
+ return result;
},
cliHints: { name: 'orphans', hidden: true },
};
diff --git a/src/core/ops/salience.ts b/src/core/ops/salience.ts
index 79c7338cbd..69965e6aef 100644
--- a/src/core/ops/salience.ts
+++ b/src/core/ops/salience.ts
@@ -13,6 +13,11 @@ import {
GET_RECENT_SALIENCE_DESCRIPTION,
FIND_ANOMALIES_DESCRIPTION,
} from '../operations-descriptions.ts';
+import {
+ dropPrivateOnlyRows,
+ findWorldVisibleSlugs,
+ resolveExcludePrivatePages,
+} from '../search/private-visibility.ts';
// --- v0.29: Salience + Anomaly Detection ---
@@ -44,12 +49,17 @@ const get_recent_salience: Operation = {
},
handler: async (ctx, p) => {
const recencyBias = p.recency_bias === 'on' ? 'on' : 'flat';
- return ctx.engine.getRecentSalience({
+ const rows = await ctx.engine.getRecentSalience({
days: typeof p.days === 'number' ? p.days : undefined,
limit: typeof p.limit === 'number' ? p.limit : undefined,
slugPrefix: typeof p.slugPrefix === 'string' ? p.slugPrefix : undefined,
recency_bias: recencyBias,
});
+ // A `visibility: private` page's slug/title/metadata must not reach
+ // remote readers through the salience list (same read-leak class as the
+ // delta page arm). The salience read is unscoped, so the private check
+ // spans the same span (empty scope).
+ return dropPrivateOnlyRows(ctx.engine, ctx.remote, rows, r => r.slug, {});
},
// hidden: 'salience' is in CLI_ONLY (src/cli.ts) — runSalience owns the CLI
// surface; the non-hidden hint was dead (CLI_ONLY wins at dispatch).
@@ -75,11 +85,66 @@ const find_anomalies: Operation = {
},
},
handler: async (ctx, p) => {
- return ctx.engine.findAnomalies({
+ const anomalies = await ctx.engine.findAnomalies({
since: typeof p.since === 'string' ? p.since : undefined,
lookback_days: typeof p.lookback_days === 'number' ? p.lookback_days : undefined,
sigma: typeof p.sigma === 'number' ? p.sigma : undefined,
});
+ // AnomalyResult.page_slugs can name `visibility: private` pages — a
+ // private slug is still page metadata a remote reader must not see.
+ // Leak shapes closed together for remote callers: the slug list is
+ // filtered; rows whose visible slugs empty out are dropped (an
+ // empty-but-present row is a hidden-activity oracle, and its
+ // cohort_value can be a tag name sourced only from private pages);
+ // `count` is adjusted by the slugs actually removed — NEVER recomputed
+ // from the list, which is display-capped at 50 (cycle/anomaly.ts) and
+ // would clamp big cohorts; `sigma_observed` is recomputed from the
+ // adjusted count with the engine's own formula so the stats stay
+ // mutually consistent and the pre-filter count is not reconstructible
+ // from mean + sigma*stddev; and a row that no longer clears the
+ // caller's threshold on its VISIBLE pages is dropped (a sub-threshold
+ // survivor is itself a hidden-activity tell). Residuals, accepted and
+ // documented: for >50-page cohorts, private slugs beyond the display
+ // cap are invisible to the adjustment (bounded imprecision, not an
+ // exact oracle), and the flip side — a >50 cohort whose visible sample
+ // is ALL private is dropped wholly even if uncapped world pages drove
+ // it (fails closed toward confidentiality); baseline_mean/stddev remain
+ // private-inclusive (world-only cohort aggregation is the deferred
+ // source-scope/row-grain TODO).
+ // includeDeleted: the anomaly queries have no deleted_at predicate, so
+ // a soft-deleted private page must still count as private-only.
+ if (await resolveExcludePrivatePages(ctx.engine, ctx.remote)) {
+ const all = [...new Set(anomalies.flatMap(a => a.page_slugs))];
+ // Keep-list probe (fail-closed): a slug hard-purged between the
+ // engine read and this probe has no page row and simply isn't kept,
+ // instead of being served because "no row" looked like "not private".
+ const keep = await findWorldVisibleSlugs(ctx.engine, all, {});
+ if (keep.size < all.length) {
+ const sigmaThreshold = typeof p.sigma === 'number' ? p.sigma : 3.0;
+ const filtered = anomalies.flatMap(a => {
+ const kept = a.page_slugs.filter(s => keep.has(s));
+ const removed = a.page_slugs.length - kept.length;
+ if (removed === 0) return [a]; // untouched rows pass through verbatim
+ if (kept.length === 0) return [];
+ const count = a.count - removed;
+ const sigma_observed =
+ a.baseline_stddev > 0
+ ? (count - a.baseline_mean) / a.baseline_stddev
+ : count - a.baseline_mean;
+ const stillAnomalous =
+ a.baseline_stddev > 0
+ ? count > a.baseline_mean + sigmaThreshold * a.baseline_stddev
+ : count > a.baseline_mean + 1;
+ if (!stillAnomalous) return [];
+ return [{ ...a, page_slugs: kept, count, sigma_observed }];
+ });
+ // Re-sort by the PUBLISHED sigma (engine sorts by pre-filter sigma,
+ // cycle/anomaly.ts) — otherwise an out-of-order pair is an
+ // ordering-channel tell that a row was privately adjusted.
+ return filtered.sort((x, y) => y.sigma_observed - x.sigma_observed);
+ }
+ }
+ return anomalies;
},
// hidden: 'anomalies' is in CLI_ONLY (src/cli.ts) — runAnomalies owns the
// CLI surface; the non-hidden hint was dead (CLI_ONLY wins at dispatch).
diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.ts
index fb8ed5d30c..071ba8f13b 100644
--- a/src/core/search/private-visibility.ts
+++ b/src/core/search/private-visibility.ts
@@ -143,3 +143,65 @@ export async function resolveExcludePrivatePages(
}
return !expose;
}
+
+/**
+ * KEEP-list inverse of findPrivateOnlySlugs: of the given slugs, which have
+ * at least one world-visible page row (deleted rows considered — see
+ * findWorldVisibleSlugs' consumers for why)? Fail-closed by construction: a
+ * slug with NO page row at all (e.g. hard-purged between a caller's list
+ * read and this probe) is simply absent from the keep-set, so a
+ * keep-list consumer drops it instead of serving it — the drop-list shape
+ * fails OPEN on exactly that TOCTOU window.
+ */
+export async function findWorldVisibleSlugs(
+ engine: BrainEngine,
+ slugs: string[],
+ scope: { sourceId?: string; sourceIds?: string[] } = {},
+): Promise<Set<string>> {
+ if (slugs.length === 0) return new Set();
+ const params: unknown[] = [slugs];
+ let scopeClause = '';
+ if (scope.sourceIds && scope.sourceIds.length > 0) {
+ params.push(scope.sourceIds);
+ scopeClause = `AND p.source_id = ANY($${params.length}::text[])`;
+ } else if (scope.sourceId) {
+ params.push(scope.sourceId);
+ scopeClause = `AND p.source_id = $${params.length}`;
+ }
+ const rows = await engine.executeRaw<{ slug: string }>(
+ `SELECT p.slug FROM pages p
+ WHERE p.slug = ANY($1::text[])
+ ${scopeClause}
+ GROUP BY p.slug
+ HAVING bool_or(${privatePagesFilterFragment('p')})`,
+ params,
+ );
+ return new Set(rows.map(r => r.slug));
+}
+
+/**
+ * Shared post-filter for list-shaped read ops (find_orphans,
+ * get_recent_salience, find_experts): one gate read + one batched KEEP-list
+ * probe, keeping only rows whose slug has a world-visible page row.
+ *
+ * Deleted rows are considered by the probe on purpose: some callers' raw
+ * list queries carry no `deleted_at` predicate, so a soft-deleted private
+ * page can still be IN the rows — a live-rows-only probe would never see
+ * it and the filter would fail open (same fail-closed reasoning as
+ * slugHiddenFromCaller above). And the keep-list shape means a slug whose
+ * page row vanished entirely (concurrent purge) drops out too, instead of
+ * being served because "no row" looked like "not private".
+ */
+export async function dropPrivateOnlyRows<T>(
+ engine: BrainEngine,
+ remote: boolean | undefined,
+ rows: T[],
+ slugOf: (row: T) => string,
+ scope: { sourceId?: string; sourceIds?: string[] } = {},
+): Promise<T[]> {
+ if (rows.length === 0) return rows;
+ if (!(await resolveExcludePrivatePages(engine, remote))) return rows;
+ const keep = await findWorldVisibleSlugs(engine, rows.map(slugOf), scope);
+ if (keep.size === rows.length) return rows;
+ return rows.filter(r => keep.has(slugOf(r)));
+}
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index b4b5c45e5c..e6c358d280 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.46.29.0 -->
+<!-- gbrain-template-stamp: 0.46.30.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/operations-trust-boundary.test.ts b/test/operations-trust-boundary.test.ts
index 54a48c15d2..7cde4502ca 100644
--- a/test/operations-trust-boundary.test.ts
+++ b/test/operations-trust-boundary.test.ts
@@ -32,6 +32,12 @@
*
* Companion guard at scripts/check-operations-filter-bypass.sh enforces
* the canonical filter site so a future HTTP route can't bypass it.
+ *
+ * Dynamic sibling: test/remote-privacy-sweep.test.ts — a corpus-seeded
+ * sweep of EVERY non-localOnly op through dispatchToolCall asserting no
+ * private-sentinel leakage (the #4546/#4549 read-leak class). This file
+ * pins the static contract + curated handler probes; the sweep catches
+ * leaks in ops neither file has heard of yet. Same doctrine, two layers.
*/
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
@@ -278,4 +284,115 @@ describe('handler invocation — historically-broken trust-boundary classes', ()
expect(message.toLowerCase()).toContain('image_path');
expect(message.toLowerCase()).toContain('permission_denied');
});
+
+ test('find_orphans / get_recent_salience / find_anomalies hide private pages from remote callers (read-leak class)', async () => {
+ // Admission per the curated-list criterion: a real exploit class fixed
+ // at the handler level — remote callers received private page
+ // slugs/titles/metadata through these list arms (found by the
+ // remote-privacy-sweep on its first run; same class as the delta page
+ // arm). Local trusted callers keep the unfiltered view.
+ //
+ // Two extra WORLD person pages make the corpus 3 same-type pages today:
+ // enough for the anomaly type-cohort to FIRE (count > mean + 1 over an
+ // empty baseline), so the find_anomalies assertions below are proven
+ // non-vacuous by a LOCAL positive control instead of leaning on an
+ // empty result.
+ const put = operations.find(op => op.name === 'put_page')!;
+ const local = makeContext({ remote: false });
+ await put.handler(local, {
+ slug: 'people/tb-priv-example',
+ content: '---\ntitle: TB_PRIVATE_TITLE_PROOF\ntype: person\nvisibility: private\n---\n\n# TB_PRIVATE_TITLE_PROOF\n\nprivate body\n',
+ });
+ await put.handler(local, {
+ slug: 'people/tb-world-a',
+ content: '---\ntitle: TB World A\ntype: person\n---\n\n# TB World A\n\nworld body\n',
+ });
+ await put.handler(local, {
+ slug: 'people/tb-world-b',
+ content: '---\ntitle: TB World B\ntype: person\n---\n\n# TB World B\n\nworld body\n',
+ });
+ const remote = makeContext({ remote: true });
+
+ type OrphanCounts = {
+ orphans: { slug: string }[];
+ total_orphans: number;
+ total_pages: number;
+ total_linkable: number;
+ excluded: number;
+ };
+ const orphans = operations.find(op => op.name === 'find_orphans')!;
+ const orphanResult = (await orphans.handler(remote, {})) as OrphanCounts;
+ const orphanRes = JSON.stringify(orphanResult);
+ expect(orphanRes).not.toContain('people/tb-priv-example');
+ expect(orphanRes).not.toContain('TB_PRIVATE_TITLE_PROOF');
+ // Count self-consistency after filtering: total_orphans mirrors the
+ // filtered list (a stale unfiltered total is a hidden-page count oracle).
+ expect(orphanResult.total_orphans).toBe(orphanResult.orphans.length);
+ const orphanLocalResult = (await orphans.handler(local, {})) as OrphanCounts;
+ const orphanLocal = JSON.stringify(orphanLocalResult);
+ expect(orphanLocal).toContain('people/tb-priv-example');
+ // Hidden orphans VANISH from every published counter: both denominators
+ // shrink by the one hidden page and `excluded` is untouched — folding
+ // hidden rows into `excluded` would be an exact one-call oracle, since
+ // the unfiltered op guarantees excluded counts only pseudo-pages.
+ expect(orphanLocalResult.total_pages - orphanResult.total_pages).toBe(1);
+ expect(orphanLocalResult.total_linkable - orphanResult.total_linkable).toBe(1);
+ expect(orphanResult.excluded).toBe(orphanLocalResult.excluded);
+
+ const salience = operations.find(op => op.name === 'get_recent_salience')!;
+ const salienceRes = JSON.stringify(await salience.handler(remote, {}));
+ expect(salienceRes).not.toContain('people/tb-priv-example');
+ expect(salienceRes).not.toContain('TB_PRIVATE_TITLE_PROOF');
+ const salienceLocal = JSON.stringify(await salience.handler(local, {}));
+ expect(salienceLocal).toContain('people/tb-priv-example');
+
+ const anomalies = operations.find(op => op.name === 'find_anomalies')!;
+ // LOCAL positive control: the person-type cohort anomaly fires and
+ // names the private slug — proving the remote assertions below are
+ // exercising a real filter, not an empty list.
+ const anomaliesLocal = JSON.stringify(await anomalies.handler(local, {}));
+ expect(anomaliesLocal).toContain('people/tb-priv-example');
+ const anomalyRows = (await anomalies.handler(remote, {})) as {
+ count: number;
+ page_slugs: string[];
+ }[];
+ const anomaliesRes = JSON.stringify(anomalyRows);
+ expect(anomaliesRes).not.toContain('people/tb-priv-example');
+ expect(anomaliesRes).toContain('people/tb-world-a'); // non-empty proof
+ for (const row of anomalyRows) {
+ // No empty-row oracle, and for this sub-cap corpus the adjusted count
+ // (original minus removed private slugs) equals the visible list —
+ // a stale unadjusted count would read 3 here and leak the hidden
+ // page's existence.
+ expect(row.page_slugs.length).toBeGreaterThan(0);
+ expect(row.count).toBe(row.page_slugs.length);
+ }
+
+ // find_experts: query the private page's OWN title so the expertise
+ // scorer must rank it if it can see it — a remote caller gets nothing,
+ // a local caller gets the row (deterministic, unlike fuzzy-threshold
+ // sweep topics).
+ const experts = operations.find(op => op.name === 'find_experts')!;
+ const expertsRes = JSON.stringify(
+ await experts.handler(remote, { topic: 'TB_PRIVATE_TITLE_PROOF' }),
+ );
+ expect(expertsRes).not.toContain('people/tb-priv-example');
+ expect(expertsRes).not.toContain('TB_PRIVATE_TITLE_PROOF');
+ const expertsLocal = JSON.stringify(
+ await experts.handler(local, { topic: 'TB_PRIVATE_TITLE_PROOF' }),
+ );
+ expect(expertsLocal).toContain('people/tb-priv-example');
+
+ // Soft-delete bypass (fail-closed probe): the raw salience/anomaly
+ // queries carry no deleted_at predicate, so a soft-deleted private page
+ // still reaches the handler rows — the post-filter must classify it
+ // private-only via includeDeleted:true or it slips through.
+ const del = operations.find(op => op.name === 'delete_page')!;
+ await del.handler(local, { slug: 'people/tb-priv-example' });
+ const salienceAfterDelete = JSON.stringify(await salience.handler(remote, {}));
+ expect(salienceAfterDelete).not.toContain('people/tb-priv-example');
+ expect(salienceAfterDelete).not.toContain('TB_PRIVATE_TITLE_PROOF');
+ const anomaliesAfterDelete = JSON.stringify(await anomalies.handler(remote, {}));
+ expect(anomaliesAfterDelete).not.toContain('people/tb-priv-example');
+ });
});
diff --git a/test/remote-privacy-sweep.test.ts b/test/remote-privacy-sweep.test.ts
new file mode 100644
index 0000000000..e0ff75cbe6
--- /dev/null
+++ b/test/remote-privacy-sweep.test.ts
@@ -0,0 +1,743 @@
+/**
+ * Remote privacy sweep — DYNAMIC, corpus-seeded leak detection across the
+ * ENTIRE dispatch surface (#4546/#4549 class closure at the dispatch layer).
+ *
+ * Why this exists: the world-only privacy boundary is enforced per-arm /
+ * per-column at N call sites, so it leaked twice arm-by-arm — #4546 (a
+ * takes/private-facts fence living in the `timeline` column was returned
+ * unstripped to remote readers) and #4549 (delta's changed-page arm exposed
+ * private page titles/slugs). This suite closes the CLASS at the shared
+ * layer: seed a corpus carrying high-entropy PRIVATE sentinels, enumerate
+ * every non-localOnly op from the registry, dispatch each one remote-shaped
+ * through `dispatchToolCall` (the exact layer both MCP transports share),
+ * and assert no private sentinel appears anywhere in the serialized
+ * response envelope — structured fields, rendered text, error messages,
+ * and the `_meta.brain_hot_memory` channel alike.
+ *
+ * Scope claim, stated honestly: this closes the DISPATCH surface for
+ * callers that carry the transport floor (`sourceId` + world-only
+ * takesHoldersAllowList — every shipped transport sets both). It does NOT
+ * cover the IPC context-pack surface (src/mcp/context-pack-handler.ts,
+ * which bypasses dispatchToolCall) nor write-triggered restoration echoes
+ * (put_page INTO fence-bearing pages — see the write-side sweep TODO).
+ *
+ * Static sibling: test/operations-trust-boundary.test.ts (contract
+ * assertions + curated handler probes) and
+ * scripts/check-operations-filter-bypass.sh. This file is the dynamic
+ * sibling — same doctrine, corpus-seeded.
+ *
+ * MAINTENANCE CONTRACT (fail-closed): adding a new operation to the
+ * registry makes this suite FAIL until the op is classified in
+ * EXPECTED_OUTCOME below (and, if it can return corpus data, given a
+ * PARAM_FACTORY entry). The failure message prints exactly what to add.
+ */
+
+import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operations, operationsByName } from '../src/core/operations.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { getBrainHotMemoryMeta } from '../src/core/facts/meta-hook.ts';
+import {
+ resetGateway,
+ __setChatTransportForTests,
+ __setEmbedTransportForTests,
+} from '../src/core/ai/gateway.ts';
+import { __setUsageLogPathForTests } from '../src/core/verbs/usage-log.ts';
+
+// ── Sentinels ────────────────────────────────────────────────────────────
+// PRIVATE sentinels: high-entropy, seeded ONLY into private artifacts
+// (titles / bodies / fact / take / fence-row CONTENT — never slugs: slugs
+// are legitimately echoed in "Page not found: <slug>" errors, so a slug
+// sentinel would false-positive on correct behavior).
+const PRIV = {
+ pageTitle: 'PRIVSWEEP_TITLE_kx9q3z',
+ pageBody: 'PRIVSWEEP_PBODY_mw7r2v',
+ fact: 'PRIVSWEEP_FACT_tj5n8d',
+ take: 'PRIVSWEEP_TAKE_qb4h6y',
+ fenceRow: 'PRIVSWEEP_FROW_zc3f9m',
+ src2Fact: 'PRIVSWEEP_S2FACT_ne2k7p',
+ src2Title: 'PRIVSWEEP_S2TITLE_ru8d4w',
+} as const;
+const PRIVATE_SENTINELS = Object.values(PRIV);
+
+// WORLD markers: positive controls proving an op actually read the corpus
+// (a sweep against an empty brain proves nothing).
+const WORLD = {
+ pageTitle: 'WORLDSWEEP_TITLE_ok11aa',
+ pageBody: 'WORLDSWEEP_PBODY_ok22bb',
+ fact: 'WORLDSWEEP_FACT_ok33cc',
+ take: 'WORLDSWEEP_TAKE_ok44dd',
+ fenceRow: 'WORLDSWEEP_FROW_ok55ee',
+ timeline: 'WORLDSWEEP_TL_ok66ff',
+ src2Page: 'WORLDSWEEP_S2PAGE_ok77gg',
+} as const;
+const WORLD_MARKERS = Object.values(WORLD);
+
+const SRC2 = 'sweepsrc2';
+/** Per-generated-case bun test timeout — a hanging op fails ITS case loudly. */
+const CASE_TIMEOUT_MS = 20_000;
+/** A cursor older than every seeded row, shared by the delta factory + anchors. */
+const SINCE_EPOCH = '2020-01-01T00:00:00.000Z';
+const WORLD_FENCE_SLUG = 'people/world-fence-example';
+const WORLD_PAGE_SLUG = 'people/world-page-example';
+const PRIV_PAGE_SLUG = 'people/priv-page-example';
+
+// Known, reviewed op-wide exemptions. An entry here exempts the WHOLE op
+// from the sentinel assertion (the substring check cannot do field-level).
+// MUST stay empty absent a written justification + review.
+const KNOWN_EXPOSED: Record<string, { why: string }> = {};
+
+let engine: PGLiteEngine;
+let home: string;
+let src2Dir: string;
+let brainDir: string;
+
+function localCtx(sourceId = 'default'): OperationContext {
+ return {
+ engine,
+ config: {},
+ logger: { info: () => {}, warn: () => {}, error: () => {} },
+ dryRun: false,
+ remote: false,
+ sourceId,
+ } as unknown as OperationContext;
+}
+
+type Shape = 'scalar' | 'federated';
+
+/**
+ * Remote-shaped call through the shared dispatcher — the same opts shape
+ * both shipped transports build (see src/mcp/server.ts and
+ * src/commands/serve-http.ts): remote:true, non-stdio transport, sourceId
+ * resolved, world-only takes floor, hot-memory metaHook. The `federated`
+ * shape adds the auth-array read grant (the #1393 leak lived in that
+ * precedence path); it still carries sourceId — dispatch hard-fails remote
+ * calls without one (missing_source_scope, dispatch.ts) exactly like the
+ * shipped HTTP transport, which always resolves a scalar default.
+ */
+async function sweepCall(name: string, params: Record<string, unknown>, shape: Shape) {
+ return dispatchToolCall(engine, name, params, {
+ remote: true,
+ transport: 'http',
+ takesHoldersAllowList: ['world'],
+ sourceId: 'default',
+ metaHook: getBrainHotMemoryMeta,
+ ...(shape === 'federated'
+ ? {
+ auth: {
+ token: 'test-token',
+ clientId: 'test-client',
+ scopes: ['read'],
+ allowedSources: ['default', SRC2],
+ },
+ }
+ : {}),
+ });
+}
+
+// ── Per-op parameter factories ───────────────────────────────────────────
+// Ops that need params to exercise the seeded corpus. Everything absent
+// here dispatches with {} and must be classified 'ok' or 'error' below.
+// A few explicit `{}` entries remain as "considered, takes no params"
+// documentation — behaviorally identical to the fallback.
+const PARAM_FACTORY: Record<string, Record<string, unknown>> = {
+ get_page: { slug: WORLD_FENCE_SLUG, include_content: true },
+ fetch: { id: WORLD_FENCE_SLUG },
+ list_pages: {},
+ search: { query: 'WORLDSWEEP' },
+ query: { query: 'WORLDSWEEP' },
+ recall: { entity: WORLD_PAGE_SLUG },
+ entity: { name: WORLD_PAGE_SLUG },
+ synthesize: { entity: WORLD_PAGE_SLUG },
+ delta: { since: SINCE_EPOCH },
+ context_pack: { entities: WORLD_PAGE_SLUG },
+ get_timeline: { slug: WORLD_PAGE_SLUG },
+ takes_list: { page_slug: WORLD_PAGE_SLUG },
+ takes_search: { query: 'WORLDSWEEP' },
+ get_tags: { slug: WORLD_PAGE_SLUG },
+ get_links: { slug: WORLD_PAGE_SLUG },
+ get_backlinks: { slug: WORLD_PAGE_SLUG },
+ traverse_graph: { slug: WORLD_PAGE_SLUG },
+ get_versions: { slug: WORLD_FENCE_SLUG },
+ get_chunks: { slug: WORLD_FENCE_SLUG },
+ resolve_slugs: { partial: 'world-page' },
+ volunteer_context: { window: 'Recent discussion about WORLDSWEEP topics and pages.' },
+ chronicle_day: { date: '2026-01-02' },
+ chronicle_since: { date: '2020-01-01' },
+ chronicle_on_this_day: { date: '2026-01-02' },
+ chronicle_last_seen: { entity: WORLD_PAGE_SLUG },
+ find_experts: { topic: 'WORLDSWEEP' },
+ find_trajectory: { entity_slug: WORLD_PAGE_SLUG },
+ find_contradictions: {},
+ search_by_image: {},
+ sources_status: { id: 'default' },
+ ontology_get: { entity: WORLD_PAGE_SLUG },
+ get_skill: { name: 'query' },
+ // Mutating ops target FRESH slugs only — never the seeded corpus. The
+ // put_page-into-fence-bearing-page restoration-echo class is explicitly
+ // NOT covered here (write-side sweep TODO).
+ put_page: { slug: 'notes/sweep-fresh-write', content: '# Fresh write\n\nNew content.\n' },
+ remember: { fact: 'fresh sweep fact', provenance: 'sweep', entity: 'people/sweep-fresh-entity' },
+ capture: { content: 'fresh sweep capture' },
+ add_tag: { slug: WORLD_PAGE_SLUG, tag: 'sweep-tag' },
+ remove_tag: { slug: WORLD_PAGE_SLUG, tag: 'sweep-tag' },
+ add_link: { from: WORLD_PAGE_SLUG, to: WORLD_FENCE_SLUG },
+ remove_link: { from: WORLD_PAGE_SLUG, to: WORLD_FENCE_SLUG },
+ add_timeline_entry: { slug: WORLD_PAGE_SLUG, date: '2026-01-03', summary: 'fresh sweep timeline entry' },
+ takes_add: { slug: WORLD_PAGE_SLUG, claim: 'fresh sweep take', kind: 'take', holder: 'world' },
+ delete_page: { slug: 'notes/sweep-fresh-write' },
+ restore_page: { slug: 'notes/sweep-fresh-write' },
+};
+
+// Per-(op × shape) overrides for ops whose behavior legitimately differs
+// with vs without an authenticated OAuth identity (the federated shape
+// carries ctx.auth; the scalar shape — like the stdio transport — doesn't).
+const EXPECTED_BY_SHAPE: Record<string, Partial<Record<Shape, Outcome>>> = {
+ whoami: { scalar: 'error', federated: 'ok' },
+ list_jobs: { scalar: 'error', federated: 'ok' },
+};
+
+// ── Expected outcome per op ──────────────────────────────────────────────
+// Buckets (asserted per case; the table's KEY SET must equal the enumerated
+// non-localOnly registry — set equality is the fail-closed maintenance
+// contract):
+// 'data' → succeeds AND response contains ≥1 WORLD marker (positive
+// control: the op provably read the corpus)
+// 'ok' → succeeds; no corpus-marker requirement
+// 'error' → isError (validation/unsupported/unavailable) — envelope
+// still sentinel-checked
+// 'denied' → publish-gated: isError naming the gate (handler-level
+// permission_denied with the mcp.* config key)
+type Outcome = 'data' | 'ok' | 'error' | 'denied';
+const EXPECTED_OUTCOME: Record<string, Outcome> = {
+ // reads that must prove corpus contact
+ get_page: 'data',
+ fetch: 'data',
+ list_pages: 'data',
+ search: 'data',
+ query: 'data',
+ recall: 'data',
+ entity: 'data',
+ delta: 'data',
+ context_pack: 'data',
+ get_timeline: 'data',
+ takes_list: 'data',
+ takes_search: 'data',
+ get_versions: 'data',
+ get_chunks: 'data',
+ resolve_slugs: 'data',
+ get_backlinks: 'data',
+ traverse_graph: 'data',
+ // reads that succeed without corpus-marker requirement
+ get_tags: 'ok',
+ get_links: 'ok',
+ list_link_sources: 'ok',
+ search_modes: 'ok',
+ get_brain_identity: 'ok',
+ whoami: 'ok', // base unused — per-shape override in EXPECTED_BY_SHAPE (above)
+ sources_list: 'ok',
+ sources_status: 'ok',
+ find_orphans: 'ok',
+ find_contradictions: 'ok',
+ find_experts: 'ok',
+ find_trajectory: 'ok',
+ find_anomalies: 'ok',
+ get_recent_salience: 'ok',
+ chronicle_day: 'ok',
+ chronicle_on_this_day: 'ok',
+ chronicle_since: 'ok',
+ chronicle_last_seen: 'ok',
+ volunteer_chronicle: 'ok',
+ volunteer_context: 'ok',
+ get_calibration_profile: 'ok',
+ takes_scorecard: 'ok',
+ takes_calibration: 'ok',
+ extraction_pending: 'ok',
+ entity_identity_list: 'ok',
+ get_active_schema_pack: 'ok',
+ list_schema_packs: 'ok',
+ schema_stats: 'ok',
+ schema_graph: 'ok',
+ ontology_get: 'ok',
+ ontology_dimensions: 'ok',
+ ontology_conflicts: 'ok',
+ get_status_snapshot: 'ok',
+ get_stats: 'ok',
+ get_health: 'ok',
+ search_stats: 'ok',
+ cache_stats: 'ok',
+ get_usage: 'ok',
+ get_job_stats: 'ok',
+ list_jobs: 'ok', // base unused — per-shape override in EXPECTED_BY_SHAPE (above)
+ quarantine_list: 'ok',
+ run_doctor: 'ok',
+ get_ingest_log: 'ok',
+ code_callers: 'error',
+ code_callees: 'error',
+ code_def: 'error',
+ code_refs: 'error',
+ code_blast: 'error',
+ code_flow: 'error',
+ schema_lint: 'ok',
+ schema_explain_type: 'error',
+ schema_review_orphans: 'ok',
+ search_by_image: 'error',
+ synthesize: 'error',
+ think: 'error',
+ request_tools: 'ok',
+ get_raw_data: 'error',
+ search_tune: 'ok',
+ // publish-gated (DB-plane rows pinned false in beforeAll)
+ list_skills: 'denied',
+ get_skill: 'denied',
+ list_brain_skillpack: 'denied',
+ advisor: 'denied',
+ // mutating ops (fresh-slug targets; envelope-echo checks only)
+ remember: 'ok',
+ forget: 'error',
+ put_page: 'ok',
+ delete_page: 'ok',
+ restore_page: 'ok',
+ capture: 'ok',
+ add_tag: 'ok',
+ remove_tag: 'ok',
+ add_link: 'ok',
+ remove_link: 'ok',
+ add_timeline_entry: 'ok',
+ revert_version: 'error',
+ put_raw_data: 'error',
+ log_ingest: 'error',
+ takes_add: 'ok',
+ takes_update: 'error',
+ takes_resolve: 'error',
+ takes_supersede: 'error',
+ ontology_propose: 'error',
+ extract_entities: 'error',
+ extract_facts: 'error',
+ forget_fact: 'error',
+ schema_apply_mutations: 'error',
+ reload_schema_pack: 'ok',
+ run_onboard: 'ok',
+ run_skillopt: 'error',
+ sources_add: 'error',
+ sources_remove: 'error',
+ submit_job: 'error',
+ get_job: 'error',
+ cancel_job: 'error',
+ retry_job: 'error',
+ get_job_progress: 'error',
+ pause_job: 'error',
+ resume_job: 'error',
+ replay_job: 'error',
+ send_job_message: 'error',
+ submit_agent: 'error',
+ get_agent_job: 'error',
+};
+
+// Destructive mutating ops run LAST within phase W so an early
+// generic-params delete can't defang later cases (eng review E5).
+const DESTRUCTIVE_RE = /forget|purge|delete|remove|cancel|clear|repair|revert|resolve|supersede/;
+
+const nonLocalOps = operations.filter(o => !o.localOnly);
+const phaseR = nonLocalOps.filter(o => !o.mutating);
+const phaseW = [...nonLocalOps.filter(o => o.mutating)].sort((a, b) => {
+ const da = DESTRUCTIVE_RE.test(a.name) ? 1 : 0;
+ const db = DESTRUCTIVE_RE.test(b.name) ? 1 : 0;
+ return da - db || a.name.localeCompare(b.name);
+});
+const localOnlyOps = operations.filter(o => o.localOnly);
+
+beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-privacy-sweep-'));
+ src2Dir = mkdtempSync(join(tmpdir(), 'gbrain-privacy-sweep-src2-'));
+ __setUsageLogPathForTests(join(home, 'usage.jsonl'));
+ // Hermeticity is ENFORCED, not assumed: null BOTH gateway transports
+ // (synthesize calls chat; embed paths call embed — a keyed dev machine
+ // must not fire real API calls). The GBRAIN_REMOTE_PRIVATE_PAGES escape
+ // hatch disables private-page exclusion outright — rather than mutating
+ // process.env (banned in parallel test files by check-test-isolation R1),
+ // fail LOUD: a machine running with privacy globally disabled SHOULD get
+ // a red privacy sweep.
+ // A previously-loaded file in the same bun process can leave the
+ // MODULE-GLOBAL gateway configured (e.g. a deterministic embedder with
+ // foreign dims) — reset config AND null transports so seeding can't trip
+ // an inherited embedding path (same hygiene as memory-verbs-conformance).
+ resetGateway();
+ __setChatTransportForTests(null);
+ __setEmbedTransportForTests(null);
+ if (process.env.GBRAIN_REMOTE_PRIVATE_PAGES === '1') {
+ throw new Error(
+ 'remote-privacy-sweep: GBRAIN_REMOTE_PRIVATE_PAGES=1 is set — the private-page ' +
+ 'exclusion is globally disabled, so this suite cannot prove anything. Unset it and re-run.',
+ );
+ }
+
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+
+ // Takes are markdown-canonical — resolveTakesRepoDir reads the
+ // `sync.repo_path` config key, so point it (and the default source's
+ // local_path, for source-scoped writes) at a writable tmpdir.
+ brainDir = mkdtempSync(join(tmpdir(), 'gbrain-privacy-sweep-brain-'));
+ await engine.setConfig('sync.repo_path', brainDir);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await (engine as any).db.query(`UPDATE sources SET local_path = $1 WHERE id = 'default'`, [brainDir]);
+
+ // buildOperationContext loads the REAL file-plane config; gate resolution
+ // is DB > file > false — pin the DB plane so a dev machine with
+ // mcp.publish_* enabled in ~/.gbrain config can't flip the denied arm.
+ await engine.setConfig('mcp.publish_skills', 'false');
+ await engine.setConfig('mcp.publish_advisor', 'false');
+
+ // ── Seed the corpus (source: default) ──────────────────────────────
+ const put = operationsByName['put_page'];
+ // 1. World page whose PRIVATE fence rows live BELOW the timeline
+ // sentinel — the exact #4546 topology (a fence in the `timeline`
+ // column of a world-visible page; a fence on a private page would
+ // never reach a remote reader at all, making red-green check (a)
+ // unimplementable).
+ await put.handler(localCtx(), {
+ slug: WORLD_FENCE_SLUG,
+ content: `---
+title: ${WORLD.pageTitle}
+type: person
+---
+
+# ${WORLD.pageTitle}
+
+${WORLD.pageBody}
+
+<!-- timeline -->
+
+- 2026-01-02: ${WORLD.timeline}
+
+## Facts
+
+<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+| 1 | ${WORLD.fenceRow} | fact | 1.0 | world | high | 2026-01-01 | | s | |
+| 2 | ${PRIV.fenceRow} | fact | 1.0 | private | high | 2026-01-01 | | s | |
+<!--- gbrain:facts:end -->
+`,
+ });
+ // 2. Plain world page (RETURNS_DATA anchor for entity/graph/takes ops).
+ await put.handler(localCtx(), {
+ slug: WORLD_PAGE_SLUG,
+ content: `---
+title: WorldSweep Page ${WORLD.pageTitle}
+type: person
+---
+
+# WorldSweep
+
+${WORLD.pageBody}
+`,
+ });
+ // 3. Private page — title AND body carry sentinels (the TITLE sentinel
+ // is what catches the #4549 metadata-leak shape in delta/list arms).
+ await put.handler(localCtx(), {
+ slug: PRIV_PAGE_SLUG,
+ content: `---
+title: ${PRIV.pageTitle}
+type: person
+visibility: private
+---
+
+# ${PRIV.pageTitle}
+
+${PRIV.pageBody}
+`,
+ });
+ // 4. Facts hot memory: one world, one private (also feeds the
+ // _meta.brain_hot_memory channel the metaHook injects).
+ const remember = operationsByName['remember'];
+ await remember.handler(localCtx(), {
+ fact: WORLD.fact,
+ provenance: 'sweep-seed',
+ entity: WORLD_PAGE_SLUG,
+ });
+ await remember.handler(localCtx(), {
+ fact: PRIV.fact,
+ provenance: 'sweep-seed',
+ entity: WORLD_PAGE_SLUG,
+ visibility: 'private',
+ });
+ // 5. Takes: world-holder (visible through the transport floor) and
+ // brain-holder (must be filtered by takesHoldersAllowList).
+ const takesAdd = operationsByName['takes_add'];
+ await takesAdd.handler(localCtx(), {
+ slug: WORLD_PAGE_SLUG,
+ claim: WORLD.take,
+ kind: 'take',
+ holder: 'world',
+ });
+ await takesAdd.handler(localCtx(), {
+ slug: WORLD_PAGE_SLUG,
+ claim: PRIV.take,
+ kind: 'take',
+ holder: 'brain',
+ });
+ // ── Source 2 (federated-arm variants) ───────────────────────────────
+ // Direct row insert: sources_add demands a committed git repo (sync
+ // machinery we don't exercise); registration is all the sweep needs.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await (engine as any).db.query(`INSERT INTO sources (id, name, local_path) VALUES ($1, $1, $2)`, [
+ SRC2,
+ src2Dir,
+ ]);
+ await put.handler(localCtx(SRC2), {
+ slug: PRIV_PAGE_SLUG,
+ content: `---
+title: ${PRIV.src2Title}
+type: person
+visibility: private
+---
+
+# ${PRIV.src2Title}
+
+private source-2 body
+`,
+ });
+ await remember.handler(localCtx(SRC2), {
+ fact: PRIV.src2Fact,
+ provenance: 'sweep-seed',
+ entity: WORLD_PAGE_SLUG,
+ visibility: 'private',
+ });
+ // World-visible src2 page: the federated arm's positive control — without
+ // it, every src2 sentinel could pass vacuously if allowedSources fan-out
+ // silently never reached source 2 (the "sweep against an empty brain
+ // proves nothing" failure mode, cross-source edition).
+ await put.handler(localCtx(SRC2), {
+ slug: 'people/world-src2-example',
+ content: `---
+title: ${WORLD.src2Page}
+type: person
+---
+
+# ${WORLD.src2Page}
+
+world source-2 body
+`,
+ });
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+ __setUsageLogPathForTests(null);
+ // Leave the process exactly as found: reset gateway config + transports
+ // so later files in this shard process inherit a clean module-global.
+ resetGateway();
+ __setChatTransportForTests(null);
+ __setEmbedTransportForTests(null);
+ try { rmSync(home, { recursive: true, force: true }); } catch { /* best-effort */ }
+ try { rmSync(src2Dir, { recursive: true, force: true }); } catch { /* best-effort */ }
+ try { rmSync(brainDir, { recursive: true, force: true }); } catch { /* best-effort */ }
+});
+
+// ── The core per-case assertion ──────────────────────────────────────────
+function assertNoPrivateSentinel(op: string, serialized: string) {
+ if (KNOWN_EXPOSED[op]) return; // op-wide, reviewed exemption
+ for (const s of PRIVATE_SENTINELS) {
+ if (serialized.includes(s)) {
+ throw new Error(
+ `PRIVACY LEAK: op "${op}" returned private sentinel "${s}" to a remote caller.\n` +
+ `Envelope excerpt: ${serialized.slice(Math.max(0, serialized.indexOf(s) - 200), serialized.indexOf(s) + 200)}`,
+ );
+ }
+ }
+}
+
+async function runCase(opName: string, shape: Shape) {
+ const params = PARAM_FACTORY[opName] ?? {};
+ const res = await sweepCall(opName, params, shape);
+ const serialized = JSON.stringify(res);
+ assertNoPrivateSentinel(opName, serialized);
+ const expected = EXPECTED_BY_SHAPE[opName]?.[shape] ?? EXPECTED_OUTCOME[opName];
+ const isError = res.isError === true;
+ if (expected === 'data') {
+ expect(isError).toBe(false);
+ const hasMarker = WORLD_MARKERS.some(m => serialized.includes(m));
+ if (!hasMarker) {
+ throw new Error(
+ `Op "${opName}" [${shape}] expected 'data' (a WORLD marker proving corpus contact) but returned none.\n` +
+ `Either fix its PARAM_FACTORY entry or reclassify in EXPECTED_OUTCOME.\nEnvelope: ${serialized.slice(0, 600)}`,
+ );
+ }
+ } else if (expected === 'ok') {
+ if (isError) {
+ throw new Error(
+ `Op "${opName}" [${shape}] expected 'ok' but errored. Reclassify in EXPECTED_OUTCOME ` +
+ `or fix its PARAM_FACTORY entry.\nEnvelope: ${serialized.slice(0, 600)}`,
+ );
+ }
+ } else if (expected === 'error') {
+ if (!isError) {
+ throw new Error(
+ `Op "${opName}" [${shape}] expected 'error' but succeeded — reclassify in EXPECTED_OUTCOME ` +
+ `(and decide whether it needs a positive control).\nEnvelope: ${serialized.slice(0, 600)}`,
+ );
+ }
+ } else if (expected === 'denied') {
+ expect(isError).toBe(true);
+ // Handler-level publish gate: permission_denied naming the mcp.* key.
+ expect(serialized).toContain('permission_denied');
+ expect(serialized).toContain('mcp.');
+ }
+ return serialized;
+}
+
+// Corpus-intact probe: the world fence page still serves its world row.
+async function assertCorpusIntact(label: string) {
+ const res = await sweepCall('get_page', PARAM_FACTORY['get_page']!, 'scalar');
+ const serialized = JSON.stringify(res);
+ expect(res.isError ?? false).toBe(false);
+ if (!serialized.includes(WORLD.fenceRow)) {
+ throw new Error(`Corpus integrity lost at "${label}" — world fence row missing. A mutating op touched the seeded corpus.`);
+ }
+ assertNoPrivateSentinel('get_page', serialized);
+}
+
+// ── Enumeration guards (vacuous-pass protection) ─────────────────────────
+describe('remote privacy sweep — enumeration + classification contract', () => {
+ it('registry enumeration is non-vacuous (≥30 non-localOnly ops)', () => {
+ expect(nonLocalOps.length).toBeGreaterThanOrEqual(30);
+ });
+
+ it('EXPECTED_OUTCOME keys set-equal the enumerated registry (maintenance contract)', () => {
+ const enumerated = new Set(nonLocalOps.map(o => o.name));
+ const classified = new Set(Object.keys(EXPECTED_OUTCOME));
+ const missing = [...enumerated].filter(n => !classified.has(n)).sort();
+ const stale = [...classified].filter(n => !enumerated.has(n)).sort();
+ if (missing.length > 0 || stale.length > 0) {
+ throw new Error(
+ `remote-privacy-sweep classification drift.\n` +
+ (missing.length
+ ? `NEW ops needing classification in EXPECTED_OUTCOME (and a PARAM_FACTORY entry if they can return corpus data):\n ${missing.join(', ')}\n`
+ : '') +
+ (stale.length ? `STALE entries for removed/renamed ops:\n ${stale.join(', ')}\n` : '') +
+ `This is the fail-closed maintenance contract: every remote-callable op MUST be privacy-swept.`,
+ );
+ }
+ });
+
+ it("'data' bucket is non-vacuous (≥15 positive-control ops)", () => {
+ const dataOps = Object.entries(EXPECTED_OUTCOME).filter(([, v]) => v === 'data');
+ expect(dataOps.length).toBeGreaterThanOrEqual(15);
+ });
+
+ it('KNOWN_EXPOSED is empty (any entry is a reviewed decision)', () => {
+ expect(Object.keys(KNOWN_EXPOSED)).toHaveLength(0);
+ });
+});
+
+// ── Phase R: non-mutating ops, pristine corpus, both ctx shapes ──────────
+describe('phase R — non-mutating ops leak no private sentinel', () => {
+ for (const op of phaseR) {
+ for (const shape of ['scalar', 'federated'] as const) {
+ it(`${op.name} [${shape}]`, async () => {
+ await runCase(op.name, shape);
+ }, CASE_TIMEOUT_MS);
+ }
+ }
+
+ it('corpus intact at end of phase R (mutability misclassification guard)', async () => {
+ await assertCorpusIntact('end of phase R');
+ });
+});
+
+// ── Phase W: mutating ops (fresh-slug targets), destructive last ─────────
+describe('phase W — mutating ops leak no private sentinel in response envelopes', () => {
+ it('corpus intact at start of phase W', async () => {
+ await assertCorpusIntact('start of phase W');
+ });
+
+ for (const op of phaseW) {
+ for (const shape of ['scalar', 'federated'] as const) {
+ it(`${op.name} [${shape}]`, async () => {
+ await runCase(op.name, shape);
+ }, CASE_TIMEOUT_MS);
+ }
+ }
+});
+
+// ── Fail-closed arm: localOnly ops deny on non-stdio transports ──────────
+describe('localOnly ops are denied fail-closed over non-stdio transports', () => {
+ for (const op of localOnlyOps) {
+ it(`${op.name} → unknown_tool envelope, no sentinel`, async () => {
+ const res = await sweepCall(op.name, {}, 'scalar');
+ const serialized = JSON.stringify(res);
+ expect(res.isError).toBe(true);
+ // The dispatcher backstop (dispatch.ts localOnly gate) answers with
+ // the same envelope as a nonexistent op so the catalog doesn't leak.
+ expect(serialized).toContain('unknown_tool');
+ assertNoPrivateSentinel(op.name, serialized);
+ }, CASE_TIMEOUT_MS);
+ }
+});
+
+// ── Discrimination anchors: the two known leak shapes stay caught ────────
+describe('known-leak discrimination anchors (#4546 / #4549)', () => {
+ it('#4546 shape: remote get_page serves the world fence row but never the private row (timeline column)', async () => {
+ const res = await sweepCall('get_page', { slug: WORLD_FENCE_SLUG, include_content: true }, 'scalar');
+ const serialized = JSON.stringify(res);
+ expect(res.isError ?? false).toBe(false);
+ expect(serialized).toContain(WORLD.fenceRow);
+ expect(serialized).not.toContain(PRIV.fenceRow);
+ });
+
+ it('#4549 shape: remote delta never carries the private page title', async () => {
+ const res = await sweepCall('delta', { since: SINCE_EPOCH }, 'scalar');
+ const serialized = JSON.stringify(res);
+ expect(res.isError ?? false).toBe(false);
+ expect(serialized).not.toContain(PRIV.pageTitle);
+ });
+
+ it('federated arm actually spans source 2; scalar arm stays source-scoped (cross-source controls)', async () => {
+ // Positive control: an allowedSources grant covering src2 must surface
+ // src2's world page through a scoped listing op.
+ const fed = await sweepCall('list_pages', {}, 'federated');
+ expect(fed.isError ?? false).toBe(false);
+ expect(JSON.stringify(fed)).toContain(WORLD.src2Page);
+ // Isolation control: the scalar default-scoped shape must NOT see src2
+ // data through a source-scoped op.
+ const scalar = await sweepCall('list_pages', {}, 'scalar');
+ expect(scalar.isError ?? false).toBe(false);
+ expect(JSON.stringify(scalar)).not.toContain(WORLD.src2Page);
+ });
+
+ // Slug-class leaks are invisible to the sentinel assertion by design
+ // (sentinels never live in slugs — legit "Page not found: <slug>" echoes
+ // would false-positive). Ops that return slug LISTS derived from data
+ // (not echoes of a requested slug) get targeted anchors instead.
+ it('slug-list arms never name the private page slug (find_anomalies / find_orphans / list_pages / delta / salience)', async () => {
+ for (const [op, params] of [
+ ['find_anomalies', {}],
+ ['find_orphans', {}],
+ ['list_pages', {}],
+ ['delta', { since: SINCE_EPOCH }],
+ ['get_recent_salience', {}],
+ ] as const) {
+ for (const shape of ['scalar', 'federated'] as const) {
+ const res = await sweepCall(op, params as Record<string, unknown>, shape);
+ const serialized = JSON.stringify(res);
+ expect(res.isError ?? false).toBe(false);
+ // Non-emptiness proof: the absence assertion below means nothing
+ // against an empty list, so each op must name at least one WORLD
+ // slug from the corpus.
+ if (!serialized.includes(WORLD_PAGE_SLUG) && !serialized.includes(WORLD_FENCE_SLUG)) {
+ throw new Error(`slug-list anchor vacuous: op "${op}" [${shape}] named no world slug — corpus/threshold drift emptied the list.`);
+ }
+ if (serialized.includes(PRIV_PAGE_SLUG)) {
+ throw new Error(`PRIVACY LEAK (slug-class): op "${op}" [${shape}] named the private page slug.`);
+ }
+ }
+ }
+ }, 30_000);
+});