Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Remote credentials can be granted the private facts in their own sources, off by default (Discussion #8194) (#9588)
Garry Tan9fbc2747ef0b
diff --git a/behavior-changes.d/private_facts_grant_8194.md b/behavior-changes.d/private_facts_grant_8194.mdnew file mode 100644index 0000000000..1898a8bf8c--- /dev/null+++ b/behavior-changes.d/private_facts_grant_8194.md@@ -0,0 +1,4 @@+---+kind: add+---+Access tokens and OAuth clients have a new private-facts grant, `none` for every existing and new token and client, so remote fact reads stay world-only until the brain host opts a connection in: `gbrain auth rescope --token <name> --private-facts granted-sources` (or `--client <id>`) means this key will read every private fact in the sources its grant lists, including facts saved private on purpose, without rewriting any fact. A source opens only when the grant lists it by id: a token with no source grant, a source federated before or after the grant was written and a request's `source_ids` never add one. A fact held on, provenanced from or about a private, `readable_by`, folder-ruled, quarantined or member page stays hidden, and so does a fact with no page to check (no holding page, or a transcript lane such as the conversation archive). `context_pack`, `delta`, writes and audience or attested reads stay world-only. `--private-facts none` turns it off on the next request. No MCP operation or admin HTTP route can set it. `gbrain auth list` and `gbrain auth clients` show it.diff --git a/changelog.d/capy-private-facts-grant-8194.md b/changelog.d/capy-private-facts-grant-8194.mdnew file mode 100644index 0000000000..3ed14ca560--- /dev/null+++ b/changelog.d/capy-private-facts-grant-8194.md@@ -0,0 +1,8 @@+**A token or OAuth client can now be allowed to read private facts in the sources its grant names, without changing any fact (`gbrain auth rescope --private-facts granted-sources`).**++<!-- behavior-change: private_facts_grant_8194 -->++### Added+- `gbrain auth rescope --token <name> --private-facts granted-sources` (or `--client <id>`) lets that one credential's remote reads see facts saved with visibility private, only in the sources its grant names explicitly; `--private-facts none` turns it off on the next request. Every existing and new token and client starts at `none` (Discussion #8194).+- It never opens a fact held on, provenanced from or about a private, `readable_by`, folder-ruled, quarantined or member page; `context_pack`, `delta`, writes and audience or attested reads stay world-only. Only the local CLI on the brain host can set it.+- `gbrain auth list` (and `--json`), `gbrain auth clients` and the rescope before/after output show the new axis.diff --git a/docs/architecture/key-files/security-continued.md b/docs/architecture/key-files/security-continued.mdindex 7dc29a562f..10ce572be2 100644--- a/docs/architecture/key-files/security-continued.md+++ b/docs/architecture/key-files/security-continued.md@@ -6,3 +6,4 @@- `src/core/outside-content.ts` — GBRA-221: `neutralizeOutsideText(text)`, the one neutralizer for text a third party wrote before it lands in a page body (Gmail/Calendar/Contacts renders in `google-render.ts`, GitHub `renderItemPage`/`renderRepoCard`, chat transcripts in `transcripts/render.ts`, `book-mirror` chapter output). It escapes every `gbrain<ws>:<ws><name>` marker token to `gbrain\:<name>` (case-insensitive), `[Source:` to `[Source\:`, and backslash-prefixes each timeline sentinel, bare `## Timeline`/`## History` heading, dated timeline row or heading, transcript message anchor and date heading, using the parsers' own predicates. Idempotent and readable; apply it per outside field (or a composed line holding one), never to a whole page that may hold gbrain's own fences or citations. Also owns `escapeAnchorLines` and `MESSAGE_ANCHOR_RE` (re-exported by `transcripts/render.ts`). New connectors use it.- `src/core/function-search-path.ts` — #7632 search_path hardening (#7688, #7785): `PINNED_FUNCTION_NAMES` (every gbrain function with a pinned search_path; `scripts/check-search-path.sh` fails one missing from it or a pinned path not ending in `pg_temp`), `FUNCTION_SEARCH_PATH_HARDENING_SQL` (the schema blob's last statement), and `hardenFunctionSearchPaths` (v277 and the end of every migration run: one transaction under the migration timeouts, a pg_proc row lock it cannot take becomes `schema_lock_blocked`, a concurrent pg_proc update is retried, returns the functions left or null when listing them failed; it first re-creates the purge and withdrawal guards its role owns, retrying a concurrent update, and a re-create failure other than SQLSTATE 42501 is thrown as `LedgerGuardRecreateError` after the hardening runs, which `hardenFailureLine` prints as a `guards:` line). Doctor checks: `src/commands/doctor/checks/guard-ledger-checks.ts` (`guard_ledger_checks`, Postgres only: names each guard missing its ledger check, from `ledgerGuardsWithoutCheck` in `src/core/guard-ledger-checks.ts`, with its owner) and `src/commands/doctor/checks/function-search-path.ts` (`function_search_path`: names any pinned function whose path does not end in `pg_temp`; the fix is `gbrain apply-migrations --yes` below v277, else the schema-qualified `ALTER FUNCTION` SQL (argument types only) in `details.sql` to run as the owner, with no runnable fix).+- `src/core/facts/private-fact-pages.ts` + `src/commands/auth-private-facts.ts` + `src/commands/auth-client-rows.ts` — the per-credential private-facts axis (`PrivateFactsGrant` `none` | `granted_sources` in `access_tokens.private_facts` and `oauth_clients.private_facts`, migration v319 `principal_private_facts`, default `none`, never in the legacy permissions mirror; set only by the local `gbrain auth rescope --token|--client --private-facts`, refused for a credential with scope sources in `src/core/access/attest-sources.ts`). MCP dispatch puts the explicitly named sources (as for private pages, never the `default` floor) in `privateFactSources()` (`src/core/search/private-visibility.ts`) for remote reads only, never for mutating ops, `context_pack` or `delta`, an asserted audience, an attested actor, a scope read or an enforced member read; `grantedPrivateFactSql` (`src/core/access/member-facts.ts`) admits a private fact only in those sources and only while `factPagesOpenSql` holds: its holding, provenance (`factProvenanceSlugSql`) and entity pages are all open (not private, `readable_by`, folder-ruled, quarantined or a member page, `factPageReasons`), and it is not unpaged or in a transcript lane (`unpagedFactSql`). `gbrain repair open-facts` shares the same page predicate. The hot-memory cache (`src/core/facts/meta-hook.ts`) keys a granted read as `<tier>+xpf=<sorted sources>` and the query cache adds `xpf=` to its knobs hash, so a payload read under the grant never serves a credential without it. `auth-private-facts.ts` renders the setting, the rescope before/after lines and the warning; `auth-client-rows.ts` is `gbrain auth clients`' listing with a degrade ladder that drops `private_facts`, then `private_pages`, on older brains. Tests: `test/private-facts-grant-8194.test.ts`, `test/e2e/private-facts-grant-postgres.test.ts`, `test/qm-scope-writes.test.ts`, `test/auth-private-pages-output.test.ts`.diff --git a/docs/guides/access-designations.md b/docs/guides/access-designations.mdindex f36706deba..8af8560a09 100644--- a/docs/guides/access-designations.md+++ b/docs/guides/access-designations.md@@ -46,12 +46,16 @@ with the brain's configured embedding provider like any other page. Seereads in every source its grant reads; the owner's source grant still bounds which sources those are. It also getsprivate facts from `recall`, the `query` facts arm, `think` trajectories, hot memory, `delta` and `context_pack` hotfacts, except a fact taken from a page it cannot read. Facts on `entity` and `context_pack` cards stay world-only for-every remote caller, the owner included.+every remote caller, the owner included, except that the private-facts grant below adds private facts to `entity` cards.-Two grants relax privacy for callers that are not the owner, and both are operator decisions:+Two grants relax page privacy for callers that are not the owner, and both are operator decisions:`gbrain auth rescope --private-pages granted-sources` (private pages in the sources that grant names) and theescape hatches `GBRAIN_REMOTE_PRIVATE_PAGES=1` / `gbrain config set search.remote_private_pages visible` (everyremote caller). Neither relaxes `readable_by` or folder rules, and neither reaches a shared-room audience.+Fact privacy has its own operator grant, `gbrain auth rescope --private-facts granted-sources`: that credential reads+facts saved `private` in the sources its grant names, never one held on, provenanced from or about a private,+`readable_by`, folder-ruled, quarantined or member page, nor one with no page to check, and never under an asserted+audience or an attested call ([MCP administration](../mcp/ADMIN.md)).`gbrain access check --token <name>` reports whether a credential reads as the owner, and`gbrain <operation> --as <member>` previews a member's view, the owner's included. Every remote response names the@@ -190,7 +194,8 @@ host saved with `visibility: "private"`, or one on a page whose `readable_by` naon a page whose readers leave the owner out (even with `reads-restricted on`) or on another member's page stays with the brain host, and one the owner confirmed or curated files a `forget_requires_owner`proposal instead, as for a shared fact. The trade-off: an owner agent that follows a planted instruction can share a factwithout passing any flag, so pass `visibility: "private"` for a fact that must stay with the owner. Extracted facts follow `facts.default_visibility` (private when unset)-and are never wider than their page. Remote fact reads return private facts to the owner only. Facts saved `private`+and are never wider than their page. Remote fact reads return private facts to the owner, and to a credential holding the private-facts grant+above (only in the sources that grant names). Facts saved `private`before `facts.default_visibility` became `world` stay private until the operator opens them from the brain host with`gbrain repair open-facts` (preview first, with an undo; see [repair](repair.md#open-facts-saved-private-before-the-world-default)).diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.mdindex 588fa855e2..56df819c5d 100644--- a/docs/guides/multi-source-brains.md+++ b/docs/guides/multi-source-brains.md@@ -324,6 +324,15 @@ who may read it, before any member's bot connects:next request, and `gbrain auth list` shows each token's setting. A harnesstoken rotation (`gbrain setup`, `gbrain bootstrap harness`) does not carrythe grant; it prints the rescope that grants it again.+- **Let a member's agent read private facts (optional).** Facts saved+ `private` stay hidden from remote reads by default. `gbrain auth rescope+ --token bot-alice-example --private-facts granted-sources` (or `--client+ <client_id>`) lets that one credential read them in the sources its grant+ names, and no others. It never opens a fact held on, provenanced from or+ about a private, `readable_by`, folder-ruled, quarantined or member page, a+ fact with no page to check, or a transcript fact; `context_pack`, `delta`+ and writes stay world-only. `--private-facts none` turns it off on the next+ request. Details: [MCP administration](../mcp/ADMIN.md).- **On a personal brain, name the owner instead.** `gbrain access owner set<member>` lets every credential bound to that member read the private pagesin all the sources its grant reads. What each designation means for eachdiff --git a/docs/guides/qm.md b/docs/guides/qm.mdindex acd9bbe72c..20d813fb77 100644--- a/docs/guides/qm.md+++ b/docs/guides/qm.md@@ -201,7 +201,8 @@ add it to a read grant, so its memory is read only by naming it in `memory_recalcredential. A person read (no sources named) never reads a scope source. A source others already read,`default`, a federated source and the credential's own write source cannot be listed; a credential withscope sources keeps its attested ops within `forget,forget_fact,get_write_request,memory_recall,memory_write` and cannot-hold `--private-pages granted-sources`. A leaked scope credential secret reads and writes every listed scope:+hold `--private-pages granted-sources` or `--private-facts granted-sources` (and a credential holding either cannot+list scope sources). A leaked scope credential secret reads and writes every listed scope:restrict it with `--operations` to the memory tools. Remote writes to `memory/scope` other than a scope`memory_write` are refused, and a `memory/scope` page that names readers, is private or sits under a folderrule takes no scope fact (`scope_page_not_shared`). On a repo-backed scope source, anyone who can push to itsdiff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 6425a8b02c..bd9443273e 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -2531,6 +2531,18 @@ at all: bind the client to the owner instead (`gbrain access owner set`, then`gbrain auth rescope --client <id> --member <owner>`), and it reads privatefacts without opening them to anyone else.+On a shared brain with several clients and no owner, `gbrain auth rescope+--token <name> --private-facts granted-sources` (or `--client <id>`) is the+per-credential alternative to opening facts: that one credential reads every+private fact in the sources its grant lists by id, including facts saved+private on purpose, nobody else does, no fact changes, and `--private-facts+none` switches it off on the next request. A source the credential only+reaches (federated, now or later, or through a future "read every shared+source" switch) never opens. It never reads a fact on a page this repair+would refuse to open, nor an `unpaged:<lane>` fact (no holding page, or a+transcript lane such as the conversation archive), which this repair opens+only by class ([MCP administration](../mcp/ADMIN.md)).+### Lost fence rowsA page rewrite that drops its `## Facts` or takes section is safe on itsdiff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.mdindex a1ebc9c77b..d7da9bee4f 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -599,6 +599,8 @@ gbrain auth rescope --client CLIENT_ID --takes-holders world,braingbrain auth rescope --client CLIENT_ID --sources none # deny-all, secret unchangedgbrain auth rescope --token agent-example --private-pages granted-sources # private pages in its granted sourcesgbrain auth rescope --client CLIENT_ID --private-pages none # hide them again+gbrain auth rescope --token agent-example --private-facts granted-sources # private facts in its granted sources+gbrain auth rescope --client CLIENT_ID --private-facts none # world-only facts again```| Flag | Value | Effect |@@ -609,6 +611,7 @@ gbrain auth rescope --client CLIENT_ID --private-pages none # hide them again| `--operations` | `op,...`, `none` or `all` | Operation snapshot; `none` refuses every operation. Client only: `all` stores no snapshot and clears the profile, so the scopes and the surface alone decide, including operations later upgrades add (tokens: `--reset-default operations`). || `--scopes` | `read,write,...` | Replaces the scopes. || `--private-pages` | `granted-sources` or `none` | Whether remote reads see `visibility: private` pages. `none` (the default for every token and client) hides them, as before. `granted-sources` shows them only in the sources this grant names: a token's `--sources` list, or a client's write source plus its read sources. The no-grant floor, federated sources the grant does not name, a client's bound source and a request's `source_id` / `source_ids` never add a source. The grant applies to `search`, `query`, `recall`, `entity`, `get_page`, `list_pages`, `get_chunks`, `get_versions`, `get_timeline`, `get_links`, `get_backlinks`, `traverse_graph` and `resolve_slugs`. `context_pack`, `delta`, `think`, recorded-time reads (`get_page` and `get_versions` with `known_as_of`) and every write keep hiding private pages even in a granted source, so a page `get_page` returns can read as missing there. In a named source it also opens privacy-alias pages (`access`, `confidentiality`), atoms, concepts and events derived from private or unknown origins, and pages with private declared lineage; pinned questions stay owner-only. Stored in its own column, not in the legacy permissions JSON, so a harness token rotation does not carry it; the rotation prints the rescope that grants it again. |+| `--private-facts` | `granted-sources` or `none` | Whether remote reads see facts saved with `visibility = 'private'` (facts saved before `facts.default_visibility world`, for example). `none` (the default for every token and client, and what an upgrade leaves every existing one at) keeps remote fact reads world-only, as before. `granted-sources` makes the key read every private fact in the sources its grant lists, including facts saved private on purpose. A source opens only when the grant lists it by id (a token's `--sources` list, or a client's write source plus its read sources); a source the key merely reaches never opens: not the no-grant floor, not a source federated before or after the grant was written, not a client's bound source, not a request's `source_id` / `source_ids`, and not any future switch that lets a key read every shared source. No fact is rewritten, so `none` takes effect on the next request. It never opens a fact held on, provenanced from or about a private, privacy-alias, `readable_by`, folder-ruled, quarantined, missing or member page (the pages `gbrain repair open-facts` refuses to open), nor a fact with no page to check: one with no holding page, or from a transcript lane (conversation extraction, the conversation archive, capture hooks, transcripts, connectors). Every other fact rule (provenance and entity page gates, trust floor, withdrawals) still applies. It applies to a credential's own non-mutating reads (`recall`, `search`, `query`, `entity` and the other fact reads); `context_pack`, `delta`, writes, an asserted audience, an attested actor and a scope read stay world-only. A credential that lists `--attest-sources` cannot hold it. Only the local CLI on the brain host sets it: no MCP operation and no admin HTTP route does. Stored in its own column; a harness token rotation does not carry it. || `--reset-default` | `sources,takes-holders,operations` | Token only: restores the `auth create` default for those axes: no source grant (the historical `default` floor), holders `world`, no operation snapshot. || `--refresh-operations` | with optional `--add op,...` or `--all-new` | Token only: previews operations added since the snapshot. Without `--add` or `--all-new` nothing is widened. || `--if-version` | `N` | Refuses unless the stored grant revision is `N`; the refusal names the current revision. |diff --git a/docs/mcp/OPENCLAW.md b/docs/mcp/OPENCLAW.mdindex 9afb2c331c..7cf6479425 100644--- a/docs/mcp/OPENCLAW.md+++ b/docs/mcp/OPENCLAW.md@@ -161,6 +161,11 @@ member relaxes it for every person the bot serves:`--private-pages granted-sources`. With it, every mapped person reads every`visibility: private` page in the bot's sources, which on a personal brain areyour own private pages.+- **No private-facts grant on the bot.** Leave its token at+ `--private-facts none`. A DM call that names a person never uses that grant+ (an asserted audience reads world-only facts), so it adds nothing for the+ people the bot serves, and any call that reaches the brain without the header+ would read every fact saved private in the bot's sources.- **Host hatches off.** `GBRAIN_REMOTE_PRIVATE_PAGES` and`search.remote_private_pages` apply to every remote caller on the host, thisbot included. Leave both unset while the bot runs.diff --git a/scripts/postgres-arm-weights.json b/scripts/postgres-arm-weights.jsonindex 22f029ef90..4f85c99460 100644--- a/scripts/postgres-arm-weights.json+++ b/scripts/postgres-arm-weights.json@@ -555,6 +555,7 @@"test/repair-frontmatter.test.ts": 26839,"test/repair-ghost-database-ahead-gbra133.test.ts": 9540,"test/repair-lost-fence-rows.test.ts": 161571,+ "test/repair-open-facts-8194.test.ts": 24878,"test/repair-private-labels-batch.test.ts": 77647,"test/repair-quoted-markers-8059.test.ts": 14972,"test/repair-receipt-compaction.test.ts": 8951,diff --git a/src/commands/auth-client-rows.ts b/src/commands/auth-client-rows.tsnew file mode 100644index 0000000000..08ae3a63dd--- /dev/null+++ b/src/commands/auth-client-rows.ts@@ -0,0 +1,74 @@+/**+ * `gbrain auth clients`'s client listing, split out of commands/auth.ts (which re-exports it) to keep that file under+ * its size ceiling: one SELECT on a current brain, a ladder of narrower projections on a brain from before each column.+ */+import type { BrainEngine } from '../core/engine.ts';+import { isMissingSchemaObject } from '../core/utils.ts';+import type { ClientRow } from './auth.ts';++/**+ * Projection-widened client listing with a degrade ladder for pre-migration+ * brains: full shape (scope + surface + source-scoping columns) → source+ * columns without surface → the bare original triple. Drops the NEWEST+ * columns first; missing columns render as null. Only schema-shape errors+ * (undefined column/table) degrade — anything else (dropped connection,+ * permission) rethrows instead of silently narrowing the listing. One round+ * trip on a current brain (the widen adds columns, not queries). Exported+ * for the unit suite.+ */+export async function listClientRows(engine: BrainEngine): Promise<ClientRow[]> {+ // The columns each degrade tier drops; any other missing object rethrows.+ const isSchemaShapeError = (e: unknown): boolean =>+ isMissingSchemaObject(e, 'table', 'oauth_clients') ||+ isMissingSchemaObject(e, 'column', ['private_facts', 'private_pages', 'allowed_operations', 'deleted_at', 'surface', 'surface_set_by', 'source_id', 'federated_read']);+ try {+ return await engine.executeRaw<ClientRow>(+ `SELECT client_id, client_name, scope, surface, surface_set_by, source_id, federated_read, allowed_operations, deleted_at, private_pages, private_facts+ FROM oauth_clients ORDER BY client_name, client_id`,+ );+ } catch (e) {+ // Brain predates the private-facts column: it reads as none.+ if (!isSchemaShapeError(e)) throw e;+ }+ try {+ return await engine.executeRaw<ClientRow>(+ `SELECT client_id, client_name, scope, surface, surface_set_by, source_id, federated_read, allowed_operations, deleted_at, private_pages+ FROM oauth_clients ORDER BY client_name, client_id`,+ );+ } catch (e) {+ // Brain predates the private-pages column: it reads as none.+ if (!isSchemaShapeError(e)) throw e;+ }+ try {+ return await engine.executeRaw<ClientRow>(+ `SELECT client_id, client_name, scope, surface, surface_set_by, source_id, federated_read, allowed_operations, deleted_at+ FROM oauth_clients ORDER BY client_name, client_id`,+ );+ } catch (e) {+ // Brain predates the operation-snapshot columns: operations read `unavailable`.+ if (!isSchemaShapeError(e)) throw e;+ }+ try {+ return await engine.executeRaw<ClientRow>(+ `SELECT client_id, client_name, scope, surface, surface_set_by, source_id, federated_read+ FROM oauth_clients ORDER BY client_name, client_id`,+ );+ } catch (e) {+ // Brain predates the surface columns — fall through. Rethrow non-shape errors.+ if (!isSchemaShapeError(e)) throw e;+ }+ try {+ const mid = await engine.executeRaw<Omit<ClientRow, 'surface' | 'surface_set_by'>>(+ `SELECT client_id, client_name, scope, source_id, federated_read+ FROM oauth_clients ORDER BY client_name, client_id`,+ );+ return mid.map(r => ({ ...r, surface: null, surface_set_by: null }));+ } catch (e) {+ // Brain predates the source-scoping columns — fall through likewise.+ if (!isSchemaShapeError(e)) throw e;+ }+ const bare = await engine.executeRaw<Pick<ClientRow, 'client_id' | 'client_name' | 'scope'>>(+ `SELECT client_id, client_name, scope FROM oauth_clients ORDER BY client_name, client_id`,+ );+ return bare.map(r => ({ ...r, surface: null, surface_set_by: null, source_id: null, federated_read: null }));+}diff --git a/src/commands/auth-private-facts.ts b/src/commands/auth-private-facts.tsnew file mode 100644index 0000000000..dfe02a9b22--- /dev/null+++ b/src/commands/auth-private-facts.ts@@ -0,0 +1,35 @@+/**+ * GBRA-575 (Discussion #8194): how `gbrain auth` shows the private-facts grant: its label in `auth clients` and+ * `auth rescope`, the warning rescope prints when it turns on, and its help lines. commands/auth.ts imports these.+ */+import type { PrivateFactsGrant } from '../core/grants/model.ts';++/** The plain warning printed when a credential's private-facts grant turns on. */+const WARNING = ' This key will read every private fact in the sources its grant names, including facts saved private on purpose.\n'+ + ' Facts on a private, readable_by, folder-ruled, quarantined or member page, and facts with no page to check\n'+ + ' (conversation archive, transcripts), stay hidden. Turn it off with --private-facts none.';++/** The private-facts axis as `auth clients` and `auth rescope` print it (`auth list` prints the mode alone). */+export function renderPrivateFacts(mode: PrivateFactsGrant | undefined): string {+ return mode === 'granted_sources' ? 'granted-sources (private facts in the sources this grant names)' : 'none';+}++/** The warning, when the grant goes from none to granted-sources; nothing otherwise. */+export function privateFactsWarning(before: PrivateFactsGrant | undefined, after: PrivateFactsGrant | undefined): string[] {+ return before !== 'granted_sources' && after === 'granted_sources' ? [WARNING] : [];+}++/** A token rescope's private-facts lines: the before/after line and the warning; nothing when it is none on both sides. */+export function privateFactsRescopeLines(before: PrivateFactsGrant | undefined, after: PrivateFactsGrant | undefined): string[] {+ if (!before && !after) return [];+ const [was, now] = [renderPrivateFacts(before), renderPrivateFacts(after)];+ return [` Private facts: ${was === now ? now : `${was} -> ${now}`}`, ...privateFactsWarning(before, after)];+}++/** The `--private-facts` lines of `gbrain auth --help`. */+export const PRIVATE_FACTS_HELP = ` --private-facts <granted-sources|none> Remote reads see every fact stamped private in the sources+ this grant lists, including facts saved private on purpose;+ never one on a private, readable_by, folder-ruled,+ quarantined or member page, or a fact with no page to check+ (transcripts); no fact is rewritten; 'none' (default)+ hides them`;diff --git a/src/commands/auth.ts b/src/commands/auth.tsindex fcb6bb19a2..04081c021c 100644--- a/src/commands/auth.ts+++ b/src/commands/auth.ts@@ -33,6 +33,8 @@ import type { OAuthTransaction } from '../core/oauth-grants.ts';import { readClientGrant, rescopeClientGrant, resolveGrantProfile, type GrantPatch } from '../core/grants/service.ts';import { parseClientRescopeArgs, parseRescopeGrantArgs, splitRescopeTarget, type RescopeGrantArgs } from '../core/grants/cli.ts';import { GRANT_PROFILES, GrantError, TOKEN_TTL_MAX_SECONDS, TOKEN_TTL_MIN_SECONDS, grantFromClient, privatePagesFromColumn, type ClientGrant, type PrivatePagesGrant } from '../core/grants/model.ts';+import { PRIVATE_FACTS_HELP, privateFactsRescopeLines, privateFactsWarning, renderPrivateFacts } from './auth-private-facts.ts';+import { listClientRows } from './auth-client-rows.ts';import { cliRenderContext, renderAction, type RenderedAction } from '../core/agent-output.ts';import type { INSTALL_SURFACE_SET_BY } from '../mcp/surface.ts';import { credentialCensus, exposureServes, sharedTokenNotice, writeExposureNotice } from '../core/grants/shared-exposure.ts';@@ -42,6 +44,7 @@ import { bindingLine, checkBindingTarget, takeBindingFlags } from './auth-bindinimport { mintToken } from './auth-mint.ts';import { assertCredentialScoped, logReadsUnscopedChange } from '../core/access/requester-scope.ts';import { exitCliError } from '../cli/cli-error.ts';+export { listClientRows, renderPrivateFacts };import { OperationError } from '../core/ops/contract.ts';/**@@ -165,7 +168,7 @@ export function renderTokenScopes(scopes: unknown): string {async function list(json: boolean) {await withConfiguredSql(async (sql) => {- // SELECT * reads every schema generation (private_pages arrives with GBRA-156's migration; absent reads as none).+ // SELECT * reads every schema generation (private_pages and private_facts arrive with their migrations; absent reads as none).const rows = await sql`SELECT * FROM access_tokensORDER BY created_at DESC@@ -173,7 +176,7 @@ async function list(json: boolean) {if (json) {console.log(JSON.stringify(rows.map(r => ({id: String(r.id), name: r.name, scopes: renderTokenScopes(r.scopes), created_at: r.created_at, last_used_at: r.last_used_at ?? null,- status: r.revoked_at ? 'revoked' : 'active', private_pages: privatePagesFromColumn(r.private_pages),+ status: r.revoked_at ? 'revoked' : 'active', private_pages: privatePagesFromColumn(r.private_pages), private_facts: privatePagesFromColumn(r.private_facts),})), null, 2));return;}@@ -181,8 +184,8 @@ async function list(json: boolean) {console.log('No tokens found. Create one: gbrain auth create "my-client"');return;}- console.log('ID Name Scopes Created Last Used Status Private pages');- console.log('─'.repeat(141));+ console.log('ID Name Scopes Created Last Used Status Private facts Private pages');+ console.log('─'.repeat(158));for (const r of rows) {const id = String(r.id).padEnd(36);const name = (r.name as string).padEnd(20);@@ -190,7 +193,8 @@ async function list(json: boolean) {const created = new Date(r.created_at as string).toISOString().slice(0, 19);const lastUsed = r.last_used_at ? new Date(r.last_used_at as string).toISOString().slice(0, 19) : 'never'.padEnd(19);const status = (r.revoked_at ? 'REVOKED' : 'active').padEnd(7);- console.log(`${id} ${name} ${scopes} ${created} ${lastUsed} ${status} ${renderPrivatePages(privatePagesFromColumn(r.private_pages))}`);+ const facts = privatePagesFromColumn(r.private_facts) === 'granted_sources' ? 'granted-sources' : 'none';+ console.log(`${id} ${name} ${scopes} ${created} ${lastUsed} ${status} ${facts.padEnd(15)} ${renderPrivatePages(privatePagesFromColumn(r.private_pages))}`);}});}@@ -941,8 +945,9 @@ function printClientGrantAxes(grant: ClientGrant, before?: ClientGrant) {const axes: Array<[string, (g: ClientGrant) => string]> = [['Scopes', g => g.scopes.join(' ') || '<none>'], ['Write source', g => g.sourcesNone ? 'none (every read and write refused)' : String(g.sourceId)],['Federated reads', g => g.federatedRead.join(', ') || '<none>'], ['Operations', g => g.allowedOperations === null ? 'all (no snapshot)' : g.allowedOperations.join(', ') || 'none'],['Slug prefixes', g => g.boundSlugPrefixes?.join(', ') || '<none>'], ['Takes holders', g => g.takesHolders === null ? 'world (default)' : g.takesHolders.join(', ') || 'none (every take hidden)'],- ['Private pages', g => renderPrivatePages(g.privatePages)], ['Tool surface', g => g.surface ?? '<server default>'], ['Delegated spending', g => g.budgetUsdPerDay === null ? 'unlimited' : '$' + g.budgetUsdPerDay + '/day']];+ ['Private pages', g => renderPrivatePages(g.privatePages)], ['Private facts', g => renderPrivateFacts(g.privateFacts)], ['Tool surface', g => g.surface ?? '<server default>'], ['Delegated spending', g => g.budgetUsdPerDay === null ? 'unlimited' : '$' + g.budgetUsdPerDay + '/day']];for (const [label, render] of axes) { const after = render(grant), was = before ? render(before) : after; console.log(` ${label}: ${was === after ? after : `${was} -> ${after}`}`); }+ if (before) for (const line of privateFactsWarning(before.privateFacts, grant.privateFacts)) console.log(line);}function printTokenRescope(result: RescopeTokenResult, json: boolean, bound?: BindingResult) {@@ -959,6 +964,7 @@ function printTokenRescope(result: RescopeTokenResult, json: boolean, bound?: Biconst [ppBefore, ppAfter] = [renderPrivatePages(result.before.privatePages), renderPrivatePages(result.after.privatePages)];console.log(` Private pages: ${ppBefore === ppAfter ? ppAfter : `${ppBefore} -> ${ppAfter}`}`);}+ for (const line of privateFactsRescopeLines(result.before.privateFacts, result.after.privateFacts)) console.log(line);console.log(` Grant revision: ${result.revision.before === result.revision.after ? result.revision.after : `${result.revision.before} -> ${result.revision.after}`}`);if (bound) console.log(bindingLine(bound, result.dryRun));if (result.drift.length && !result.written) {@@ -1043,6 +1049,8 @@ export interface ClientRow {deleted_at?: string | Date | null;/** GBRA-156 private-pages axis; absent on schemas without it (reads as none). */private_pages?: string | null;+ /** GBRA-575 private-facts axis; absent on schemas without it (reads as none). */+ private_facts?: string | null;}/** The operation-snapshot axis of one client, as `auth clients` reports it. */@@ -1099,64 +1107,6 @@ export function clientOperationsLines(row: ClientRow): string[] {return lines;}-/**- * Projection-widened client listing with a degrade ladder for pre-migration- * brains: full shape (scope + surface + source-scoping columns) → source- * columns without surface → the bare original triple. Drops the NEWEST- * columns first; missing columns render as null. Only schema-shape errors- * (undefined column/table) degrade — anything else (dropped connection,- * permission) rethrows instead of silently narrowing the listing. One round- * trip on a current brain (the widen adds columns, not queries). Exported- * for the unit suite.- */-export async function listClientRows(engine: BrainEngine): Promise<ClientRow[]> {- // The columns each degrade tier drops; any other missing object rethrows.- const isSchemaShapeError = (e: unknown): boolean =>- isMissingSchemaObject(e, 'table', 'oauth_clients') ||- isMissingSchemaObject(e, 'column', ['private_pages', 'allowed_operations', 'deleted_at', 'surface', 'surface_set_by', 'source_id', 'federated_read']);- try {- return await engine.executeRaw<ClientRow>(- `SELECT client_id, client_name, scope, surface, surface_set_by, source_id, federated_read, allowed_operations, deleted_at, private_pages- FROM oauth_clients ORDER BY client_name, client_id`,- );- } catch (e) {- // Brain predates the private-pages column: it reads as none.- if (!isSchemaShapeError(e)) throw e;- }- try {- return await engine.executeRaw<ClientRow>(- `SELECT client_id, client_name, scope, surface, surface_set_by, source_id, federated_read, allowed_operations, deleted_at- FROM oauth_clients ORDER BY client_name, client_id`,- );- } catch (e) {- // Brain predates the operation-snapshot columns: operations read `unavailable`.- if (!isSchemaShapeError(e)) throw e;- }- try {- return await engine.executeRaw<ClientRow>(- `SELECT client_id, client_name, scope, surface, surface_set_by, source_id, federated_read- FROM oauth_clients ORDER BY client_name, client_id`,- );- } catch (e) {- // Brain predates the surface columns — fall through. Rethrow non-shape errors.- if (!isSchemaShapeError(e)) throw e;- }- try {- const mid = await engine.executeRaw<Omit<ClientRow, 'surface' | 'surface_set_by'>>(- `SELECT client_id, client_name, scope, source_id, federated_read- FROM oauth_clients ORDER BY client_name, client_id`,- );- return mid.map(r => ({ ...r, surface: null, surface_set_by: null }));- } catch (e) {- // Brain predates the source-scoping columns — fall through likewise.- if (!isSchemaShapeError(e)) throw e;- }- const bare = await engine.executeRaw<Pick<ClientRow, 'client_id' | 'client_name' | 'scope'>>(- `SELECT client_id, client_name, scope FROM oauth_clients ORDER BY client_name, client_id`,- );- return bare.map(r => ({ ...r, surface: null, surface_set_by: null, source_id: null, federated_read: null }));-}-/** Clients whose stored or outstanding access-token lifetime an upgrade brought inside the 90-day maximum. */export async function tokenLifetimeClampedClients(engine: BrainEngine): Promise<Set<string>> {try {@@ -1208,6 +1158,7 @@ async function clientsCmd(args: string[]) {source_id: c.source_id,federated_read: c.federated_read,private_pages: privatePagesFromColumn(c.private_pages),+ private_facts: privatePagesFromColumn(c.private_facts),...clientOperationsView(c),revoked_at: c.deleted_at ?? null,token_lifetime_clamped: lifetimeClamped.has(c.client_id),@@ -1235,6 +1186,7 @@ async function clientsCmd(args: string[]) {console.log(` scopes: ${c.scope ?? '<none>'} surface: ${surfaceStr}`);console.log(` write source: ${c.source_id ?? '<none>'} federated reads: ${(c.federated_read ?? []).join(', ') || '<none>'}`);console.log(` private pages: ${renderPrivatePages(privatePagesFromColumn(c.private_pages))}`);+ console.log(` private facts: ${renderPrivateFacts(privatePagesFromColumn(c.private_facts))}`);for (const line of clientOperationsLines(c)) console.log(line);if (lifetimeClamped.has(c.client_id)) console.log(' access-token lifetime: clamped to the 90-day maximum by an upgrade (docs/mcp/ADMIN.md#access-token-lifetime)');if (parsed.usage) {@@ -1337,7 +1289,7 @@ Usage:page no rule restricts on purpose (credential_scope_required)gbrain auth set-min-trust <client|token> <tier|none> Set or clear the read floor of an OAuth client (id)or legacy token (id or name). Local CLI only.- gbrain auth list [--json] List all tokens (id, scopes, usage, private pages)+ gbrain auth list [--json] List all tokens (id, scopes, usage, private facts and pages)gbrain auth revoke <name> Revoke a legacy token (ALL active rows with that name)gbrain auth revoke --id <uuid> Revoke exactly one token by id (names are not unique)gbrain auth rescope --token <name>|--id <uuid>|--client <client_id>|<name> [options]@@ -1372,6 +1324,7 @@ Usage:sources this grant names explicitly (never theno-grant floor, federation, a client's bound sourceor a request's source_ids); 'none' (default) hides them+${PRIVATE_FACTS_HELP}--reset-default <sources,takes-holders,operations> Token only: restore the auth create default for those axes--refresh-operations [--add <op,...>|--all-new] Token only: preview operations added since the snapshot;widen only by the ones --add names (or all with --all-new)diff --git a/src/core/access/attest-sources.ts b/src/core/access/attest-sources.tsindex b214d386ea..5ca4797ad8 100644--- a/src/core/access/attest-sources.ts+++ b/src/core/access/attest-sources.ts@@ -72,7 +72,7 @@ export async function markedScopeSources(db: Db, ids: readonly string[], lock?:}export interface CredentialRef { kind: 'token' | 'client'; id: string }-interface CredentialSources { ref: CredentialRef; reads: string[]; write: string | null; attest: string[]; privatePages: boolean; label: string }+interface CredentialSources { ref: CredentialRef; reads: string[]; write: string | null; attest: string[]; privatePages: boolean; privateFacts: boolean; label: string }const same = (a: CredentialRef, b: CredentialRef | null | undefined) => !!b && a.kind === b.kind && a.id === b.id;const strings = (v: unknown): string[] => Array.isArray(v) ? v.filter((s): s is string => typeof s === 'string') : [];@@ -98,10 +98,10 @@ async function credentialSources(sql: SqlQuery): Promise<CredentialSources[]> {...clients.map(row => {const g = grantFromRow(row);return { ref: { kind: 'client' as const, id: g.clientId }, reads: clientGrantReads(g), write: g.sourcesNone === true ? null : g.sourceId ?? 'default',- attest: strings(row.attest_sources), privatePages: row.private_pages === 'granted_sources', label: `OAuth client ${g.clientId}` };+ attest: strings(row.attest_sources), privatePages: row.private_pages === 'granted_sources', privateFacts: row.private_facts === 'granted_sources', label: `OAuth client ${g.clientId}` };}),...tokens.map(row => ({ ref: { kind: 'token' as const, id: String(row.id) }, ...sourcesOf(grantFromTokenRow(row).sources),- attest: strings(row.attest_sources), privatePages: row.private_pages === 'granted_sources', label: `token ${String(row.name ?? row.id)}` })),+ attest: strings(row.attest_sources), privatePages: row.private_pages === 'granted_sources', privateFacts: row.private_facts === 'granted_sources', label: `token ${String(row.name ?? row.id)}` })),];}@@ -110,13 +110,17 @@ async function credentialSources(sql: SqlQuery): Promise<CredentialSources[]> {* being written (null for one not inserted yet), whose stored attest_sources are honoured. `default` is never a scope* source (applyAttestSources refuses it), so a default-only grant reads nothing.*/-export async function assertScopeSourceGrant(db: Db, self: CredentialRef | null, reads: readonly string[], opts: { privatePages?: boolean; writeSource?: string | null } = {}): Promise<void> {+export async function assertScopeSourceGrant(db: Db, self: CredentialRef | null, reads: readonly string[], opts: { privatePages?: boolean; privateFacts?: boolean; writeSource?: string | null } = {}): Promise<void> {const sql = sqlOf(db);- const attest = self && (opts.privatePages || opts.writeSource) ? (await credentialSources(sql)).find(c => same(c.ref, self))?.attest ?? [] : [];+ const attest = self && (opts.privatePages || opts.privateFacts || opts.writeSource) ? (await credentialSources(sql)).find(c => same(c.ref, self))?.attest ?? [] : [];if (opts.privatePages && attest.length) {throw new GrantError('invalid_grant', 'This credential lists scope sources (--attest-sources), so it cannot hold the private-pages grant; nothing changed. '+ 'A scope credential reads only shared memory: use a separate credential for private pages.');}+ if (opts.privateFacts && attest.length) {+ throw new GrantError('invalid_grant', 'This credential lists scope sources (--attest-sources), so it cannot hold the private-facts grant; nothing changed. '+ + 'A scope credential reads only shared memory: use a separate credential for private facts.');+ }if (opts.writeSource && attest.includes(opts.writeSource)) {throw new GrantError('invalid_grant', `Source ${opts.writeSource} is in this credential's --attest-sources, so it cannot be its write source (where member pages live); nothing changed. `+ 'Keep member pages and each scope in separate sources: pick another write source.');@@ -160,6 +164,9 @@ export async function applyAttestSources(db: Db, self: CredentialRef, next: readif (added.length && mine?.privatePages) {throw attestInvalid('This credential holds the private-pages grant, so it cannot list scope sources; nothing changed.', 'Clear it first (gbrain auth rescope ... --private-pages none): a scope credential reads only shared memory.');}+ if (added.length && mine?.privateFacts) {+ throw attestInvalid('This credential holds the private-facts grant, so it cannot list scope sources; nothing changed.', 'Clear it first (gbrain auth rescope ... --private-facts none): a scope credential reads only shared memory.');+ }for (const s of added) {const [row] = await sql`SELECT archived, config FROM sources WHERE id = ${s}`;if (!row || row.archived === true) throw attestInvalid(`--attest-sources names ${s}, which is not an active source.`, 'Add a dedicated source for the scope first (gbrain sources add <id>: with a path on a repo brain, without one on a repo-less brain), then list it.');diff --git a/src/core/access/member-facts.ts b/src/core/access/member-facts.tsindex 77ad06ddce..8d845e4866 100644--- a/src/core/access/member-facts.ts+++ b/src/core/access/member-facts.ts@@ -12,7 +12,8 @@*/import { createHash } from 'node:crypto';import type { OperationContext } from '../ops/contract.ts';-import { currentCallerAccess, folderRestrictedSql, isDerivationPrivate, privatePagesFilterForCaller, withFolderRestricted } from '../search/private-visibility.ts';+import { currentCallerAccess, folderRestrictedSql, isDerivationPrivate, privateFactSources, privatePagesFilterForCaller, withFolderRestricted } from '../search/private-visibility.ts';+import { factPagesOpenSql, unpagedFactSql } from '../facts/private-fact-pages.ts';import type { BrainEngine } from '../engine.ts';import { ACCESS_ID_RE, MEMBER_PAGE_PREFIX, normalizeReaders, SCOPE_PAGE_SLUG } from './principals.ts';import { opError, type OperationError } from '../ops/contract.ts';@@ -155,13 +156,27 @@ export async function ownMemberFactIds(engine: Pick<BrainEngine, 'executeRaw'>,return new Set(rows.map(r => Number(r.id)));}-/** A remote fact read's visibility list as SQL: the listed values, widened only by memberFactAdmitSql. */+/**+ * GBRA-575: the private facts the current caller's private-facts grant admits: a fact stamped private in a source the+ * grant lists by id (privateFactSources) whose holding, provenance and entity pages are none of member,+ * derivation-private (private, privacy alias, readable_by, folder rule), missing or quarantined (factPagesOpenSql, the+ * same pages `gbrain repair open-facts` refuses to open), and that has a page to check: never an unpaged or+ * transcript-lane fact (unpagedFactSql), conversation archive included. FALSE outside such a grant. Source ids passed+ * isValidSourceId, so they embed as literals.+ */+export function grantedPrivateFactSql(alias: string): string {+ const sources = privateFactSources();+ if (!sources.length) return 'FALSE';+ return `(${alias}.visibility = 'private' AND ${alias}.source_id IN (${sources.map(s => `'${s}'`).join(', ')}) AND NOT COALESCE(${unpagedFactSql(alias)}, false) AND ${factPagesOpenSql(alias)})`;+}++/** A remote fact read's visibility list as SQL: the listed values, widened only by memberFactAdmitSql and grantedPrivateFactSql. */export function factVisibilitySql(alias: string, visibility: readonly string[]): string {const known = (['world', 'private'] as const).filter(v => visibility.includes(v));const listed = known.length ? `${alias}.visibility IN (${known.map(v => `'${v}'`).join(', ')})` : 'FALSE';if (known.includes('private')) return listed;- const own = memberFactAdmitSql(alias);- return own === 'FALSE' ? listed : `(${listed} OR ${own})`;+ const widened = [memberFactAdmitSql(alias), grantedPrivateFactSql(alias)].filter(sql => sql !== 'FALSE');+ return widened.length ? `(${[listed, ...widened].join(' OR ')})` : listed;}/**diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex d159b613dc..0087a8bbb6 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -14,13 +14,13 @@// (help-text mentions count): accepting an ignored flag is the pre-#2185// status quo; missing a real one breaks working invocations.export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {- 'access': ['--add', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--allow-without-owner', '--approved', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--bind-token', '--brain', '--client', '--dry-run', '--email', '--expect', '--file', '--grant-types', '--groups', '--help', '--http', '--id', '--if-version', '--json', '--kind', '--labelled-only', '--limit', '--may-act-for', '--member', '--members', '--members-file', '--migrate-legacy', '--name', '--no-open-pages', '--operation', '--operations', '--prefix', '--private-pages', '--qm', '--raw-only', '--readers', '--reads-unscoped', '--refresh-operations', '--reset-default', '--revision', '--scopes', '--slug', '--source', '--sources', '--stdio-member', '--takes-holders', '--to', '--token', '--tools-json', '--yes'],+ 'access': ['--add', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--allow-without-owner', '--approved', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--bind-token', '--brain', '--client', '--dry-run', '--email', '--expect', '--file', '--grant-types', '--groups', '--help', '--http', '--id', '--if-version', '--json', '--kind', '--labelled-only', '--limit', '--may-act-for', '--member', '--members', '--members-file', '--migrate-legacy', '--name', '--no-open-pages', '--operation', '--operations', '--prefix', '--private-facts', '--private-pages', '--qm', '--raw-only', '--readers', '--reads-unscoped', '--refresh-operations', '--reset-default', '--revision', '--scopes', '--slug', '--source', '--sources', '--stdio-member', '--takes-holders', '--to', '--token', '--tools-json', '--yes'],'advisor': ['--apply', '--brain', '--help', '--json', '--skills-dir', '--source', '--workspace', '--yes'],'agent': ['--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated-read', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-follow', '--port', '--preset', '--reissue', '--scopes', '--show-token', '--since', '--source', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],'anomalies': ['--all', '--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--request-id', '--sigma', '--since', '--source'],'append': ['--brain', '--expect-tail', '--expected-revision', '--file', '--force', '--help', '--json', '--region', '--request-id', '--separator', '--source'],'apply-migrations': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--apply', '--apply-rewrites', '--backup-confirmed', '--brain', '--break-lock', '--concurrency', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--install', '--json', '--legacy-lock', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--only', '--path', '--prefer-postgres', '--probe', '--repo', '--require-db', '--skip-verify', '--source', '--statement-timeout', '--uninstall', '--url', '--yes'],- 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--allowed-operations', '--apply', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--email', '--enable', '--enable-dcr-insecure', '--expect', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--group-by', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--may-act-for', '--member', '--members', '--migrate-legacy', '--min-trust', '--no-pull', '--only', '--operation', '--operations', '--origin', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--private-pages', '--probe', '--profile', '--qm', '--read-sources', '--reads-unscoped', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retire', '--scopes', '--self-transfer', '--shared-skills', '--since', '--slug-prefixes', '--source', '--source-ids', '--sources', '--state', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--unsettle', '--usage', '--wait', '--warn-only', '--yes'],+ 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--allowed-operations', '--apply', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--email', '--enable', '--enable-dcr-insecure', '--expect', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--group-by', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--may-act-for', '--member', '--members', '--migrate-legacy', '--min-trust', '--no-pull', '--only', '--operation', '--operations', '--origin', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--private-facts', '--private-pages', '--probe', '--profile', '--qm', '--read-sources', '--reads-unscoped', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retire', '--scopes', '--self-transfer', '--shared-skills', '--since', '--slug-prefixes', '--source', '--source-ids', '--sources', '--state', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--unsettle', '--usage', '--wait', '--warn-only', '--yes'],'autopilot': ['--apply', '--backend', '--batch', '--brain', '--channel', '--check', '--concurrent', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-embed-cache', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--pause', '--phase', '--quiet', '--reader-mode', '--reason', '--refresh-cache', '--refs', '--remediation-plan', '--repo', '--restart-only', '--resume', '--retry-global', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--trust', '--unattended', '--uninstall', '--user', '--verify', '--version', '--yes'],'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],'backup': ['--accept-pending', '--as', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--purge-mirror', '--quiet', '--restore-only', '--room', '--source', '--timeout', '--timings', '--wait'],@@ -117,7 +117,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--allow-without-owner', '--apply', '--as', '--audit', '--auto-additive', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--conflicts', '--created-before', '--cursor', '--cwd', '--day', '--diff', '--email', '--expect', '--explain', '--ff-only', '--follow', '--force', '--force-break-lock', '--from', '--full', '--full-history', '--generation', '--held', '--help', '--id', '--ids-file', '--include-ambiguous', '--include-cross-entity', '--include-failures', '--include-repairs', '--json', '--keep', '--key', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--mode', '--no-accept-pending', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--out', '--prefer', '--prefix', '--preview', '--principal', '--probe', '--progress-interval', '--progress-json', '--propose', '--provenance', '--quiet', '--readers', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--room', '--rules', '--run', '--scopes', '--seat', '--session', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--slugs-file', '--source', '--stale', '--state', '--timeout', '--timings', '--undo', '--url', '--wait', '--yes'],'repair-jsonb': ['--accept-pending', '--as', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--room', '--source', '--supabase', '--timeout', '--timings', '--url', '--wait'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],- 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--approval-out', '--approved', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--force-with-lease', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--heads', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--list-out', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--mode', '--name', '--name-only', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-edit', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-follow-tags', '--no-harden', '--no-lanes', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--readers', '--reads-unscoped', '--rebase', '--recurse-submodules', '--redirect-uri', '--refresh-operations', '--remote', '--remove', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retire', '--retry-failed', '--sample', '--scan-secrets', '--scan-timeout', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--stat', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--uninstall', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],+ 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--approval-out', '--approved', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--force-with-lease', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--heads', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--list-out', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--mode', '--name', '--name-only', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-edit', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-follow-tags', '--no-harden', '--no-lanes', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--prefix', '--preview', '--private-facts', '--private-pages', '--probe', '--profile', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--readers', '--reads-unscoped', '--rebase', '--recurse-submodules', '--redirect-uri', '--refresh-operations', '--remote', '--remove', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retire', '--retry-failed', '--sample', '--scan-secrets', '--scan-timeout', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--stat', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--uninstall', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],'retrieval-upgrade': ['--accept-pending', '--all', '--as', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--plan', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--room', '--slugs', '--source', '--stale', '--status', '--timeout', '--timings', '--to', '--wait', '--yes'],'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],@@ -132,7 +132,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'skillpack': ['--accept-historical', '--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fail-on-skipped', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-diff', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--update-untouched', '--url', '--verify', '--version', '--workspace', '--yes'],'skillpack-check': ['--accept-pending', '--as', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--room', '--source', '--strict', '--timeout', '--timings', '--wait', '--yes'],'smoke-test': ['--brain', '--help', '--json', '--source'],- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--approval-out', '--approved', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--channels', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-with-lease', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--heads', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--list-out', '--local', '--local-env-vars', '--lookback-days', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--max-requests', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--mode', '--name', '--name-only', '--no-accept-pending', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-edit', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-follow-tags', '--no-harden', '--no-lanes', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--progress-interval', '--progress-json', '--provider', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--readers', '--reads-unscoped', '--rebase', '--record', '--recurse-submodules', '--redirect-uri', '--refresh-operations', '--remote', '--remove', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retire', '--retry-failed', '--room', '--sample', '--scan-secrets', '--scan-timeout', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--skip', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--stat', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--sync-interval-min', '--takes-holders', '--timeout', '--timezone', '--timings', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--transcript', '--unindexed', '--uninstall', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--visibility', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],+ 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--approval-out', '--approved', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--channels', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-with-lease', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--heads', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--list-out', '--local', '--local-env-vars', '--lookback-days', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--max-requests', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--mode', '--name', '--name-only', '--no-accept-pending', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-edit', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-follow-tags', '--no-harden', '--no-lanes', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--prefix', '--preview', '--private-facts', '--private-pages', '--probe', '--profile', '--progress-interval', '--progress-json', '--provider', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--readers', '--reads-unscoped', '--rebase', '--record', '--recurse-submodules', '--redirect-uri', '--refresh-operations', '--remote', '--remove', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retire', '--retry-failed', '--room', '--sample', '--scan-secrets', '--scan-timeout', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--skip', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--stat', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--sync-interval-min', '--takes-holders', '--timeout', '--timezone', '--timings', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--transcript', '--unindexed', '--uninstall', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--visibility', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--check', '--code', '--concurrency', '--confirm-destructive', '--count', '--cursor', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--hold-state', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--limit', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--reason', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--apply', '--brain', '--card', '--client', '--dir', '--drop-field', '--dry-run', '--expect', '--expected-revision', '--finalize', '--from-prefix', '--help', '--id', '--json', '--jsonl', '--no-pull', '--only', '--out', '--patch', '--plan', '--push-remote', '--repo', '--restore-only', '--restored-to', '--scopes', '--source', '--status', '--store', '--to'],'sweep': ['--accept-pending', '--apply', '--as', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--room', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.tsindex 88839c73e4..9fe20b97bb 100644--- a/src/core/deletion-inventory.ts+++ b/src/core/deletion-inventory.ts@@ -45,7 +45,7 @@ const ROWS: readonly Row[] = [['access_policy_revisions', 'out_of_scope', 'no_memory_text', 'source_id rules digest origin proposed_by approved_by change_kind operation_id'],['access_policy_state', 'out_of_scope', 'no_memory_text', 'source_id'],['access_rules', 'out_of_scope', 'no_memory_text', 'source_id rule_id prefix readable_by created_by'],- ['access_tokens', 'out_of_scope', 'secret_material', 'name token_hash scopes permissions source_grant source_id federated_read allowed_operations takes_holders min_trust private_pages member_id may_act_for attest_actor attest_ops attest_read attest_sources'],+ ['access_tokens', 'out_of_scope', 'secret_material', 'name token_hash scopes permissions source_grant source_id federated_read allowed_operations takes_holders min_trust private_pages private_facts member_id may_act_for attest_actor attest_ops attest_read attest_sources'],['belief_events', 'swept', 'belief_ledger', 'event_key source_id slug subject_kind subject_key event_type origin trust_tier writer_tier tier_basis visibility value value_hash prior_hash state_hash cause claim_fp redacted_fields'],['belief_page_lifetimes', 'out_of_scope', 'text_free_ledger', 'source_id slug'],['belief_redactions', 'out_of_scope', 'text_free_ledger', 'source_id subject_key field field_hash released_hash'],@@ -121,7 +121,7 @@ const ROWS: readonly Row[] = [['minion_lease_pressure_log', 'out_of_scope', 'no_memory_text', 'lease_key queue_name job_name model provider'],['minion_self_fix_log', 'out_of_scope', 'no_memory_text', 'classifier_bucket policy_applied outcome'],['needs_rederive', 'out_of_scope', 'text_free_ledger', 'derived_table derived_id source_id reason'],- ['oauth_clients', 'out_of_scope', 'secret_material', 'client_id client_secret_hash client_name redirect_uris grant_types scope token_endpoint_auth_method source_id federated_read bound_tools bound_source_id bound_brain_id bound_slug_prefixes surface surface_set_by allowed_operations delegated_slug_prefixes delegated_namespace grant_profile grant_repair_reasons source_grant takes_holders min_trust registered_via private_pages member_id may_act_for attest_actor attest_ops attest_read attest_sources'],+ ['oauth_clients', 'out_of_scope', 'secret_material', 'client_id client_secret_hash client_name redirect_uris grant_types scope token_endpoint_auth_method source_id federated_read bound_tools bound_source_id bound_brain_id bound_slug_prefixes surface surface_set_by allowed_operations delegated_slug_prefixes delegated_namespace grant_profile grant_repair_reasons source_grant takes_holders min_trust registered_via private_pages private_facts member_id may_act_for attest_actor attest_ops attest_read attest_sources'],['oauth_codes', 'out_of_scope', 'secret_material', 'code_hash client_id scopes code_challenge code_challenge_method redirect_uri state resource'],['oauth_grant_audit', 'out_of_scope', 'no_memory_text', 'client_id actor action before_grant after_grant'],['oauth_tokens', 'out_of_scope', 'secret_material', 'token_hash token_type client_id scopes resource grant_type'],diff --git a/src/core/facts/meta-hook.ts b/src/core/facts/meta-hook.tsindex c172279e79..ecc12faaec 100644--- a/src/core/facts/meta-hook.ts+++ b/src/core/facts/meta-hook.ts@@ -44,7 +44,7 @@ import { partitionForActivation, suppressionSummary } from '../eligibility/activimport { trustFields } from '../eligibility/labels.ts';import { quoteFacts } from '../search/transcript-quote.ts';import { eligibilityCacheField, readTrustGeneration } from '../eligibility/generation.ts';-import { callerRelaxesPrivacy, resolveExcludePrivatePages, worldOnlyFacts } from '../search/private-visibility.ts';+import { callerRelaxesPrivacy, privateFactSources, resolveExcludePrivatePages, worldOnlyFacts } from '../search/private-visibility.ts';import { isConfigTruthy } from '../config.ts';import { callerIdentityKey } from '../access/member-facts.ts';@@ -163,7 +163,9 @@ export async function getBrainHotMemoryMeta(// GST-2089: the brain owner reads private facts too, so its remote tier is marked apart from every world-only tier.const worldOnly = worldOnlyFacts(ctx.remote);const pageTier = !excludePrivate ? 'world+private-pages' : callerRelaxesPrivacy() ? 'world+private-pages-readers' : 'world';- const tier = ctx.remote === false ? 'all' : worldOnly ? pageTier : `private-facts+${pageTier}`;+ // GBRA-575: a world-only read under a private-facts grant admits private facts in the granted sources, so it has its own tier.+ const granted = worldOnly ? [...privateFactSources()].sort().join(',') : '';+ const tier = ctx.remote === false ? 'all' : !worldOnly ? `private-facts+${pageTier}` : granted ? `${pageTier}+xpf=${granted}` : pageTier;// encodeCacheField (F5): source_id / session_id are caller-controlled and// may contain the '::' delimiter; percent-encode ':' so bumpHotMemoryCache's// split('::') can never mis-slice a component.diff --git a/src/core/facts/private-fact-pages.ts b/src/core/facts/private-fact-pages.tsnew file mode 100644index 0000000000..b811bec42f--- /dev/null+++ b/src/core/facts/private-fact-pages.ts@@ -0,0 +1,62 @@+/**+ * The pages a private fact is judged on, shared by `gbrain repair open-facts` (repair/open-facts.ts, which opens such a+ * fact) and the GBRA-575 private-facts grant (access/member-facts.ts factVisibilitySql, which lets one credential read+ * it): its holding page, its provenance page and its entity page. A fact stays private when any of them is a member page,+ * derivation-private in any row with the slug (deleted or not), missing or quarantined, and a fact with no page to+ * check (unpagedFactSql) never opens through the grant. Pure SQL text, no imports beyond+ * the predicates it reuses, so both sides load it without a cycle.+ */+import { MEMBER_PAGE_PREFIX } from '../access/principals.ts';+import { quarantineFilterFragment } from '../quarantine.ts';+import { derivationPrivateSql } from '../search/private-visibility.ts';++/**+ * The page a fact says it came from (not the page holding it): the page-write+ * session (`put_page:<slug>`, `sync:<slug>`), else the slug a page-write or+ * extract_facts lane records first in `context`.+ */+export function factProvenanceSlugSql(f: string): string {+ return `regexp_replace(COALESCE(+ CASE WHEN ${f}.source_session ~ '^(put_page|sync):' THEN regexp_replace(${f}.source_session, '^(put_page|sync):', '') END,+ CASE WHEN ${f}.source IN ('mcp:put_page','sync:import','file_upload','code_import','hook:writeback','mcp:extract_facts')+ THEN NULLIF(split_part(btrim(COALESCE(${f}.context,'')), ' ', 1), '') END), '\\.md$', '')`;+}++/** The transcript lanes: conversation extraction, capture hooks, the corpus sweep, transcripts and connectors. */+const transcriptLanesSql = (f: string) => `(${f}.source LIKE 'cli:extract-conversation-facts%' OR ${f}.source IN ('hook:writeback', 'hook:compact', 'sweep:corpus')+ OR ${f}.source LIKE 'transcript:%' OR ${f}.source LIKE 'connector:%')`;++/** A fact with no page to check: no holding page, or from a transcript lane (open-facts' unpaged:<lane> class; NULL reads as paged). */+export const unpagedFactSql = (f: string) => `(${f}.source_markdown_slug IS NULL OR ${transcriptLanesSql(f)})`;++/** Whether fact `f` is held on, provenanced from or about a member page (memory/members/<id>); NULL when no slug is set. */+export function factOnMemberPageSql(f: string): string {+ const member = (expr: string) => `left(${expr}, ${MEMBER_PAGE_PREFIX.length}) = '${MEMBER_PAGE_PREFIX}'`;+ return `(${member(`${f}.source_markdown_slug`)} OR ${member(`${f}.entity_slug`)} OR ${member(`(${factProvenanceSlugSql(f)})`)})`;+}++/** Any page row with the slug (deleted or not) that is derivation-private. */+const anyPrivatePage = (f: string, slug: string, alias: string) =>+ `EXISTS (SELECT 1 FROM pages ${alias} WHERE ${alias}.source_id = ${f}.source_id AND ${alias}.slug = ${slug} AND ${derivationPrivateSql(alias)})`;+const livePage = (f: string, slug: string, alias: string, extra = 'true') =>+ `EXISTS (SELECT 1 FROM pages ${alias} WHERE ${alias}.source_id = ${f}.source_id AND ${alias}.slug = ${slug} AND ${alias}.deleted_at IS NULL AND ${extra})`;++/** The page reasons fact `f` stays private, in the order the open-facts preview reports them: [reason, condition]. */+export function factPageReasons(f: string): Array<[string, string]> {+ const prov = `(${factProvenanceSlugSql(f)})`;+ const holding = `${f}.source_markdown_slug`;+ return [+ ['holding_page_private', `${holding} IS NOT NULL AND ${anyPrivatePage(f, holding, 'oh')}`],+ ['holding_page_missing', `${holding} IS NOT NULL AND NOT ${livePage(f, holding, 'oh')}`],+ ['holding_page_quarantined', `${holding} IS NOT NULL AND ${livePage(f, holding, 'oh', `NOT ${quarantineFilterFragment('oh')}`)}`],+ ['provenance_private', `${prov} IS NOT NULL AND ${anyPrivatePage(f, prov, 'op')}`],+ ['provenance_unresolved', `${prov} IS NOT NULL AND NOT ${livePage(f, prov, 'op')}`],+ ['provenance_quarantined', `${prov} IS NOT NULL AND ${livePage(f, prov, 'op', `NOT ${quarantineFilterFragment('op')}`)}`],+ ['entity_page_private', `${f}.entity_slug IS NOT NULL AND ${anyPrivatePage(f, `${f}.entity_slug`, 'oe')}`],+ ];+}++/** GBRA-575: none of fact `f`'s pages keeps it private (no member page, no page reason); a NULL test counts as not private. */+export function factPagesOpenSql(f: string): string {+ return `NOT COALESCE(${factOnMemberPageSql(f)} OR ${factPageReasons(f).map(([, condition]) => `(${condition})`).join(' OR ')}, false)`;+}diff --git a/src/core/grants/cli.ts b/src/core/grants/cli.tsindex c4eb374320..8db56c0660 100644--- a/src/core/grants/cli.ts+++ b/src/core/grants/cli.ts@@ -1,4 +1,4 @@-import { GRANT_PROFILES, GrantError, validatePrincipalGrant, type GrantPatch, type GrantProfileId, type PrivatePagesGrant } from './model.ts';+import { GRANT_PROFILES, GrantError, validatePrincipalGrant, type GrantPatch, type GrantProfileId, type PrivateFactsGrant, type PrivatePagesGrant } from './model.ts';import { parseScopeString, assertAllowedScopes } from '../scope.ts';import { isValidHolder } from '../takes-fence.ts';@@ -67,6 +67,7 @@ function parseRescopeGrantFlags(args: string[]): RescopeGrantArgs {result.expectedRevision = Number(value);break;case '--private-pages': result.patch.privatePages = parsePrivatePagesFlag(value); break;+ case '--private-facts': result.patch.privateFacts = parsePrivateFactsFlag(value); break;default: throw new GrantError('invalid_grant', `Unknown flag: ${flag}`);}}@@ -81,6 +82,13 @@ export function parsePrivatePagesFlag(value: string): PrivatePagesGrant {throw new GrantError('invalid_grant', '--private-pages must be granted-sources or none', ['private_pages_invalid']);}+/** `--private-facts granted-sources|none` (GBRA-575): local CLI only; no MCP operation or admin HTTP edit parses it. */+export function parsePrivateFactsFlag(value: string): PrivateFactsGrant {+ if (value === 'granted-sources') return 'granted_sources';+ if (value === 'none') return 'none';+ throw new GrantError('invalid_grant', '--private-facts must be granted-sources or none', ['private_facts_invalid']);+}+/*** `all`: store no operation snapshot, so the scopes and the surface alone* decide, including operations later releases add. A null list is valid only@@ -190,7 +198,7 @@ export function parseClientRescopeArgs(clientId: string, args: string[]): Rescopconst result = parseRescopeGrantFlags(legacy);if (sources !== undefined) {validatePrincipalGrant({- principal: { kind: 'oauth_client', id: clientId }, scopes: [], allowedOperations: null, takesHolders: null, privatePages: 'none', revision: 0,+ principal: { kind: 'oauth_client', id: clientId }, scopes: [], allowedOperations: null, takesHolders: null, privatePages: 'none', privateFacts: 'none', revision: 0,shape: 'unified', drift: [], permissionsMalformed: false,sources: sources.length === 0 ? { kind: 'none' } : { kind: 'federated', writeSource: sources[0], readSources: sources },}, { operationNames: new Set() });diff --git a/src/core/grants/legacy-token.ts b/src/core/grants/legacy-token.tsindex be5a64b11b..2527f89239 100644--- a/src/core/grants/legacy-token.ts+++ b/src/core/grants/legacy-token.ts@@ -7,6 +7,8 @@* - operations (`--operations a,b|none`, `--refresh-operations`)* - private pages (`--private-pages granted-sources|none`): stored in* `private_pages` only, never in the `permissions` mirror+ * - private facts (`--private-facts granted-sources|none`, GBRA-575): stored+ * in `private_facts` only, likewise** `none` stores the explicit empty list (deny-all). An omitted flag preserves* the stored value. `--reset-default <axes>` restores the `auth create`@@ -34,9 +36,9 @@ import { isUndefinedColumnError } from '../utils.ts';import { requiresExplicitApproval } from '../ops/execution-prerequisites.ts';import {GrantError, LEGACY_GRANT_AXES, grantFromTokenRow, permissionsMirror, tokenGrantColumnValues, tokenGrantFromColumns,- tokenGrantFromPermissions, validatePrincipalGrant, TOKEN_GRANT_COLUMNS, type LegacyGrantAxis, type PrincipalGrant, type PrivatePagesGrant,+ tokenGrantFromPermissions, validatePrincipalGrant, TOKEN_GRANT_COLUMNS, type LegacyGrantAxis, type PrincipalGrant, type PrivateFactsGrant, type PrivatePagesGrant,} from './model.ts';-import { parsePrivatePagesFlag } from './cli.ts';+import { parsePrivateFactsFlag, parsePrivatePagesFlag } from './cli.ts';export type { LegacyGrantAxis } from './model.ts';@@ -49,6 +51,7 @@ export interface RescopeTokenArgs {operations?: string[];scopes?: string[];privatePages?: PrivatePagesGrant;+ privateFacts?: PrivateFactsGrant;reset: LegacyGrantAxis[];refreshOperations: boolean;add?: string[];@@ -65,6 +68,8 @@ export interface LegacyTokenGrantView {operations: string[] | 'unrestricted';/** Present only when granted, so a 'none' token's view is unchanged. */privatePages?: 'granted_sources';+ /** GBRA-575: likewise. */+ privateFacts?: 'granted_sources';}export interface RescopeTokenResult {@@ -127,6 +132,7 @@ export function parseRescopeTokenArgs(args: string[]): RescopeTokenArgs {break;case '--add': out.add = csvOrNone(value); break;case '--private-pages': out.privatePages = parsePrivatePagesFlag(value); break;+ case '--private-facts': out.privateFacts = parsePrivateFactsFlag(value); break;case '--scopes':out.scopes = csvOrNone(value.replaceAll(' ', ','));if (out.scopes.length === 0) throw new GrantError('invalid_grant', '--scopes needs at least one scope (to cut a token off, use --sources none or gbrain auth revoke)');@@ -158,13 +164,14 @@ export function parseRescopeTokenArgs(args: string[]): RescopeTokenArgs {return { target, ...out };}-function grantView(g: TokenGrantAxes & Pick<PrincipalGrant, 'privatePages'>): LegacyTokenGrantView {+function grantView(g: TokenGrantAxes & Pick<PrincipalGrant, 'privatePages' | 'privateFacts'>): LegacyTokenGrantView {const s = g.sources;return {sources: s.kind === 'default' ? 'default' : s.kind === 'none' ? [] : s.kind === 'scalar' ? [s.writeSource] : [...s.readSources],takesHolders: g.takesHolders ?? ['world'],operations: g.allowedOperations ?? 'unrestricted',...(g.privatePages === 'granted_sources' ? { privatePages: g.privatePages } : {}),+ ...(g.privateFacts === 'granted_sources' ? { privateFacts: g.privateFacts } : {}),};}@@ -193,7 +200,7 @@ async function assertActiveSources(engine: BrainEngine, ids: string[]): Promise<const SCHEMA_HINT = 'this brain predates the unified token grant columns (access_tokens.source_grant); run `gbrain apply-migrations --yes` (no user decision needed), then retry';function schemaError(error: unknown): unknown {- return ['source_grant', 'grant_revision', 'private_pages', ...TOKEN_GRANT_COLUMNS].some(c => isUndefinedColumnError(error, c)) ? new GrantError('grant_schema_required', SCHEMA_HINT) : error;+ return ['source_grant', 'grant_revision', 'private_pages', 'private_facts', ...TOKEN_GRANT_COLUMNS].some(c => isUndefinedColumnError(error, c)) ? new GrantError('grant_schema_required', SCHEMA_HINT) : error;}/** Write the unified columns and the `permissions` mirror in one UPDATE; returns the new revision. */@@ -297,11 +304,12 @@ async function rescopeInTransaction(tx: BrainEngine, args: RescopeTokenArgs): Pr}, { operationNames: all });const privatePages = args.privatePages ?? current.privatePages;+ const privateFacts = args.privateFacts ?? current.privateFacts;const edits = args.sources !== undefined || args.takesHolders !== undefined || opsEdited || args.reset.length > 0 || args.scopes !== undefined- || args.privatePages !== undefined;+ || args.privatePages !== undefined || args.privateFacts !== undefined;if (edits && !args.adopt && current.drift.length) throw driftRefusal(name, id, current.drift);const before = grantView(current);- const after = grantView({ ...next, privatePages });+ const after = grantView({ ...next, privatePages, privateFacts });const changed = JSON.stringify(before) !== JSON.stringify(after)|| (args.scopes !== undefined && JSON.stringify(args.scopes) !== JSON.stringify(current.scopes));const write = !args.dryRun && (edits || Boolean(args.adopt));@@ -310,6 +318,10 @@ async function rescopeInTransaction(tx: BrainEngine, args: RescopeTokenArgs): Prawait (await import('../access/attest-sources.ts')).assertScopeSourceGrant(tx, { kind: 'token', id }, [], { privatePages: privatePages === 'granted_sources' });await tx.executeRaw('UPDATE access_tokens SET private_pages = $2 WHERE id = $1::uuid', [id, privatePages]);}+ if (write && privateFacts !== current.privateFacts) {+ await (await import('../access/attest-sources.ts')).assertScopeSourceGrant(tx, { kind: 'token', id }, [], { privateFacts: privateFacts === 'granted_sources' });+ await tx.executeRaw('UPDATE access_tokens SET private_facts = $2 WHERE id = $1::uuid', [id, privateFacts]);+ }return {id, name, dryRun: args.dryRun, changed, before, after,shape: current.shape, migrated: write && current.shape === 'legacy_permissions', written: write,diff --git a/src/core/grants/model.ts b/src/core/grants/model.tsindex 6697882b9e..28fce65b9d 100644--- a/src/core/grants/model.ts+++ b/src/core/grants/model.ts@@ -14,6 +14,14 @@ export type GrantSurface = 'verbs' | 'starter' | 'full';*/export type PrivatePagesGrant = 'none' | 'granted_sources';export const PRIVATE_PAGES_GRANTS: readonly PrivatePagesGrant[] = ['none', 'granted_sources'];+/**+ * GBRA-575 (Discussion #8194): whether a remote caller reads facts stamped+ * `visibility = 'private'` in the sources its grant names explicitly+ * (`granted_sources`) or in none (`none`, the default). Stored in+ * `private_facts` on access_tokens and oauth_clients, set only by the local+ * `gbrain auth rescope`; no fact is rewritten.+ */+export type PrivateFactsGrant = PrivatePagesGrant;/** Access-token lifetime bounds for every per-client override and the server default: 1 minute to 90 days. */export const TOKEN_TTL_MIN_SECONDS = 60;@@ -31,6 +39,7 @@ export interface ClientGrant {/** Takes-holder allow-list; null = the default ['world'], [] = deny-all. */takesHolders: string[] | null;privatePages: PrivatePagesGrant;+ privateFacts: PrivateFactsGrant;boundSlugPrefixes: string[] | null;allowedOperations: string[] | null;boundTools: string[] | null;@@ -88,7 +97,7 @@ export function grantFromRow(row: Record<string, unknown>): ClientGrant {scopes: parseScopeString(nullable(row.scope) ?? ''),sourceId: nullable(row.source_id), federatedRead: stringArray(row.federated_read) ?? [],sourcesNone: row.source_grant === 'none', takesHolders: stringArray(row.takes_holders),- privatePages: privatePagesFromColumn(row.private_pages),+ privatePages: privatePagesFromColumn(row.private_pages), privateFacts: privatePagesFromColumn(row.private_facts),boundSlugPrefixes: legacyPrefixes, allowedOperations: stringArray(row.allowed_operations),boundTools: stringArray(row.bound_tools), boundSourceId: nullable(row.bound_source_id),boundBrainId: normalizeGrantBrain(nullable(row.bound_brain_id)),@@ -106,7 +115,7 @@ export function grantFromRow(row: Record<string, unknown>): ClientGrant {};}-/** A `private_pages` column value; anything but `granted_sources` reads as `none` (fail closed). */+/** A `private_pages` or `private_facts` column value; anything but `granted_sources` reads as `none` (fail closed). */export function privatePagesFromColumn(value: unknown): PrivatePagesGrant {return value === 'granted_sources' ? 'granted_sources' : 'none';}@@ -154,6 +163,7 @@ export function validateClientGrant(grant: ClientGrant, ctx: GrantValidationContif (grant.surface !== null && !['verbs', 'starter', 'full'].includes(grant.surface)) reasons.push('surface_invalid');if (grant.profile !== null && !(GRANT_PROFILES as readonly string[]).includes(grant.profile)) reasons.push('profile_invalid');if (grant.privatePages !== undefined && !PRIVATE_PAGES_GRANTS.includes(grant.privatePages)) reasons.push('private_pages_invalid');+ if (grant.privateFacts !== undefined && !PRIVATE_PAGES_GRANTS.includes(grant.privateFacts)) reasons.push('private_facts_invalid');if (!Number.isSafeInteger(grant.boundMaxConcurrent) || grant.boundMaxConcurrent < 1) reasons.push('concurrency_invalid');if (hasScope(grant.scopes, 'agent')) reasons.push(...delegationReasons(grant, ctx));if (reasons.length) throw new GrantError('invalid_grant', `Invalid client grant: ${[...new Set(reasons)].join(', ')}`, [...new Set(reasons)]);@@ -183,6 +193,7 @@ export interface PrincipalGrant {/** null = the default ['world']; [] = deny-all. */takesHolders: string[] | null;privatePages: PrivatePagesGrant;+ privateFacts: PrivateFactsGrant;revision: number;shape: 'unified' | 'legacy_permissions';/**@@ -281,6 +292,7 @@ export function grantFromTokenRow(row: TokenGrantRow): PrincipalGrant {principal: { kind: 'legacy_token' as const, id: String(row.id) },scopes: normalizeTokenScopes(row.scopes) ?? ['read', 'write', 'admin'],privatePages: privatePagesFromColumn(row.private_pages),+ privateFacts: privatePagesFromColumn(row.private_facts),revision: Number(row.grant_revision ?? 0),};const { malformed, ...legacy } = tokenGrantFromPermissions(row.permissions);@@ -306,7 +318,7 @@ export function grantFromClient(grant: ClientGrant): PrincipalGrant {return {principal: { kind: 'oauth_client', id: grant.clientId }, scopes: [...grant.scopes], sources,allowedOperations: grant.allowedOperations, takesHolders: grant.takesHolders ?? null,- privatePages: privatePagesFromColumn(grant.privatePages), revision: grant.revision,+ privatePages: privatePagesFromColumn(grant.privatePages), privateFacts: privatePagesFromColumn(grant.privateFacts), revision: grant.revision,shape: 'unified', drift: [], permissionsMalformed: false,};}@@ -328,17 +340,25 @@ export function authSourcesFromGrant(g: PrincipalGrant): { sourceId: string; all* floor (`default`), `none` and the `none` axis yield nothing.*/export function privatePagesSources(g: Pick<PrincipalGrant, 'sources' | 'privatePages'>): string[] {- if (g.privatePages !== 'granted_sources') return [];- const s = g.sources;+ return g.privatePages === 'granted_sources' ? namedSources(g.sources) : [];+}++/** GBRA-575: the sources whose private facts this grant's principal may read remotely; the same named sources as privatePagesSources. */+export function privateFactsSources(g: Pick<PrincipalGrant, 'sources' | 'privateFacts'>): string[] {+ return g.privateFacts === 'granted_sources' ? namedSources(g.sources) : [];+}++function namedSources(s: GrantSources): string[] {if (s.kind === 'scalar') return [s.writeSource];if (s.kind === 'federated') return [...new Set([s.writeSource, ...s.readSources])];return [];}-/** The AuthInfo `privatePages` field for this grant; empty when nothing is private-readable. */-export function privatePagesAuth(g: Pick<PrincipalGrant, 'sources' | 'privatePages'>): { privatePages?: { mode: 'granted_sources'; sources: string[] } } {- const sources = privatePagesSources(g);- return sources.length ? { privatePages: { mode: 'granted_sources', sources } } : {};+/** The AuthInfo `privatePages` and (GBRA-575) `privateFacts` fields for this grant; each absent when it opens nothing. Both verifiers spread it. */+export function privatePagesAuth(g: Pick<PrincipalGrant, 'sources' | 'privatePages' | 'privateFacts'>): { privatePages?: { mode: 'granted_sources'; sources: string[] }; privateFacts?: { mode: 'granted_sources'; sources: string[] } } {+ const pages = privatePagesSources(g);+ const facts = privateFactsSources(g);+ return { ...(pages.length ? { privatePages: { mode: 'granted_sources', sources: pages } } : {}), ...(facts.length ? { privateFacts: { mode: 'granted_sources', sources: facts } } : {}) };}/**@@ -396,7 +416,7 @@ export const TOKEN_GRANT_COLUMNS = ['source_grant', 'source_id', 'federated_read* transaction selects these by name: a prepared SELECT * whose plan was cached before a migration added a column* fails there with 0A000 ("cached plan must not change result type") until the connection re-prepares it.*/-export const TOKEN_GRANT_ROW_COLUMNS = ['id', 'scopes', 'permissions', 'private_pages', 'grant_revision', ...TOKEN_GRANT_COLUMNS] as const;+export const TOKEN_GRANT_ROW_COLUMNS = ['id', 'scopes', 'permissions', 'private_pages', 'private_facts', 'grant_revision', ...TOKEN_GRANT_COLUMNS] as const;/*** The select list of `TOKEN_GRANT_ROW_COLUMNS` that this brain's access_tokens has. Admission authorizes before it* replays an accepted request or refuses a schema behind this build, and membership has no schema admission, so adiff --git a/src/core/grants/service.ts b/src/core/grants/service.tsindex ddedc983d1..a4017b44eb 100644--- a/src/core/grants/service.ts+++ b/src/core/grants/service.ts@@ -27,7 +27,7 @@ export interface GrantMutationOptions {servingBrainId?: string;}export interface GrantMutationResult { before: ClientGrant; after: ClientGrant; revision: number; dryRun: boolean }-const PATCH_FIELDS = new Set<keyof GrantPatch>(['scopes', 'sourceId', 'federatedRead', 'sourcesNone', 'takesHolders', 'boundSlugPrefixes', 'allowedOperations', 'boundTools', 'boundSourceId', 'boundBrainId', 'delegatedSlugPrefixes', 'delegatedNamespace', 'boundMaxConcurrent', 'budgetUsdPerDay', 'surface', 'surfaceSetBy', 'tokenTtlSeconds', 'profile', 'repairReasons', 'privatePages']);+const PATCH_FIELDS = new Set<keyof GrantPatch>(['scopes', 'sourceId', 'federatedRead', 'sourcesNone', 'takesHolders', 'boundSlugPrefixes', 'allowedOperations', 'boundTools', 'boundSourceId', 'boundBrainId', 'delegatedSlugPrefixes', 'delegatedNamespace', 'boundMaxConcurrent', 'budgetUsdPerDay', 'surface', 'surfaceSetBy', 'tokenTtlSeconds', 'profile', 'repairReasons', 'privatePages', 'privateFacts']);export function assertGrantPatch(patch: GrantPatch): void {for (const key of Object.keys(patch)) {if (!PATCH_FIELDS.has(key as keyof GrantPatch)) throw new GrantError('invalid_grant', `Unknown grant field: ${key}`);@@ -117,6 +117,7 @@ export async function rescopeClientGrantInTransaction(db: GrantDatabase, clientIif (!rows.length) throw new GrantError('client_not_found', `No OAuth client found with id "${clientId}"`);if (!('grant_revision' in rows[0]) || !('takes_holders' in rows[0])) throw new GrantError('grant_schema_required', 'Run gbrain apply-migrations --yes before changing client grants');if (patch.privatePages !== undefined && !('private_pages' in rows[0])) throw new GrantError('grant_schema_required', 'Run gbrain apply-migrations --yes before changing the private-pages grant');+ if (patch.privateFacts !== undefined && !('private_facts' in rows[0])) throw new GrantError('grant_schema_required', 'Run gbrain apply-migrations --yes before changing the private-facts grant');const before = grantFromRow(rows[0]);if (opts.expectedRevision !== undefined && before.revision !== opts.expectedRevision) {throw new GrantError('grant_conflict', `Grant changed (expected revision ${opts.expectedRevision}, current ${before.revision}); review a fresh preview`);@@ -195,7 +196,8 @@ export async function persistGrant(sql: SqlQuery, before: ClientGrant, after: Clconst { assertScopeSourceGrant, clientGrantReads } = await import('../access/attest-sources.ts');const widened = clientGrantReads(after).filter(s => !clientGrantReads(before).includes(s));await assertScopeSourceGrant(sql, { kind: 'client', id: before.clientId }, widened, {- privatePages: after.privatePages === 'granted_sources' && before.privatePages !== 'granted_sources', writeSource: after.sourcesNone === true ? null : after.sourceId ?? 'default',+ privatePages: after.privatePages === 'granted_sources' && before.privatePages !== 'granted_sources',+ privateFacts: after.privateFacts === 'granted_sources' && before.privateFacts !== 'granted_sources', writeSource: after.sourcesNone === true ? null : after.sourceId ?? 'default',});const result = await sql`WITH updated AS (@@ -242,6 +244,9 @@ export async function persistGrant(sql: SqlQuery, before: ClientGrant, after: Clif ((after.privatePages ?? 'none') !== (before.privatePages ?? 'none')) {await sql`UPDATE oauth_clients SET private_pages = ${after.privatePages} WHERE client_id = ${before.clientId}`;}+ if ((after.privateFacts ?? 'none') !== (before.privateFacts ?? 'none')) {+ await sql`UPDATE oauth_clients SET private_facts = ${after.privateFacts} WHERE client_id = ${before.clientId}`;+ }}export { GrantError, grantFromRow, validateClientGrant, delegationReasons, intersectGrantedScopes } from './model.ts';diff --git a/src/core/oauth-provider.ts b/src/core/oauth-provider.tsindex cec39d10a8..eae7b6c87e 100644--- a/src/core/oauth-provider.ts+++ b/src/core/oauth-provider.ts@@ -926,7 +926,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {...(rowSurfaceSetBy !== undefined ? { surfaceSetBy: rowSurfaceSetBy } : {}),// #5575 (CEO-18): the client's read floor; current_grant is the whole row, so no projection rung needs it....(storedMinTrust(currentGrant.min_trust) ? { minTrust: storedMinTrust(currentGrant.min_trust) } : {}),- // GBRA-156: private pages in the sources the client's grant names (source_id + federated_read), never its bound source.+ // GBRA-156 / GBRA-575: private pages and private facts in the sources the client's grant names (source_id + federated_read), never its bound source....(sourcesNone || rowSourceId === undefined ? {} : privatePagesAuth(grantFromClient(grantFromRow({ ...currentGrant, source_id: rowSourceId, federated_read: allowedSources ?? [] })))),} as CoreAuthInfo as SdkAuthInfo;}diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.tsindex e74f666e0a..a987f547d3 100644--- a/src/core/ops/contract.ts+++ b/src/core/ops/contract.ts@@ -453,6 +453,13 @@ export interface AuthInfo {* private-readable set of each non-mutating call. Undefined = `none`.*/privatePages?: { mode: 'granted_sources'; sources: string[] };+ /**+ * GBRA-575: the grant's `private_facts: granted_sources` axis, set at token+ * verification from the live row, with the same explicitly named sources.+ * MCP dispatch makes them the private-fact sources of each non-mutating call+ * (CallerAccess.privateFactSources). Undefined = `none`.+ */+ privateFacts?: { mode: 'granted_sources'; sources: string[] };/** Current transport ceiling applied to this authenticated request. */effectiveSurface?: 'verbs' | 'starter' | 'full';/**diff --git a/src/core/repair/open-facts.ts b/src/core/repair/open-facts.tsindex c1f0ffcdf8..d2c51c19d0 100644--- a/src/core/repair/open-facts.ts+++ b/src/core/repair/open-facts.ts@@ -37,9 +37,7 @@ import { serializePageToMarkdown } from '../markdown.ts';import { strikeFenceRow } from '../facts/forget.ts';import { opError, OperationError, type OperationContext } from '../ops/contract.ts';import { trustedCliRequired } from '../ops/op-fix.ts';-import { MEMBER_PAGE_PREFIX } from '../access/member-facts.ts';-import { quarantineFilterFragment } from '../quarantine.ts';-import { derivationPrivateSql } from '../search/private-visibility.ts';+import { factOnMemberPageSql, factPageReasons, factProvenanceSlugSql, unpagedFactSql } from '../facts/private-fact-pages.ts';import { isSegmentedPage } from '../page-body/page-shape.ts';import { authorizeWrite } from '../persistence/authority.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';@@ -51,7 +49,7 @@ import { managedPersistenceEnabled } from '../persistence/ownership.ts';import { maintenancePreflight, publishMaintenancePage, submitDatabaseMaintenanceIntent } from '../persistence/prepared-maintenance.ts';import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';import { filesInCheckout, importAtRevision, labelFileRefusal, writeLabelFile } from './label-write.ts';-import { factProvenanceSlugSql, PLAN_STATEMENT_MS } from './visibility.ts';+import { PLAN_STATEMENT_MS } from './visibility.ts';import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairPlanOptions, type RepairScope } from './core.ts';export const OPEN_FACTS_INTENT = 'managed_maintenance_open_fact_visibility';@@ -80,45 +78,28 @@ interface Group { mode: 'open' | 'close'; source_id: string; slug: string; fenceinterface OpenItem extends RepairItem { group: Group; hash: string; ledger: OpenFactsLedger; brain_id: string }interface PlannedRow extends FactRef { cls: string; fence: boolean }-const TRANSCRIPT_LANES = (f: string) => `(${f}.source LIKE 'cli:extract-conversation-facts%' OR ${f}.source IN ('hook:writeback', 'hook:compact', 'sweep:corpus')- OR ${f}.source LIKE 'transcript:%' OR ${f}.source LIKE 'connector:%')`;-/** A fact's class: unpaged:<lane> (no holding page, or a transcript lane), fenced, or unfenced. */-export const openFactClassSql = (f: string) => `(CASE WHEN ${f}.source_markdown_slug IS NULL OR ${TRANSCRIPT_LANES(f)} THEN 'unpaged:' || COALESCE(NULLIF(${f}.source, ''), 'unknown')+export const openFactClassSql = (f: string) => `(CASE WHEN ${unpagedFactSql(f)} THEN 'unpaged:' || COALESCE(NULLIF(${f}.source, ''), 'unknown')WHEN ${f}.row_num IS NOT NULL THEN 'fenced' ELSE 'unfenced' END)`;-/** Any page row with the slug (deleted or not) that is derivation-private. */-const anyPrivatePage = (f: string, slug: string, alias: string) =>- `EXISTS (SELECT 1 FROM pages ${alias} WHERE ${alias}.source_id = ${f}.source_id AND ${alias}.slug = ${slug} AND ${derivationPrivateSql(alias)})`;-const livePage = (f: string, slug: string, alias: string, extra = 'true') =>- `EXISTS (SELECT 1 FROM pages ${alias} WHERE ${alias}.source_id = ${f}.source_id AND ${alias}.slug = ${slug} AND ${alias}.deleted_at IS NULL AND ${extra})`;-/*** Why a private fact `f` stays private, or NULL when it may open: the one exclusion expression the preview, the reason* counts and the locked apply share. A trust contest is any pending proposal on the row (a hold, a forget, a supersession)* or a widening (`before_state.visibility`) the owner rejected or undid: an owner's decision is never overridden.*/export function openFactsReasonSql(f: string): string {- const prov = `(${factProvenanceSlugSql(f)})`;- const member = (expr: string) => `left(${expr}, ${MEMBER_PAGE_PREFIX.length}) = '${MEMBER_PAGE_PREFIX}'`;return `(CASEWHEN ${f}.expired_at IS NOT NULL THEN 'expired'WHEN ${f}.superseded_by IS NOT NULL THEN 'superseded'WHEN ${f}.valid_until IS NOT NULL AND ${f}.valid_until <= now() THEN 'lapsed'- WHEN ${member(`${f}.source_markdown_slug`)} OR ${member(`${f}.entity_slug`)} OR ${member(prov)} THEN 'member_page'+ WHEN ${factOnMemberPageSql(f)} THEN 'member_page'WHEN EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id = ${f}.source_idAND w.fact_hash IN (gbrain_fact_fingerprint(${f}.fact), gbrain_fact_fingerprint_v1(${f}.fact)) AND (w.subject = '*' OR w.subject = ${f}.entity_slug))OR EXISTS (SELECT 1 FROM fact_purges x WHERE x.source_id = ${f}.source_id AND x.fact_hash = gbrain_fact_fingerprint(${f}.fact)AND (x.subject = '*' OR x.subject = ${f}.entity_slug)) THEN 'withdrawn'WHEN EXISTS (SELECT 1 FROM trust_proposals tp WHERE ((tp.target_table = 'facts' AND tp.target_id = ${f}.id) OR (tp.related_table = 'facts' AND tp.related_id = ${f}.id))AND (tp.status = 'pending' OR (tp.action = 'supersede_fact' AND tp.status IN ('rejected', 'undone') AND tp.before_state->'visibility' IS NOT NULL))) THEN 'contested'- WHEN ${f}.source_markdown_slug IS NOT NULL AND ${anyPrivatePage(f, `${f}.source_markdown_slug`, 'oh')} THEN 'holding_page_private'- WHEN ${f}.source_markdown_slug IS NOT NULL AND NOT ${livePage(f, `${f}.source_markdown_slug`, 'oh')} THEN 'holding_page_missing'- WHEN ${f}.source_markdown_slug IS NOT NULL AND ${livePage(f, `${f}.source_markdown_slug`, 'oh', `NOT ${quarantineFilterFragment('oh')}`)} THEN 'holding_page_quarantined'- WHEN ${prov} IS NOT NULL AND ${anyPrivatePage(f, prov, 'op')} THEN 'provenance_private'- WHEN ${prov} IS NOT NULL AND NOT ${livePage(f, prov, 'op')} THEN 'provenance_unresolved'- WHEN ${prov} IS NOT NULL AND ${livePage(f, prov, 'op', `NOT ${quarantineFilterFragment('op')}`)} THEN 'provenance_quarantined'- WHEN ${f}.entity_slug IS NOT NULL AND ${anyPrivatePage(f, `${f}.entity_slug`, 'oe')} THEN 'entity_page_private'+ ${factPageReasons(f).map(([reason, condition]) => `WHEN ${condition} THEN '${reason}'`).join('\n ')}ELSE NULL END)`;}diff --git a/src/core/repair/visibility.ts b/src/core/repair/visibility.tsindex f615a269af..c113a93206 100644--- a/src/core/repair/visibility.ts+++ b/src/core/repair/visibility.ts@@ -43,6 +43,7 @@ import type { BrainEngine } from '../engine.ts';import { serializePageToMarkdown } from '../markdown.ts';import { derivationPrivateSql, effectiveVisibility, folderRestrictedSql, privacyAliasSql, privateSnapshotFilterFragment, strictestVisibility, type Visibility } from '../search/private-visibility.ts';import { strikeFenceRow } from '../facts/forget.ts';+import { factProvenanceSlugSql } from '../facts/private-fact-pages.ts';import { opError, OperationError } from '../ops/contract.ts';import { authorizeWrite } from '../persistence/authority.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';@@ -209,18 +210,6 @@ export async function planVisibilityRepair(engine: BrainEngine, sourceIds: strinresiduals: Object.assign({}, ...parts.map(part => part.residuals)) as Record<string, number> };}-/**- * The page a fact says it came from (not the page holding it): the page-write- * session (`put_page:<slug>`, `sync:<slug>`), else the slug a page-write or- * extract_facts lane records first in `context`.- */-export function factProvenanceSlugSql(f: string): string {- return `regexp_replace(COALESCE(- CASE WHEN ${f}.source_session ~ '^(put_page|sync):' THEN regexp_replace(${f}.source_session, '^(put_page|sync):', '') END,- CASE WHEN ${f}.source IN ('mcp:put_page','sync:import','file_upload','code_import','hook:writeback','mcp:extract_facts')- THEN NULLIF(split_part(btrim(COALESCE(${f}.context,'')), ' ', 1), '') END), '\\.md$', '')`;-}-/*** Active `world` facts held in, or extracted from, a page that is private by* its `visibility`, its declared lineage or a privacy alias. `readable` says adiff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 86d2aebb51..85e81e2a08 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 318;+export const LATEST_SCHEMA_VERSION = 319;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 0af151dad4..874183243a 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -319,6 +319,7 @@ import { v315 } from './v315-facts-context-head-index.ts';import { v316 } from './v316-pages-source-type-index.ts';import { v317 } from './v317-pages-projection-waiting-index.ts';import { v318 } from './v318-guard-ledgers-fail-closed.ts';+import { v319 } from './v319-principal-private-facts.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -636,4 +637,5 @@ export const MIGRATIONS: Migration[] = [v316,v317,v318,+ v319,];diff --git a/src/core/schema-migrations/v319-principal-private-facts.ts b/src/core/schema-migrations/v319-principal-private-facts.tsnew file mode 100644index 0000000000..f3327d4cbf--- /dev/null+++ b/src/core/schema-migrations/v319-principal-private-facts.ts@@ -0,0 +1,26 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// GBRA-575 (Discussion #8194): the per-principal private-facts grant axis+// (grants/model.ts PrivateFactsGrant). `granted_sources` lets a remote token or+// OAuth client read facts stamped `visibility = 'private'` in the sources its+// grant names explicitly, without rewriting any fact; `none` (the default+// every existing row reads) keeps them hidden. A constant default, so no row is+// rewritten. Not mirrored into access_tokens.permissions: older binaries read+// only the mirror and keep world-only facts. No schema.sql mirror, like+// private_pages (v280): both columns exist only through migrations, so fresh+// installs and upgrades end with the same column order.+// Provisional number: confirmed at landing.+export const v319: Migration = {+ version: 319,+ name: 'principal_private_facts',+ idempotent: true,+ sql: `+ALTER TABLE access_tokens ADD COLUMN IF NOT EXISTS private_facts TEXT NOT NULL DEFAULT 'none'+ CHECK (private_facts IN ('none', 'granted_sources'));+ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS private_facts TEXT NOT NULL DEFAULT 'none'+ CHECK (private_facts IN ('none', 'granted_sources'));+`,+};diff --git a/src/core/search/entity-facts.ts b/src/core/search/entity-facts.tsindex 5ebbf4df70..33794705f9 100644--- a/src/core/search/entity-facts.ts+++ b/src/core/search/entity-facts.ts@@ -20,6 +20,7 @@import type { BrainEngine } from '../engine.ts';import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';import { privateFactFilterForCaller } from './private-visibility.ts';+import { grantedPrivateFactSql } from '../access/member-facts.ts';import { factEntitySlugs } from '../mentions/siblings.ts';import { resolveQueryEntities, type ResolvedEntity } from './alias-fanout.ts';import { collapseFactReads } from '../facts/capture-dedup.ts';@@ -47,7 +48,7 @@ export function stripCollapseColumns<T extends CollapseColumns & { collapsed_ids}async function newestFacts(engine: BrainEngine, sourceId: string, slugs: string[], opts: { remote: boolean; minTrust?: TrustTier }, limit: number): Promise<Array<EntityFact & CollapseColumns>> {- const visibility = opts.remote ? `AND f.visibility = 'world' AND ${privateFactFilterForCaller('f')}` : '';+ const visibility = opts.remote ? `AND (f.visibility = 'world' OR ${grantedPrivateFactSql('f')}) AND ${privateFactFilterForCaller('f')}` : '';const rows = await engine.executeRaw<EntityFact & CollapseColumns>(`SELECT f.id, f.fact, f.entity_slug, f.kind, f.valid_from::text AS valid_from, f.source, ${SAVED_FACT_COLLAPSE_COLUMNS}FROM facts fdiff --git a/src/core/search/mode.ts b/src/core/search/mode.tsindex 60654f56f9..533225fd8a 100644--- a/src/core/search/mode.ts+++ b/src/core/search/mode.ts@@ -27,7 +27,7 @@ import { normalizeChainSlots } from './relational-chain.ts';import { createHash } from 'crypto';import { CR_MODES, type CRMode } from '../types.ts';import { getFtsLanguage } from '../fts-language.ts';-import { privateReadableSources, currentCallerAccess } from './private-visibility.ts';+import { privateFactSources, privateReadableSources, currentCallerAccess } from './private-visibility.ts';import { loadConfigSnapshot, type BulkConfigReader } from '../config-snapshot.ts';import { pickDecideConfig } from '../ai/decide/config.ts';import { getRecipe } from '../ai/recipes/index.ts';@@ -1330,9 +1330,9 @@ export function knobsHash(// a part, so every row written without one keeps its key.if (ctx?.queryPrefix) parts.push(`qp=${createHash('sha256').update(ctx.queryPrefix).digest('hex').slice(0, 16)}`);// GBRA-156 (append-only, no bump): a read granted private pages keys on its sorted private-readable- // set (read here so every knobsHash() caller is covered); an empty set adds no part and keeps the key.+ // set (read here so every knobsHash() caller is covered); an empty set adds no part and keeps the key. GBRA-575: xpf= likewise, its private-fact sources.const privateReadable = ctx?.excludePrivate === true ? privateReadableSources() : [];- if (privateReadable.length) parts.push(`xpr=${[...privateReadable].sort().join(',')}`);+ for (const [key, ids] of [['xpr', privateReadable], ['xpf', privateFactSources()]] as const) if (ids.length) parts.push(`${key}=${[...ids].sort().join(',')}`);// GBRA-218 (append-only, no bump): a read under the read policy keys on its member identity (sorted at// record time) and on a privacy relaxation (operator or, GST-2059, owner); an unbound, unrelaxed read adds no part.if (ctx?.excludePrivate === true) {diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.tsindex 3fd1f05529..96f27aea30 100644--- a/src/core/search/private-visibility.ts+++ b/src/core/search/private-visibility.ts@@ -302,6 +302,10 @@ export function privatePagesFilterFragmentFast(pageAlias: string): string {* may see, from its grant's `private_pages: granted_sources` axis (never the* no-grant floor, federation, an OAuth client's bound source or a request's* `source_ids`); empty for writes;+ * - privateFactSources: GBRA-575, the sources whose private facts the read may+ * see, from its grant's `private_facts: granted_sources` axis, on the same+ * terms as privateReadableSources; empty for writes, audiences, attested+ * actors and scope reads (privateFactSources());* - hidePrivate: false only when an operator relaxed privacy for remote reads* (GBRAIN_REMOTE_PRIVATE_PAGES=1 or search.remote_private_pages=visible),* or the caller is the brain owner (owner);@@ -346,6 +350,7 @@ export interface CallerAccess {/** GBRA-218 (A2): prefixes that read as nobody (a narrowing being stamped, an invalid policy file); prefix '' is the whole source. */folderCoverage: readonly FolderCoverage[];privateReadableSources: readonly string[];+ privateFactSources: readonly string[];hidePrivate: boolean;owner: boolean;/**@@ -385,7 +390,7 @@ const callerAccessStore = new AsyncLocalStorage<CallerAccess>();/** The current read's caller-access record (see CallerAccess). */export function currentCallerAccess(): CallerAccess {- return callerAccessStore.getStore() ?? { identity: [], audience: null, audienceIdentities: [], actor: null, satisfiedRuleIds: [], folderCoverage: [], privateReadableSources: [], hidePrivate: !processPrivacyRelaxed(), owner: false, lineage: false, ownerReadsRestricted: false, audienceKindMembers: [], labelledOnly: false, applyRemoteReadPolicy: false, restricted: true, remotePolicy: null };+ return callerAccessStore.getStore() ?? { identity: [], audience: null, audienceIdentities: [], actor: null, satisfiedRuleIds: [], folderCoverage: [], privateReadableSources: [], privateFactSources: [], hidePrivate: !processPrivacyRelaxed(), owner: false, lineage: false, ownerReadsRestricted: false, audienceKindMembers: [], labelledOnly: false, applyRemoteReadPolicy: false, restricted: true, remotePolicy: null };}/** Runs `fn` under `access` merged over the current record; an invalid identity or source id empties that set (fail closed). */@@ -395,6 +400,7 @@ export function withCallerAccess<T>(access: Partial<CallerAccess>, fn: () => T):const sources = access.privateReadableSources ?? base.privateReadableSources;const validIds = identity.length > 0 && validIdentity(identity);const fresh = access.identity !== undefined || access.audienceIdentities !== undefined;+ const factSources = access.privateFactSources ?? (fresh ? [] : base.privateFactSources);const audienceIdentities = (access.audienceIdentities ?? (fresh ? [] : base.audienceIdentities)).map(id => id.length && validIdentity(id) ? Object.freeze([...new Set(id)].sort()) : Object.freeze([] as string[]));const audience = access.audience !== undefined ? access.audience : fresh ? null : base.audience;@@ -409,6 +415,7 @@ export function withCallerAccess<T>(access: Partial<CallerAccess>, fn: () => T):satisfiedRuleIds: satisfied.length && satisfied.every(validQualifiedRuleId) ? Object.freeze([...new Set(satisfied)].sort()) : Object.freeze([]),folderCoverage: Object.freeze([...(access.folderCoverage ?? base.folderCoverage)].map(c => Object.freeze({ source_id: c.source_id, prefix: c.prefix }))),privateReadableSources: sources.length && sources.every(isValidSourceId) ? Object.freeze([...new Set(sources)]) : Object.freeze([]),+ privateFactSources: factSources.length && factSources.every(isValidSourceId) ? Object.freeze([...new Set(factSources)]) : Object.freeze([]),hidePrivate: access.hidePrivate ?? (fresh ? true : base.hidePrivate),owner: access.owner ?? (fresh ? false : base.owner),...lineageReads(access.owner ?? (fresh ? false : base.owner), audienceIdentities.length <= 1,@@ -456,11 +463,24 @@ export function callerIsOwner(): boolean {* GST-2089: whether a fact read stays world-only (visibility = 'world'). Only the trusted local CLI (remote strictly* false) and the brain owner (CallerAccess.owner, the page rule) read private facts; provenance, source grants and* member access still apply to both. Fact arms decide their visibility list here and nowhere else.+ * GBRA-575: a world-only read is not always world-only row by row. Its caller's private-facts grant+ * (privateFactSources) still admits private facts in the sources that grant names: the visibility list stays+ * ['world'] and factVisibilitySql widens it per row, because a whole-read boolean cannot see which source a row is in.*/export function worldOnlyFacts(remote: boolean | undefined): boolean {return remote !== false && !callerIsOwner();}+/**+ * GBRA-575: the sources whose private facts a world-only read (worldOnlyFacts true) still admits: the grant's+ * `private_facts: granted_sources` sources, which dispatch sets only on a credential's own non-mutating read. Empty+ * for an audience, an attested actor and a labelled-only caller, and outside a remote record.+ */+export function privateFactSources(): readonly string[] {+ const access = currentCallerAccess();+ return access.audience || access.actor || access.labelledOnly ? [] : access.privateFactSources;+}+/** The current caller's member identity; empty outside a bound remote read or a local --as, and for an audience of several entries (see callerIdentities). */export function callerIdentity(): readonly string[] {return currentCallerAccess().identity;diff --git a/src/core/search/saved-facts-match.ts b/src/core/search/saved-facts-match.tsindex d6d6033065..3ebabd4c99 100644--- a/src/core/search/saved-facts-match.ts+++ b/src/core/search/saved-facts-match.ts@@ -14,6 +14,7 @@ import { projectionEligibleSql } from '../eligibility/sql.ts';import { factsFtsDocument, getFtsLanguage } from '../fts-language.ts';import { hasCJK } from '../cjk.ts';import { privateFactFilterForCaller, resolveExcludePrivatePages } from './private-visibility.ts';+import { grantedPrivateFactSql } from '../access/member-facts.ts';import { SAVED_FACT_COLLAPSE_COLUMNS, type CollapseColumns } from './entity-facts.ts';/** Words too common to count toward a saved-fact match; also the coverage relevance stopwords in ops/search.ts. */@@ -121,7 +122,7 @@ export async function matchingSavedFacts(ctx: OperationContext, scope: { sourceIconst active = `f.source_id = ANY($1::text[])AND f.expired_at IS NULL AND (f.valid_until IS NULL OR f.valid_until > now())AND f.source != ALL($2::text[])- ${ctx.remote !== false ? `AND f.visibility = 'world'` : ''}`;+ ${ctx.remote !== false ? `AND (f.visibility = 'world' OR ${grantedPrivateFactSql('f')})` : ''}`;const eligible = `${excludePrivate ? `AND ${privateFactFilterForCaller('f', true)}` : ''}AND ${projectionEligibleSql('facts', 'f', { floor: scope.minTrust })}`;const lang = getFtsLanguage();diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 0b0024798a..efc957c357 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -1013,7 +1013,7 @@ export async function dispatchToolCall(// #6721: a read op answers every config read from one snapshot of the table// (config-snapshot.ts); a write reads config live, so it sees its own writes.// GBRA-156: and reads the brain identity and each local writer's credential once for its pre-submission checks.- // GBRA-156: a remote read sees private pages only in the sources its grant names under private_pages: granted_sources.+ // GBRA-156: a remote read sees private pages only in the sources its grant names under private_pages: granted_sources; GBRA-575: private facts under private_facts, only on a credential's own read (no audience, actor, scope read or enforced member).// Writes, local callers and every path outside this call keep the empty set, so they hide or see exactly what they did.// context_pack and delta stay world-only for every caller unless a trusted local one passes include_private, so no grant widens them.// GBRA-498: a room declaration only marks the answer; its argument is taken out here, before any validation,@@ -1024,12 +1024,12 @@ export async function dispatchToolCall(const op = operations.find(o => o.name === name);const readOnly = op?.mutating === false;const args = op && params ? normalizeOptionalParams(op, params) : params;- const privateSources = readOnly && opts.remote !== false && !WORLD_ONLY_PACK_OPS.has(name) ? opts.auth?.privatePages?.sources : undefined;+ const [privateSources, privateFactSources] = readOnly && opts.remote !== false && !WORLD_ONLY_PACK_OPS.has(name) ? [opts.auth?.privatePages?.sources, opts.auth?.privateFacts?.sources] : [];const resolved = opts.metaHook && (opts.hotMemoryOff === true || hotMemoryOffIn(params)) ? { ...opts, metaHook: undefined } : opts;// GBRA-218: a remote call also carries its credential's member identity, which every caller-aware read checks page readers against.// GBRA-231: or the audience a shared agent's harness asserts, resolved (and refused) on every call before any work.const run = async () => {- if (opts.remote === false) return qmMemoryToolResult(name, await withCallerAccess({ privateReadableSources: [] }, () => withRequestIdentityMemo(() => dispatchResolvedCall(engine, name, params, resolved))));+ if (opts.remote === false) return qmMemoryToolResult(name, await withCallerAccess({ privateReadableSources: [], privateFactSources: [] }, () => withRequestIdentityMemo(() => dispatchResolvedCall(engine, name, params, resolved))));// GST-359 C1: or the person a trusted system attests (x-qm-actor), decided here too, before any work (access/actor.ts).let audience: AudiencePrincipal[] | null = null;let attested: Awaited<ReturnType<typeof resolveAttestedActor>> = null;@@ -1090,7 +1090,7 @@ export async function dispatchToolCall(}if (audience || attested?.actor) assertion('accepted');const callParams = attested ? attested.params : args;- return withCallerAccess(access, async () => {+ return withCallerAccess({ ...access, privateFactSources: privateFactSources && !audience && !attested?.actor && readMode === null && !opts.enforcedMember ? privateFactSources : [] }, async () => {const out = await withRequestIdentityMemo(() => withReadMode(readMode, () => dispatchResolvedCall(engine, name, callParams, scoped)));// _meta.access (MCP_META_CHANNELS.md): the view this call was answered under, for the harness; own producer, isolated.try { out._meta = { ...(out._meta ?? {}), access: await appliedAccessSummary(engine, scoped.auth, [scoped.sourceId, ...(scoped.localFederatedSourceIds ?? [])]) }; } catch { /* the key is absent */ }diff --git a/test/auth-private-pages-output.test.ts b/test/auth-private-pages-output.test.tsindex 89df687a8c..3925a86437 100644--- a/test/auth-private-pages-output.test.ts+++ b/test/auth-private-pages-output.test.ts@@ -70,10 +70,10 @@ describe('private-pages grant output (#8104)', () => {expect(privatePagesFromColumn(null)).toBe('none');});- test('auth list --json prints exactly id, name, scopes, created_at, last_used_at, status and private_pages: never token_hash', async () => {+ test('auth list --json prints exactly id, name, scopes, created_at, last_used_at, status, private_pages and private_facts: never token_hash', async () => {const tokens = JSON.parse(await auth(['list', '--json'])) as Array<Record<string, unknown>>;for (const t of tokens) {- expect(Object.keys(t).sort()).toEqual(['created_at', 'id', 'last_used_at', 'name', 'private_pages', 'scopes', 'status']);+ expect(Object.keys(t).sort()).toEqual(['created_at', 'id', 'last_used_at', 'name', 'private_facts', 'private_pages', 'scopes', 'status']);}expect(JSON.stringify(tokens)).not.toContain('token_hash');const byName = Object.fromEntries(tokens.map(t => [t.name as string, [t.status, t.private_pages]]));@@ -107,6 +107,11 @@ describe('private-pages grant output (#8104)', () => {test('a brain without the private_pages column lists its clients with private pages none (the top rung of the fallback ladder)', async () => {// Last test of the file: the column is dropped from this throwaway brain.const rows = await withBrain(async engine => {+ // Value: protects=a brain without oauth_clients.private_facts still lists clients with private_pages (second rung); fails_when=private_facts leaves the degrade list or the rung is removed; why_new=only the private_pages rung was driven; seam=none; no_claim=Postgres error codes (PGLite only)+ await engine.executeRaw('ALTER TABLE oauth_clients DROP COLUMN private_facts');+ const facts = (await listClientRows(engine)).find(r => r.client_id === 'client-granted')!;+ expect(facts.private_pages).toBe('granted_sources');+ expect((facts as { private_facts?: unknown }).private_facts).toBeUndefined();await engine.executeRaw('ALTER TABLE oauth_clients DROP COLUMN private_pages');return listClientRows(engine);});diff --git a/test/e2e/private-facts-grant-postgres.test.ts b/test/e2e/private-facts-grant-postgres.test.tsnew file mode 100644index 0000000000..5419b059e1--- /dev/null+++ b/test/e2e/private-facts-grant-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../private-facts-grant-8194.test.ts'));diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex 21fe995d38..8b1d9e0f1c 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -36,6 +36,7 @@"access_rules.access_rules_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES access_policy_state(source_id) ON DELETE CASCADE","access_tokens.access_tokens_min_trust_check": "c CHECK (((min_trust IS NULL) OR (min_trust = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))","access_tokens.access_tokens_pkey": "p PRIMARY KEY (id)",+ "access_tokens.access_tokens_private_facts_check": "c CHECK ((private_facts = ANY (ARRAY['none'::text, 'granted_sources'::text])))","access_tokens.access_tokens_private_pages_check": "c CHECK ((private_pages = ANY (ARRAY['none'::text, 'granted_sources'::text])))","access_tokens.access_tokens_source_grant_check": "c CHECK ((source_grant = ANY (ARRAY['default'::text, 'scalar'::text, 'federated'::text, 'none'::text])))","access_tokens.access_tokens_token_hash_key": "u UNIQUE (token_hash)",@@ -260,6 +261,7 @@"oauth_clients.oauth_clients_complete_agent_grant": "c CHECK (((NOT (COALESCE(scope, ''::text) ~ '(^|[[:space:]])agent([[:space:]]|$)'::text)) OR ((COALESCE(cardinality(bound_tools), 0) > 0) AND (source_id IS NOT NULL) AND (bound_source_id IS NOT NULL) AND (bound_source_id = source_id) AND COALESCE((source_id = ANY (federated_read)), false) AND (((delegated_namespace = 'job'::text) AND (delegated_slug_prefixes IS NULL)) OR ((delegated_namespace = 'prefixes'::text) AND (COALESCE(cardinality(delegated_slug_prefixes), 0) > 0))) AND (bound_max_concurrent > 0))))","oauth_clients.oauth_clients_min_trust_check": "c CHECK (((min_trust IS NULL) OR (min_trust = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))","oauth_clients.oauth_clients_pkey": "p PRIMARY KEY (client_id)",+ "oauth_clients.oauth_clients_private_facts_check": "c CHECK ((private_facts = ANY (ARRAY['none'::text, 'granted_sources'::text])))","oauth_clients.oauth_clients_private_pages_check": "c CHECK ((private_pages = ANY (ARRAY['none'::text, 'granted_sources'::text])))","oauth_clients.oauth_clients_registered_via_check": "c CHECK ((registered_via = 'dcr'::text))","oauth_clients.oauth_clients_source_grant_check": "c CHECK ((source_grant = 'none'::text))",@@ -1978,7 +1980,8 @@"20 attest_ops ARRAY/_text NULL","21 attest_sources ARRAY/_text NULL","22 attest_read text/text NULL",- "23 reads_unscoped timestamp with time zone/timestamptz NULL"+ "23 reads_unscoped timestamp with time zone/timestamptz NULL",+ "24 private_facts text/text NOT NULL DEFAULT 'none'::text"],"flags": "relkind=r rls=false force_rls=false"},@@ -3302,7 +3305,8 @@"37 attest_ops ARRAY/_text NULL","38 attest_sources ARRAY/_text NULL","39 attest_read text/text NULL",- "40 reads_unscoped timestamp with time zone/timestamptz NULL"+ "40 reads_unscoped timestamp with time zone/timestamptz NULL",+ "41 private_facts text/text NOT NULL DEFAULT 'none'::text"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex 09fcc914cf..811d977f73 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -36,6 +36,7 @@"access_rules.access_rules_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES access_policy_state(source_id) ON DELETE CASCADE","access_tokens.access_tokens_min_trust_check": "c CHECK (((min_trust IS NULL) OR (min_trust = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))","access_tokens.access_tokens_pkey": "p PRIMARY KEY (id)",+ "access_tokens.access_tokens_private_facts_check": "c CHECK ((private_facts = ANY (ARRAY['none'::text, 'granted_sources'::text])))","access_tokens.access_tokens_private_pages_check": "c CHECK ((private_pages = ANY (ARRAY['none'::text, 'granted_sources'::text])))","access_tokens.access_tokens_source_grant_check": "c CHECK ((source_grant = ANY (ARRAY['default'::text, 'scalar'::text, 'federated'::text, 'none'::text])))","access_tokens.access_tokens_token_hash_key": "u UNIQUE (token_hash)",@@ -260,6 +261,7 @@"oauth_clients.oauth_clients_complete_agent_grant": "c CHECK (((NOT (COALESCE(scope, ''::text) ~ '(^|[[:space:]])agent([[:space:]]|$)'::text)) OR ((COALESCE(cardinality(bound_tools), 0) > 0) AND (source_id IS NOT NULL) AND (bound_source_id IS NOT NULL) AND (bound_source_id = source_id) AND COALESCE((source_id = ANY (federated_read)), false) AND (((delegated_namespace = 'job'::text) AND (delegated_slug_prefixes IS NULL)) OR ((delegated_namespace = 'prefixes'::text) AND (COALESCE(cardinality(delegated_slug_prefixes), 0) > 0))) AND (bound_max_concurrent > 0))))","oauth_clients.oauth_clients_min_trust_check": "c CHECK (((min_trust IS NULL) OR (min_trust = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))","oauth_clients.oauth_clients_pkey": "p PRIMARY KEY (client_id)",+ "oauth_clients.oauth_clients_private_facts_check": "c CHECK ((private_facts = ANY (ARRAY['none'::text, 'granted_sources'::text])))","oauth_clients.oauth_clients_private_pages_check": "c CHECK ((private_pages = ANY (ARRAY['none'::text, 'granted_sources'::text])))","oauth_clients.oauth_clients_registered_via_check": "c CHECK ((registered_via = 'dcr'::text))","oauth_clients.oauth_clients_source_grant_check": "c CHECK ((source_grant = 'none'::text))",@@ -1978,7 +1980,8 @@"20 attest_ops ARRAY/_text NULL","21 attest_sources ARRAY/_text NULL","22 attest_read text/text NULL",- "23 reads_unscoped timestamp with time zone/timestamptz NULL"+ "23 reads_unscoped timestamp with time zone/timestamptz NULL",+ "24 private_facts text/text NOT NULL DEFAULT 'none'::text"],"flags": "relkind=r rls=false force_rls=false"},@@ -3302,7 +3305,8 @@"37 attest_ops ARRAY/_text NULL","38 attest_sources ARRAY/_text NULL","39 attest_read text/text NULL",- "40 reads_unscoped timestamp with time zone/timestamptz NULL"+ "40 reads_unscoped timestamp with time zone/timestamptz NULL",+ "41 private_facts text/text NOT NULL DEFAULT 'none'::text"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex 8ee24805f6..24fb4537f0 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -36,6 +36,7 @@"access_rules.access_rules_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES access_policy_state(source_id) ON DELETE CASCADE","access_tokens.access_tokens_min_trust_check": "c CHECK (((min_trust IS NULL) OR (min_trust = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))","access_tokens.access_tokens_pkey": "p PRIMARY KEY (id)",+ "access_tokens.access_tokens_private_facts_check": "c CHECK ((private_facts = ANY (ARRAY['none'::text, 'granted_sources'::text])))","access_tokens.access_tokens_private_pages_check": "c CHECK ((private_pages = ANY (ARRAY['none'::text, 'granted_sources'::text])))","access_tokens.access_tokens_source_grant_check": "c CHECK ((source_grant = ANY (ARRAY['default'::text, 'scalar'::text, 'federated'::text, 'none'::text])))","access_tokens.access_tokens_token_hash_key": "u UNIQUE (token_hash)",@@ -260,6 +261,7 @@"oauth_clients.oauth_clients_complete_agent_grant": "c CHECK (((NOT (COALESCE(scope, ''::text) ~ '(^|[[:space:]])agent([[:space:]]|$)'::text)) OR ((COALESCE(cardinality(bound_tools), 0) > 0) AND (source_id IS NOT NULL) AND (bound_source_id IS NOT NULL) AND (bound_source_id = source_id) AND COALESCE((source_id = ANY (federated_read)), false) AND (((delegated_namespace = 'job'::text) AND (delegated_slug_prefixes IS NULL)) OR ((delegated_namespace = 'prefixes'::text) AND (COALESCE(cardinality(delegated_slug_prefixes), 0) > 0))) AND (bound_max_concurrent > 0))))","oauth_clients.oauth_clients_min_trust_check": "c CHECK (((min_trust IS NULL) OR (min_trust = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))","oauth_clients.oauth_clients_pkey": "p PRIMARY KEY (client_id)",+ "oauth_clients.oauth_clients_private_facts_check": "c CHECK ((private_facts = ANY (ARRAY['none'::text, 'granted_sources'::text])))","oauth_clients.oauth_clients_private_pages_check": "c CHECK ((private_pages = ANY (ARRAY['none'::text, 'granted_sources'::text])))","oauth_clients.oauth_clients_registered_via_check": "c CHECK ((registered_via = 'dcr'::text))","oauth_clients.oauth_clients_source_grant_check": "c CHECK ((source_grant = 'none'::text))",@@ -1974,7 +1976,8 @@"20 attest_ops ARRAY/_text NULL","21 attest_sources ARRAY/_text NULL","22 attest_read text/text NULL",- "23 reads_unscoped timestamp with time zone/timestamptz NULL"+ "23 reads_unscoped timestamp with time zone/timestamptz NULL",+ "24 private_facts text/text NOT NULL DEFAULT 'none'::text"],"flags": "relkind=r rls=false force_rls=false"},@@ -3298,7 +3301,8 @@"37 attest_ops ARRAY/_text NULL","38 attest_sources ARRAY/_text NULL","39 attest_read text/text NULL",- "40 reads_unscoped timestamp with time zone/timestamptz NULL"+ "40 reads_unscoped timestamp with time zone/timestamptz NULL",+ "41 private_facts text/text NOT NULL DEFAULT 'none'::text"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex 08336e78ad..285d700078 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -36,6 +36,7 @@"access_rules.access_rules_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES access_policy_state(source_id) ON DELETE CASCADE","access_tokens.access_tokens_min_trust_check": "c CHECK (((min_trust IS NULL) OR (min_trust = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))","access_tokens.access_tokens_pkey": "p PRIMARY KEY (id)",+ "access_tokens.access_tokens_private_facts_check": "c CHECK ((private_facts = ANY (ARRAY['none'::text, 'granted_sources'::text])))","access_tokens.access_tokens_private_pages_check": "c CHECK ((private_pages = ANY (ARRAY['none'::text, 'granted_sources'::text])))","access_tokens.access_tokens_source_grant_check": "c CHECK ((source_grant = ANY (ARRAY['default'::text, 'scalar'::text, 'federated'::text, 'none'::text])))","access_tokens.access_tokens_token_hash_key": "u UNIQUE (token_hash)",@@ -264,6 +265,7 @@"oauth_clients.oauth_clients_complete_agent_grant": "c CHECK (((NOT (COALESCE(scope, ''::text) ~ '(^|[[:space:]])agent([[:space:]]|$)'::text)) OR ((COALESCE(cardinality(bound_tools), 0) > 0) AND (source_id IS NOT NULL) AND (bound_source_id IS NOT NULL) AND (bound_source_id = source_id) AND COALESCE((source_id = ANY (federated_read)), false) AND (((delegated_namespace = 'job'::text) AND (delegated_slug_prefixes IS NULL)) OR ((delegated_namespace = 'prefixes'::text) AND (COALESCE(cardinality(delegated_slug_prefixes), 0) > 0))) AND (bound_max_concurrent > 0))))","oauth_clients.oauth_clients_min_trust_check": "c CHECK (((min_trust IS NULL) OR (min_trust = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))","oauth_clients.oauth_clients_pkey": "p PRIMARY KEY (client_id)",+ "oauth_clients.oauth_clients_private_facts_check": "c CHECK ((private_facts = ANY (ARRAY['none'::text, 'granted_sources'::text])))","oauth_clients.oauth_clients_private_pages_check": "c CHECK ((private_pages = ANY (ARRAY['none'::text, 'granted_sources'::text])))","oauth_clients.oauth_clients_registered_via_check": "c CHECK ((registered_via = 'dcr'::text))","oauth_clients.oauth_clients_source_grant_check": "c CHECK ((source_grant = 'none'::text))",@@ -1979,7 +1981,8 @@"20 attest_ops ARRAY/_text NULL","21 attest_sources ARRAY/_text NULL","22 attest_read text/text NULL",- "23 reads_unscoped timestamp with time zone/timestamptz NULL"+ "23 reads_unscoped timestamp with time zone/timestamptz NULL",+ "24 private_facts text/text NOT NULL DEFAULT 'none'::text"],"flags": "relkind=r rls=true force_rls=false"},@@ -3314,7 +3317,8 @@"37 attest_ops ARRAY/_text NULL","38 attest_sources ARRAY/_text NULL","39 attest_read text/text NULL",- "40 reads_unscoped timestamp with time zone/timestamptz NULL"+ "40 reads_unscoped timestamp with time zone/timestamptz NULL",+ "41 private_facts text/text NOT NULL DEFAULT 'none'::text"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex 0c0f0b2f9b..ef6ad27408 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -36,6 +36,7 @@"access_rules.access_rules_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES access_policy_state(source_id) ON DELETE CASCADE","access_tokens.access_tokens_min_trust_check": "c CHECK (((min_trust IS NULL) OR (min_trust = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))","access_tokens.access_tokens_pkey": "p PRIMARY KEY (id)",+ "access_tokens.access_tokens_private_facts_check": "c CHECK ((private_facts = ANY (ARRAY['none'::text, 'granted_sources'::text])))","access_tokens.access_tokens_private_pages_check": "c CHECK ((private_pages = ANY (ARRAY['none'::text, 'granted_sources'::text])))","access_tokens.access_tokens_source_grant_check": "c CHECK ((source_grant = ANY (ARRAY['default'::text, 'scalar'::text, 'federated'::text, 'none'::text])))","access_tokens.access_tokens_token_hash_key": "u UNIQUE (token_hash)",@@ -264,6 +265,7 @@"oauth_clients.oauth_clients_complete_agent_grant": "c CHECK (((NOT (COALESCE(scope, ''::text) ~ '(^|[[:space:]])agent([[:space:]]|$)'::text)) OR ((COALESCE(cardinality(bound_tools), 0) > 0) AND (source_id IS NOT NULL) AND (bound_source_id IS NOT NULL) AND (bound_source_id = source_id) AND COALESCE((source_id = ANY (federated_read)), false) AND (((delegated_namespace = 'job'::text) AND (delegated_slug_prefixes IS NULL)) OR ((delegated_namespace = 'prefixes'::text) AND (COALESCE(cardinality(delegated_slug_prefixes), 0) > 0))) AND (bound_max_concurrent > 0))))","oauth_clients.oauth_clients_min_trust_check": "c CHECK (((min_trust IS NULL) OR (min_trust = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))","oauth_clients.oauth_clients_pkey": "p PRIMARY KEY (client_id)",+ "oauth_clients.oauth_clients_private_facts_check": "c CHECK ((private_facts = ANY (ARRAY['none'::text, 'granted_sources'::text])))","oauth_clients.oauth_clients_private_pages_check": "c CHECK ((private_pages = ANY (ARRAY['none'::text, 'granted_sources'::text])))","oauth_clients.oauth_clients_registered_via_check": "c CHECK ((registered_via = 'dcr'::text))","oauth_clients.oauth_clients_source_grant_check": "c CHECK ((source_grant = 'none'::text))",@@ -1979,7 +1981,8 @@"20 attest_ops ARRAY/_text NULL","21 attest_sources ARRAY/_text NULL","22 attest_read text/text NULL",- "23 reads_unscoped timestamp with time zone/timestamptz NULL"+ "23 reads_unscoped timestamp with time zone/timestamptz NULL",+ "24 private_facts text/text NOT NULL DEFAULT 'none'::text"],"flags": "relkind=r rls=true force_rls=false"},@@ -3314,7 +3317,8 @@"37 attest_ops ARRAY/_text NULL","38 attest_sources ARRAY/_text NULL","39 attest_read text/text NULL",- "40 reads_unscoped timestamp with time zone/timestamptz NULL"+ "40 reads_unscoped timestamp with time zone/timestamptz NULL",+ "41 private_facts text/text NOT NULL DEFAULT 'none'::text"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex 4b1cec5459..291792fe16 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -36,6 +36,7 @@"access_rules.access_rules_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES access_policy_state(source_id) ON DELETE CASCADE","access_tokens.access_tokens_min_trust_check": "c CHECK (((min_trust IS NULL) OR (min_trust = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))","access_tokens.access_tokens_pkey": "p PRIMARY KEY (id)",+ "access_tokens.access_tokens_private_facts_check": "c CHECK ((private_facts = ANY (ARRAY['none'::text, 'granted_sources'::text])))","access_tokens.access_tokens_private_pages_check": "c CHECK ((private_pages = ANY (ARRAY['none'::text, 'granted_sources'::text])))","access_tokens.access_tokens_source_grant_check": "c CHECK ((source_grant = ANY (ARRAY['default'::text, 'scalar'::text, 'federated'::text, 'none'::text])))","access_tokens.access_tokens_token_hash_key": "u UNIQUE (token_hash)",@@ -264,6 +265,7 @@"oauth_clients.oauth_clients_complete_agent_grant": "c CHECK (((NOT (COALESCE(scope, ''::text) ~ '(^|[[:space:]])agent([[:space:]]|$)'::text)) OR ((COALESCE(cardinality(bound_tools), 0) > 0) AND (source_id IS NOT NULL) AND (bound_source_id IS NOT NULL) AND (bound_source_id = source_id) AND COALESCE((source_id = ANY (federated_read)), false) AND (((delegated_namespace = 'job'::text) AND (delegated_slug_prefixes IS NULL)) OR ((delegated_namespace = 'prefixes'::text) AND (COALESCE(cardinality(delegated_slug_prefixes), 0) > 0))) AND (bound_max_concurrent > 0))))","oauth_clients.oauth_clients_min_trust_check": "c CHECK (((min_trust IS NULL) OR (min_trust = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))","oauth_clients.oauth_clients_pkey": "p PRIMARY KEY (client_id)",+ "oauth_clients.oauth_clients_private_facts_check": "c CHECK ((private_facts = ANY (ARRAY['none'::text, 'granted_sources'::text])))","oauth_clients.oauth_clients_private_pages_check": "c CHECK ((private_pages = ANY (ARRAY['none'::text, 'granted_sources'::text])))","oauth_clients.oauth_clients_registered_via_check": "c CHECK ((registered_via = 'dcr'::text))","oauth_clients.oauth_clients_source_grant_check": "c CHECK ((source_grant = 'none'::text))",@@ -1975,7 +1977,8 @@"20 attest_ops ARRAY/_text NULL","21 attest_sources ARRAY/_text NULL","22 attest_read text/text NULL",- "23 reads_unscoped timestamp with time zone/timestamptz NULL"+ "23 reads_unscoped timestamp with time zone/timestamptz NULL",+ "24 private_facts text/text NOT NULL DEFAULT 'none'::text"],"flags": "relkind=r rls=true force_rls=false"},@@ -3310,7 +3313,8 @@"37 attest_ops ARRAY/_text NULL","38 attest_sources ARRAY/_text NULL","39 attest_read text/text NULL",- "40 reads_unscoped timestamp with time zone/timestamptz NULL"+ "40 reads_unscoped timestamp with time zone/timestamptz NULL",+ "41 private_facts text/text NOT NULL DEFAULT 'none'::text"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex bab1af28cb..8a683ac724 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -6750,6 +6750,7 @@"member?: { id: string; groups: string[]; } | null | undefined","minTrust?: \"user_confirmed\" | \"operator_curated\" | \"tool_observed\" | \"agent_written\" | \"unknown\" | \"external_untrusted\" | undefined","principal?: { kind: \"oauth_client\" | \"legacy_token\"; id: string; } | undefined",+ "privateFacts?: { mode: \"granted_sources\"; sources: string[]; } | undefined","privatePages?: { mode: \"granted_sources\"; sources: string[]; } | undefined","readsUnscoped?: boolean | undefined","scopes: string[]",diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 43e92f733f..69c405f937 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 313,+ "count": 314,"gaps": [17,18,@@ -72,7 +72,7 @@"ensureFactsFtsIndex": "95e723314ac30cea2db48e0e167c554ef1fa06df80cae765faa2a080a3a655c2","failClosedLedgerGuards": "dadd3ceb13286ca7ab969a911a310c87be313de6ec2c2c8e14d3f95b72901481","getFtsLanguage": "0d790b4c4af1f67a2a1bbd59470beb13f434917b381931baf8404a41c5d903db",- "grantFromRow": "e31bd308b413c11f2879ac4393fbc0362a1a974f937196f11029481e4dc64f69",+ "grantFromRow": "d0b537d687ed3f88f61e33b88490c6dcc74b829485b0c2c44d3238d100c4c3a7","hardenFunctionSearchPaths": "ca7bce96a087bfb4644268e5c2ad0ace76532905ceffb4efdc69608e0ef11894","hnswMaxDimsForType": "a187cdcc520f813b7c39da97ce53da58509232ed9f851627ef41abfe1b68bd26","identityIndexHasSource": "ab7e4cad64ebf233f3a884816c114b0c582f4f2166c3bcf19ed8d92bcfcf3807",@@ -105,7 +105,7 @@"widenIdentityIndex": "86a6176bd7637d964dbc1d3cd3b1bdfa3ca0161e1ee248c37d7380a1471282e6","withSchemaLockTimeout": "95605bd3004955e11e936c7a4aa6889319b401098abf9db18ef3e48da2c3fc59"},- "latest": 318,+ "latest": 319,"records": [{"handler": {@@ -5203,6 +5203,19 @@"transaction": "absent","verify": "absent","version": 318+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "principal_private_facts",+ "sql": {+ "length": 301,+ "sha256": "af474ba82428e4e78e45de2dc84b8d016b954d920ab0e4285d47a2261db08669"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 319}],"versions": [@@ -5518,7 +5531,8 @@315,316,317,- 318+ 318,+ 319]},"normalizer": "migrations-record-v1"diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.jsonindex 02547b3de2..cd3220f8c8 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json@@ -36,6 +36,7 @@"access_rules.access_rules_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES access_policy_state(source_id) ON DELETE CASCADE","access_tokens.access_tokens_min_trust_check": "c CHECK (((min_trust IS NULL) OR (min_trust = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))","access_tokens.access_tokens_pkey": "p PRIMARY KEY (id)",+ "access_tokens.access_tokens_private_facts_check": "c CHECK ((private_facts = ANY (ARRAY['none'::text, 'granted_sources'::text])))","access_tokens.access_tokens_private_pages_check": "c CHECK ((private_pages = ANY (ARRAY['none'::text, 'granted_sources'::text])))","access_tokens.access_tokens_source_grant_check": "c CHECK ((source_grant = ANY (ARRAY['default'::text, 'scalar'::text, 'federated'::text, 'none'::text])))","access_tokens.access_tokens_token_hash_key": "u UNIQUE (token_hash)",@@ -260,6 +261,7 @@"oauth_clients.oauth_clients_complete_agent_grant": "c CHECK (((NOT (COALESCE(scope, ''::text) ~ '(^|[[:space:]])agent([[:space:]]|$)'::text)) OR ((COALESCE(cardinality(bound_tools), 0) > 0) AND (source_id IS NOT NULL) AND (bound_source_id IS NOT NULL) AND (bound_source_id = source_id) AND COALESCE((source_id = ANY (federated_read)), false) AND (((delegated_namespace = 'job'::text) AND (delegated_slug_prefixes IS NULL)) OR ((delegated_namespace = 'prefixes'::text) AND (COALESCE(cardinality(delegated_slug_prefixes), 0) > 0))) AND (bound_max_concurrent > 0))))","oauth_clients.oauth_clients_min_trust_check": "c CHECK (((min_trust IS NULL) OR (min_trust = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))","oauth_clients.oauth_clients_pkey": "p PRIMARY KEY (client_id)",+ "oauth_clients.oauth_clients_private_facts_check": "c CHECK ((private_facts = ANY (ARRAY['none'::text, 'granted_sources'::text])))","oauth_clients.oauth_clients_private_pages_check": "c CHECK ((private_pages = ANY (ARRAY['none'::text, 'granted_sources'::text])))","oauth_clients.oauth_clients_registered_via_check": "c CHECK ((registered_via = 'dcr'::text))","oauth_clients.oauth_clients_source_grant_check": "c CHECK ((source_grant = 'none'::text))",@@ -1978,7 +1980,8 @@"20 attest_ops ARRAY/_text NULL","21 attest_sources ARRAY/_text NULL","22 attest_read text/text NULL",- "23 reads_unscoped timestamp with time zone/timestamptz NULL"+ "23 reads_unscoped timestamp with time zone/timestamptz NULL",+ "24 private_facts text/text NOT NULL DEFAULT 'none'::text"],"flags": "relkind=r rls=false force_rls=false"},@@ -3302,7 +3305,8 @@"37 attest_ops ARRAY/_text NULL","38 attest_sources ARRAY/_text NULL","39 attest_read text/text NULL",- "40 reads_unscoped timestamp with time zone/timestamptz NULL"+ "40 reads_unscoped timestamp with time zone/timestamptz NULL",+ "41 private_facts text/text NOT NULL DEFAULT 'none'::text"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/private-facts-grant-8194.test.ts b/test/private-facts-grant-8194.test.tsnew file mode 100644index 0000000000..ee9fb0e855--- /dev/null+++ b/test/private-facts-grant-8194.test.ts@@ -0,0 +1,414 @@+/**+ * Discussion #8194 (GBRA-575 part 2): the per-credential private-facts grant (`private_facts: granted_sources`).+ *+ * 1. Protects: a remote token or OAuth client whose grant carries `private_facts: granted_sources` (set only by the+ * local `gbrain auth rescope --private-facts`) reads facts stamped `visibility = 'private'` in the sources its grant+ * names explicitly, without any stored fact changing; every other remote caller keeps world-only facts. Facts held+ * on, provenanced from or about a private, reader-restricted or member page stay hidden with the grant on.+ * `--private-facts none` turns it off on the next request; an upgraded brain starts every credential at none; no MCP+ * operation or admin HTTP grant edit can set it.+ * 2. Fails when: a private fact reaches a credential at none, a credential with no source grant, a source the grant+ * does not list (federated, even after the grant is written, or named by the request), another credential, or comes+ * from a private, readable_by, member or derivation-private page, or has no page to check (no holding page, or a+ * transcript lane); or the granted credential does not see a private fact on a world page in its granted source; or+ * the axis or its plain warning is missing from `auth list`, `auth clients`, the help or the rescope output.+ * 3. Existing coverage (repair-open-facts-8194, private-pages-grant) pins world-only facts for every non-owner caller.+ * 4. Real seams: tokens and clients minted and rescoped through the grant service and CLI parsers, verified by the serve+ * --http verifier, dispatched through MCP dispatch with remote=true; PGLite, and Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { createEngine } from '../src/core/engine-factory.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { mintLegacyToken } from '../src/core/token-mint.ts';+import { parseRescopeTokenArgs, rescopeLegacyToken } from '../src/core/grants/legacy-token.ts';+import { parseClientRescopeArgs } from '../src/core/grants/cli.ts';+import { readClientGrant, rescopeClientGrant } from '../src/core/grants/service.ts';+import { noGrantFederatedScope } from '../src/core/source-resolver.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { getBrainHotMemoryMeta, __resetHotMemoryCacheForTests } from '../src/core/facts/meta-hook.ts';+import { operations } from '../src/core/operations.ts';+import { parseAdminGrantRequest } from '../src/commands/serve-http-grants.ts';+import { runAuth } from '../src/commands/auth.ts';+import { runSources } from '../src/commands/sources.ts';+import { LATEST_VERSION, runMigrations } from '../src/core/migrate.ts';+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import type { AuthInfo } from '../src/core/ops/contract.ts';+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';+import { withEnv } from './helpers/with-env.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';++const GRANTED = 'pf-alpha';+const TEAM = 'pf-team';+const OTHER = 'pf-bravo';+const FED = 'pf-fed';+/** A source created and federated after every grant is written: the floor credential reaches it, no grant lists it. */+const LATE = 'pf-late';+const ENTITY = 'companies/acme-example';++/** The one private fact the switch opens: on a world page in the granted source. */+const OPENS = 'orchardline canary alpha private';+const WORLD = 'orchardline canary alpha world';+const WORLD_FED = 'orchardline canary fed world';+const WORLD_LATE = 'orchardline canary late world';+/** Private facts the switch never opens, by why. */+const CLOSED: Record<string, string> = {+ other_source: 'orchardline canary bravo private',+ federated_source: 'orchardline canary fed private',+ default_source: 'orchardline canary default private',+ private_page: 'orchardline canary held private page',+ readers_page: 'orchardline canary readers page',+ member_page: 'orchardline canary member page',+ derived_page: 'orchardline canary derived private',+ quarantined_page: 'orchardline canary quarantined page',+ unpaged: 'orchardline canary unpaged private',+ transcript_lane: 'orchardline canary transcript lane private',+ late_federated: 'orchardline canary late private',+};+/** The plain warning `auth rescope` prints when the switch turns on. */+const WARNING = 'This key will read every private fact in the sources its grant names, including facts saved private on purpose';++const worldPage = (title: string) => '---\ntype: company\ntitle: ' + title + '\n---\n\n# ' + title + '\n\nOrchardline company page.\n';++async function dbFact(engine: BrainEngine, sourceId: string, fact: string, visibility: 'private' | 'world', holder: string | null, opts: { source?: string; session?: string } = {}): Promise<void> {+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(+ 'INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, source_session, source_markdown_slug) VALUES ($1, $2, $3, \'fact\', $4, $5, $6, $7)', // gbrain-allow-direct-insert: legacy database-only fact fixture+ [sourceId, ENTITY, fact, visibility, opts.source ?? 'mcp:extract_facts', opts.session ?? null, holder]), TEST_WRITE_ATTRIBUTION));+}++for (const kind of testBackends()) {+ describe('private_facts grant axis (' + kind + ')', () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ const tokens: Record<string, string> = {};+ const clients: Record<string, string> = {};+ const setupErrors: string[] = [];++ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ const verify = async (token: string) => await provider().verifyAccessToken(token) as unknown as AuthInfo & { privateFacts?: unknown };+ const rescopeToken = async (name: string, ...args: string[]) => rescopeLegacyToken(engine, parseRescopeTokenArgs([name, ...args]));+ const rescopeClient = async (clientId: string, ...args: string[]) =>+ rescopeClientGrant(engine, clientId, parseClientRescopeArgs(clientId, args).patch, { actor: 'test', expectedRevision: (await readClientGrant(engine, clientId)).revision });++ /** One MCP call as serve --http makes it: the verifier's AuthInfo, read live, and the transport's dispatch options. */+ async function call(token: string, op: string, params: Record<string, unknown>, extra: { metaHook?: typeof getBrainHotMemoryMeta; sessionId?: string } = {}): Promise<{ isError: boolean; text: string; meta?: Record<string, unknown> }> {+ __resetPrivateVisibilityCacheForTests();+ const auth = await verify(token);+ const sourceId = auth.sourceId ?? 'default';+ const localFederated = await noGrantFederatedScope(engine, auth.hasSourceGrant, sourceId);+ const out = await dispatchToolCall(engine, op, { ...params }, {+ remote: true, transport: 'http', auth, sourceId, takesHoldersAllowList: auth.takesHoldersAllowList ?? ['world'],+ ...(localFederated ? { localFederatedSourceIds: localFederated } : {}), ...extra,+ });+ return { isError: out.isError === true, text: out.content.map(c => c.text).join('\n'), meta: (out as { _meta?: Record<string, unknown> })._meta };+ }+ const local = async (op: string, params: Record<string, unknown>) =>+ (await dispatchToolCall(engine, op, { ...params }, { remote: false, sourceId: GRANTED })).content.map(c => c.text).join('\n');+ const reads = (): Array<[string, string, Record<string, unknown>]> => [+ ['recall entity', 'recall', { entity: ENTITY }],+ ['recall query', 'recall', { query: 'orchardline canary' }],+ ['search', 'search', { query: 'orchardline canary', fields: 'full' }],+ ];+ const closedSeen = (text: string) => Object.entries(CLOSED).filter(([, fact]) => text.includes(fact)).map(([why]) => why);++ beforeAll(async () => {+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }+ __resetPrivateVisibilityCacheForTests();+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.setConfig('brain.audience', 'shared');+ for (const id of [GRANTED, TEAM, OTHER]) await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [id]);+ await engine.executeRaw('INSERT INTO sources (id, name, config) VALUES ($1, $1, \'{"federated": true}\'::jsonb) ON CONFLICT (id) DO NOTHING', [FED]);+ await engine.executeRaw('UPDATE sources SET config = jsonb_set(COALESCE(config, \'{}\'::jsonb), \'{federated}\', \'true\'::jsonb) WHERE id = \'default\'');+ for (const source of [GRANTED, OTHER, FED, 'default']) await importFromContent(engine, ENTITY, worldPage('Acme Example'), { sourceId: source });+ await importFromContent(engine, 'notes/private-src', '---\ntype: note\ntitle: Private source\nvisibility: private\n---\n\n# Private source\n\nPrivate notes.\n', { sourceId: GRANTED });+ await importFromContent(engine, 'notes/readers-only', '---\ntype: note\ntitle: Readers only\nreadable_by: [alice-example]\n---\n\n# Readers only\n\nRestricted notes.\n', { sourceId: GRANTED });+ await importFromContent(engine, 'notes/held-back', worldPage('Held back'), { sourceId: GRANTED });+ await engine.transaction(tx => withCoordinatedWrite(tx, [GRANTED], () => tx.executeRaw(+ `UPDATE pages SET frontmatter = frontmatter || '{"quarantine":{"reason":"junk_pattern","detail":"fixture","assessed_at":"2026-09-01T00:00:00Z"}}'::jsonb WHERE source_id = $1 AND slug = 'notes/held-back'`,+ [GRANTED]), TEST_WRITE_ATTRIBUTION));+ await importFromContent(engine, 'memory/members/alice-example', '---\ntype: note\ntitle: Memory of alice-example\nreadable_by:\n - member:alice-example\n---\n\n# Memory\n', { sourceId: GRANTED });+ await dbFact(engine, GRANTED, OPENS, 'private', ENTITY);+ await dbFact(engine, GRANTED, WORLD, 'world', ENTITY);+ await dbFact(engine, OTHER, CLOSED.other_source, 'private', ENTITY);+ await dbFact(engine, FED, CLOSED.federated_source, 'private', ENTITY);+ await dbFact(engine, FED, WORLD_FED, 'world', ENTITY);+ await dbFact(engine, 'default', CLOSED.default_source, 'private', ENTITY);+ await dbFact(engine, GRANTED, CLOSED.private_page, 'private', 'notes/private-src');+ await dbFact(engine, GRANTED, CLOSED.readers_page, 'private', 'notes/readers-only');+ await dbFact(engine, GRANTED, CLOSED.member_page, 'private', 'memory/members/alice-example');+ await dbFact(engine, GRANTED, CLOSED.quarantined_page, 'private', 'notes/held-back');+ await dbFact(engine, GRANTED, CLOSED.derived_page, 'private', ENTITY, { source: 'mcp:put_page', session: 'put_page:notes/private-src' });+ await dbFact(engine, GRANTED, CLOSED.unpaged, 'private', null);+ await dbFact(engine, GRANTED, CLOSED.transcript_lane, 'private', ENTITY, { source: 'cli:extract-conversation-facts' });++ const mint = async (name: string, sources?: string[]) => {+ const minted = await mintLegacyToken(engine, { name, scopes: ['read'], takesHolders: ['world'], ...(sources ? { sourceGrant: sources } : {}) });+ await readsUnscopedOnPurpose(engine, minted.id);+ tokens[name] = minted.token;+ };+ await mint('facts-bot', [GRANTED, TEAM]);+ await mint('facts-plain', [GRANTED, TEAM]);+ await mint('facts-floor');+ const register = async (name: string, sourceId: string, read: string[]) => {+ const p = provider();+ const { clientId, clientSecret } = await p.registerClientManual(name, ['client_credentials'], 'read', [], sourceId, read);+ await readsUnscopedOnPurpose(engine, clientId, 'client');+ clients[name] = clientId;+ tokens[name] = (await p.exchangeClientCredentials(clientId, clientSecret!)).access_token;+ };+ await register('client-facts', GRANTED, [GRANTED, TEAM]);+ await register('client-plain', GRANTED, [GRANTED, TEAM]);+ for (const step of [() => rescopeToken('facts-bot', '--private-facts', 'granted-sources'), () => rescopeToken('facts-floor', '--private-facts', 'granted-sources'),+ () => rescopeClient(clients['client-facts'], '--private-facts', 'granted-sources')]) {+ await step().catch((e: unknown) => { setupErrors.push(e instanceof Error ? e.message : String(e)); });+ }+ }, 240_000);++ afterAll(async () => {+ resetGateway();+ await disposePersistenceConsumer(engine);+ await close?.();+ }, 60_000);++ test('fixture control: the trusted local caller recalls the private facts; a credential left at none sees only world ones', async () => {+ const all = await local('recall', { entity: ENTITY, source_id: GRANTED });+ expect({ opens: all.includes(OPENS), world: all.includes(WORLD), page: all.includes(CLOSED.private_page), unpaged: all.includes(CLOSED.unpaged), transcript: all.includes(CLOSED.transcript_lane) })+ .toEqual({ opens: true, world: true, page: true, unpaged: true, transcript: true });+ expect(await local('recall', { entity: ENTITY, source_id: FED })).toContain(CLOSED.federated_source);+ for (const who of ['facts-plain', 'client-plain']) {+ for (const [label, op, params] of reads()) {+ const out = await call(tokens[who], op, params);+ expect({ who, label, isError: out.isError, opens: out.text.includes(OPENS), closed: closedSeen(out.text) }).toEqual({ who, label, isError: false, opens: false, closed: [] });+ }+ expect((await call(tokens[who], 'recall', { entity: ENTITY })).text).toContain(WORLD);+ }+ }, 120_000);++ test('the CLI sets the switch: the stored column and the verifier carry it, for the grant sources only', async () => {+ expect(setupErrors).toEqual([]);+ const rows = await engine.executeRaw<{ name: string; private_facts: string }>("SELECT name, private_facts FROM access_tokens WHERE name LIKE 'facts-%' ORDER BY name");+ expect(rows.map(r => [r.name, r.private_facts])).toEqual([['facts-bot', 'granted_sources'], ['facts-floor', 'granted_sources'], ['facts-plain', 'none']]);+ expect((await verify(tokens['facts-bot'])).privateFacts).toEqual({ mode: 'granted_sources', sources: [GRANTED, TEAM] });+ expect((await verify(tokens['client-facts'])).privateFacts).toEqual({ mode: 'granted_sources', sources: [GRANTED, TEAM] });+ for (const who of ['facts-plain', 'client-plain', 'facts-floor']) expect({ who, pf: (await verify(tokens[who])).privateFacts }).toEqual({ who, pf: undefined });+ const [stored] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE fact LIKE 'orchardline canary%' AND visibility = 'private'");+ expect(stored.n).toBe(11);+ });++ test('with the switch on, recall and search read the private fact on a world page in the granted source, and nothing it must not', async () => {+ for (const who of ['facts-bot', 'client-facts']) {+ for (const [label, op, params] of reads()) {+ const out = await call(tokens[who], op, params);+ expect({ who, label, isError: out.isError, opens: out.text.includes(OPENS), closed: closedSeen(out.text) }).toEqual({ who, label, isError: false, opens: true, closed: [] });+ }+ }+ }, 120_000);++ test('facts with no page to check stay hidden with the switch on: an unpaged fact and a transcript-lane fact with a holding page', async () => {+ for (const who of ['facts-bot', 'client-facts']) {+ for (const [label, op, params] of reads()) {+ const out = await call(tokens[who], op, params);+ expect({ who, label, opens: out.text.includes(OPENS), unpaged: out.text.includes(CLOSED.unpaged), transcript: out.text.includes(CLOSED.transcript_lane) })+ .toEqual({ who, label, opens: true, unpaged: false, transcript: false });+ }+ }+ }, 120_000);++ test('the page exclusions are the grant\'s own: they hold with the remote privacy hatch on, which relaxes only private pages', async () => {+ await withEnv({ GBRAIN_REMOTE_PRIVATE_PAGES: '1' }, async () => {+ const bot = await call(tokens['facts-bot'], 'recall', { entity: ENTITY });+ expect({ opens: bot.text.includes(OPENS), closed: closedSeen(bot.text) }).toEqual({ opens: true, closed: [] });+ const plain = await call(tokens['facts-plain'], 'recall', { entity: ENTITY });+ expect({ opens: plain.text.includes(OPENS), closed: closedSeen(plain.text) }).toEqual({ opens: false, closed: [] });+ });+ }, 120_000);++ test('the hot-memory cache never serves a payload read under the grant to a credential without it', async () => {+ const hot = async (who: string) => JSON.stringify((await call(tokens[who], 'search', { query: 'orchardline canary', fields: 'full' }, { metaHook: getBrainHotMemoryMeta, sessionId: 'pf-hot-session' })).meta?.brain_hot_memory ?? null);+ __resetHotMemoryCacheForTests();+ const cold = await hot('facts-plain');+ __resetHotMemoryCacheForTests();+ const granted = await hot('facts-bot');+ const plain = await hot('facts-plain');+ __resetHotMemoryCacheForTests();+ expect({ cold: cold.includes(OPENS), granted: granted.includes(OPENS), plain: plain.includes(OPENS), closed: closedSeen(granted + plain) }).toEqual({ cold: false, granted: true, plain: false, closed: [] });+ expect(plain).toBe(cold);+ }, 120_000);++ test('another credential with the same sources and no switch is unaffected', async () => {+ for (const who of ['facts-plain', 'client-plain']) {+ const out = await call(tokens[who], 'recall', { entity: ENTITY });+ expect({ who, opens: out.text.includes(OPENS), world: out.text.includes(WORLD) }).toEqual({ who, opens: false, world: true });+ }+ }, 120_000);++ test('a source the grant does not name stays closed, even when the request names it', async () => {+ for (const args of [{ source_id: OTHER }, { source_ids: [OTHER] }, { source_ids: [FED] }, { source_id: 'default' }]) {+ const out = await call(tokens['facts-bot'], 'recall', { entity: ENTITY, ...args });+ expect({ args, closed: closedSeen(out.text), opens: out.text.includes(OPENS) }).toEqual({ args, closed: [], opens: false });+ }+ const team = await call(tokens['facts-bot'], 'recall', { entity: ENTITY, source_ids: [TEAM] });+ expect(team.text).not.toContain(OPENS);+ }, 120_000);++ test('a source the credential reaches but its grant does not list never opens, though federated after the grant is written', async () => {+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [LATE]);+ await importFromContent(engine, ENTITY, worldPage('Acme Example'), { sourceId: LATE });+ await dbFact(engine, LATE, CLOSED.late_federated, 'private', ENTITY);+ await dbFact(engine, LATE, WORLD_LATE, 'world', ENTITY);+ await runSources(engine, ['federate', LATE]);+ const [config] = await engine.executeRaw<{ federated: unknown }>("SELECT config->'federated' AS federated FROM sources WHERE id = $1", [LATE]);+ expect(String(config.federated)).toBe('true');+ expect(await local('recall', { entity: ENTITY, source_id: LATE })).toContain(CLOSED.late_federated);+ expect((await verify(tokens['facts-bot'])).privateFacts).toEqual({ mode: 'granted_sources', sources: [GRANTED, TEAM] });+ expect((await verify(tokens['client-facts'])).privateFacts).toEqual({ mode: 'granted_sources', sources: [GRANTED, TEAM] });+ expect((await verify(tokens['facts-floor'])).privateFacts).toBeUndefined();+ const reached = await call(tokens['facts-floor'], 'recall', { entity: ENTITY, source_ids: [LATE] });+ expect({ reached: reached.text.includes(WORLD_LATE), closed: closedSeen(reached.text) }).toEqual({ reached: true, closed: [] });+ for (const who of ['facts-floor', 'facts-bot', 'client-facts']) {+ for (const [label, op, params] of [...reads(), ['recall late', 'recall', { entity: ENTITY, source_ids: [LATE] }] as [string, string, Record<string, unknown>]]) {+ const out = await call(tokens[who], op, params);+ expect({ who, label, closed: closedSeen(out.text) }).toEqual({ who, label, closed: [] });+ }+ }+ for (const who of ['facts-bot', 'client-facts']) expect((await call(tokens[who], 'recall', { entity: ENTITY })).text).toContain(OPENS);+ }, 120_000);++ test('a credential with no source grant gets nothing from the switch, in default or a federated source it reads', async () => {+ for (const args of [{}, { source_ids: [FED] }, { source_id: 'default' }]) {+ const out = await call(tokens['facts-floor'], 'recall', { entity: ENTITY, ...args });+ expect({ args, isError: out.isError, closed: closedSeen(out.text), opens: out.text.includes(OPENS) }).toEqual({ args, isError: false, closed: [], opens: false });+ }+ expect((await call(tokens['facts-floor'], 'recall', { entity: ENTITY, source_ids: [FED] })).text).toContain(WORLD_FED);+ const search = await call(tokens['facts-floor'], 'search', { query: 'orchardline canary', fields: 'full' });+ expect(closedSeen(search.text)).toEqual([]);+ }, 120_000);++ test('--private-facts none turns it off on the next request (token and client)', async () => {+ expect((await call(tokens['facts-bot'], 'recall', { entity: ENTITY })).text).toContain(OPENS);+ await rescopeToken('facts-bot', '--private-facts', 'none');+ await rescopeClient(clients['client-facts'], '--private-facts', 'none');+ try {+ for (const who of ['facts-bot', 'client-facts']) {+ for (const [label, op, params] of reads()) {+ const out = await call(tokens[who], op, params);+ expect({ who, label, opens: out.text.includes(OPENS) }).toEqual({ who, label, opens: false });+ }+ }+ } finally {+ await rescopeToken('facts-bot', '--private-facts', 'granted-sources');+ await rescopeClient(clients['client-facts'], '--private-facts', 'granted-sources');+ }+ expect((await call(tokens['facts-bot'], 'recall', { entity: ENTITY })).text).toContain(OPENS);+ }, 120_000);++ test('no MCP operation or admin HTTP grant edit can set it', async () => {+ const exposing = operations.filter(op => Object.keys(op.params ?? {}).some(k => /private_?facts/i.test(k))).map(op => op.name);+ expect(exposing).toEqual([]);+ const before = await readClientGrant(engine, clients['client-plain']);+ const parsed = parseAdminGrantRequest({ clientId: clients['client-plain'], privateFacts: 'granted_sources', private_facts: 'granted_sources', scopes: 'read' }, before);+ expect(Object.keys(parsed.patch)).not.toContain('privateFacts');+ const out = await call(tokens['client-plain'], 'recall', { entity: ENTITY, private_facts: 'granted_sources' });+ expect(out.text).not.toContain(OPENS);+ const [row] = await engine.executeRaw<{ private_facts: string }>('SELECT private_facts FROM oauth_clients WHERE client_id = $1', [clients['client-plain']]);+ expect(row.private_facts).toBe('none');+ });+ });+}++describe('private_facts migration and operator output', () => {+ let root: string, home: string, db: string;+ const env = () => ({ GBRAIN_HOME: home, HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_SOURCE: undefined });+ const GRANTED_LABEL = 'granted-sources (private facts in the sources this grant names)';+ async function withBrain<T>(run: (engine: BrainEngine) => Promise<T>): Promise<T> {+ const config = { engine: 'pglite' as const, database_path: db };+ const engine = await createEngine(config);+ await engine.connect(config);+ try { return await run(engine); } finally { await engine.disconnect(); }+ }+ async function auth(args: string[]): Promise<string> {+ const lines: string[] = [];+ const original = console.log;+ const exit = process.exit;+ console.log = (...parts: unknown[]) => { lines.push(parts.join(' ')); };+ process.exit = ((code?: number) => { throw new Error(`auth exited ${code}`); }) as typeof process.exit;+ try { await withEnv(env(), () => runAuth(args)); } finally { console.log = original; process.exit = exit; }+ return lines.join('\n');+ }++ beforeAll(async () => {+ root = mkdtempSync(join(tmpdir(), 'gb-private-facts-'));+ home = join(root, 'home');+ db = join(root, 'db');+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: db }));+ await withBrain(async engine => {+ await engine.initSchema();+ await mintLegacyToken(engine, { name: 'alice-example', scopes: ['read'], takesHolders: ['world'], sourceGrant: ['default'] });+ await mintLegacyToken(engine, { name: 'bob-example', scopes: ['read'], takesHolders: ['world'], sourceGrant: ['default'] });+ await engine.executeRaw("INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read) VALUES ('client-a', 'client-a', 'read', 'default', ARRAY['default'])");+ });+ }, 120_000);+ afterAll(() => { rmSync(root, { recursive: true, force: true }); });++ test('the migration on an existing brain leaves every token and client at none', async () => {+ await withBrain(async engine => {+ await engine.executeRaw('ALTER TABLE access_tokens DROP COLUMN IF EXISTS private_facts');+ await engine.executeRaw('ALTER TABLE oauth_clients DROP COLUMN IF EXISTS private_facts');+ // Value: protects=before the migration, --private-facts on a client or token refuses grant_schema_required and writes nothing; fails_when=the column guard or schemaError mapping is removed; why_new=no test drove a rescope on a brain without the column; seam=none; no_claim=Postgres error codes (PGLite only)+ const clientRefusal = await rescopeClientGrant(engine, 'client-a', { privateFacts: 'granted_sources' }, { actor: 'test' }).then(() => null, (e: { code?: string }) => e);+ expect(clientRefusal?.code).toBe('grant_schema_required');+ const tokenRefusal = await rescopeLegacyToken(engine, parseRescopeTokenArgs(['alice-example', '--private-facts', 'granted-sources'])).then(() => null, (e: { code?: string }) => e);+ expect(tokenRefusal?.code).toBe('grant_schema_required');+ await engine.setConfig('version', String(LATEST_VERSION - 1));+ await runMigrations(engine);+ expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION));+ const tokens = await engine.executeRaw<{ private_facts: string }>('SELECT private_facts FROM access_tokens');+ const clients = await engine.executeRaw<{ private_facts: string }>('SELECT private_facts FROM oauth_clients');+ expect(tokens.map(r => r.private_facts)).toEqual(['none', 'none']);+ expect(clients.map(r => r.private_facts)).toEqual(['none']);+ await expect(engine.executeRaw("UPDATE access_tokens SET private_facts = 'all'")).rejects.toThrow();+ });+ }, 120_000);++ test('auth rescope prints the before and after for a token and a client; auth list and auth clients show it', async () => {+ const token = await auth(['rescope', '--token', 'alice-example', '--private-facts', 'granted-sources']);+ expect(token).toContain(' Private facts: none -> ' + GRANTED_LABEL);+ expect(token).toContain(WARNING);+ const client = await auth(['rescope', '--client', 'client-a', '--private-facts', 'granted-sources', '--dry-run']);+ expect(client).toContain(' Private facts: none -> ' + GRANTED_LABEL);+ expect(client).toContain(WARNING);+ const help = (await auth(['--help'])).replace(/\s+/g, ' ');+ expect(help).toContain('including facts saved private on purpose');+ expect(help).toContain('a fact with no page to check');+ await auth(['rescope', '--client', 'client-a', '--private-facts', 'granted-sources']);+ const listed = JSON.parse(await auth(['list', '--json'])) as Array<Record<string, unknown>>;+ expect(Object.fromEntries(listed.map(t => [t.name, t.private_facts]))).toEqual({ 'alice-example': 'granted_sources', 'bob-example': 'none' });+ const text = await auth(['list']);+ expect(text.split('\n')[0]).toContain('Private facts');+ expect(text.split('\n').find(l => l.includes('alice-example'))).toMatch(/active\s+granted-sources\s+none$/);+ expect(text.split('\n').find(l => l.includes('bob-example'))).toMatch(/active\s+none\s+none$/);+ const clients = await auth(['clients']);+ expect(clients).toContain(' private facts: ' + GRANTED_LABEL);+ const json = JSON.parse(await auth(['clients', '--json'])) as { clients: Array<{ client_id: string; private_facts: string }> };+ expect(json.clients.find(c => c.client_id === 'client-a')?.private_facts).toBe('granted_sources');+ const off = await auth(['rescope', '--token', 'alice-example', '--private-facts', 'none']);+ expect(off).toContain(' Private facts: ' + GRANTED_LABEL + ' -> none');+ expect(off).not.toContain(WARNING);+ }, 120_000);+});diff --git a/test/qm-scope-writes.test.ts b/test/qm-scope-writes.test.tsindex 246d04feea..d949f02f2b 100644--- a/test/qm-scope-writes.test.ts+++ b/test/qm-scope-writes.test.ts@@ -361,6 +361,14 @@ for (const kind of testBackends()) {expect(await federated()).not.toContain(SCOPE_A);expect((await markedScopeSources(engine, [SCOPE_A])).has(SCOPE_A)).toBe(true);expect((await refusal(rescopeClientGrant(engine, clients.scopes!.id, { privatePages: 'granted_sources' }, { actor: 'test' })))?.message).toContain('private-pages');+ // Value: protects=a scope (attest-sources) credential cannot take the private-facts grant; fails_when=the privateFacts attest guard in assertScopeSourceGrant is dropped; why_new=only private-pages was asserted; seam=none; no_claim=the reverse order (attest after grant) in applyAttestSources+ expect((await refusal(rescopeClientGrant(engine, clients.scopes!.id, { privateFacts: 'granted_sources' }, { actor: 'test' })))?.message).toContain('private-facts grant');+ // Value: protects=applyAttestSources refuses scope sources for a credential holding the private-facts grant, writing nothing; fails_when=the privateFacts guard in applyAttestSources is dropped; why_new=only the grant-after-attest order was asserted; seam=none; no_claim=the token path (client fixture only)+ await engine.executeRaw(`UPDATE oauth_clients SET private_facts = 'granted_sources' WHERE client_id = $1`, [clients.plain!.id]);+ expect((await refusal(bindCredential(engine, { kind: 'client', id: clients.plain!.id }, { attestActor: 'qm', attestOps: MEMORY_OPS, attestSources: [SCOPE_A] })))?.message).toContain('holds the private-facts grant, so it cannot list scope sources');+ const [plainRow] = await engine.executeRaw<{ attest_sources: string[] | null }>('SELECT attest_sources FROM oauth_clients WHERE client_id = $1', [clients.plain!.id]);+ expect(plainRow!.attest_sources ?? []).toEqual([]);+ await engine.executeRaw(`UPDATE oauth_clients SET private_facts = 'none' WHERE client_id = $1`, [clients.plain!.id]);await engine.executeRaw(`UPDATE oauth_clients SET deleted_at = now() WHERE client_id = $1`, [clients.scopes!.id]);expect((await refusal(rescopeClientGrant(engine, clients.plain!.id, { federatedRead: [SHARED, SCOPE_A] }, { actor: 'test' })))?.message).toContain('QM scope source');await engine.executeRaw(`UPDATE oauth_clients SET deleted_at = NULL WHERE client_id = $1`, [clients.scopes!.id]);diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.tsindex 949f2e5fd6..60c2cb9397 100644--- a/test/schema-bootstrap-coverage.test.ts+++ b/test/schema-bootstrap-coverage.test.ts@@ -1003,6 +1003,10 @@ const COLUMN_EXEMPTIONS = new Set<string>([// reads them, and grant reads treat a missing column as 'none'.'access_tokens.private_pages','oauth_clients.private_pages',+ // GBRA-575 access_tokens/oauth_clients.private_facts (migration+ // principal_private_facts): the same shape and rationale as private_pages.+ 'access_tokens.private_facts',+ 'oauth_clients.private_facts',// T7 — search_telemetry rank-1 drift columns (migration v111). search_telemetry// is created entirely by migration v57 (not in the schema blob), so the v57+v111// chain handles fresh + upgrade; no CREATE INDEX references these columns, so