Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Shared company brains: setup names an owner and opens the company source to member keys, and messages say where pages land (GBRA-585) (#9625)

Garry Tan2bde6a57fdc6
diff --git a/behavior-changes.d/auth_create_member_read_write_gbra585.md b/behavior-changes.d/auth_create_member_read_write_gbra585.md
new file mode 100644
index 0000000000..c304843d41
--- /dev/null
+++ b/behavior-changes.d/auth_create_member_read_write_gbra585.md
@@ -0,0 +1,4 @@
+---
+kind: default
+---
+gbrain auth create <name> --member <id> without --scopes now mints a key with read and write only. It used to mint the grandfathered full access, admin included, so a key handed to one person could call admin tools such as get_stats and see brain-wide counts. A script that runs gbrain auth create --member and then calls an admin tool with that key now gets insufficient_scope; pass --scopes read,write,admin to mint the old full access. An explicit --scopes still wins, a token made without --member keeps the old default, and tokens that already exist are not changed.
diff --git a/behavior-changes.d/serves_labelled_only_needs_owner_gbra585.md b/behavior-changes.d/serves_labelled_only_needs_owner_gbra585.md
new file mode 100644
index 0000000000..c244e1ef6b
--- /dev/null
+++ b/behavior-changes.d/serves_labelled_only_needs_owner_gbra585.md
@@ -0,0 +1,4 @@
+---
+kind: action
+---
+gbrain access serves several --labelled-only on a brain that has the company source and no owner now stops with a BLOCKED company/ line and writes nothing, where it used to label the members. The labelled-only run adds a folder rule company/ in source company so labelled-only members still read the company pages, and that rule's readers start with the brain owner. Run it again with --owner <member id> (the member is added when missing and named the owner), or name the owner first with gbrain access owner set <member> and run it unchanged.
diff --git a/behavior-changes.d/setup_history_choice_gbra585.md b/behavior-changes.d/setup_history_choice_gbra585.md
new file mode 100644
index 0000000000..81e556b385
--- /dev/null
+++ b/behavior-changes.d/setup_history_choice_gbra585.md
@@ -0,0 +1,4 @@
+---
+kind: action
+---
+gbrain setup <harness> --serves several on a brain that serves one person and already holds pages no rule or readable_by restricts (a journal, DMs, chat, mail, the conversation archive) now refuses with setup_history_choice_required and writes nothing. The refusal names how many pages every member's key would read, how many are DMs, chat or mail and how many are in the conversation archive; it also refuses when it cannot count them. Run it again with --labelled-only to keep that history private (each member reads only pages labelled for them; on a brain with the company source, setup also adds one folder rule, company/ in source company, readable by the owner and the members, so they still read the company pages and calls, and a re-run adds new members to it, which waits for gbrain access apply because it widens the rule) or with --open-history to let every member read it, which is what setup did before without asking. A new brain, a brain with no such pages and a brain that already serves several people are not asked.
diff --git a/behavior-changes.d/setup_member_keys_read_company_gbra585.md b/behavior-changes.d/setup_member_keys_read_company_gbra585.md
new file mode 100644
index 0000000000..63261030e1
--- /dev/null
+++ b/behavior-changes.d/setup_member_keys_read_company_gbra585.md
@@ -0,0 +1,4 @@
+---
+kind: default
+---
+gbrain setup <harness> --serves several and gbrain access serves several now mint each member key with a fixed source list instead of the default grant: it writes to the run's source and reads that source, the company source when it exists (gbrain setup --shape company), and every source federated when the key is minted. So members read the company pages and imported calls, including calls they did not attend, without federating company, which stays out of default search. A source federated later reaches these keys only when you run setup again (a re-run adds sources to such a key and never removes one); before, a member key read every federated source as soon as it was federated. A key for a named --source now also reads the federated sources and company. Keys minted before this release, and any key setup did not mint with a list, are not changed. The preview names the list and how many pages company holds.
diff --git a/behavior-changes.d/setup_names_owner_gbra585.md b/behavior-changes.d/setup_names_owner_gbra585.md
new file mode 100644
index 0000000000..f281655b64
--- /dev/null
+++ b/behavior-changes.d/setup_names_owner_gbra585.md
@@ -0,0 +1,4 @@
+---
+kind: default
+---
+gbrain setup <harness> --serves several (and gbrain access serves several --owner <id>) now names the brain owner when the brain has none: it adds a member from --owner <id>, or by default from your login name as a member id, and runs gbrain access owner set on it. The preview shows it first. An owner that is already set is kept, and no key or OAuth client is rebound: the receipt lists each live credential bound to no member with the gbrain auth rescope --token|--client <name> --member <owner> command that binds it. A script that ran setup --serves several on a brain with no owner now finds one more enabled member, the owner, in gbrain access member list. Pass --owner <id> to choose who it is.
diff --git a/changelog.d/gbra585-company-first-week.md b/changelog.d/gbra585-company-first-week.md
new file mode 100644
index 0000000000..619f181e77
--- /dev/null
+++ b/changelog.d/gbra585-company-first-week.md
@@ -0,0 +1,11 @@
+**Shared company brains now say where a page with no source landed and who can read it, how to back up a Postgres brain, what a member's agent should do when a page is missing, and how to plug a member's key into their harness.**
+
+### Fixed
+- On a brain that serves several people, `gbrain put` with no `--source` now reports a `placement` block. It names the source the page went to, the rule that picked it and who can read it, and gives the `--source` and `readable_by` fixes. Where pages land is unchanged, and a one-person brain prints nothing new.
+- `gbrain backup create` on a Postgres brain names a `pg_dump` and `pg_restore` database dump and says that `gbrain export` is not a backup. Doctor's backup advice now names the full backup for the brain's engine and counts the brain's current pages instead of a count cached while the brain was empty.
+- Setup for a brain that serves several people says that no member key it created can read the imported calls yet, says that a running `serve` on PGLite blocks other CLI commands (with `gbrain migrate --to postgres` as the way out), and explains why the conversation archive is on. `gbrain transcripts archive status` and doctor print the same reason.
+- The upgrade summary for shared skills no longer tells a fresh brain it owes host action when the only open item is a client that has not enrolled yet.
+- A member's agent gets the same neutral reply for a missing page and a restricted one, with no host command in it. A refused shared `remember` suggests remembering without sharing, and the `sources_not_readable` message says it counted only pages every reader can see.
+- `gbrain sources add` asks whether a new source should be shared instead of pushing federation, and a client that was narrowed on purpose stops getting a widen notice on calls it is allowed to make.
+- `gbrain connect --harness` given `--token` or a plain key file prints the exact `gbrain connect` command to use, and the token note no longer calls every token full access. The setup guide has a new section on putting a member's key into their harness.
+- `gbrain guests init` and `gbrain sources writers --add` refuse an OAuth client writer that names no registered client. The approve command printed by an access-rule preview now includes `--expect`, and a delegated write's `--source-id` now writes to that source, as a direct write already did.
diff --git a/changelog.d/gbra585-company-setup-access.md b/changelog.d/gbra585-company-setup-access.md
new file mode 100644
index 0000000000..fb1a595c02
--- /dev/null
+++ b/changelog.d/gbra585-company-setup-access.md
@@ -0,0 +1,17 @@
+**`gbrain setup --serves several` now makes a company brain that is safe to share: it names an owner, gives each member a key that reads the company pages, and asks before it shares a personal brain's history.**
+
+<!-- behavior-change: setup_names_owner_gbra585 -->
+<!-- behavior-change: auth_create_member_read_write_gbra585 -->
+<!-- behavior-change: setup_member_keys_read_company_gbra585 -->
+<!-- behavior-change: setup_history_choice_gbra585 -->
+<!-- behavior-change: serves_labelled_only_needs_owner_gbra585 -->
+
+### Changed
+- `gbrain setup <harness> --serves several` names the brain owner when the brain has none: `--owner <id>`, or by default your login name as a member id. The preview shows it first, an owner already set is kept, and the receipt lists each live key or OAuth client bound to no member with the `gbrain auth rescope` command that binds it.
+- Member keys that setup mints read a fixed list of sources. The list holds the run's source, the `company` source when it exists, and every source federated at mint time. Members read the company pages and imported calls without federating `company`. A setup re-run adds sources to such a key and never removes one; keys minted before this release are not changed.
+- `gbrain auth create <name> --member <id>` without `--scopes` mints a key with read and write only, not admin. Pass `--scopes read,write,admin` for the old full access.
+- On a brain that serves one person and already holds pages no rule restricts (a journal, DMs, chat, mail, the conversation archive), `--serves several` refuses with `setup_history_choice_required` and writes nothing. It names how many pages members would read and suggests two commands: `--labelled-only` keeps that history private, and `--open-history` lets every member read it. It also refuses when it cannot count those pages. The suggested `--labelled-only` command leaves out the brain's owner, who reads the whole brain, and pins `--owner`.
+
+### Added
+- `--open-history` on `gbrain setup`. On a brain with the company source, a `--labelled-only` run adds one folder rule, `company/` in source `company`, readable by the owner and the members, so they still read the company pages. A re-run adds new members to that rule and waits for `gbrain access apply`, because it widens the rule.
+- The layout's readers line now names who actually reads imported calls on a shared brain.
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 7c018dde4c..1bae816e43 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -814,6 +814,30 @@ to connect: it diagnoses the dir from disk, names the repair command, reports
retained repair backups, and escalates when repairs keep recurring (that
means the unclean-shutdown genesis is still active — see the ladder's rung 4).
+<a id="pglite-live-serve"></a>
+### PGLite while `gbrain serve` runs (`pglite_busy` reason `live_serve`)
+
+One gbrain process opens a PGLite brain at a time. While `gbrain serve` (stdio
+or `--http`) holds it, page and fact writes from the CLI (`gbrain put`,
+`gbrain remember`) go through the running server and work. Commands that need
+the database to themselves, which includes the admin commands
+(`gbrain access …`, `gbrain sources …`, `gbrain auth …`) and most reads,
+refuse with `pglite_busy` reason `live_serve`. The refusal names the server's
+PID, and its fix is two steps: stop that server, then run the command again.
+Never remove the lock of a server that is still running.
+
+On a brain that serves one person this is a short pause: quit the agent
+session (a stdio serve) or stop `gbrain serve --http`, run the command, and
+start it again. On a brain that serves several people over
+`gbrain serve --http`, every member's connection drops while the server is
+stopped, for every admin step. Move such a brain to Postgres, where the server
+and the admin commands run side by side: preview with the read-only
+`gbrain migrate --to postgres --url-env GBRAIN_TARGET_URL --plan --json`,
+then follow [Move a PGLite brain to Postgres](guides/move-to-postgres.md). The
+move carries members, tokens, `readable_by` and facts across.
+`gbrain setup <harness> --serves several` on PGLite says this in its
+`engine` line.
+
<a id="legacy-pglite-lock"></a>
### Legacy PGLite lock (`pglite_busy` reason `legacy_owner_unverified`)
diff --git a/docs/architecture/key-files/access.md b/docs/architecture/key-files/access.md
index 282b08a132..ad5293c0cc 100644
--- a/docs/architecture/key-files/access.md
+++ b/docs/architecture/key-files/access.md
@@ -6,10 +6,11 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/access/` (GBRA-218) — per-member read access inside one source. `principals.ts` normalizes frontmatter `readable_by` (bare id = `member:<id>`, `group:<g>`, ASCII case fold, space trim; anything malformed is `['!nobody']`); it is the row twin of the SQL `gbrain_access_readers()` (`test/access-principals.test.ts` holds them equal). A BEFORE trigger keeps `pages.page_readers` equal to that function (direct writes to the column are recomputed), and predicates test the array, never the function, which costs ~0.2 ms per row. A page that names readers with no derived value yet (written before the migration) reads as nobody until `gbrain repair access` (`repair/access.ts`). `members.ts` (members, groups, tombstoned ids never reused, bindings), `token-binding.ts` (the verifiers' join; a credential bound to a disabled, tombstoned or missing member is refused with `access_member_disabled`) and `caller.ts` (`remoteCallerAccess`: the identity dispatch puts on the caller-access record; stdio binds through `serve --stdio-member`, else `mcp.stdio_member`; publication re-resolves from the stored principal; a binding lookup that fails never reads as unbound: a statement error throws `access_identity_unavailable` (retryable, `fix.next: wait`), a transient failure (`transientDatabaseFailure`, `transientInterruption` in `persistence/transient-retry.ts`) or a non-statement failure is rethrown unchanged for the persistence consumer, and only a schema missing `access_members`, `access_group_members` or `member_id` reads as unbound). In `search/private-visibility.ts` every page fragment is `accessAllowedSql` AND the privacy part: plain fragments use the empty identity (over-hide, never leak), `*ForCaller` fragments the caller's, and `GBRAIN_REMOTE_PRIVATE_PAGES`, `search.remote_private_pages` and `granted_sources` relax only the privacy part (`privacyForCaller`). GST-2490: an owner read (`CallerAccess.lineage` with `owner`, read-only ops only) uses `lineageAccessSql`: the owner's readers and folder rules as for any member, with `gbrain_access_origin_hidden_for()` (v304; per origin `gbrain_access_origin_closed_for()`) in place of the every-caller lineage, so a derivative or fact passes when the owner reads every origin; `ownerReadsRestricted` (config `access.owner_reads_restricted`, `owner.ts` `setOwnerReadsRestricted`, local only) also passes pages kept to other members except another member's own member page and pending coverage. `access check`, `who-can-read`, `whoami` (`ownerReadsRestrictedNotice`) and doctor `access_owner_reads_restricted` report it; test `test/owner-reads-restricted.test.ts` (both engines, database and access.yml rules). GBRA-108 (migration v305, `v305-access-lineage-designs.ts`): `access_rules.covers_derived` (default true) — a raw-only rule (`folder-rules.ts` `covers_derived: false`, `rule add --raw-only`; digest unchanged for covering rules; true→false is the held widening `derived_released`, false→true the narrowing `derived_covered`) is dropped from an origin's rule set by the SQL function `gbrain_access_lineage_rules()` inside `gbrain_access_origin_restricted()` and the 10-argument `gbrain_access_origin_closed_for()`, so it keeps its pages but not their lineage (a page's own readers still close it; fact provenance filters judge with `derived = true`). `access_members.kind` (`person` | `audience`, `members.ts` `setMemberKind`, local only): an owner read carries `CallerAccess.audienceKindMembers`, whose member pages pass the readers test and the member-page exemptions (`audiencePages`, `notOtherMemberPageSql`, the `p_audience_pages` argument of the 9-argument `gbrain_access_origin_hidden_for()`). Config `access.members_read_lineage` (`lineage.ts`, local only) sets `CallerAccess.lineage` for any member read speaking for itself (`caller.ts`; never an audience of several or an unbound credential; `withCallerAccess` drops it for several identities and keeps the owner opt-in and audience members owner-only). Cache keys: `knobsHash` `xol=3` and `xak=`, `callerIdentityKey` `owner_reads`/`audience_kind`. Doctor `access_lineage` (`checks/access-lineage.ts`). Tests: `test/access-raw-only-rules.test.ts`, `test/access-audience-members.test.ts`, `test/access-members-read-lineage.test.ts` (both engines, both stores; fixture `test/helpers/access-lineage-fixture.ts`). GBRA-108 design 1 (the labelled-only migration, `schema-migrations/v*-access-labelled-only.ts`): `access_members.labelled_only` (`labelled-only.ts` `setMemberLabelledOnly`, local only, refused on the owner with `access_labelled_only_owner` from `owner.ts`, which `setOwner` also raises) sets `CallerAccess.labelledOnly` (`caller.ts`, `actor.ts`, `as-preview.ts`; fails closed to true when the table cannot be read). `private-visibility.ts` `labelledOnlySql` ANDs `page_readers && identity OR folder_rule_ids && satisfied` into `callerAccessSql`, `callerReadersAllowedSql` (a snapshot needs its own readers or a rule on the live page) and the fact filters (`labelledOnlyFactSql`: a fact on the caller's own member page while it names the member, or under member lineage a provenance page that passes; else FALSE); under member lineage a derived row may pass through `gbrain_access_origin_labelled_for()` (every origin labelled, none missing). Remote read gates that are not caller-aware use `remoteReadFloorSql` / `remoteProvenanceFloorSql` (the plain fragment, plus the labelled-only conjunct only for a labelled-only caller); `test/remote-read-floor.test.ts` lists the sites that keep the plain fragment. `labelledOnlyFor` never reports the configured owner, and dispatch refuses a scope read for a labelled-only person (`scope-read.ts` `scopeReadLabelledOnlyRefused`). The entity page of a fact is judged by the ordinary policy. Writes: `persistence/page-visibility.ts` (`writerReadPolicySql`, `remoteLabelsChecked` → `assertLabelledOnlyCreate` → `access_labelled_only_unnamed`), `cli/enforced-member.ts` `memberPageView`. Cache keys `xlo=1`, `labelled_only`; doctor `access_labelled_only_members` (`checks/access-labelled-only.ts`). Test: `test/access-labelled-only.test.ts` (both engines, both storesA derivative of a page that names readers is otherwise hidden from every remote caller (`originAllowedSql`, which calls the SQL function `gbrain_access_origin_restricted()` only for atom, question, concept, event or `derived_from` rows, so each read plans one call instead of four subplans). Both parts lead with column tests (`page_readers IS NULL`, `type`) so row estimates follow column statistics; an expression test such as `->'readable_by' IS NULL` estimates almost no rows and sent restricted vector searches into nested-loop sequential scans. The index walk's page probe (`INDEX_WALK_PAGE_COLUMNS`) projects `page_readers`. Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`. Folder rules (A2) keep whole folders of a source to named members. `folder-rules.ts` is the grammar (`.gbrain/access.yml`: `rules:` of `id`, `prefix`, `readable_by`), `classifyRulebook` (each change is narrowing or widening; the target installs only the narrowing part) and `matchingRuleIds`. `policy.ts` owns the one applied rulebook for both stores: `access_rules` (source-qualified ids), the append-only `access_policy_revisions` log, `access_pending_coverage` (prefixes that read as nobody while a narrowing restamps, or while a committed file is invalid) and `sources.config.access_store`, persisted at the first rule and changed only by `policy-migrate.ts` (journaled in `access_policy_migrations`). `proposeRevision` installs narrowing at once under a per-source row lock and holds widening for `applyApproved` (`plan_hash`, `preview_changed`); `restampSource` rewrites `pages.folder_rule_ids` in id windows, then clears pending coverage under the lock; re-proposing the same rulebook finishes an interrupted restamp. A trigger stamps `folder_rule_ids` from the SQL function `gbrain_access_folder_rules()` on insert and on slug or source change, never from git on the serve path. `policy-git.ts` is the git store (files committed through the commit door, applied by `syncAccessPolicyAt` from sync preflight and before and after every managed pass (`performManagedSync`: sync, drain, `sources refresh`, git conversion), read with `git show` at the synced commit (GST-2331: every read under `HARDENED_GIT_ARGS` and `NO_LAZY_FETCH_ENV`, so a partial clone fetches nothing; a policy file the commit names that the clone lacks, or a history the replay cannot read, makes the source read as nobody until the objects are fetched: the problem names the exact `git cat-file -p` or `git log --first-parent -p` that fetches them, and the next sync applies the rules and clears the mark); a database with no revision yet replays each committed `access.yml` since the `access.approved` baseline, so a rebuild holds a removal a plain commit made); `policy-transfer.ts` carries the applied rulebook through `gbrain export` and installs it before any page in `gbrain import`; `policy-notice.ts` is the `access_policy_pending` degraded notice. In `private-visibility.ts`, `folderRulesAllowedSql` sits inside `accessAllowedSql` (`folder_rule_ids IS NULL OR folder_rule_ids <@ <satisfied ids>` plus coverage conjuncts), so no hatch, grant or `--as` relaxes it, and the unrestricted short form tests `folder_rule_ids IS NULL` next to `page_readers IS NULL` (v283 triggers set `access.restrictions_present` on the first rule or pending prefix); `caller.ts`'s `folderAccessFor` fails closed to whole-source coverage. CLI: `src/commands/access-rules.ts`; doctor: `src/commands/doctor/checks/folder-access.ts`. Tests: `test/access-folder-rules.test.ts` (database store, both engines), `test/access-folder-rules-git.test.ts`, `test/access-folder-transfer.test.ts`, `test/access-folder-doctor.test.ts`. Shared agents (B, GBRA-231): `audience.ts` parses the audience a harness asserts (`X-Gbrain-On-Behalf-Of` or request-level `_meta.on_behalf_of`, 1-50 principals, `guest` = the empty identity; the same key inside tool arguments is refused) and appends each assertion to `access-audience-YYYY-Www.jsonl`. Dispatch resolves it on every remote call through `caller.ts` (`resolveAudienceIdentities`: every entry must be in the credential's live `may_act_for`, then name an enabled member or existing group); the caller-access record then carries `audienceIdentities`, and `accessAllowedForAllSql` needs one readers conjunct per identity, folder rules the intersection of each entry's satisfied set (`folderAccessForAll`). Privacy relaxes only for a one-member audience. Writes carry the audience as `WriteAuthority.actingFor` (re-resolved at publication) and agent jobs as `grant.actingFor`. Every remote response carries `_meta.access` (`appliedAccessSummary`), which `whoami` returns as `access.applied`; doctor `access_may_act_for_wildcard` (`checks/shared-agent-access.ts`) warns on `*`. Tests: `test/access-on-behalf-of.test.ts` (both engines), `test/e2e/serve-http-on-behalf-of.test.ts`. Rooms (GST-2639): `room.ts` reads the shared chat an answer goes into (`readRoomDeclaration`: the `X-Gbrain-Room` header, request-level `_meta.room` and a `room` tool argument, which is stripped before the handler; the argument can only add people, a disagreement sets `conflict`; an empty or malformed channel is `invalid`, never a refusal) and `assessRoom` marks a copy of a covered op's result (`ROOM_COVERED_OPS`) plus hot memory with `room_access`: pages through `privatePagesFilterForCaller` under the room's caller-access record (`audienceCallerAccess`, the audience branch of `remoteCallerAccess`), facts through `factVisibilitySql` and `privateProvenanceFilterUnderPolicy`, with reasons `readers`, `folder_rule`, `labelled_only`, `private_label`, `derived`, `personal_source` (a page the room could otherwise read that sits in someone's personal source while the room holds anyone else: `hiddenPersonalSources`). It never throws, never narrows, reorders or fails the read (a failure, the 3 s deadline, more than 2,000 references or an uncovered op leave the body unchanged and mark items unknown), writes `_meta.room` and the notices `room_above_level`, `room_hints_unavailable`, `room_conflict`, and appends a count-only `room_marked` audit row. `resolveAudienceIdentities` takes `mayActFor: 'owner_room_assessment'` to skip `may_act_for` for the owner's room only. Dispatch ignores a room on a trusted local call. Test: `test/access-room.test.ts` (both engines, repo-less). Attested actor (C1, GST-359): `actor-model.ts` (dependency-free: `x-qm-actor`, `acting_user`, `EXTERNAL_ID_RE` = 1-256 visible ASCII, `attestRightFrom`: the right counts only for a member-less credential whose token is legacy or `client_credentials`, read from `oauth_tokens.grant_type`) and `actor.ts`. `resolveAttestedActor` runs in dispatch before any work: an invalid id refuses `actor_not_attested` (`invalid_actor_id`) before any lookup, then the right, the op list (`attest_ops`, default `get_write_request,memory_recall,memory_write`), `acting_user` = header (stripped), and `actorCoverage` (the one coverage test: live right plus a live link in `access_member_links` to an enabled member, compared exactly) or `actor_unlinked`. GST-1158: `scope-read.ts` holds `SCOPE_READ_ACCESS` (no identity, actor or audience; privacy never relaxed) and `SCOPE_READ_OPS`; dispatch runs an attested call to one of those ops that names `source_id`/`source_ids` under that record (`attestedReadMode`, which refuses `__all__`/`all_sources`), or as the person when the right's `attest_read` (v298, `--attest-read`; over HTTP `attestRead` on `/admin/api/access/attest`) is `person`, and handlers read the mode with `currentReadMode`. GST-2407: `context_pack` is a scope read too: its `entity_refs` count as naming sources, `assertPackConfined` refuses before any read a scope call without `source_id`, with an `entity_refs` entry in another source or with `session_id`, and the handler reads the named source as home (core block, pull brief, hot facts). `attest_read = 'scope'` refuses a call that names no actor (`actor_required`). Tests: `test/qm-scope-read.test.ts` (both engines), `test/doctor-attest-read-shared-scope.test.ts`. GBRA-284: `member-sources.ts` binds a source to its member (`access_member_sources`, v299; `gbrain access member source add|remove|list`); `attestedReadScope`, called in dispatch for every attested call and in `minions/tools/brain-allowlist.ts` for an attested job's tool calls, replaces the call's read grant with the grant minus personal sources bound to another member (every personal source under a scope read), so every resolver refuses or skips them like out-of-grant sources and nothing is added. Test: `test/qm-personal-sources.test.ts` (both engines). `ACTOR_DEFERRED_OPS` (`capture`, `extract_facts`, take writes, `list_write_conflicts`, and since GST-2249 W1 every page write; `test/qm-attest-write-boundary.test.ts` classifies every attestable mutating operation) are never attestable: refused by `parseAttestOps`, `bindCredential`, every call and the stored re-check, which also re-checks `attest_ops` for a queued write's operation and each job tool call. Under the header serve-http lists only attested tools and refuses `resources/read`. `attestedCallerAccess` is a one-member audience with privacy never relaxed (no granted sources, no hatch), never B's `may_act_for` path. Writes store `WriteAuthority.actingFor = {system, external_id, member}` and jobs `grant.actor`; `storedActorIdentity` re-resolves both through `actorCoverage` and refuses when the member changed. `linkMember` / `unlinkMember` / `listMemberLinks` back `gbrain access member link|unlink|links`; `linkMemberByEmail` (GST-1158) finds the member by its declared email (`members.ts` `memberByEmail`: `access_members.email`, migration v301, case-folded, unique, cleared on removal; `not_found` when none, `email_ambiguous` when several) and then links exactly as `linkMember`, from the local CLI and the owner-session routes in `src/commands/serve-http-access.ts` only; `--attest-actor` / `--attest-ops` on `auth rescope` (`members.ts`) only for a member-less legacy token or confidential client-credentials client. Migration v286. Tests: `test/access-qm-actor.test.ts` (both engines), `test/e2e/serve-http-qm-actor.test.ts`. Member facts (C2, GST-359): `member-facts.ts`. A remote `remember` from an attested actor or a lone-member credential (`callerMember`, never an audience of several) writes to `memory/members/<member>` (`memberFactPage`; `persistence/memory-prepare.ts` creates the page with `readable_by: [member:<id>]`), `visibility: private`, `infer_entity` off, the entity kept as `entity_slug`, unless the call passes `share: true` (GST-2243), which takes the ordinary world route to the subject's page; a member's explicit `visibility: "world"` is refused in `remember`'s validation (`member_share_required`), so a batch with one such item saves nothing. GST-2346 D1: the owner speaking for itself (`ownerSpeaksForItself`: `CallerAccess.owner`, no actor or audience, no subagent, no slug fence) takes the world route unless it passes `visibility: "private"` or the page or `facts.default_visibility` makes the default private (then its member page), is never refused `member_share_required`, and its `forget` of a fact off its member page takes the ordinary remote path when that path reads the fact. A fact off every member and scope page, on a page the owner reads under the GST-2490 rule with the opt-in off (`ownerReadPolicyFragment`) and may write as a member, a page whose readers name it included, with the fact's entity page judged the same way (`ownerReachesFact`, `forget-prepare.ts`), is withdrawn too: submission marks the request `owner_reach`, and preparation judges the owner again from the stored authority (`storedOwnerSpeaksForItself`, `page-visibility.ts`), so a writer that is no longer the owner gets `not_found`; a more trusted fact files the `forget_requires_owner` proposal. A member id whose page slug `slugifyPath` would change (`a--b`, `zed-`) is refused (`invalid_params`). The page must name that member alone (`memberPageIsOwn`, checked at submission and again in preparation, `memberPageNotOwned`), and remote writes under `memory/members/` go only to the caller's own page (`assertMemberPageWriter`, called from `ops/context.ts` `enforceClientSlugFence`, so every remote page write passes it; trusted local callers are unaffected). Reads widen a world-only fact list only by `memberFactAdmitSql` (a private fact on the caller's own live member page whose readers and folder rules admit the caller; `factVisibilitySql` in `engine-sql/facts.ts` and `search/fact-relevance.ts`), and `privateProvenanceFilterUnderPolicy` judges a member-page fact's source page as the caller (every other fact keeps the empty identity, so a fact from a page that names readers stays hidden from every remote caller). Writers never cross pages: `facts/single-prepare.ts` (`SingleFactIntent.page_slug`) and `trust/supersede-handlers.ts` dedup, supersede and contest only within the member page, and no other write matches a fact there (`onMemberPageSql`); a remote save there meets only the page's own withdrawals and those of a claim its member reads (`memberPageWithdrawal`), and the insert guards mark a member-page row only by its page's own withdrawals (`schema-migrations/*-member-page-withdrawal-scope.ts`), so a claim the member never read cannot refuse or expire its save; consolidation skips facts whose page names readers (`readersSourcedFactSql`). Per-person keys: `callerIdentityKey` joins the hot-memory cache key (`facts/meta-hook.ts`, `::xid=`), `callerSessionKey` the `delta` cursor (`ops/facts.ts`), `sameAttestedActor` gates receipts (`persistence/authority.ts` `ownRequestAccessible`) and replays (`persistence/journal.ts`) on the stored actor, else the stored audience, and `get_agent_job` and the owner-fenced `get_job`, `wait_job`, `get_job_progress`, `list_jobs` and `cancel_job` match the job's `grant.actor` (system, external id, member) and `grant.actingFor` (the same distinct audience entries; `jobActorSql` in `minions/types.ts`), so a job or receipt with an actor or audience reads as missing to the bare client and to other actors and audiences, and one with neither to every actor and audience. Tests: `test/access-member-facts.test.ts` (both engines), `test/access-member-sweep.test.ts` (every attestable op as Bob, the bare client and an unbound credential; `test/helpers/member-sweep.ts`), `test/e2e/serve-http-member-sweep.test.ts` (two members over a real `serve --http` on a keyless repo-less brain).
- `src/core/access/open-twins.ts` (GST-2603) — `openTwins(engine, pages, readers, cover)`: for the pages a label or rule preview changes, the live pages with the same slug in other sources that are not private by their own labels (`privateSnapshotFilterFragment`; no links are read) and that the empty identity or an enabled member outside `readers` passes by its own readers and folder rules (`readersAllowedSql`, `folderRulesAllowedSql` with `folderAccessFor`), since labels and rules apply per source. Read-only and bounded (`OPEN_TWINS_PAGES` 1000 pages checked, `OPEN_TWINS_LISTED` 50 named, `count` over all); never part of a preview hash. Callers: `repair/visibility.ts` (pages turning private, owner inside), `repair/readers.ts` (`--readers`), `repair/private-labels.ts` (`--class restore`) and `commands/access-rules.ts` `previewRules` (each narrowed rule's pages); `cover(source, slugs)` names the same repair or rule with `--source <other>`. Test: `test/label-repair-derived-stamps-gst2603.test.ts`.
- `src/core/access/federation-exposure.ts` (#8982) — `remotePagesFederationExposes(engine, source)`: the live pages of a source that name no readers and no folder rule, that the read paths' privacy rules (`privacyPartSql`) do not hide from a no-grant connection (#9068; skipped when `remotePrivacyRelaxed` says an operator opted out), and whose live revision (`pages.revision_principal_*`) or any version (`page_versions.write_principal_*`) a token or OAuth client wrote (revoked or deleted included; no record keeps a credential's member at write time, so an unbound, rebound or deleted one counts and each example names its member now; a tag change moves the revision attribution without a version, hiding the earlier author): count, the first five slugs, and shell-quoted `who-can-read` / `access rule add` commands. `remotePagesFederationExposesOrWarn` runs it, after the change commits, only for a change that added the source to the no-grant floor (federate reads the prior state under the source row lock), and turns a failed read into a stderr warning, so the caller's federation never changes. Read by `sources federate`, the unmanaged `sources restore` (stderr; `--json` as `pages_exposed`) and the managed `source_lifecycle` restore result. Pinned by `test/sources-federate-member-pages.test.ts` and `test/federation-exposure-private-9068.test.ts`.
-- `src/core/access/serves.ts` + `src/commands/access-serves.ts` (GST-363 PR 1) — whether a brain serves several people (`brainServes`: config `access.serves` `one`|`several` wins, else `access.serves_derived`, which migration v309's trigger keeps as `several` while 2+ members are enabled; `since` is `access.serves_since`, set once) and `gbrain access serves [several --members a,b [--yes]]`: preview, then config, members (kept when present), one folder rule `people/<member>/` per member through `addFolderRules` (`access-rules.ts`, the `rule add` preview-then-write path; a git store commits `.gbrain/access.yml` through the commit door), and one read-write token `member-<id>` per member through `auth-mint.ts` (the `auth create` mint) written to `<configDir>/member-keys/<id>.key` (0600, dir 0700, refused inside a git work tree: `access_serves_key_dir_in_git`). Idempotent on the member id; a token whose file is gone is reported, never re-minted. `GBRAIN_SETUP_ABORT_AFTER=serves-members|serves-rules|serves-key` is the crash seam. Doctor: `checks/unlabeled-people-folders.ts` fails a `people/<x>/` folder with pages no rule covers on a several-person brain. Tests: `test/setup-serves-several.test.ts` (both engines), `test/setup-serves-stdio-member.test.ts` and `test/setup-serves-upgrade.test.ts` (PGLite), shared setup in `test/helpers/setup-serves-box.ts`. GST-2670: `src/core/access/open-pages.ts` counts the pages every member's key reads (`openPages`: `accessAllowedSql` with the empty identity under `withoutCallerAccess`, so it never depends on the caller; private pages split out unless `remotePrivacyRelaxed` or a reading member's `private_pages` grant opens their source; throws `open_pages_unknown` when `gbrain_access_state_unreadable()`; Postgres runs it read-only under `SET LOCAL statement_timeout`), over the sources the bound tokens, OAuth clients and config `mcp.stdio_member` binding of enabled, non-labelled-only members other than the owner read (`credentialReadSources`, `stdioReadSources`), or every source when none reads one (doctor then reports information); `SENSITIVE_PAGE_TYPES` (`grants/shared-exposure.ts`) is the DM, chat, conversation and mail tier. `readOpenPages` never throws; `ServesReceipt.open_pages` / `open_pages_error` carry it in the preview and receipt (planned members counted against the source their keys will read, this run's `people/<member>/` rules excluded), `gbrain access serves` prints it, `--labelled-only` calls `setMemberLabelledOnly` after the members step (the owner in the roster is BLOCKED), doctor `checks/open-shared-pages.ts` warns on sensitive pages, and `printOpenPagesUpgradeNotice` runs in post-upgrade. Callers gate on `brainServes`, so a one-person brain runs no query. Test: `test/open-shared-pages.test.ts` (both engines, repo-less).
+- `src/core/access/serves.ts` + `src/commands/access-serves.ts` (GST-363 PR 1) — whether a brain serves several people (`brainServes`: config `access.serves` `one`|`several` wins, else `access.serves_derived`, which migration v309's trigger keeps as `several` while 2+ members are enabled; `since` is `access.serves_since`, set once) and `gbrain access serves [several --members a,b [--yes]]`: preview, then config, members (kept when present), one folder rule `people/<member>/` per member through `addFolderRules` (`access-rules.ts`, the `rule add` preview-then-write path; a git store commits `.gbrain/access.yml` through the commit door), and one read-write token `member-<id>` per member through `auth-mint.ts` (the `auth create` mint) written to `<configDir>/member-keys/<id>.key` (0600, dir 0700, refused inside a git work tree: `access_serves_key_dir_in_git`). Idempotent on the member id; a token whose file is gone is reported, never re-minted. GBRA-585 D: `--owner <id>` (setup passes `--owner` or the login name, `loginOwnerId` in `setup-serves.ts`) names the owner when none is configured (member added when missing, then `setOwner`), keeps a configured one, and lists live unbound tokens and OAuth clients in `unbound` with their `auth rescope … --member <owner>` command; it rebinds none. GBRA-585 A: keys it mints get the `federated` grant kind from `memberKeyReadSources` (`open-pages.ts`: the run's source, `company` when it exists, every source federated now); a kept key named `member-<id>` that already holds a list for the run's source gains new sources through `rescopeLegacyToken` and never loses one; any other kept key is untouched. `receipt.reads` (and `readsLines`) names the list and the company page and call counts; setup's `servesAfterLayout` re-runs the child after the layout step adds `company` in the same run. GBRA-585 C: `servesPreflight` (`setup-serves.ts`) runs the child as a preview on a brain that serves one person and refuses `setup_history_choice_required` through `historyRefusal` when its `open_pages` count is above 0 or unreadable, unless `--labelled-only` or `--open-history` is passed; `OpenPages.archive` counts the open `conversations/` pages. With `--labelled-only` on a brain with the `company` source, `planCompanyRule` (`access-serves.ts`) plans `receipt.company_rule`: one rule `company/` in source `company` readable by the owner (required), the run's members and every enabled member that is not labelled-only, written through `addFolderRules` (database store on a repo-less brain, git first on a repo one); a re-run only adds readers, and that widening is recorded and held for `gbrain access apply`. `GBRAIN_SETUP_ABORT_AFTER=serves-members|serves-rules|serves-key` is the crash seam. Doctor: `checks/unlabeled-people-folders.ts` fails a `people/<x>/` folder with pages no rule covers on a several-person brain. Tests: `test/setup-serves-several.test.ts` (both engines), `test/setup-serves-stdio-member.test.ts` and `test/setup-serves-upgrade.test.ts` (PGLite), shared setup in `test/helpers/setup-serves-box.ts`. GST-2670: `src/core/access/open-pages.ts` counts the pages every member's key reads (`openPages`: `accessAllowedSql` with the empty identity under `withoutCallerAccess`, so it never depends on the caller; private pages split out unless `remotePrivacyRelaxed` or a reading member's `private_pages` grant opens their source; throws `open_pages_unknown` when `gbrain_access_state_unreadable()`; Postgres runs it read-only under `SET LOCAL statement_timeout`), over the sources the bound tokens, OAuth clients and config `mcp.stdio_member` binding of enabled, non-labelled-only members other than the owner read (`credentialReadSources`, `stdioReadSources`), or every source when none reads one (doctor then reports information); `SENSITIVE_PAGE_TYPES` (`grants/shared-exposure.ts`) is the DM, chat, conversation and mail tier. `readOpenPages` never throws; `ServesReceipt.open_pages` / `open_pages_error` carry it in the preview and receipt (planned members counted against the source their keys will read, this run's `people/<member>/` rules excluded), `gbrain access serves` prints it, `--labelled-only` calls `setMemberLabelledOnly` after the members step (the owner in the roster is BLOCKED), doctor `checks/open-shared-pages.ts` warns on sensitive pages, and `printOpenPagesUpgradeNotice` runs in post-upgrade. Callers gate on `brainServes`, so a one-person brain runs no query. Test: `test/open-shared-pages.test.ts` (both engines, repo-less).
- `src/commands/repair-propose.ts` (GST-2670 phase 2) — `gbrain repair visibility --propose [--source <id>] [--out <dir>]`, preview only: gated on `brainServes` (a one-person or pinned-one brain gets "nothing to propose" before any pages query), it reads the open pages through `open-pages.ts` `withOpenScope` / `openPageSql` / `membersReadOpen` (the same predicates as the count), takes each page's `participants`, `attendees`, `to`, `from`, `cc` entries (`Name <a@b>` read as the address), matches each to an enabled member's declared email through `assertMemberEmail` (exact, case-folded; anything else is `unmatched`), groups pages by source and reader set with the owner (`ownerView`) first, writes one slugs file per set (0600, split at `READERS_MAX_PAGES`) under `<configDir>/visibility-proposals/` or `--out` (refused inside a git work tree with `gitRootAbove` from `access-serves.ts`: `repair_propose_dir_in_git`), and prints the `repair visibility --slugs-file --readers` command per set and the `access rule add --prefix` command per folder of `SENSITIVE_PAGE_TYPES` pages with no address list. Writes no label, rule, config or page. `src/commands/repair.ts` parses `--propose`/`--out` (only `--source`, `--out`, `--json` beside it) and dispatches before the kind run. Test: `test/repair-visibility-propose-gst2670.test.ts` (both engines, repo-less).
- `gbrain serve --stdio-member <id>` (GST-363 PR 3) — `parseStdioMemberFlag`, `registeredStdioMember` and `withStdioMember` live in `src/core/stdio-member-flag.ts` (kept out of `mcp-registration.ts` so serve and doctor pick up no registration flags); serve passes the value to `startMcpServer`, dispatch sets `OperationContext.stdioMember` only for an unauthenticated stdio call, and `caller.ts` resolves it live ahead of config `mcp.stdio_member` (a disabled or unknown member reads as nobody, no fallback). Stored writes stamp it on `WriteAuthority.stdioMember` (jsonb, no migration); a stdio watch uses principal id `registration` so the wake drain re-checks that member. Setup writes it into one claude-code or codex entry (`ClaudeSetupPlan`/`CodexSetupPlan.stdioMember`); inspection reports an owned entry's member so setup re-runs and `refreshHookLaunchers` carry it, and `setupRerunArgv` never names it.
- `src/core/access/requester-scope.ts` + `src/commands/doctor/checks/unscoped-shared-reads.ts` (GST-363 PR 2) — on a brain that serves several people (`servesPolicyFrom` in `search/private-visibility.ts`, read from the request config snapshot: explicit `access.serves` wins, else `access.serves_derived`; a brain pinned `one` never gates) a remote read from a connection bound to no member (no member identity, no audience, not attested, no `reads_unscoped`) is refused `requester_scope_required` before any work. Deny by default: every op not `mutating: true`, and every read-scope one (`think`), except `REQUESTER_SCOPE_EXEMPT` and `OWN_JOB_OPS` for a non-admin credential; `test/requester-scope.test.ts` pins the list and spies every handler. `requesterScopeGate` runs in `dispatchToolCall` after access resolves (attested calls exempt; an unreachable op keeps the unknown-tool envelope) and in `brain-allowlist.ts` `scopedJobAccess` per job tool call; a bound caller's access is never changed. `readsUnscoped`/`createdAt` come from the verifiers (`token-binding.ts` `credentialScopeFields`), else `credentialScopeFor`. Grace: 14 days from `access.serves_since` (migration v309's trigger sets it once) for connections created at or before it (unknown creation and stdio count as old), with `_meta.access.requester_scope`; `access.requester_scope_enforce false` (hosted) gives the notice only. An unreadable policy (`servesUnknown`) is read once more (`withServesReread`); a second failure refuses `requester_scope_unknown` (retryable). `assertCredentialScoped` refuses unbound `auth create`/`register-client` and `POST /admin/api/api-keys` (`credential_scope_required`); `--reads-unscoped [none]` changes go to the `access-reads-unscoped` audit file. `unscopedConnections` feeds doctor `unscoped_shared_reads`, `whoami` (`requesterScopeView`) and post-upgrade.
+- `src/core/access/implicit-placement.ts` (GBRA-585) — `withImplicitPlacement`: a trusted local `put_page` (`remote === false`, `localSourceImplicit`, no `source_id` param) on a brain that serves several people (`brainServes`) returns `placement` (`source_id`, `picked_by` one of `local_path`/`brain_default`/`sole_non_default`/`seed_default`, `readers` from `whoCanRead`, and a `note` naming the `--source` and `readable_by` fixes). Routing is unchanged; a one-person brain, a remote caller and a sourced put get nothing, and a failed read never fails the write. The live owner socket marks an unsourced CLI call implicit (`provider.ts`, `DispatchOpts.localSourceImplicit`). Test: `test/put-implicit-placement-gbra585.test.ts`.
- `src/core/access/stdio-bind-route.ts` + `src/commands/doctor/checks/shared-stdio-binding.ts` (GST-363 PR 2) — `stdioBindRoute()` is the one place that says how to bind an unbound stdio connection: `gbrain setup claude-code|codex --stdio-member <id>` for a harness one person uses (that harness entry, either engine), else a per-person `serve --http` key. The requester-scope refusal and notice, `gbrain access owner`'s Bind-one line and whoami's unbound note read it. Doctor `shared_stdio_binding` fails when `mcp.stdio_member` is set and `sharedStdioHarness()` (`setup-serves.ts`; a `hermes` on PATH counts only as a script, not React Native's compiled engine) finds OpenClaw or Hermes on a brain that serves several people (not applicable on a one-person brain); fix `gbrain config unset mcp.stdio_member`. `requesterScopeRefuses()` lets dispatch drop hot memory from the ops the gate does not cover for a connection it would refuse. Tests: `test/shared-stdio-binding.test.ts`.
- `src/core/ops/qm-memory.ts` (GST-359 D) — QM's memory provider pair. `memory_recall` reads the attested person's own last-24-hour facts on their member page (`listFactsSince` with `sourceMarkdownSlug`), then `rankFactsByQuestion` over the facts they may read, renders one plain line per fact (`plainFactText` strips fence and heading markers) and cuts at a line within `max_chars` (`boundFactLines`). A call that names `source_id` or `source_ids` (full surface only) reads as that scope instead: `recallSources` resolves them through `requestSourceScope` (a source outside the credential's grant is `permission_denied`), `SCOPE_READ_ACCESS` empties identity, actor and audience, so no own facts and no member-page fact are read, restricted pages stay hidden and privacy is never relaxed; the query is ranked on its first 2,000 characters (`MEMORY_RECALL_QUERY_CHARS`). `memory_write` validates 1-20 facts, derives each request id from uuidv5(member, idempotency_key) (`memoryWriteRequestId`) and saves through `remember`'s handler with `ctx.attestedOp = 'memory_write'`, which the stored write authority keeps (`WriteAuthority.attestedOp`) so publication and receipt reads re-check that operation's attest right. `qmMemoryToolResult` (dispatch) moves the result into `structuredContent` and leaves the model text in `content`; GST-1158 F2 does the same for an attested call to a contract v3 personal tool (`QM_PERSONAL_OPS`), keeping its JSON in `content` (a list as `structuredContent.results`; context_pack's text alone, like memory_recall), and dispatch measures that frame against the result cap again; each memory_recall fact carries `arm` (`own` or `ranked`, F5) and `own_page` (GST-2407: `member-facts.ts` `ownMemberFactIds`, the one set forget_fact's ownership gate also reads); `unlinkedRecallResult` is the empty success dispatch's `actorRefusal` returns for an unlinked person. Contract fixture: `scripts/build-qm-memory-contract.ts` writes `docs/contracts/qm-memory-provider/v1.json` (frozen, byte-identical) and `v2.json` (the scope read and write; `regen:all` artifacts; `v3.json` adds the personal tools with frozen result shapes; `v4.json` adds memory_propose, each personal tool's `scope_read` marking and `own_page`; `v5.json` marks context_pack `scope_read`, v4's markings frozen as `V4_SCOPE_READ_OPS`). Scope writes (GST-1113): `memory_write {source_id}` saves on `memory/scope` in a scope source listed in the credential's `attest_sources` (migration v293, on `access_tokens` and `oauth_clients`); `access/attest-sources.ts` holds `perCallWriteSource` (the one exemption from the one-write-source checks in `page-mutations.ts`, `memory-mutations.ts` and `persistence/authority.ts`, keyed to that slug and re-checked at publication through `actorCoverage(..., source)`), the sticky mark `sources.config.qm_scope` (set by `applyAttestSources` under row locks; `isSourceFederated` ignores federation on it), `assertScopeSourceGrant` (in `insertClientGrant`, `persistGrant`, `writeTokenGrant` and `insertUnifiedToken`) and `withoutScopeSources` (a person recall never reads a scope source). `member-facts.ts` `assertScopePageWriter` keeps other remote writers off `memory/scope`. Tests: `test/qm-scope-writes.test.ts` (both engines), `test/qm-memory-tools.test.ts` (both engines), `test/qm-personal-tools.test.ts` (v3 tools over dispatch, both engines), `test/qm-memory-contract.test.ts` (drift), `test/e2e/serve-http-qm-memory.test.ts` (keyless `serve --http`).
- `src/cli/enforced-member.ts` + `src/cli/enforced-member-classes.ts` + `src/cli/enforced-commit-push.ts`: enforced member mode ([guide](../../guides/enforced-member.md)). With `GBRAIN_ENFORCED_MEMBER` set, `enforcedGate` in `src/cli/main.ts` classifies the command before any dispatch (`enforcedClassOf`: read, write, allowed, silent or refused; anything unclassified is refused, exit 3, `enforced_member_refused`). An empty value, an unknown member or the owner id refuses everything. The gate classifies before help: a refused command refuses with `--help` too, and an allowed one prints only its static help. `checkEnforcedOpArgs` first refuses every write operation except `get_write_request` with reason `writes_off` (`refuseWritesOff`) when the brain's config `access.enforced_member_writes` (database only, read by `enforcedWritesMode`: `checked` or unset, `refuse_pages`, else `refuse`, also on a failed read) is not `checked`, before any member, page or source lookup, and `checkEnforcedCommitPush` refuses a named-path commit the same way under `refuse` before any path lookup; then it refuses a named source (`--source`, `--source-id`, `--source-ids`) the member cannot read or that is not registered, alike. Reads go through `dispatchToolCall` (with only the operation's declared params; the source travels as the call's `sourceId`) with `remote: true`, `transport: 'stdio'`, `stdioMember` and `enforcedMember: true` (dispatch forces `hidePrivate`, `owner: false` and no private-readable sources), minus other members' personal sources (`hiddenPersonalSources`; an explicit `--source` naming one refuses), and `namesHiddenPage` withholds any output that still names a hidden page. Writes stay trusted local writes (`ctx.remote` false): `checkEnforcedWrite` refuses a target the member cannot read (`memberPageView`) and any label change, and `remember` needs `--entity` naming a readable page (`checkEnforcedRemember`, the one decision point). `write-request` answers only ids in the member's receipt ledger (`recordEnforcedReceipts`, `configDir()/enforced-member/<member>.receipts`); any other id is swapped for a fresh one, so it answers as unknown. sync, `sources refresh` and `git commit-push` (checked by `checkEnforcedCommitPush`: every named path readable, no label or `.gbrain/` change, refused modes) run with output replaced by one line (`withWithheldOutput`, which also captures the fd-1 chain through `setStdoutCapture`); `doctor` prints only check names, statuses and counts (`withDoctorCounts`); sync and `sources refresh` take only their listed flags and a readable source (`syncSourceArg`); `entity` and every coverage notice drop the mention coverage count (`withoutCoverageCounts`); `timeline-add` refuses a gbrain fence marker; `hook` succeeds silently. The warm CLI socket, the persistence delegate and the skill-resolver fast path are skipped under the mode. Tests: `test/enforced-member.serial.test.ts`, `test/enforced-member-writes.serial.test.ts` and `test/enforced-member-writes-setting.serial.test.ts` (CLI subprocesses, both engines, repo-less and git; shared setup in `test/helpers/enforced-member-brain.ts`), `test/enforced-member-classes.test.ts` (every command and operation classified once), `test/enforced-member-writes-off.test.ts` (the switch's values and a failed read).
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.md
index 4bb0d5d832..2ebf1668a3 100644
--- a/docs/architecture/key-files/agent-contract.md
+++ b/docs/architecture/key-files/agent-contract.md
@@ -26,7 +26,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-
- `src/cli/json-guard.ts` — picks the `--json` guard mode for an invocation: on only when `jsonRequested(argv)` and the command-table record declares `json: 'document' | 'ndjson'`; wires the E11 `json_document_missing` hook (document mode, exit 0; the event records `command`, `version`, `guard: 'document'` and `exit_code: 0`, never argv values; `outcome` keeps its value, #6629/D26). The guard itself is `installStdoutPipeDelivery({ json })` in `src/core/cli-force-exit.ts`: stdout writes and console.log/info/debug go to stderr, only `writeStdoutFinal`/`writeNdjsonLine` reach fd 1, a non-zero exit with no document writes the fallback document, `spawnCliChild` pipes child stdout to stderr. Test: `test/cli-json-guard.test.ts`. A record whose subcommands differ in shape declares `jsonSubcommands` (keyed by the first positional after the command; `eval`). `writeCliError` adds `status:'error'` to the envelope under the ndjson guard; `writeCliRefusal` (cli-error.ts) keeps a site's pre-v1 stderr line and writes the envelope under `--json`. D5 (`test/cli-contract.test.ts`) has one row per declaration, `<command> <sub>` included.
- `scripts/check-agent-contract.ts` — syntax-only AST scanner (≈2 s) in `bun run verify` and `guards-manifest.tsv` (fixtures `test/fixtures/guards/check-agent-contract.ts/`). Rules: suggestion-less `OperationError`, `throw new Error` in ops/mcp/handlers, hand-built `fix`/`next_action` command strings, legacy advice keys, raw interactive stdin/readline/raw-mode outside `interaction.ts`/`consent.ts`, raw "re-run with --yes" strings outside `consent.ts`, `stdio: 'inherit'` outside `spawnCliChild`, marker literals outside `agent-output.ts`/`agent-markers.ts`, `verify.argv` naming a non-read-only command (read_only command-table records + a static read-only list), plus unregistered codes and code naming (never baselined). Two more never-baselined rules keep every refusal's next step site-specific: `defaulted-suggestion` (a function that builds an error through `opError`, `new OperationError`, `usageError`, `invalidParam` or `hostOnlyError` from a `*suggestion`/`*hint` parameter with a default, an optional marker or a `??` fallback) and `generic-suggestion` (a suggestion whose whole text is a denylisted phrase such as "see --help", "check your input" or "try again", at a constructor or at a call site of a file-local funnel). `funnelSites(files?)` lists every funnel call site (`invalid`, `fail`, `usage`, `deny`, …) with its literal suggestion texts, resolving file-level string constants; `test/helpers/agent-envelope.ts` (`expectFunnelSuggestions`, `envelopeFor`, `caught`) drives the per-funnel table tests in each module's owner test. Per-rule shrink-only baselines in `scripts/agent-contract-baselines/<rule>.tsv`; `--update` lowers them and refuses growth.
- `src/core/interop-notices.ts` — Lane F notice producers (pure; callers emit). `DEGRADED_STAGE_GUIDANCE` (closed, typed exhaustive over recall-affecting stages + the verbs' markers) → one `degraded_recall` notice (kind degraded: names the stages, says a thin result is not proof of absence; fix = the embeddings enablement or a doctor diagnostic; a `rerank_failed` stage names its reason, the `fused_order` fallback and the session's reranker-degraded call count, and when no other stage needs a fix its fix follows the reason: `timeout`/`rate_limited` repeat the same call after 5/20 s (`actor: provider`, `next: wait`), `auth` is the user's key (credentials), the rest run doctor verified by `reranker_health` (`test/rerank-degraded-notice.serial.test.ts`); none on a brain keyless by choice, whose why says no query text was sent and that `gbrain doctor --json` names the enable command). `embeddingOptedOutFor` reads the opt-out markers (search/query degraded reason `embedding_disabled`, recall `keyword_only_embedding_disabled` in `search_degraded` or `facts_degraded.reason`, think `QUESTION_EMBED_SKIPPED_EMBEDDING_DISABLED`); `factEmbeddingDisabled` (src/core/embedding-disabled.ts) gates every query and fact embed. With the call's `_meta.retrieval.coverage`, `degradedRecallNotice` leaves `projection_pending` out when no pending page could match the query, otherwise names the count in its why, and escalates when it is the only stage. That why is worded by class (#7492): text pages are being indexed; could-affect images (`could_affect.pending_images`, the `sealable`/`reimport` classes) never index on their own, so the why names `gbrain projections drain`, the paid re-import and doctor's `text_projection_readiness`, and when projection_pending is the only doctor stage the fix is that read-only check (`gbrain doctor --only text_projection_readiness --json`). `sourceBindingNarrowedNotice` (per-call info: a GBRAIN_SOURCE/.gbrain-source bound stdio read that came back empty while other sources are readable; fix = the explicit `source_id` read). `recallStagesFor` maps recall's `search_degraded` and `facts_degraded.reason` (question ranking) to stages. `recallInteropNotices` is dispatch's one producer call. `chatKeyFix` (credentials + paid, both providers, free fallback, never a key on a command line), `keylessThinkNotice`, `thinkNotSavedNotice`, `degradedDedupNotice`, `privateFactNotice` (#6606: a local... (line truncated to 2000 chars)
-- `src/core/sources-not-readable.ts` — `assertUnscopedReadReachesPages`, the `sources_not_readable` refusal (class host_only) dispatch runs after a handler's empty result (`emptyRead`, so a read that returns rows costs no extra query): an unscoped `search`/`query`/`recall`/`list_pages` (no `source_id`, no non-empty `source_ids`) from a remote connection with no source grant (no `allowedSources`, `hasSourceGrant` not true, no stdio binding; OAuth clients always carry a grant) whose `federatedSearchScope` holds no live page (for `recall` and `query`, no world fact either) while another live, unarchived source does. One `CASE WHEN EXISTS` read, fail-open on any error. The message and suggestion never name a hidden source; the fix is the host's `gbrain sources federate <source>` (`hostFix`, input `source`: ask the user), with the token rescope named in the suggestion. A scope holding pages that matched nothing and a brain with no pages read as before (`test/mcp-sources-not-readable.test.ts`).
+- `src/core/sources-not-readable.ts` — `assertUnscopedReadReachesPages`, the `sources_not_readable` refusal (class host_only) dispatch runs after a handler's empty result (`emptyRead`, so a read that returns rows costs no extra query): an unscoped `search`/`query`/`recall`/`list_pages` (no `source_id`, no non-empty `source_ids`) from a remote connection with no source grant (no `allowedSources`, `hasSourceGrant` not true, no stdio binding; OAuth clients always carry a grant) whose `federatedSearchScope` holds no live page every reader of its source can read (pages kept to named readers, or private when remote reads exclude them, do not count, and the message says so; for `recall` and `query`, no world fact either) while another live, unarchived source does (GBRA-585). One `CASE WHEN EXISTS` read, fail-open on any error. The message and suggestion never name a hidden source; the fix is the host's `gbrain sources federate <source>` (`hostFix`, input `source`: ask the user), with the token rescope named in the suggestion. A scope holding pages that matched nothing and a brain with no pages read as before (`test/mcp-sources-not-readable.test.ts`).
- `src/core/degraded-stamp.ts` — GBRA-200 degraded stamp (pure). `degradedStampFor(op, result, meta, notices)` derives `{reasons}` from the call's `_meta.retrieval.degraded` recall-affecting stages (keyword-only markers normalized to `embed_unavailable`; `projection_pending` dropped when no pending page could match), the result body's degraded fields (recall `search_degraded`/`facts_degraded`, `degraded_reason`, get_page `file_held`, think/synthesize `GATHER_*` warnings, search_exact, open_loops, rank_entities) and the call's `kind: degraded` result notices, read before the notice ledger dedupes them; null when clean. Dispatch writes `_meta.degraded` and appends `degradedStampLine` as the last content block; `src/cli/op-notices.ts` `withDegradedStamp` puts it on a `--json` object as `degraded`, else on stderr (the routed thin-client path uses the server's stamp). Vocabulary: AGENT_OPERATOR_v1.md, "Degraded stamp". Tests: `test/degraded-stamp.test.ts` (each class, pure), `test/degraded-stamp-paths.serial.test.ts` (dispatch on PGLite: provider down, timeout, rank bound, recall, think, keyless dedupe), `test/degraded-stamp-cli.test.ts` (real CLI).
- `src/mcp/status-mode.ts` + `src/commands/serve-status.ts` + `src/commands/serve-http-status.ts` + `src/core/serve-http-status-marker.ts` — F4 status-only serve, stdio and `--http`. cli.ts hands over a host-brain `serve` (not `--fail-fast`/`GBRAIN_SERVE_FAIL_FAST=1`) with no config, an unreadable config, a missing or repair-failed brain, or a PGLite lock held by a live holder; `runStatusModeServe` is the one entry point for both transports and logs `serve_status_mode_enter` / `serve_status_mode_recovered` (`reason`, `transport`, `elapsed_ms`) as one-line JSON on stderr. `probeStatus` reads config + `peekLock` only; `reprobe(state, connect)` is the one re-probe (no lock attempt while blocked, `resetReadinessMemo()` before the throw-only connect from `src/core/engine-connect.ts`); a check that must run on every re-probe hooks the `probeAgain` wrapper in `runStatusModeServe`. stdio: a gated lazy engine (`createDegradedEngine` with the configured `kind`, reconnect `statusReconnect`, ≤1 attempt / 5 s inside tool calls) marked with `StatusModeState`; `statusPayload` → `{status, reason, why (lock owner PID/transport, brain path, config path), fix, user_message, decisions, share_http_plan}`. `--http`: `runHttpStatusServe` binds one `node:http` listener with a mutable handler (`/health` 503 + `Retry-After: 5` + `instance`; `/mcp` stateless SDK server with only `gbrain_status`; every other route a 503 `serve_status_only` envelope), each response built from the allowlist in `httpStatusPayload`/`httpStatusEnvelope` with `reason` collapsed to `unavailable`; a single-flight chained 5 s tick runs the re-probe, and on a connect `runServe(..., { adoptServer })` builds the full app and swaps the handler on the same listener; a failed build disconnects the engine and stays status-only (`brain_unopenable`); SIGINT/SIGTERM during a recovery waits for it, then closes once. The marker `GBRAIN_HOME/serve-http-status-<port>.json` `{pid, instance_nonce, brain_id, bind, port, reason, since}`... (line truncated to 2000 chars)
- `src/mcp/initialize-context.ts` — per-initialize inputs for the generated instructions (`httpInstructionTools`: the tools/list filters with publish gates read on initialize; `instructionReadiness`: config plane + probed tier within 250 ms, HTTP view redacted) and `stdioCapabilityReadiness` (F2). Test: `test/mcp-capabilities-readiness.test.ts`.
diff --git a/docs/architecture/key-files/commands-1-continued.md b/docs/architecture/key-files/commands-1-continued.md
new file mode 100644
index 0000000000..d930da034d
--- /dev/null
+++ b/docs/architecture/key-files/commands-1-continued.md
@@ -0,0 +1,8 @@
+# Key files: Commands (1/6, continued)
+
+[Subsystem index](../KEY_FILES.md) · [Previous entries](commands-1.md). Read only the entries relevant to your change.
+Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
+
+- `src/commands/connect.ts` + `src/core/connect-probe.ts` — `gbrain connect <mcp-url> [--token <bearer>]` one-command coding-agent onboarding from a bearer token. Turns an MCP URL + token into a paste-ready `claude mcp add ... -H "Authorization: Bearer ..."` block (default) or, with `--install`, runs it directly and smoke-tests the token. Direct HTTP MCP — Claude Code talks straight to a remote `gbrain serve --http`, no local install needed. Token resolution: `--token` > `$GBRAIN_REMOTE_TOKEN` > placeholder (print) / error (install). The generated block tells the agent to call `get_brain_identity` + `list_skills` (the `LEARN_INSTRUCTION` export, which names `capture` — a starter-surface MCP op — alongside `put_page` for full-control writes) with a core-tools fallback for hosts without skill publishing. URL normalization appends `/mcp` to a bare host but REJECTS a scheme-less host; the pure registration helpers (`normalizeMcpUrl`, `isLinkLocalOrMetadata`, `buildClaudeMcpAddArgv` with its optional scope param — claude's default is `local`, so the harness lane passes `user` explicitly — `buildCodexMcpAddArgv`, `validateToken`, `redactToken`, `shellQuote`/`cmdString`, `issuerFromMcpUrl`, the `OAUTH_SECRET_NOTE` secret-hygiene constant, and `openclawThinClientBlock` — the honest openclaw wiring print: a scoped `gbrain init --mcp-only` thin-client block, deliberately NOT a stdio mcpServers config since that grants full local DB access) live in `src/core/mcp-registration.ts` (core must not import from commands; connect.ts re-exports them — `OAUTH_SECRET_NOTE` included — so its surface and tests are unchanged) and are unit-tested. Flags: `--token`, `--name <id>` (default `gbrain`, validated against `NAME_RE`), `--agent claude-code|codex|opencode|perplexity|generic`, `--install`, `--yes` (the user's approval for `--install`: `installConsent` asks through `requireConsent`, effects `credentials` + `persistent_install`, via the `isTTY`/`promptYesNo` seams; non-TTY without it exits 3 with the consent payload, whose argv omits the token value), `--force`, `--json` (token redacted unless `--show-token`), `--timeout-ms`. `connect` is in `CLI_ONLY` + `CLI_ONLY_SELF_HELP`; dispatched in `cli.ts:handleCliOnly` with no local DB connect. `AGENT_SPECS` drives per-agent rendering + `--install`: `claude-code` → `buildClaudeMcpAddArgv` (literal `-H "Authorization: Bearer <tok>"`); `codex` → `buildCodexMcpAddArgv` = `codex mcp add <name> --url <url> --bearer-token-env-var GBRAIN_REMOTE_TOKEN` (on the CONNECT lane Codex reads the token from the env var at runtime, never written to config — the harness lane in `src/core/bootstrap/harness.ts` is the deliberate exception, writing a managed block with the inline `http_headers = { Authorization = "Bearer <t>" }` credential (codex-cli >=0.149 rejects inline `bearer_token` for streamable_http at config load) because framework-spawned codex inherits no shell profile; `--install` runs it and prints an `export GBRAIN_REMOTE_TOKEN` hint when missing); `opencode` → `buildOpencodeMcpAddArgv` = `opencode mcp add <name> --url <url> --header "Authorization=Bearer {env:GBRAIN_REMOTE_TOKEN}"` (the interpolation is stored LITERALLY and resolved by opencode at read time — token never in argv/config/--json; `--install` writes the entry directly through `ConnectDeps.writeOpencodeRemoteEntry` → `opencode-json.ts` in env token mode, no binary required; `--force` maps to the writer's `allowReplaceOtherSource` so an OURS entry at an old url — a rotated serve — is replaceable, mirroring the exec lanes' `--force` semantics, while foreign same-name entries still refuse with url-appropriate copy: pick `--name`); `perplexity` + `generic` are `installable:false` and reject `--install`. `--oauth` (`supportsOAuth:true` = perplexity/generic only) emits an OAuth 2.1 client-credentials connector block (Issuer URL via `issuerFromMcpUrl` = mcp-url minus `/mcp`, Client ID, Client Secret) — least-privilege scopes + short-lived rotating tokens vs a long-lived full-access secret. Creds from `--client-id`/`--client-secret` (BYO) or `--register` (`deps.registerOAuthClient` shells `gbrain auth register-client <name> --grant-types client_credentials --scopes <DEFAULT_SCOPES="read write"> --token-endpoint-auth-method client_secret_post` and parses `Client ID:`/`Client Secret:`); `--oauth` rejected for claude-code/codex and incompatible with `--install`. `buildJson` is a generic shape (`agent`, `command`/`command_argv` null for perplexity/generic, `header`, `env_var`, oauth fields with redaction); the codex `command` carries only the env-var name, never the token. `cmdString(binary, argv)` POSIX-single-quotes args. `ConnectDeps` = `{isTTY, promptYesNo, hasBinary(bin), runBinary(bin, argv), probe, env(name), registerOAuthClient, writeOpencodeRemoteEntry}` — binary-generic so `claude` and `codex` share the exec path while opencode rides the writer member; `env` injectable for tests. Security: rendered command single-quotes the token so shell metacharacters can't run code when pasted; token validated before it lands in an HTTP header; link-local / cloud-metadata addresses (incl. IPv4-mapped IPv6 `::ffff:169.254.x.x` and AWS IMDSv2-over-IPv6 `fd00:ec2::254`) refused as a token-exfil guard while localhost/RFC1918/LAN stay allowed; token redacted from all error output. `src/core/connect-probe.ts` is the raw-bearer MCP smoke probe backing `--install`: connects the official MCP SDK `Client` over `StreamableHTTPClientTransport` with a STATIC `Authorization` header (no OAuth/discovery — distinct from `mcp-client.ts:callRemoteTool` which is OAuth-only and `remote-mcp-probe.ts:smokeTestMcp` which only sends `initialize`), runs the full `initialize` handshake via `client.connect()`, then calls `get_brain_identity` (read-scope, non-localOnly) to prove a tool call round-trips. Never throws — every failure maps to `{ ok: false, reason: 'auth' | 'unreachable' | 'timeout' | 'tool_error' | 'unknown', message }` so a wrong/expired token fails at setup, not on the agent's first request. `DEFAULT_PROBE_TIMEOUT_MS = 15_000` shared with `connect.ts`. `serve-http.ts` adds exported pure `skillPublishStatus(publishSkills)` for the startup banner `Skills: published / not published` line + a one-line `gbrain config set mcp.publish_skills true` stderr nudge when publishing is OFF. Docs: `docs/mcp/CODEX.md`, `docs/mcp/PERPLEXITY.md`, `docs/mcp/CLAUDE_CODE.md`, `docs/tutorials/connect-coding-agent.md`. Pinned by `test/connect.test.ts` (pure-helper + render, all five agents incl. the opencode writer-install lane) + `test/connect-bearer.test.ts` (raw-bearer probe + full OAuth chain register→connect→discovery→`/token` mint→`get_brain_identity`, client registered in `beforeAll` before serve takes the PGLite single-writer lock; drives real `claude` + `codex` binaries through `connect --install` with sandboxed `HOME`/`CODEX_HOME`, asserts registration + token never in Codex config, skips when a binary is absent) + `test/serve-stdio-roundtrip.test.ts` (spawns real `gbrain serve` stdio against a fresh `init --pglite` brain, drives the SDK client through `initialize`→`tools/list`→`tools/call`, asserts the advertised core-tool set including `capture`, a starter-surface MCP op) + `test/serve-skills-publish-nudge.test.ts`.
+
+- `src/commands/db-repair.ts` — `gbrain db-repair [--yes] [--apply-rewrites] [--json] [--force] [--undo-last-rewrite] [--dry-run]`: ENGINE-FREE Postgres-access repair, sibling of pglite-repair (PGLite brains are redirected there). Never calls connectEngine; default invocation is DIAGNOSE-ONLY (`--dry-run` is an explicit alias). Consent is tiered and flag-gated, never TTY-dependent: auto tier under `--yes` (bounded reconnects, pending migrations in-process, `CREATE EXTENSION vector`, `docker start` of gbrain's own container via `docker-postgres.ts`); rewrite tier under `--yes --apply-rewrites` only (config-file `database_url` rewrites — pooler form, session pooler, `?sslmode=require` — printed first, candidate connect-probed BEFORE persisting, receipted, undo-able); manual tier never applied (credentials/paused-project/env recipes printed — relaying the recipe IS the repair). `--apply-rewrites` without `--yes` is an error. Invariants: fix targets derive only from the CURRENT config URL, never error text; the prober uses exactly ONE connection (`poolSize: 1` — diagnosing pool exhaustion with a 10-connection pool would worsen the outage); rewrite cooldown is ≤24h per (reason, action) with `--force` bypass while auto-tier fixes are NEVER cooldown-blocked (availability first); every rewrite stores the prior URL in the 0600 `~/.gbrain/db-repair-undo.json` (a secret — never the redacted receipts) and `--undo-last-rewrite` (`--yes`-gated) restores it — undo runs INSIDE the advisory lock, emits the same `--json` envelope, validates the record's postgres:// scheme before restoring, and is itself reversible (the outgoing URL becomes the new undo record); an `O_EXCL`-created advisory lockfile blocks concurrent double-rewrites (check-then-write race closed; one stale-holder retry; other write failures stay fail-open); a healthy probe exits 0 "nothing to fix" (the forged-marker defense) and additionally REPORTS (never rewrites) stale DB-plane `engine`/`database_url` rows; the schema probe treats a ZERO-ROW `pg_extension` result as `pgvector_missing` (the query never errors on an absent extension); the docker arm matches the container's REAL inspected host port (`deps.docker.hostPort`) as well as the default 5434; a successful rewrite prints the "restart long-lived gbrain processes" note (config rewrites reach NEW processes only). Refusals: thin-client (no local DB), non-host brain resolution (a mount outage must never rewrite host config — mount-targeted repair is a filed TODO), PGLite (→ pglite-repair). Injectable `DbRepairDeps` prober/executor seam for tests; `defaultDeps.probeAccess` is also reused by the init ladder (one prober, one contract). Pinned by `test/db-repair.serial.test.ts`. D2 (`json: 'document'`): a healthy/fixed report is the pretty legacy document; an unfixed one (exit 1) is a one-line `database_error` envelope leading with the report keys (`reason` = diagnosis reason, fix = the tier's next step: `--yes` for auto, `--yes --apply-rewrites` with consent `credentials` for rewrite, none for manual); pre-probe refusals keep their stderr line and add an envelope (`unknown_flag`/`invalid_params` exit 2, `requires_local_engine`, `config_error`, `lock_busy`, `not_found`, `no_brain`). Healthy success shape: `test/e2e/cli-json-commands-postgres.test.ts`.
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.md
index 4071250265..39652fbba5 100644
--- a/docs/architecture/key-files/commands-1.md
+++ b/docs/architecture/key-files/commands-1.md
@@ -15,7 +15,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/anomalies.ts` — `gbrain anomalies [--since YYYY-MM-DD] [--lookback-days N] [--sigma N] [--json]`: cohort-level activity outliers. Calls `engine.findAnomalies(opts)`. Two cohort kinds: tag, type. At most 20 `page_slugs` per cohort (`page_slugs_complete: false`; local `--all` lists all; `test/anomalies-bounded-7246.test.ts`).
-- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + auth code in one transaction; `process.exit(1)` on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`; legacy tokens with no scopes grant grandfather to `read+write+admin` on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. Every SQL site routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` (and `executeRawJsonb` for the takes-holders `permissions` JSONB column) so `gbrain auth` works against PGLite; the takes-holders write goes through `executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])` which round-trips with `jsonb_typeof = 'object'`. `register-client` accepts `--source <id>` (write authority, scalar), `--federated-read <S1,S2,...>` (read scope, array), and `--token-ttl <seconds>` (per-client access-token TTL persisted to `oauth_clients.token_ttl`, bounds `TOKEN_TTL_MIN_SECONDS`=60 to `TOKEN_TTL_MAX_SECONDS`=7,776,000/90d) and prints the resolved `Write source` + `Federated reads`; clients without a `source_id` backfill to `'default'` via migration v60. The registration core is the exported `registerScopedClient(sql, engine, name, parsed, opts)` — exit-free, print-free, injected-handle (engine-bound callers like `agent register` pass the dispatcher's engine; a second `withConfiguredSql` engine self-deadlocks PGLite's single-writer lock), returns a `RegisteredClient` data object and throws on failure; the thin CLI wrapper owns exit/print. Its printer `formatRegisterClientOutput` is a BYTE-PINNED contract (connect.ts's `defaultRegisterOAuthClient` regex-scrapes `Client ID:`/`Client Secret:` from it in production) — pinned by `test/auth-register-client-output-pin.test.ts`. `preflightOauthClientColumns(sql)` probes `information_schema.columns` for the optional columns (`token_ttl`, `surface`, `federated_read`, `source_id`, `deleted_at`) so statement shapes are decided BEFORE any transaction — Postgres/PGLite abort the whole tx on any statement error (25P02) and SqlQuery has no savepoint seam, so "catch 42703 and continue" inside a tx is impossible; skipped optional writes surface as `RegisteredClient.skipped` with an apply-migrations hint. `gbrain auth clients [--usage] [--days N] [--json]` lists clients with scopes, per-client surface, write source (`source_id`), federated reads (`federated_read`) and the operation snapshot — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); `clientOperationsView` reports four distinct operation states (SQL NULL = `operations: "all"` with `includes_future_operations: true` and a re-pin `fix` naming `auth rescope --client <id> --operations <list>` or `--profile`; `[]` = deny-all; an explicit list; `unavailable` when the schema predates `allowed_operations`) and marks soft-revoked clients (`deleted_at`) `revoked` with no fix (`test/auth-clients-operations.test.ts`, both engines); `tokenLifetimeClampedClients` reads the migration's `clamp_token_ttl` / `shorten_access_tokens` audit rows so the listing marks clients whose access-token lifetime an upgrade brought inside 90 days (`token_lifetime_clamped` in `--json`); the `TOKEN_TTL_*` bounds are re-exported from `src/core/grants/model.ts`; `--usage` joins op-call counts and coverage via `src/core/mcp-usage.ts`. The bare `gbrain auth create <name>` form (no `--takes-holders`) mints a token via the exported pure `parseAuthCreateArgs(rest)`. Pinned by `test/auth-create-args.test.ts` + `test/auth-register-client-args.test.ts`. F3: `gbrain auth rescope` (`runRescope`) is the one grant editor for tokens (`--token`/`--id`) and OAuth clients (`--client`), with a bare-name resolver, `--migrate-legacy [--dry-run]`, and refusals printed as JSON on stdout under `--json`; `rescope-token`, `rescope-client` and `permissions set-takes-holders` are aliases routed through it.
+- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + auth code in one transaction; `process.exit(1)` on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`; legacy tokens with no scopes grant grandfather to `read+write+admin` on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. `--member` without `--scopes` mints `MEMBER_TOKEN_SCOPES` (read,write). Every SQL site routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` (and `executeRawJsonb` for the takes-holders `permissions` JSONB column) so `gbrain auth` works against PGLite; the takes-holders write goes through `executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])` which round-trips with `jsonb_typeof = 'object'`. `register-client` accepts `--source <id>` (write authority, scalar), `--federated-read <S1,S2,...>` (read scope, array), and `--token-ttl <seconds>` (per-client access-token TTL persisted to `oauth_clients.token_ttl`, bounds `TOKEN_TTL_MIN_SECONDS`=60 to `TOKEN_TTL_MAX_SECONDS`=7,776,000/90d) and prints the resolved `Write source` + `Federated reads`; clients without a `source_id` backfill to `'default'` via migration v60. The registration core is the exported `registerScopedClient(sql, engine, name, parsed, opts)` — exit-free, print-free, injected-handle (engine-bound callers like `agent register` pass the dispatcher's engine; a second `withConfiguredSql` engine self-deadlocks PGLite's single-writer lock), returns a `RegisteredClient` data object and throws on failure; the thin CLI wrapper owns exit/print. Its printer `formatRegisterClientOutput` is a BYTE-PINNED contract (connect.ts's `defaultRegisterOAuthClient` regex-scrapes `Client ID:`/`Client Secret:` from it in production) — pinned by `test/auth-register-client-output-pin.test.ts`. `preflightOauthClientColumns(sql)` probes `information_schema.columns` for the optional columns (`token_ttl`, `surface`, `federated_read`, `source_id`, `deleted_at`) so statement shapes are decided BEFORE any transaction — Postgres/PGLite abort the whole tx on any statement error (25P02) and SqlQuery has no savepoint seam, so "catch 42703 and continue" inside a tx is impossible; skipped optional writes surface as `RegisteredClient.skipped` with an apply-migrations hint. `gbrain auth clients [--usage] [--days N] [--json]` lists clients with scopes, per-client surface, write source (`source_id`), federated reads (`federated_read`) and the operation snapshot — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); `clientOperationsView` reports four distinct operation states (SQL NULL = `operations: "all"` with `includes_future_operations: true` and a re-pin `fix` naming `auth rescope --client <id> --operations <list>` or `--profile`; `[]` = deny-all; an explicit list; `unavailable` when the schema predates `allowed_operations`) and marks soft-revoked clients (`deleted_at`) `revoked` with no fix (`test/auth-clients-operations.test.ts`, both engines); `tokenLifetimeClampedClients` reads the migration's `clamp_token_ttl` / `shorten_access_tokens` audit rows so the listing marks clients whose access-token lifetime an upgrade brought inside 90 days (`token_lifetime_clamped` in `--json`); the `TOKEN_TTL_*` bounds are re-exported from `src/core/grants/model.ts`; `--usage` joins op-call counts and coverage via `src/core/mcp-usage.ts`. The bare `gbrain auth create <name>` form (no `--takes-holders`) mints a token via the exported pure `parseAuthCreateArgs(rest)`. Pinned by `test/auth-create-args.test.ts` + `test/auth-register-client-args.test.ts`. F3: `gbrain auth rescope` (`runRescope`) is the one grant editor for tokens (`--token`/`--id`) and OAuth clients (`--client`), with a bare-name resolver, `--migrate-legacy [--dry-run]`, and refusals printed as JSON on stdout under `--json`; `rescope-token`, `rescope-client` and `permissions set-takes-holders` are aliases routed through it.
- `src/commands/autopilot-retry-global.ts` — `gbrain autopilot --retry-global [--phase <name>] [--json]` (GBRA-130 A-10): clears `retry_at` on the backed-off phase streaks in `autopilot.global_maintenance.progress` (one phase, or all), keeping each count, so the next brain-wide pass runs the phase again; names a running `autopilot-global-maintenance` job, whose next progress save can restore the back-off. Test: `test/pathological/a10-global-maintenance-stamp.test.ts`.
- `src/commands/autopilot-pause.ts` — engine-free `gbrain autopilot pause [--reason <text>]` / `resume`: writes or removes the operator marker `autopilot-operator-paused` (`autopilotOperatorPauseMarkerPath` in `src/core/autopilot-paths.ts`, with `autopilotPaused()` and `autopilotPauseReason()`). The daemon loop and job workers honor it like the migration hold; `--install` (and so `gbrain upgrade`) clears only a leaked migration hold, and resume never clears a migration or restore hold. Test: `test/autopilot-operator-pause.test.ts`.
@@ -45,6 +45,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/config/contextual-mode-hint.ts` — `contextualModeHint(sourceId?)` (#5012 item 6), printed after `config set search.contextual_retrieval` and `sources set-cr-mode`: existing pages keep the mode recorded at import, the new mode applies to later imports, and `gbrain repair contextual-mode [--source <id>] --apply` stamps pages with none.
- `src/commands/config/facts-values.ts` — `config set` value checks for `facts.*` keys, called from `setConfigWithDecideHooks` before the write: `facts.page_write_notability_filter` (#6231) must be a `NOTABILITY_FILTERS` value (`invalid_params` with a `config get` verify, nothing written), and `facts.drain_*` keeps `drain-config.ts`'s validation. Pinned by `test/config-set.test.ts`.
-- `src/commands/connect.ts` + `src/core/connect-probe.ts` — `gbrain connect <mcp-url> [--token <bearer>]` one-command coding-agent onboarding from a bearer token. Turns an MCP URL + token into a paste-ready `claude mcp add ... -H "Authorization: Bearer ..."` block (default) or, with `--install`, runs it directly and smoke-tests the token. Direct HTTP MCP — Claude Code talks straight to a remote `gbrain serve --http`, no local install needed. Token resolution: `--token` > `$GBRAIN_REMOTE_TOKEN` > placeholder (print) / error (install). The generated block tells the agent to call `get_brain_identity` + `list_skills` (the `LEARN_INSTRUCTION` export, which names `capture` — a starter-surface MCP op — alongside `put_page` for full-control writes) with a core-tools fallback for hosts without skill publishing. URL normalization appends `/mcp` to a bare host but REJECTS a scheme-less host; the pure registration helpers (`normalizeMcpUrl`, `isLinkLocalOrMetadata`, `buildClaudeMcpAddArgv` with its optional scope param — claude's default is `local`, so the harness lane passes `user` explicitly — `buildCodexMcpAddArgv`, `validateToken`, `redactToken`, `shellQuote`/`cmdString`, `issuerFromMcpUrl`, the `OAUTH_SECRET_NOTE` secret-hygiene constant, and `openclawThinClientBlock` — the honest openclaw wiring print: a scoped `gbrain init --mcp-only` thin-client block, deliberately NOT a stdio mcpServers config since that grants full local DB access) live in `src/core/mcp-registration.ts` (core must not import from commands; connect.ts re-exports them — `OAUTH_SECRET_NOTE` included — so its surface and tests are unchanged) and are unit-tested. Flags: `--token`, `--name <id>` (default `gbrain`, validated against `NAME_RE`), `--agent claude-code|codex|opencode|perplexity|generic`, `--install`, `--yes` (the user's approval for `--install`: `installConsent` asks through `requireConsent`, effects `credentials` + `persistent_install`, via the `isTTY`/`promptYesNo` seams; non-TTY without it exits 3 with the consent payload, whose argv omits the token value), `--force`, `--json` (token redacted unless `--show-token`), `--timeout-ms`. `connect` is in `CLI_ONLY` + `CLI_ONLY_SELF_HELP`; dispatched in `cli.ts:handleCliOnly` with no local DB connect. `AGENT_SPECS` drives per-agent rendering + `--install`: `claude-code` → `buildClaudeMcpAddArgv` (literal `-H "Authorization: Bearer <tok>"`); `codex` → `buildCodexMcpAddArgv` = `codex mcp add <name> --url <url> --bearer-token-env-var GBRAIN_REMOTE_TOKEN` (on the CONNECT lane Codex reads the token from the env var at runtime, never written to config — the harness lane in `src/core/bootstrap/harness.ts` is the deliberate exception, writing a managed block with the inline `http_headers = { Authorization = "Bearer <t>" }` credential (codex-cli >=0.149 rejects inline `bearer_token` for streamable_http at config load) because framework-spawned codex inherits no shell profile; `--install` runs it and prints an `export GBRAIN_REMOTE_TOKEN` hint when missing); `opencode` → `buildOpencodeMcpAddArgv` = `opencode mcp add <name> --url <url> --header "Authorization=Bearer {env:GBRAIN_REMOTE_TOKEN}"` (the interpolation is stored LITERALLY and resolved by opencode at read time — token never in argv/config/--json; `--install` writes the entry directly through `ConnectDeps.writeOpencodeRemoteEntry` → `opencode-json.ts` in env token mode, no binary required; `--force` maps to the writer's `allowReplaceOtherSource` so an OURS entry at an old url — a rotated serve — is replaceable, mirroring the exec lanes' `--force` semantics, while foreign same-name entries still refuse with url-appropriate copy: pick `--name`); `perplexity` + `generic` are `installable:false` and reject `--install`. `--oauth` (`supportsOAuth:true` = perplexity/generic only) emits an OAuth 2.1 client-credentials connector block (Issuer URL via `issuerFromMcpUrl` = mcp-url minus `/mcp`, Client ID, Client Secret) — least-privilege scopes + short-lived rotating tokens vs a long-lived full-access secret. Creds from `--client-id`/`--client-secret` (BYO) or `--register` (`deps.registerOAuthClient` shells `gbrain auth register-client <name> --grant-types client_credentials --scopes <DEFAULT_SCOPES="read write"> --token-endpoint-auth-method client_secret_post` and parses `Client ID:`/`Client Secret:`); `--oauth` rejected for claude-code/codex and incompatible with `--install`. `buildJson` is a generic shape (`agent`, `command`/`command_argv` null for perplexity/generic, `header`, `env_var`, oauth fields with redaction); the codex `command` carries only the env-var name, never the token. `cmdString(binary, argv)` POSIX-single-quotes args. `ConnectDeps` = `{isTTY, promptYesNo, hasBinary(bin), runBinary(bin, argv), probe, env(name), registerOAuthClient, writeOpencodeRemoteEntry}` — binary-generic so `claude` and `codex` share the exec path while opencode rides the writer member; `env` injectable for tests. Security: rendered command single-quotes the token so shell metacharacters can't run code when pasted; token validated before it lands in an HTTP header; link-local / cloud-metadata addresses (incl. IPv4-mapped IPv6 `::ffff:169.254.x.x` and AWS IMDSv2-over-IPv6 `fd00:ec2::254`) refused as a token-exfil guard while localhost/RFC1918/LAN stay allowed; token redacted from all error output. `src/core/connect-probe.ts` is the raw-bearer MCP smoke probe backing `--install`: connects the official MCP SDK `Client` over `StreamableHTTPClientTransport` with a STATIC `Authorization` header (no OAuth/discovery — distinct from `mcp-client.ts:callRemoteTool` which is OAuth-only and `remote-mcp-probe.ts:smokeTestMcp` which only sends `initialize`), runs the full `initialize` handshake via `client.connect()`, then calls `get_brain_identity` (read-scope, non-localOnly) to prove a tool call round-trips. Never throws — every failure maps to `{ ok: false, reason: 'auth' | 'unreachable' | 'timeout' | 'tool_error' | 'unknown', message }` so a wrong/expired token fails at setup, not on the agent's first request. `DEFAULT_PROBE_TIMEOUT_MS = 15_000` shared with `connect.ts`. `serve-http.ts` adds exported pure `skillPublishStatus(publishSkills)` for the startup banner `Skills: published / not published` line + a one-line `gbrain config set mcp.publish_skills true` stderr nudge when publishing is OFF. Docs: `docs/mcp/CODEX.md`, `docs/mcp/PERPLEXITY.md`, `docs/mcp/CLAUDE_CODE.md`, `docs/tutorials/connect-coding-agent.md`. Pinned by `test/connect.test.ts` (pure-helper + render, all five agents incl. the opencode writer-install lane) + `test/connect-bearer.test.ts` (raw-bearer probe + full OAuth chain register→connect→discovery→`/token` mint→`get_brain_identity`, client registered in `beforeAll` before serve takes the PGLite single-writer lock; drives real `claude` + `codex` binaries through `connect --install` with sandboxed `HOME`/`CODEX_HOME`, asserts registration + token never in Codex config, skips when a binary is absent) + `test/serve-stdio-roundtrip.test.ts` (spawns real `gbrain serve` stdio against a fresh `init --pglite` brain, drives the SDK client through `initialize`→`tools/list`→`tools/call`, asserts the advertised core-tool set including `capture`, a starter-surface MCP op) + `test/serve-skills-publish-nudge.test.ts`.
-
-- `src/commands/db-repair.ts` — `gbrain db-repair [--yes] [--apply-rewrites] [--json] [--force] [--undo-last-rewrite] [--dry-run]`: ENGINE-FREE Postgres-access repair, sibling of pglite-repair (PGLite brains are redirected there). Never calls connectEngine; default invocation is DIAGNOSE-ONLY (`--dry-run` is an explicit alias). Consent is tiered and flag-gated, never TTY-dependent: auto tier under `--yes` (bounded reconnects, pending migrations in-process, `CREATE EXTENSION vector`, `docker start` of gbrain's own container via `docker-postgres.ts`); rewrite tier under `--yes --apply-rewrites` only (config-file `database_url` rewrites — pooler form, session pooler, `?sslmode=require` — printed first, candidate connect-probed BEFORE persisting, receipted, undo-able); manual tier never applied (credentials/paused-project/env recipes printed — relaying the recipe IS the repair). `--apply-rewrites` without `--yes` is an error. Invariants: fix targets derive only from the CURRENT config URL, never error text; the prober uses exactly ONE connection (`poolSize: 1` — diagnosing pool exhaustion with a 10-connection pool would worsen the outage); rewrite cooldown is ≤24h per (reason, action) with `--force` bypass while auto-tier fixes are NEVER cooldown-blocked (availability first); every rewrite stores the prior URL in the 0600 `~/.gbrain/db-repair-undo.json` (a secret — never the redacted receipts) and `--undo-last-rewrite` (`--yes`-gated) restores it — undo runs INSIDE the advisory lock, emits the same `--json` envelope, validates the record's postgres:// scheme before restoring, and is itself reversible (the outgoing URL becomes the new undo record); an `O_EXCL`-created advisory lockfile blocks concurrent double-rewrites (check-then-write race closed; one stale-holder retry; other write failures stay fail-open); a healthy probe exits 0 "nothing to fix" (the forged-marker defense) and additionally REPORTS (never rewrites) stale DB-plane `engine`/`database_url` rows; the schema probe treats a ZERO-ROW `pg_extension` result as `pgvector_missing` (the query never errors on an absent extension); the docker arm matches the container's REAL inspected host port (`deps.docker.hostPort`) as well as the default 5434; a successful rewrite prints the "restart long-lived gbrain processes" note (config rewrites reach NEW processes only). Refusals: thin-client (no local DB), non-host brain resolution (a mount outage must never rewrite host config — mount-targeted repair is a filed TODO), PGLite (→ pglite-repair). Injectable `DbRepairDeps` prober/executor seam for tests; `defaultDeps.probeAccess` is also reused by the init ladder (one prober, one contract). Pinned by `test/db-repair.serial.test.ts`. D2 (`json: 'document'`): a healthy/fixed report is the pretty legacy document; an unfixed one (exit 1) is a one-line `database_error` envelope leading with the report keys (`reason` = diagnosis reason, fix = the tier's next step: `--yes` for auto, `--yes --apply-rewrites` with consent `credentials` for rewrite, none for manual); pre-probe refusals keep their stderr line and add an envelope (`unknown_flag`/`invalid_params` exit 2, `requires_local_engine`, `config_error`, `lock_busy`, `not_found`, `no_brain`). Healthy success shape: `test/e2e/cli-json-commands-postgres.test.ts`.
+Continued in [Commands (1/6, continued)](commands-1-continued.md).
diff --git a/docs/architecture/key-files/commands-5-continued.md b/docs/architecture/key-files/commands-5-continued.md
index fefd5af896..92ac131e08 100644
--- a/docs/architecture/key-files/commands-5-continued.md
+++ b/docs/architecture/key-files/commands-5-continued.md
@@ -14,7 +14,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/guests.ts` — `gbrain guests init [--source <id>] [--writer <kind>:<id>]... [--yes]` (GBRA-504): previews by default; `--yes` creates or marks the source database-only, federated, `guest: true` with `trust_ceiling`, and its `guest_sources` row in one transaction (`core/guests/sources.ts`). Refuses a source with a local_path. `gbrain guests promote <slug> [--to] [--source] [--guest-source] [--json]` runs op `promote_guest_note` as the trusted local CLI (`core/guests/promote.ts`); `gbrain guests grant-owner-clients [--source] [--yes] [--json]` previews, then adds the guest source to owner credentials' read lists (`core/guests/owner-credentials.ts`).
- `src/commands/sources-writers.ts` — `gbrain sources writers <id> [--add|--remove <w>] [--clear] [--json]`: lists or changes `guest_sources.writers`; refuses a source that is not a guest source.
-- `src/commands/sources-add-next.ts` — GBRA-156: `noGrantFloorNext(engine, id)`, the federate step `sources add` prints when a new non-federated source leaves the no-grant floor (`localFederatedSourceIds(engine, 'default', 'seed_default')`, else `['default']`) holding no live page a remote read may show (private pages excluded when remote reads exclude them); returns `{ command, argv, why }` or null. One read, no write; `sources add` treats a failed read as no step.
+- `src/commands/sources-add-next.ts` — GBRA-156: `noGrantFloorNext(engine, id)`, the federate step `sources add` prints when a new non-federated source leaves the no-grant floor (`localFederatedSourceIds(engine, 'default', 'seed_default')`, else `['default']`) holding no live page a remote read may show (private pages excluded when remote reads exclude them); returns `{ command, argv, why }` or null; the notice asks the user whether the source should be shared (a private source needs nothing). One read, no write; `sources add` treats a failed read as no step.
- `src/commands/sources.ts` — `gbrain sources {list,add,remove,archive,restore,archived,purge,current,status,audit,refresh,set-calendar}`; `set-calendar` dispatches to `src/commands/sources-set-calendar.ts`, and `set-cr-mode` prints `contextualModeHint` after the write. `refresh` dispatches to `src/commands/sources-refresh.ts` (argument parsing, stdout text or `--json` result/refusal objects, exit 1 on refusal or an unfinished sync; protocol in `src/core/persistence/worktree-refresh.ts`, where a fence lock timeout (55P03) becomes `refresh_lock_timeout` naming the open transactions holding the fenced tables, and any other untyped throw becomes an `internal_error` refusal whose `why` carries the stack and whose fix names the refresh row it left for the next run to resume, GBRA-250). `current [--json]` calls `resolveSourceWithTier()` and prints `source_id`, `tier` (`flag | env | dotfile | local_path | brain_default | seed_default`), and optional `detail` (decision table in `skills/conventions/brain-routing.md`). `status [--json]` — read-only per-source dashboard (last sync, staleness, page count, embedding coverage, unacked failures); thin wrapper around `buildSyncStatusReport` + `printSyncStatusReport` from `src/commands/sync.ts`; `--json` emits stable `{schema_version: 1, sources, ...}` on stdout; filters input to `local_path IS NOT NULL AND archived IS NOT TRUE`. `audit <id> [--json]` — read-only dry-run disk scan for size distribution + would-blocks + junk-pattern hits WITHOUT touching the DB; walks `sources.local_path`, reads each markdown file, runs `assessContent()` from `src/core/content-sanity.ts`, aggregates by verdict (`ok | warn_oversize | hard_block_junk_pattern`). The live `runStatus` health table gains a `BACKFILL` column between `EMBED` and `FAILS` (`active(N)` beats `queued(N)` beats `idle`, from `SourceMetrics.backfill_active` / `backfill_queued` in `src/core/source-health.ts`) so operators see deferred `embed-backfill` minion work after `sync --all` exits 0; `jobCountsBySource` in `source-health.ts` widens its `minion_jobs` SQL with two `COUNT(*) FILTER (WHERE name = 'embed-backfill' AND ...)` aggregates (best-effort, all-0 on pre-minions brains). `remove` pre-checks OAuth-client referents (guided refusal via `formatClientReferentsBlock` — the raw FK violation never reaches the operator), then commits the row DELETE atomically with an in-tx referents re-check (a registration racing the pre-check maps to the same guided refusal); durability-scaffolding teardown (`unhardenBrainRepo`: hook/cron/credential) runs only AFTER the commit, so a refused delete leaves the scaffolding intact. `purge` runs the same referents pre-check before its hard DELETE. `add` without `--federated` or `--no-federated` stores the source non-federated and warns on stderr that a remote token or agent connection with no source grant cannot read it, naming `gbrain sources federate <id>` and `gbrain auth rescope --token <name> --sources <id>`; when the no-grant floor (the default source plus federated sources) then holds no live page it also prints `next: gbrain sources federate <id>` on stdout (`noGrantFloorNext` in `sources-add-next.ts`). `add --json` prints one object (`id`, `name`, `local_path`, `remote_url`, `federated`, and `next` with `command`/`argv`/`why` when that step applies) and moves the human lines to stderr (`test/sources-add-federation-warning.test.ts`). `federate <id> [--json]` and `restore <id>` print on stderr, after the change commits, the pages a remote credential wrote without readers that the change makes readable to no-grant connections (`core/access/federation-exposure.ts`); `federate --json` prints one object (`id`, `federated`, `pages_exposed`) and moves the human lines to stderr. Pinned by `test/content-sanity.test.ts`, `test/import-file-content-sanity.test.ts`, `test/source-health.test.ts`.
- `src/commands/status-funnel.ts` — `gbrain status --funnel [--json] [--enable | --delete]` (D8 adoption funnel): engine-free, dispatched from `src/cli/main.ts` before any connect so it works before `gbrain init` and on a thin client; reads and writes only the local record through `src/core/funnel.ts`. Guide: `docs/guides/adoption-funnel.md`. Tests: `test/funnel.test.ts`, `test/funnel-cli.test.ts`.
diff --git a/docs/architecture/key-files/google-and-loops-more.md b/docs/architecture/key-files/google-and-loops-more.md
index 124a744e53..ca6ceb99f9 100644
--- a/docs/architecture/key-files/google-and-loops-more.md
+++ b/docs/architecture/key-files/google-and-loops-more.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md) · [Previous entries](google-and-loops.md).
- `src/core/harness/oauth-setup.ts` + `client-setup.ts` — explicit client metadata projection, flow selection, native OAuth setup/private-file validation, and live-row-locked secret delivery recovery. Public PKCE needs no journal; confidential exports validate the retained secret against current registration, and machine exports discard cached tokens. Unknown/mixed flows refuse until an explicit supported flow is selected.
-- `src/core/harness/capabilities.ts` + `src/mcp/capabilities.ts` — Shared effective-grant orientation for OAuth whoami and authenticated `gbrain://capabilities`. A stored client token lifetime outside 60 to 7,776,000 seconds (`AuthInfo.tokenTtlSeconds`) reports `token_ttl_invalid`, and the delegation repair template then includes a `--token-ttl <APPROVED_TTL_SECONDS>` choice, since every grant write validates the merged lifetime. The resource preserves the exact seven-tool surface; source, operation, scope, fence and server-gate restrictions remain enforced at dispatch. `grant_diagnosis` (shared with doctor `grant_new_ops_available` through `grantOperationGaps`, `grantAge` and `grantRescopeArgvs`) counts the operations the grant's scopes allow but its operation snapshot, its client pin or the server ceiling block, names none of them, keeps inferred grant age apart (`intent_unknown` without catalog provenance), and builds host commands only from the verifier's principal. No worker probe or per-tool database query during discovery (one audit read for provenance when a snapshot excludes operations). Shared administration guidance explains separate owner authority, links the MCP admin runbook, and exposes an admin URL only for a configured credential-free HTTP MCP endpoint. Stdio never infers an HTTP address. D4 in band: `grantBlockedNotice(diagnosis, {refused})` builds the `grant_blocked_operations` notice (blocker counts, grant age apart, missing scope only when refused) and `grantRepairAction` the host-owned repair (preview argv, `then` apply, verify = doctor `grant_new_ops_available` or `whoami`; server ceiling alone → the read-only doctor check). Dispatch (`grantBlockedNotices`) delivers it once per (principal, session) or, stateless, per (principal, grant revision).
+- `src/core/harness/capabilities.ts` + `src/mcp/capabilities.ts` — Shared effective-grant orientation for OAuth whoami and authenticated `gbrain://capabilities`. A stored client token lifetime outside 60 to 7,776,000 seconds (`AuthInfo.tokenTtlSeconds`) reports `token_ttl_invalid`, and the delegation repair template then includes a `--token-ttl <APPROVED_TTL_SECONDS>` choice, since every grant write validates the merged lifetime. The resource preserves the exact seven-tool surface; source, operation, scope, fence and server-gate restrictions remain enforced at dispatch. `grant_diagnosis` (shared with doctor `grant_new_ops_available` through `grantOperationGaps`, `grantAge` and `grantRescopeArgvs`) counts the operations the grant's scopes allow but its operation snapshot, its client pin or the server ceiling block, names none of them, keeps inferred grant age apart (`intent_unknown` without catalog provenance), and builds host commands only from the verifier's principal. No worker probe or per-tool database query during discovery (one audit read for provenance when a snapshot excludes operations). Shared administration guidance explains separate owner authority, links the MCP admin runbook, and exposes an admin URL only for a configured credential-free HTTP MCP endpoint. Stdio never infers an HTTP address. D4 in band: `grantBlockedNotice(diagnosis, {refused})` builds the `grant_blocked_operations` notice (blocker counts, grant age apart, missing scope only when refused; a client narrowed on purpose — grant age `provenance_recorded`, nothing predating, every blocker an operation snapshot — gets it only on a refused call) and `grantRepairAction` the host-owned repair (preview argv, `then` apply, verify = doctor `grant_new_ops_available` or `whoami`; server ceiling alone → the read-only doctor check). Dispatch (`grantBlockedNotices`) delivers it once per (principal, session) or, stateless, per (principal, grant revision).
- `src/commands/mcp.ts` + `mcp-provision.ts` + `harness-connect.ts` — Host-side grant/preview/CAS and recoverable private delivery, followed by installation inside the intended harness. Codex, Claude Code and opencode installs (`src/core/harness/install.ts`) store the bearer token inline in the harness config; `inlineTokenReceipt` adds `token_storage`, `config_path`, `renew_command`, `if_exposed` (invalidate-tokens preview/apply, renew, reload; `renew_command` carries `--fresh-token` for renewable handoffs so it always exchanges a new token) and a `token_warning` when a Git working tree would commit the file, and `harness-connect.ts` repeats them on stderr in human mode without printing the token (#5775; `test/harness-token-receipt.test.ts`). Running PGLite hosts are administered through their authenticated API, never by opening a second database process. CLI status uses the delivery-aware exit verdict. `mcp-admin.ts` and `mcp-admin-http.ts` provide engine-free owner commands with explicit-file/env credential precedence, in-memory sessions, private native exports, versioned lifecycle previews, and safe stage/outcome/remedy receipts. Unknown mutation outcomes require inspection instead of automatic repetition. `runMcp` also dispatches `gbrain mcp expose` to `runMcpExpose` (dynamic import of `./mcp-expose.ts`; HELP carries the expose lines so the flag registry harvests them) and sets the CLI exit verdict from its returned code. `mcpNeedsEngine(args)` is true only for `grant` without an owner credential (`--admin-token-file` or `GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) and outside help; `admin`, `expose`, and `verify` never open the database.
- `src/commands/mcp-expose.ts` — `gbrain mcp expose [--port N] [--funnel] [--surface] [--enable-dcr] [--no-tailscale] [--no-service] [--no-install] [--force] [--dry-run] [--yes] [--json]` / `--status` / `--remove`: publishes `gbrain serve --http` on the user's Tailscale tailnet (Serve by default, Funnel only with the explicit flag) and keeps it running as a user service. `runMcpExpose(args, deps?)` returns the exit code (0 done, 1 failed, 2 needs `--yes`, the prompt was declined, or a step is pending — a tailnet feature to enable, Tailscale login, tailnet certificate). Arg validation via `validateHarnessArguments` (exclusive pairs `--status`/`--remove`, `--funnel`/`--no-tailscale`, `--dry-run`/`--status`); the help text names every flag and the `verify.local` / `verify.tailnet` checks. Ordered named checks — `plan` (platform, execution environment, engine kind from `loadConfig()`; thin clients are refused with "run on the brain host"; `engine === 'unknown'` — no config or an unreadable one — without `--no-service` is refused as `no_brain_config` / exit 1 with next action `gbrain init` BEFORE consent, because a service around a missing brain only crash-loops, while `--dry-run` still prints the plan with the refusal marked and exits 0; on a PGLite engine `deps.pgliteHolder` (default `probeLivePgliteHolder` from `src/core/bootstrap/uninstall.ts`, a read-only lock-file probe) is consulted with `cfg.database_path`, and a live holder that is not our own managed service — receipt present with `service.state` `running`/`loaded` — adds a `Lock` plan line plus a `pglite_lock` check with status `warn` (never a stop); `--no-tailscale` over an existing receipt whose `tailscale.dns_name` is set (a live Serve/Funnel mapping) is refused BEFORE consent as `tailscale_receipt_present` / exit 1 with next actions `gbrain mcp expose --remove --yes` and the re-run without the flag — `--dry-run` marks it `WOULD BE REFUSED`; then probes `127.0.0.1:<port>` with `probeOccupied(d, port, url)` — occupied when EITHER the injectable `deps.tcpProbe` (default `defaultTcpProbe`, one `node:net` connect, socket destroyed on every outcome; true on connect, false on refusal / timeout / throw) accepts a TCP connect OR the `/health` fetch RESOLVES with ANY status (2xx, 404, 500), so a non-HTTP listener counts too; only both rejecting is free — and refuses a foreign listener with no receipt claiming that port as `foreign_listener` BEFORE anything is published unless `--no-service`; the message names the interrupted-run escape hatch `gbrain mcp expose --remove --yes`; `probeHealth` (`res.ok`) stays the bar for `verify.local` / `verify.tailnet` / `--status`), `consent` (shared `confirmOrFinish` for publish and `--remove`: one stderr y/N prompt on a TTY; declining is `pending` / exit 2 / `declined` with "Nothing changed. Re-run with --yes to confirm."; non-interactive without `--yes` prints the plan and exits 2 / `confirmation_required`; every re-run hint is rendered by `rerunCommand(opts)` — the user's publish flags + `--yes`), `tailscale.binary` (install plan: brew cask on macOS — then `open -a Tailscale` and a bounded poll of `tailscale status --json`, up to 20 attempts 1s apart, breaking as soon as the app's daemon answers and otherwise falling through to the login step's daemon-not-running handling — official installer on Linux, `--no-install` → exit 1), `tailscale.login` (Linux `sudo tailscale set --operator=<user>` non-fatal then flagless `sudo tailscale up` — `sudo` is put in front of the binary ONLY when `isSystemTailscaleBinary(binary)` holds (one of `TAILSCALE_BINARY_CANDIDATES`, literally or via `realpathSync`); a user-writable `tailscale` found on PATH stops the step as `pending` / exit 2 / `tailscale_login_manual` with the message "tailscale at <path> is not a system install, so gbrain will not run it with sudo. If you trust that binary, sign in yourself (this runs it as root): `sudo <path> set --operator=$USER && sudo <path> up`, then re-run: <rerun>" — the command is `tailscaleManualLoginCommand(binary)`, naming the discovered path shell-quoted, because a binary outside sudo's `secure_path` is exactly this case — and never spawns `sudo`; macOS `tailscale up`; bounded wait via `GBRAIN_TAILSCALE_LOGIN_TIMEOUT_MS`), `tailscale.identity` (MagicDNS name → `public_url`; pre-checks so `tailscale serve`/`funnel` — which wait interactively instead of failing when a feature is off — are never started blind: empty `CertDomains` → `pending` / exit 2 / `tailscale_https_not_enabled` with `TAILSCALE_ADMIN_DNS_URL`; `--funnel` with `funnelCapable === false` → `tailscale_funnel_not_enabled` with the ACL admin + Funnel KB URLs; `funnelCapable === null` proceeds), `tailscale.publish` (reads the serve config through `readServeView`, which FAILS CLOSED — it returns `{ view: ServeStatusView | null, stderr, status }` with `view: null` when `tailscale serve status --json` exits non-zero / is killed (`status: null`) or when stdout is not a JSON object per `parseServeStatusStrict`; an empty document / `{}` / `null` from exit 0 is the legitimately empty view — a null view before `--bg` is described once by `describeServeReadFailure` (`{ kind, detail, fix }` from one `classifyTailscaleError` call), records `tailscale.publish` = fail and returns exit 1 with reason `tailscale_<kind>` without publishing; a null view after `--bg` is `tailscale_publish_unconfirmed` naming the read failure; refuses a `/` handler proxying a different port, a foreground session or a raw TCP forward without `--force` as `foreign_serve_config` — `next_actions` says `tailscale serve status`, only `message` explains `--force`; `PUBLISH_TIMEOUT_MS` (60s) bounds `--bg`, `SERVE_OFF_TIMEOUT_MS` (30s) every `--https=443 --set-path=/ off` and `STATUS_READ_TIMEOUT_MS` (15s) both status reads; a `status: null` timeout is `unknown` with a run-by-hand hint; stderr classified by `classifyTailscaleError` as the second line of defense; switching our own handler's shape pre-clears ONLY in the funnel → tailnet direction (`funnel --https=443 --set-path=/ off` before `serve --bg`, because `serve --bg` over a Funnel mount keeps `AllowFunnel`; tailnet → funnel is one atomic `funnel --bg`), and when that pre-off was followed by a failed publish (non-zero, timeout, or unconfirmed) `restorePrevious` best-effort re-publishes the previous shape with `tailscaleServeArgv(port, { funnel: true })`, re-reads the view, and appends to the `tailscale.publish` detail whether "the previous funnel handler was restored" or "could NOT be restored"; the existing receipt is never touched on those paths), `admin_token` (ensure the 0600 token file, never printed), `service` (launchd / systemd user unit / `manual` fallback with the exact foreground and `nohup` commands; a `--no-service` re-run carries the existing receipt's service block unchanged and does not rewrite the wrapper; `service_install_failed` still writes the receipt with `service.state: 'stopped'` before exit 1 so `--status`/`--remove` can clean up the published handler; the receipt is ALSO written right after a successful service step — service state as probed at that moment — before verify runs, so a kill during verify always leaves `--status`/`--remove` something to find), `verify.local` (wall-clock `/health` polling up to 20s, timeout → `warn`, exit 2, `verify.tailnet` skipped), `verify.tailnet` (up to 30s, `pending` is exit 2 — EXCEPT when the last probe's rejection was a name-resolution failure per `mcp-expose-probe.ts`: Bun's `fetch` rejects an unresolvable host and a refused connection with the same "Unable to connect. Is the computer able to access the url?" / `ConnectionRefused`, so after a rejected fetch the URL's hostname (never an IP literal or `localhost`) is handed to `deps.lookup` — default `dns.promises.lookup`, bounded by the probe timeout — and a rejection with code `ENOTFOUND` / `EAI_AGAIN` / `EAI_NONAME` / `EAI_NODATA` / `DNS_ENOTFOUND` (or a message naming one) is the verdict, the fetch-message regex staying a secondary hint; a name that resolves but does not answer stays `pending`: then the check is `warn` with `unresolvedDetail(dnsName)` — "this host cannot resolve <name> (MagicDNS may be off here: `tailscale set --accept-dns=true`); devices that do resolve it may already reach the server" — and the run exits 0, since this host's resolver says nothing about the server), `receipt` (rewrites the early receipt with the settled state — the supervisor is re-probed once verify.local ran — keeping `created_at`). The admin-token, service and verify steps run inside one try: a THROW there after this run's `--bg` succeeded but BEFORE the early receipt is rolled back by `rollbackAfterThrow(d, s, opts, published, error, receiptWritten)` — the fresh handler is turned off again with `tailscaleServeOffArgv({ funnel })` only when no `/` handler for our port existed before the run (a pre-existing one is left in place), a `rollback` check records what happened — "turned off again" is claimed only when a re-read of the serve view after an exit-0 `off` no longer shows our port; an exit-0 `off` whose re-read still shows it is a `warn` "NOT turned off (… the handler is still present)", an unreadable re-read is a `warn` "state unknown", and an `off` that exits non-zero or throws is a `warn` whose message says the handler was NOT turned off — no receipt is written, and the error is re-thrown so the outer catch reports `mcp_expose_failed` with a message naming the handler state; once the early receipt is on disk (`receiptWritten`, checked first) a throw tears nothing down (`rollback` = skipped pointing at `--status` / `--remove --yes`), because the receipt makes everything findable (the non-throwing `service_install_failed` path keeps its partial receipt). Success banner and `next_actions` gate the local-agent line on the engine: Postgres → `gbrain bootstrap harness --yes --port N`; PGLite → pre-mint (`gbrain auth create … --scopes read,write` before the service runs) + `--token`, or the scoped `mcp grant … --url http://127.0.0.1:N/mcp --admin-token-file …` + `gbrain connect … --install` path, and "host-side commands fail with `live_serve` — administer through the running server". `--json` emits one stdout document `{ status, receipt, checks[], next_actions, reason?, message? }` with prose on stderr; every `inherit` subprocess redirects its stdout to stderr under `--json`. `--status` and `--remove` read the receipt through `readExposeReceipt`'s shape guard (a partial receipt is `not_exposed` / "nothing to remove", never a crash) and execute the tailscale binary from `resolveReceiptBinary`: the receipt's recorded path is honored only when it still exists AND is either what `findTailscaleBinary` finds now or one of `TAILSCALE_BINARY_CANDIDATES`, otherwise discovery wins — a path in a receipt is data, never a licence to run it. the probes — `probeHealth` (`res.ok`), `probeOccupied` (any response, or an accepted TCP connect), the bounded never-throwing `tryFetch` → `FetchOutcome { res, unresolved }`, `pollHealth` → `{ ok, unresolved }` with the LAST probe's resolution verdict, `unresolvedDetail`, `defaultTcpProbe`, `defaultLookup` — live in `src/commands/mcp-expose-probe.ts` and take the narrow `ProbeDeps` slice of the resolved deps (`fetch`, `tcpProbe`, `lookup`, `now`, `sleep`, `healthIntervalMs`); `defaultTcpProbe` is re-exported here so its import site never moved; `isLiveService(state)` is the one definition of "the supervisor reports our service" (`running` or `loaded`) used by the lock-holder exemption, the service check, `--status` and both `--remove` paths; `serviceLabel` builds on `serviceKindLabel` (`launchd <label>` / `systemd (user) <unit>`). `--status` runs its four independent probes (serve config, supervisor state, local and tailnet `/health`) concurrently with `Promise.all` and still reports the checks in the fixed order `receipt`, `tailscale.publish`, `service`, `verify.local`, `verify.tailnet`; an unreadable serve config (null view) is a FAILED `tailscale.publish` check / exit 1, never "handler present"; a tailnet `/health` rejected for name resolution is `verify.tailnet` = warn (same `unresolvedDetail`), not `pending`, and does not by itself make the exit non-zero. `--status` with NO receipt is `runStatusWithoutReceipt`: it runs the read-only `probeLeftovers(d, opts.port)` (`--port` is honored) and, when the wrapper, the plist / unit or a live service, or a `/` handler on `:443` proxying the port is found, emits one `warn` check per artifact (`receipt`, `service`, `tailscale.publish`, `files`), pushes `recoveryCommand(port, force)` (`gbrain mcp expose --remove --yes`, `--force` only when a handler stands alone with no wrapper / service corroborating it, `--port N` when non-default) to `next_actions`, and finishes `error` / exit 1 / `leftovers_without_receipt` (also under `--json`); an unreadable serve status alone is a caveat warn, not a leftover; nothing found keeps the `not_exposed` answer (exit 0, `--json` exit 2). `--remove` (consent; decline is `pending` / exit 2) probes the supervisor and removes a service that exists even when the receipt says skipped — `recordServiceUninstall` prints the uninstall notes, and when `launchdBootoutFailed(result)` (a `launchctl bootout failed: …` / `unload failed: …` note, i.e. a non-"not loaded" failure) the `service` check is `warn` pointing at `launchctl print gui/$(id -u)/com.gbrain.serve` and "the launchd job (bootout failed)" is added to "Left in place"; it returns the one-line service summary quoted below — then clears only gbrain's own serve/funnel handler through `turnOffOurHandler` (Funnel off first; every `off` is `--https=443 --set-path=/ off`, scoped to our `/` mount; the serve config is re-read only after an `off` command ran, otherwise the view already read is reused; a failed re-read is reported as `unknown` — a warn, never "gone"; a foreign port on `:443` gets "nothing to turn off"). `--remove` never reports success while our handler survives: when `turnOffOurHandler` returns `remaining` as a handler (`tailscale.publish` = fail) or `'unknown'` (= warn), `finishHandlerNotRemoved` keeps the receipt AND the wrapper (mirroring the unreadable-status branch), records `receipt` = skipped "kept: …", pushes `tailscale serve status` + the re-run to `next_actions`, says which service outcome already happened, and exits 1 with reason `handler_not_removed`; `--remove` never runs `tailscale serve reset`, never uninstalls or logs out, keeps the admin token unless `--force` (deleted through the same `unlinkQuietly` as the wrapper and receipt), and unlinks the wrapper / receipt / token ONLY when the path's directory is the serve directory — a receipt path elsewhere is left untouched and named in "Left in place" (also in the plan). The receipt's recorded `plist_path` / `unit_path` are data, never a licence: `uninstallServeService` is always handed the computed `d.plistPath` / `d.unitPath` (home + the fixed label / unit name), and a recorded path that differs is not touched and is named in "Left in place" as "recorded in the receipt but not the expected location". A null serve view during `--remove` fails closed: `tailscale.publish` = fail "could not read tailscale serve status; handler left as is", reason `tailscale_serve_status_unreadable`, exit 1, and the receipt AND wrapper are kept so a re-run finishes the job. With NO receipt, `runRemoveWithoutReceipt` recovers from what is on disk through the same `probeLeftovers` `--status` uses (`wrapperPath(serveDir)`, the launchd plist / systemd unit or a `running`/`loaded` service, a `/` handler on `:443` proxying `opts.port` — `--port` may accompany `--remove`, default 3131); inside it the supervisor chain (`probeServiceTarget` → `serveServiceState`) and the `readServeView` read run concurrently under `Promise.all` (the binary is resolved synchronously first) and the plan / checks are emitted in the fixed order afterwards; the re-run hints come from `recoveryCommand`. The handler is turned off only with corroborating gbrain evidence — the wrapper present, our unit/plist present, or the supervisor reporting our service live — or with `--force`, because another tool may proxy `:443` to the same port: a handler standing alone is reported (`tailscale.publish` = warn naming the proxy target and `--force`, next action `gbrain mcp expose --remove --yes --force`) and left in place on the "not exposed — nothing to remove" exit-0 path; with `--force` the plan line says so. Otherwise it prints a "Recovering without a receipt" plan (`receipt` check = warn), takes consent as usual, removes exactly those artifacts (service via the supervisor — the same `recordServiceUninstall` bootout-failure warn applies — wrapper, the handler — funnel off first when `AllowFunnel` lists the host), leaves the admin token file, and finishes `removed` with reason `recovered_without_receipt`; a handler that survives the `off` is `handler_not_removed` / exit 1 here too, with the wrapper deliberately KEPT as the corroboration the re-run needs (`files` = skipped "kept: the wrapper"; the re-run hint carries `--force` when no wrapper is left); an unreadable serve status on this path (gbrain evidence present, `serveUnreadable` set) fails closed exactly like the receipt path — the service, when found, is still uninstalled, the plan says the handler cannot be checked and the wrapper is kept, `tailscale.publish` = fail "…; handler state unknown", `files` = skipped "kept: the wrapper" (or "nothing (no wrapper was found)"), `next_actions` = `tailscale serve status --json` + the recovery command (`--force` when no wrapper is left), exit 1 with reason `tailscale_serve_status_unreadable` and message "could not read tailscale serve status; handler state unknown"; when nothing of ours is found the answer stays "not exposed — nothing to remove", exit 0 (an unreadable serve status is then only the caveat warn — there is nothing to keep and a handler alone would not be touched anyway). Every filesystem/exec effect goes through injectable deps so tests run against a fake runner in a tmpdir. Success guidance separates owner login, native OAuth registration, and machine grant/install. It uses the expose-managed owner file only when installing or keeping that service; publication with `--no-service` and no managed service instead requires the existing server's independently configured owner credential. Publishing receipts and health checks do not certify client authorization or native activation. The `Next` block, and a fully verified `--status`, add one-click client lines from `connector-install-links.ts` (Cursor always, Claude only for a Funnel receipt); `--json` carries them as `install_links` only when at least one link exists.
- `src/core/connector-install-links.ts` — pure builders for one-click client links: `cursorInstallLink(mcpUrl, name='gbrain')` (Cursor's documented `cursor://anysphere.cursor-deeplink/mcp/install?name=…&config=…`, config = base64 of `JSON.stringify({ url })`, then `encodeURIComponent`), `claudeConnectorLink(mcpUrl, name='GBrain')` (Anthropic's documented custom connector install link, `https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=…&connectorUrl=…`), `connectorInstallLinks(mcpUrl, isPublic)` (Claude only when `isPublic`, since claude.ai connects from Anthropic's cloud) `installLinkLines(links, isPublic)` (the two-column human lines) and `printInstallLinks(mcpUrl, isPublic, say)` (builds, prints, returns the links for `--json`). Every builder returns null unless the URL parses as absolute `https:` with a hostname and no userinfo, so a link never carries a credential. `test/connector-install-links.test.ts` pins the docs' gbrain.io links to these builders.
diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.md
index 217b19e2e0..c9baa6def1 100644
--- a/docs/architecture/key-files/google-and-loops.md
+++ b/docs/architecture/key-files/google-and-loops.md
@@ -44,6 +44,6 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding
- `src/core/backup/{archive,snapshot,quarantine,private-path}.ts` — bounded full-PGLite snapshots with checksums, credential-reference exclusions and fresh-root restoration. Portable entry validation rejects traversal, Windows aliases and case/normalization/file-directory collisions independently of native confinement. Recorded path flavor controls nested managed-path rebasing; unrecognized absolute page origins stay unchanged with reconnect guidance. Hold the database lock, detect changing inventories, detach external roots and quarantine unfinished jobs without deleting spending evidence. Windows uses direct .NET file/directory security APIs through bounded built-in PowerShell, without cmdlets, to protect new empty work/root/archive-temp paths before payload writes. Readback requires the current owner, protected DACL and exact deduplicated owner-plus-SYSTEM full-control rules, inheritance and propagation; unavailable enforcement refuses without changing existing parents or source data. Never replace the source installation. `backup-portability-native.serial.test.ts` checks real restore, fresh-process reopen, failure preservation and platform-native access controls with an independent read-only ACL inspector.
- `src/core/backup/preflight.ts` — #6649: before `createPgliteBackup` takes the lock, `pgliteBackupPreflight` refuses a flat or symlinked data dir (`unmanaged_database_path`) and an estimated archive over `BACKUP_ARCHIVE_MAX_BYTES` (`backup_too_large`: `estimatedTarBytes` counts tar headers and padding, plus managed files), both with the ask-user physical-copy runbook fix. `backup.ts` renders those two codes as their own envelope (legacy `reason` kept) instead of `storage_error`. Doctor's `pglite_data_dir` (`backupSizeCheck` in `checks/db-connection.ts`) warns on a healthy PGLite brain from 75% of the cap. `test/backup-preflight-6649.serial.test.ts` uses sparse files and runs the restore drill.
- `src/core/harness/registry.ts` — Canonical adapter identities, supported transports, credential-delivery mechanisms, guide links and dated evidence; legacy connection/register vocabularies derive their facts here. `scripts/build-harness-docs.ts` emits the user-facing adapter reference. A `manual` adapter such as `hermes` (stdio, `docs/mcp/HERMES.md`) installs as `pending` with its guide; no adapter claims a runtime-tested session without dated evidence.
-- `src/core/harness/credentials.ts` + `delivery.ts` + `install.ts` — Private credential handoff and host delivery journal, ownership-preserving native configuration and isolated thin launchers. A committed active client and matching current secret are prerequisites for recovery. Machine handoffs preserve optional POST/Basic authentication methods. Native setup is a distinct nested-client artifact; metadata reads never access journals or SDK client objects containing hashes. Configuration removal and server revocation are separate actions.
+- `src/core/harness/credentials.ts` + `delivery.ts` + `install.ts` — Private credential handoff and host delivery journal, ownership-preserving native configuration and isolated thin launchers. A committed active client and matching current secret are prerequisites for recovery. Machine handoffs preserve optional POST/Basic authentication methods. Native setup is a distinct nested-client artifact; metadata reads never access journals or SDK client objects containing hashes. Configuration removal and server revocation are separate actions. `readCredentials` throws `PlainBearerKeyFile` for a file that holds one bare bearer key (a `member-keys/<member>.key`) instead of a handoff, so `harness-connect.ts` can print the bearer-token `gbrain connect` command for it (`test/connect-member-key-gbra585.test.ts`).
[Continue this subsystem](google-and-loops-continued.md) · [More entries](google-and-loops-more.md).
diff --git a/docs/architecture/key-files/shared-skills.md b/docs/architecture/key-files/shared-skills.md
index adeccb064a..9bb15cb0d0 100644
--- a/docs/architecture/key-files/shared-skills.md
+++ b/docs/architecture/key-files/shared-skills.md
@@ -5,7 +5,7 @@
- `src/core/shared-skills/{schema-all,schema,persistence-schema,membership-schema,access-schema}.ts` supplies shared schema migration/bootstrap SQL. Access DDL explicitly enables row-level security for bypass-capable owners even when the database-wide event trigger is unavailable. Protocol guards reject old consumer claims and writes before filesystem effects, each with SQLSTATE 42501 and a fixed `<code>: <diagnostic>` message; the request and effect guards refuse `writer_coordinator_required: writer state is unreadable to this database role` when the writing role cannot see the `persistence_brain` floor, and activation refuses with the same message any role that row-level security filters on `sources` or the request, effect, worktree and binding tables (only the table owner or a BYPASSRLS role activates). During publication `persistence/publication-failure.ts` types them by innermost guard frame plus exact diagnostic (#7777: `writer_upgrade_required`, `writer_not_quiesced`, `unsupported_mutation_protocol`, or `writer_coordinator_required` with relationship `unreadable_state`) and `connector-errors.ts` `guardRefusalHint` names the remedy (also the role remedy `UNREADABLE_STATE_HINT` for any guard's `unreadable_state`, whose raise's `state` table `guardDetail` keeps owner-only, #7780) (receipts via `receiptDeliveredHint`, docs anchor `protocol-guard`, and writer status `recent_failures[].next_action`; `test/protocol-guard-refusal-7777.test.ts`, both engines, checks every 42501 raise in `persistence-schema.ts` is typed); elsewhere the caller gets the raw 42501, which generic database output labels `permission_denied`. Their function bodies are exported alone so a migration replaces them without re-creating triggers. `src/core/persistence/{protocol,skill-activation,bundle-files}.ts` implements explicit owner/quiescence activation and bounded whole-set recovery while preserving the existing page target and permanent receipt identity.
- `src/core/shared-skills/{membership,membership-authority,membership-types,adapter}.ts` implements own-principal enrollment, source/policy-bound follow approval, issued batch acknowledgments and conflict-safe immutable local caches. Acknowledgments are self-reported delivery, never vendor-native activation. Enforced library admission rechecks freshness and requirements; native instruction routers remain advisory until separately observed. The adapter's leave treats a server `membership_inactive` (its own enrollment epoch was left or re-enrolled past) as remote cleanup complete (`remote_membership_reason: superseded`), so harness rotation converges; `gbrain bootstrap harness --refresh-skills` re-runs `join` to adopt the current epoch.
- `src/core/harness/{shared-skills,native-router}.ts` connects the enrollment protocol to target-local installation and ownership-tracked Claude Code, Codex and opencode router placement. Native registration, restart and actual task use are separate states. Removal keeps modified files and reports retained native state.
-- `src/core/shared-skills/{setup,setup-bundle,setup-files,migration,migration-export}.ts` owns combined-content roots, compile-safe starter skills, staged legacy adoption and explicitly approved DB-only export with round-trip validation. `installPackagedSharedSkills` resumes (or keeps, once committed) the caller's newest packaged adoption of the source incarnation's `gbrain-memory` pack before admitting one, since the adoption key binds the release-stamped `skillpack.json` and README (#8453). Existing roots, opt-outs, private/excluded skills and grant ceilings survive upgrades. `src/commands/migrations/shared-content.ts` integrates previews and recurring pending-stage reconciliation into the migration runner. The 0.53 migration retakes an inventory that never completed at a corrected root (#5569), moves a DB-only export checkpoint that stopped before its source was bound (stage `inventory` or `exported`, no started claim) to another absent `--content-root` and rechecks the checkpoint's inventory (#8528): a root inside a Git worktree is refused before any page is staged, the old staging directory is removed under the lock only when it holds nothing but the export's own bytes (else the move is refused, naming it), a filled earlier root is kept and named in `earlier_roots` and `pending_actions`, and every run refuses if the checkpoint changed while it waited for its lock, refuses at inventory a pack whose adoption would exceed `packFiles` (A-NEW-4), and accepts a post-inventory change only through `--accept-reviewed-inventory <source>=<inventoryDigest>` printed in the conflict reason (#5476).
+- `src/core/shared-skills/{setup,setup-bundle,setup-files,migration,migration-export}.ts` owns combined-content roots, compile-safe starter skills, staged legacy adoption and explicitly approved DB-only export with round-trip validation. `installPackagedSharedSkills` resumes (or keeps, once committed) the caller's newest packaged adoption of the source incarnation's `gbrain-memory` pack before admitting one, since the adoption key binds the release-stamped `skillpack.json` and README (#8453). Existing roots, opt-outs, private/excluded skills and grant ceilings survive upgrades. `src/commands/migrations/shared-content.ts` integrates previews and recurring pending-stage reconciliation into the migration runner; its console summary counts only sources that owe host work by `sharedSkillsHostWork`'s rule, so a source whose only open stage is an unverified client enrollment (`members`) or a policy-blocked projection is printed as information (`(no host action owed)`), never as "need host action" (GBRA-585; `test/shared-skills-notice-fresh-brain.test.ts`). The 0.53 migration retakes an inventory that never completed at a corrected root (#5569), moves a DB-only export checkpoint that stopped before its source was bound (stage `inventory` or `exported`, no started claim) to another absent `--content-root` and rechecks the checkpoint's inventory (#8528): a root inside a Git worktree is refused before any page is staged, the old staging directory is removed under the lock only when it holds nothing but the export's own bytes (else the move is refused, naming it), a filled earlier root is kept and named in `earlier_roots` and `pending_actions`, and every run refuses if the checkpoint changed while it waited for its lock, refuses at inventory a pack whose adoption would exceed `packFiles` (A-NEW-4), and accepts a post-inventory change only through `--accept-reviewed-inventory <source>=<inventoryDigest>` printed in the conflict reason (#5476).
- `src/core/shared-skills/{setup-source-policy,content-freshness}.ts` excludes external, connector, company and opted-out (`config.shared_skills=false`) sources from owned-root scaffolding and freshness exemptions. A completed content receipt must match the current brain, incarnation, source root and active owner binding. `src/commands/doctor/checks/canonical-content.ts` reports pending publication and recovery separately; it never invents an upstream sync timestamp. `src/core/shared-skills/adopted-packs.ts` names the sources holding an adopted pack (`source_routing_health` skips their zero-page warning) and, of those, the read-only catalogs (no commit, no `.git` when the checkout is readable) that `sync_freshness` exempts; a failing read exempts nothing and is a note. `staleOwnedContent` names a receipt, or an unfinished setup checkpoint, left on an old root (doctor `content_receipt_stale`); `setup.ts` refuses a resumed setup whose checkpoint names another root with `gbrain repair content-receipt-root --source <id>` as the fix, or, for a source with no canonical owner (which the repair cannot list), with the `gbrain sources writer claim <id> --path <root> --dry-run --json` preview as the first step (#7915). `src/core/shared-skills/receipt-root.ts` (`rebindContentReceipts`) rebinds the receipt root and `root_identity` of every current incarnation on the moved worktrees (nested by `relative_path`) inside the writer transfer accept and `sources set-path` transactions. `src/core/repair/content-receipt-root.ts` (`gbrain repair content-receipt-root`, explicit-only, preview-bound, owner host) rebinds a stale receipt when the source path is the owner root and the owner tree hashes to the recorded manifest, else lists `source_path_mismatch` / `tree_mismatch` (both digests) / `not_owner_host` / `root_missing`; it keeps `<key>.backup`. Test: `test/pathological/c7-content-receipt-root.test.ts`.
- `src/core/shared-skills/{source-opt-out,inventory-limits}.ts` and `src/commands/sources-shared-skills.ts` implement `gbrain sources shared-skills <id> on|off|status`: `off` writes `config.shared_skills=false`, `on` deletes it and releases a parked inventory, and every form reports the configured value and the effective policy mode with its reason. Trusted local only; a remote attempt gets `trusted_local_only` with a `host_admin` fix and a read-only verify. `inventorySkillpack` reads its file-count, total-byte, per-file and entry bounds from the capped `shared_skills.inventory.*` keys; confinement checks are fixed. An overflow (`payload_too_large`) parks the source in its per-source migration record, so the 0.53.0 orchestrator completes and later runs skip it until the bounds change, it opts out, or it is released. `src/commands/doctor/checks/shared-skills.ts` (`shared_skills_sources`) lists opted-out and parked sources. Operator recipe: `docs/guides/shared-brain-skills.md#choose-which-sources-adopt-shared-skills`.
- `src/core/shared-skills/optimizer.ts` stages opt-in optimization outside canonical roots with the original grants, immutable approved closure and protected metadata. Publication rechecks authority and the original revision through the coordinator; provider evaluation cannot write canonical skill files directly.
diff --git a/docs/architecture/key-files/workspace-push-and-backup.md b/docs/architecture/key-files/workspace-push-and-backup.md
index 6708a95e25..957da027c3 100644
--- a/docs/architecture/key-files/workspace-push-and-backup.md
+++ b/docs/architecture/key-files/workspace-push-and-backup.md
@@ -7,7 +7,7 @@ and the backup coverage verdicts that read its status records. Operator
guide: [backup check](../../operations/backup-check.md).
Key files:
-- `src/core/backup/coverage.ts` + `src/core/backup/repository.ts` — local Git discovery and bounded remote readback. Trusted non-quiet local backup CLI/doctor may read at most eight refs per sweep with a shared eight-second budget, two-second subprocess timeout and no prompts, pushes or fetches; pending/oldest evidence rotates first. An ordinary (non-forced) `getBackupStatus` re-probes before the one-hour sweep clock expires when the cached verdict still has pending repository evidence (a configured remote left `budget_exhausted`, relabelled `stale`, or `verified` older than the evidence window), at most once per `BACKUP_CONTINUATION_THROTTLE_MS` (60 s); real failures (`unavailable`, `mismatch`, `missing_ref`) are not retried per check (#6614, #6687; `test/backup-pending-continuation.serial.test.ts`). `budgetAllowsProbe` starts a probe only with its full two-second slot inside the deadline (a sub-slot leftover defers the root as `budget_exhausted` and the sweep keeps that root's first-pass `verified` evidence); an `unavailable` verification carries `cause: 'timeout' | 'exit'` (#6499). #6907: the slot is `resolveBackupRemoteTimeoutMs` (env `GBRAIN_BACKUP_REMOTE_TIMEOUT_MS` > DB `backup.remote_timeout_ms` > 2 s, clamped 500-30000 ms; the budget is `max(8 s, 4 slots)`), a timed-out probe is `isRemoteTimeout` (counted in `totals.remote_timeouts`, reason "remote check timed out"), and `worktreeDirty` streams `git status --porcelain` and stops at the first non-metadata line (`test/pathological/s-6907-backup-check-bounds.test.ts`). Both git calls run with `backupGitEnv()`, an allowlist (`HOME`, `PATH`, `XDG_CONFIG_HOME`, `SSH_AUTH_SOCK`, `GIT_CONFIG_GLOBAL`, proxy variables, and Windows profile variables) under the no-prompt overrides, so user Git config and credential helpers apply but `GIT_DIR`/`GIT_WORK_TREE` never do (#5794). `currentBackupEvidence` retains one-hour readback only while source kind/id, physical Git directory, HEAD, branch, origin, push-status identity and clean tree match. `recoverable_repos` counts clean matching remote HEADs, while `configured_repos` counts configuration; expired, failed, mismatched, dirty or budget-exhausted observations cannot turn coverage green. New matching readback can supersede historical push failure without erasing it. Background/stdio are local-only; remote MCP doctor and the advisor's remote collector use the aggregate cache only, read through `currentBackupEvidence`. A failed refresh is degraded and does not overwrite a valid cache. Git covers committed files, not DB-only facts/config/credentials. API connector sources are not repositories: a `connector_database` source (managed, unbound) and an unmanaged connector whose directory is not a Git repo each become a `connector` info asset with the `gbrain sync --source <id> --full` fix (not `gbrain export`: the connector sync rebuilds pages from the provider and never reads a Markdown dump, so an export is an archive, not a restore path), while a bound connector keeps the repository verdict. The doctor `backup_coverage` message and the advisor collector list each asset that keeps the verdict in warn with its reason (`blockingAssetReasons` in status-file.ts: `no git remote`, `remote configured, nothing pushed`, `dirty`, a fixed `unknown` code, unverified remote) locally, and reason counts only on the remote surface; a warn with no blocking asset leads with the stale or degraded cause. `gbrain backup status` names a fix for dirty and unverified rows too. Tests: `test/backup-verification.serial.test.ts`, `test/backup-git-env.test.ts`, `test/backup-coverage.serial.test.ts`, `test/doctor-backup-coverage.serial.test.ts`, `test/e2e/backup-coverage-parity.test.ts`. #6083: `assessBackupRepository` drops physical-root metadata (`withoutPhysicalRootMetadata`) from both porcelain probes, classifies a root with no origin remote as `no_remote` even after a recorded push failure, and gives a managed canonical worktree (`managedFilesystemRootFor`) the read-only `gbrain sources writer status [<source>] --probe --json` fix instead of the refused `sources push` (`backup-coverage.ts` explains that fix with the retry-effects step).
+- `src/core/backup/coverage.ts` + `src/core/backup/repository.ts` — local Git discovery and bounded remote readback. Trusted non-quiet local backup CLI/doctor may read at most eight refs per sweep with a shared eight-second budget, two-second subprocess timeout and no prompts, pushes or fetches; pending/oldest evidence rotates first. An ordinary (non-forced) `getBackupStatus` re-probes before the one-hour sweep clock expires when the cached verdict still has pending repository evidence (a configured remote left `budget_exhausted`, relabelled `stale`, or `verified` older than the evidence window), at most once per `BACKUP_CONTINUATION_THROTTLE_MS` (60 s); real failures (`unavailable`, `mismatch`, `missing_ref`) are not retried per check (#6614, #6687; `test/backup-pending-continuation.serial.test.ts`). A reused cached verdict whose page+fact count still says the brain is too young to coach re-reads that count (`brainMaturity`), so a verdict cached on an empty brain at init never reports 0 on a full one (GBRA-585). Doctor's fix for a `not_a_git_repo` source is the engine's full backup, `gbrain backup create` on PGLite or `postgresDumpFix()` (pg_dump, `src/core/backup/preflight.ts`) on Postgres, never `gbrain export`; `gbrain backup create` on a Postgres brain refuses with that same fix (`storage_error`, legacy reason `pglite_required`). `budgetAllowsProbe` starts a probe only with its full two-second slot inside the deadline (a sub-slot leftover defers the root as `budget_exhausted` and the sweep keeps that root's first-pass `verified` evidence); an `unavailable` verification carries `cause: 'timeout' | 'exit'` (#6499). #6907: the slot is `resolveBackupRemoteTimeoutMs` (env `GBRAIN_BACKUP_REMOTE_TIMEOUT_MS` > DB `backup.remote_timeout_ms` > 2 s, clamped 500-30000 ms; the budget is `max(8 s, 4 slots)`), a timed-out probe is `isRemoteTimeout` (counted in `totals.remote_timeouts`, reason "remote check timed out"), and `worktreeDirty` streams `git status --porcelain` and stops at the first non-metadata line (`test/pathological/s-6907-backup-check-bounds.test.ts`). Both git calls run with `backupGitEnv()`, an allowlist (`HOME`, `PATH`, `XDG_CONFIG_HOME`, `SSH_AUTH_SOCK`, `GIT_CONFIG_GLOBAL`, proxy variables, and Windows profile variables) under the no-prompt overrides, so user Git config and credential helpers apply but `GIT_DIR`/`GIT_WORK_TREE` never do (#5794). `currentBackupEvidence` retains one-hour readback only while source kind/id, physical Git directory, HEAD, branch, origin, push-status identity and clean tree match. `recoverable_repos` counts clean matching remote HEADs, while `configured_repos` counts configuration; expired, failed, mismatched, dirty or budget-exhausted observations cannot turn coverage green. New matching readback can supersede historical push failure without erasing it. Background/stdio are local-only; remote MCP doctor and the advisor's remote collector use the aggregate cache only, read through `currentBackupEvidence`. A failed refresh is degraded and does not overwrite a valid cache. Git covers committed files, not DB-only facts/config/credentials. API connector sources are not repositories: a `connector_database` source (managed, unbound) and an unmanaged connector whose directory is not a Git repo each become a `connector` info asset with the `gbrain sync --source <id> --full` fix (not `gbrain export`: the connector sync rebuilds pages from the provider and never reads a Markdown dump, so an export is an archive, not a restore path), while a bound connector keeps the repository verdict. The doctor `backup_coverage` message and the advisor collector list each asset that keeps the verdict in warn with its reason (`blockingAssetReasons` in status-file.ts: `no git remote`, `remote configured, nothing pushed`, `dirty`, a fixed `unknown` code, unverified remote) locally, and reason counts only on the remote surface; a warn with no blocking asset leads with the stale or degraded cause. `gbrain backup status` names a fix for dirty and unverified rows too. Tests: `test/backup-verification.serial.test.ts`, `test/backup-git-env.test.ts`, `test/backup-coverage.serial.test.ts`, `test/doctor-backup-coverage.serial.test.ts`, `test/e2e/backup-coverage-parity.test.ts`. #6083: `assessBackupRepository` drops physical-root metadata (`withoutPhysicalRootMetadata`) from both porcelain probes, classifies a root with no origin remote as `no_remote` even after a recorded push failure, and gives a managed canonical worktree (`managedFilesystemRootFor`) the read-only `gbrain sources writer status [<source>] --probe --json` fix instead of the refused `sources push` (`backup-coverage.ts` explains that fix with the retry-effects step).
- `src/core/workspace-push.ts` — `gbrain sources push`: deny-glob backstop (tracked `*.pglite`/`.env*`, and since #5186 the ownership markers `.gbrain-owner.json` / `.gbrain-owner-*.json` / `.gbrain-owner.json.*.tmp` plus `.gbrain-bootstrap.lock/**`, refused regardless of .gitignore state; untracked matches are excluded from the commit and named in `excludedUntracked`) → stage FIRST → secret-scan the STAGED index blobs via `git cat-file` (closes the scan-then-stage TOCTOU — scanned bytes == committed bytes) → commit FIRST → divergence-safe pull → push, under one cross-platform lock (mkdir-atomic; flock is not a dependency — macOS) keyed on the repo's realpath, so a symlinked spelling and git's physical toplevel share it (an absent path hashes its raw string). The pre-push secret gate FAILS CLOSED: an unreadable, oversized (> `PUSH_STREAM_SCAN_MAX_BYTES`, 512 MiB), or otherwise unscannable staged blob returns `blocked_unscannable` (nothing committed) instead of sailing through. A blob up to `PUSH_MAX_SCAN_BYTES` (25 MiB) is read whole and scanned by `scanText` as before; a larger one is found by its index size (one `ls-files -s` plus one `cat-file --batch-check`, `stagedBlobSizes`), streamed by oid through `git cat-file blob` into `scanTextStream` (`secret-scan-stream.ts`) and fails closed when git errors, runs past 10 minutes or delivers a byte count other than the recorded size (`test/workspace-push-large-blob.serial.test.ts`: a clean 30 MiB file pushes, secrets across window seams block once each with their line, the ceiling still blocks) — only a confirmed staged deletion is skipped, and binary/NUL-sniffed blobs are scanned anyway. Statuses map to exit codes in `src/commands/sources.ts`: `pushed`/`skipped_in_flight` → 0; `blocked_secrets`/`blocked_tracked_deny`/`blocked_unscannable`/`refused_visibility` → 5; `pull_conflict`/`push_failed`/other → 1. Refuses public AND unverifiable remotes (never fail-open); pushes even on clean trees; writes `<home>/bootstrap/push-status.json`. Parent-repo-aware (a source may be a subdirectory of the workspace repo). A `blocked_secrets` result carries `PushSecretFinding[]`: each finding adds `file`, `since`, the absolute `allowlistPath` of the root `.gbrain-scan-allow`, a shell-quoted `allowCommand` (`printf` append, runnable from any cwd), `retryCommand` (`gbrain sources push --path <abs>` plus the run's `--branch`/`--allow-unverified-remote`), `docs` (`SECRET_SCAN_REFUSAL_DOCS`, the `write-refusals.md#secret-scan-refusals-and-redaction` anchor; keep that heading) and, when the scanner's `legacyFingerprint` matches an allowlist entry, `staleAllowlistEntry { entry, replacement }`. `formatBlockedSecrets` renders the CLI text from the same objects, so human and `--json` output carry the same commands, and no field holds a value. `blockedSecretsReason` keeps `reason` a one-line summary (count, first location, pattern) within the 140 chars `sanitizePushReason` passes. `bootstrap/verify.ts` and `bootstrap/repo.ts` refusals reuse the docs anchor and print fingerprint, `since` and the absolute allowlist path. `pushStatusForWorkspace(entries, ws)` picks the record whose `repoRoot` resolves to `ws` (a single legacy record without `repoRoot` is attributed to it); `bootstrap status` `support.last_push` and doctor `bootstrap_push_health`'s dirty-tree FAIL use only that record (`test/doctor-not-verified-5432.test.ts`). Tests: `test/workspace-push-guidance.test.ts`, `test/sources-push-cli.serial.test.ts`. #6083: the managed-guard refusal record carries `code: writer_coordinator_required` (`PushStatusEntry.code`); the hook push call sites (`dirtyTreePush`, `stopPushIfDue`, SessionEnd) skip a managed root with heartbeat reason `push_managed_coordinator`; doctor `bootstrap_push_health` (`src/commands/doctor/bootstrap-checks.ts` `recordedPushFailureCheck`) reports ok when every recorded failure's tree now matches its configured origin with nothing uncommitted. #5799: `isSupersededPushStatus(entry)` / `livePushStatuses(entries)` drop a record the managed topology has superseded (code or reason prefix `writer_coordinator_required`, or a `repoRoot` that is a managed worktree now; an unreadable marker is not assumed managed), because the coordinator's git effect never writes push-status and the refusal would otherwise feed the hook's FAILING banner and staleness note forever (`test/workspace-push-superseded-status.test.ts`); the hook call sites read `livePushStatuses(readPushStatuses())`. `readPushStatuses` skips per-root records whose `repoRoot` stat answers ENOENT or ENOTDIR (a deleted workspace) and unreadable files (torn or non-object JSON, a missing-absolute or non-string `repoRoot`, any other stat error such as EACCES); the keyed `readPushStatusForRoot` parses with the same rule. `pushStatusRecordCounts` tells the two apart, so doctor's `bootstrap_push_health` reports files kept only for deleted workspaces as `ok` and anything unreadable as `push status unreadable`; no status file is changed or removed (#7377, `test/push-status-gone-roots-7377.test.ts`).
## Shared-checkout git writer
diff --git a/docs/contracts/public-surface.json b/docs/contracts/public-surface.json
index 0014ebf901..c91d7fed61 100644
--- a/docs/contracts/public-surface.json
+++ b/docs/contracts/public-surface.json
@@ -2912,6 +2912,7 @@
"serve_unhealthy_exit": 69,
"settle_mismatch": 1,
"setup_harness_unsupported": 2,
+ "setup_history_choice_required": 1,
"setup_hosted_connection": 1,
"setup_owner_conflict": 1,
"setup_serves_several": 1,
diff --git a/docs/guides/access-designations.md b/docs/guides/access-designations.md
index 93d8c931ee..6c05afc9dc 100644
--- a/docs/guides/access-designations.md
+++ b/docs/guides/access-designations.md
@@ -19,7 +19,8 @@ Five kinds of caller read a brain:
sub-agents included, with `gbrain auth rescope --token <name> --member <owner>`. A Claude Code or Codex install
only the owner uses: `gbrain setup <claude-code|codex> --stdio-member <owner>`, which binds that harness's stdio
entry on that machine and nothing else (PGLite or Postgres); for a harness several people talk to, one key per
- person over `gbrain serve --http` (`gbrain auth create <name> --member <id>`). On a single-user brain this is how the owner's own
+ person over `gbrain serve --http` (`gbrain auth create <name> --member <id>`, which mints read and write only; add
+ `--scopes read,write,admin` for a key that also runs admin tools). On a single-user brain this is how the owner's own
agent reads the whole brain.
- **Other members**: credentials bound to any other enabled member.
- **Public or unbound callers**: credentials bound to no member, and audiences that include a guest.
@@ -224,7 +225,7 @@ page private only by a privacy alias, a pinned question, a derived type or a pri
`visibility: private` by any of these writes that states no visibility, and a pinned question keeps its
`pinned_question`. The revision and the journaled request (`ownerWrite`) name the owner's credential. Readers lists and
folder rules that leave the owner out still refuse it, a soft-deleted private page stays refused, and every other caller
-is refused as before; to keep an owner agent from changing private pages, give it a credential without write scope (`gbrain auth create <name> --member <owner> --scopes read`; without `--scopes` the token gets full access).
+is refused as before; to keep an owner agent from changing private pages, give it a credential without write scope (`gbrain auth create <name> --member <owner> --scopes read`; without `--scopes` a `--member` token gets read and write, and `--scopes read,write,admin` adds admin).
**The owner opt-in.** `gbrain access owner reads-restricted on` (config `access.owner_reads_restricted`, off by
default and unchanged on upgrade) lets the owner's credentials read the pages that `readable_by` lists, folder rules
diff --git a/docs/guides/brain-layout.md b/docs/guides/brain-layout.md
index 1a30342530..bfe837991d 100644
--- a/docs/guides/brain-layout.md
+++ b/docs/guides/brain-layout.md
@@ -64,7 +64,12 @@ gbrain setup claude-code --shape both --notes ~/notes --docs ~/acme-example/docs
the `company` source reads them, and no one else. Setup prints who that is, for example
`readable by: everyone who can read source company (this brain serves one person)`, or
on a brain that serves several people, the members the source's access rules allow
- (`gbrain access who-can-read <slug> --source company` shows the same). These are not
+ (`gbrain access who-can-read <slug> --source company` shows the same). There, the member
+ keys `gbrain setup --serves several` mints read the `company` source, so every member
+ reads every call, including calls they did not attend; other keys read it only when
+ their grant names it, and `company` stays out of default search. With `--labelled-only`,
+ setup adds one `company/` rule, so the line names that rule's readers (the owner and the
+ members) instead. These are not
your agent conversations: those go to `conversations/` through the
[conversation archive](conversation-archive.md), which `--transcripts` never touches.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 46172f70ca..23bd2291a3 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -4986,6 +4986,14 @@ More: [docs/guides/write-refusals.md#settle_mismatch](../../docs/guides/write-re
More: [docs/guides/repair.md#setup-harness-unsupported](../../docs/guides/repair.md#setup-harness-unsupported)
+### setup_history_choice_required
+
+<a id="setup_history_choice_required"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| gbrain setup --serves several would turn a brain that serves one person shared while it holds pages no rule restricts, and nobody chose what happens to them, so setup wrote nothing. | Each member key setup mints reads every page no rule or readable_by restricts, so the owner's journal, DMs, chat, mail and conversation archive would reach every member; only the admin can decide that. | Run setup again with --labelled-only to keep that history private (each member reads only pages labelled for them) or with --open-history to let the members read it. Run: gbrain doctor --only open_shared_pages --json | agent | `repeat the read that failed` | 1 | no |
+
### setup_hosted_connection
<a id="setup_hosted_connection"></a>
@@ -5572,7 +5580,7 @@ More: [docs/guides/write-refusals.md#source_writer_restricted](../../docs/guides
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| An unscoped search, query, recall or list_pages came back empty and was refused: every source this connection can read (the default source and federated sources) holds no page search returns (for recall and query, no active world fact either), while other sources on the brain hold such pages it cannot read (not federated, and no source grant). | Answering would return an empty result that reads like a clean miss. The check is one yes/no about the whole brain, independent of the query: whether another source holds pages; it never says another source matches the question. Quarantined pages count on neither side, nor private pages when remote reads exclude them. The refusal names the host command that federates a source or grants this connection the sources it should read; it never names a hidden source and never widens access. A scope that holds pages but matched nothing, a granted token, an OAuth client, a bound connection and a read that names a source are never refused. | Ask the user which source these connections should read; the brain host runs `gbrain sources federate <source>`, or grants the token its sources with `gbrain auth rescope --token <name> --sources <ids>`. | host_admin | `gbrain doctor --json` | 1 | no |
+| An unscoped search, query, recall or list_pages came back empty and was refused: every source this connection can read (the default source and federated sources) holds no page every reader of that source can read (pages kept to named readers or private do not count; for recall and query, no active world fact either), while other sources on the brain hold such pages it cannot read (not federated, and no source grant). | Answering would return an empty result that reads like a clean miss. The check is one yes/no about the whole brain, independent of the query: whether another source holds pages; it never says another source matches the question. Quarantined pages count on neither side, nor private pages when remote reads exclude them. The refusal names the host command that federates a source or grants this connection the sources it should read; it never names a hidden source and never widens access. A scope that holds pages but matched nothing, a granted token, an OAuth client, a bound connection and a read that names a source are never refused. | Ask the user which source these connections should read; the brain host runs `gbrain sources federate <source>`, or grants the token its sources with `gbrain auth rescope --token <name> --sources <ids>`. | host_admin | `gbrain doctor --json` | 1 | no |
More: [docs/guides/multi-source-brains.md#an-unscoped-connection-whose-sources-hold-no-pages](../../docs/guides/multi-source-brains.md#an-unscoped-connection-whose-sources-hold-no-pages)
diff --git a/docs/guides/guest-notes.md b/docs/guides/guest-notes.md
index ab55d4b202..89b57d1eac 100644
--- a/docs/guides/guest-notes.md
+++ b/docs/guides/guest-notes.md
@@ -85,6 +85,11 @@ writer list. Every `init` previews first and writes nothing without `--yes`.
gbrain guests init --writer oauth_client:<client id> --yes
```
+ An `oauth_client` writer must name a client registered on this brain
+ (`gbrain auth clients --json` lists them). An unknown or deleted id is
+ refused with `client_not_found` and nothing is written; `sources writers
+ --add` checks the same way.
+
Plain `gbrain auth rescope --client <client id>` prints the client's operations
and slug prefixes but not who it may act for. `gbrain auth rescope --client
<client id> --json` prints the whole grant, and `gbrain access check --client
diff --git a/docs/guides/hosted-harness-access.md b/docs/guides/hosted-harness-access.md
index 49716238ab..017ed668f7 100644
--- a/docs/guides/hosted-harness-access.md
+++ b/docs/guides/hosted-harness-access.md
@@ -11,6 +11,7 @@ does not configure your laptop or Bot. First select the connection method:
| Harness has native OAuth/PKCE settings | [Native OAuth path](#native-oauth-path) below |
| Managed bearer configuration or a thin CLI adapter | The [machine handoff path](#1-grant-access-on-the-brain-host) below |
| Open the dashboard, inspect clients, change permissions, or end access | [MCP administration](../mcp/ADMIN.md) |
+| A member key `gbrain setup --serves several` minted (`member-keys/<member>.key`) | [A member's key into their harness](setup.md#a-members-key-into-their-harness) |
An endpoint URL, ordinary OAuth token, client secret, or MCP `admin` scope does
not grant owner administration. The owner uses a separately protected bootstrap
diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.md
index 1900be8ba2..5f45b7dfa1 100644
--- a/docs/guides/memory-boundaries.md
+++ b/docs/guides/memory-boundaries.md
@@ -461,13 +461,27 @@ in a form the scanner does not match (split it, or describe it) or move the
mention after the real fence. Pinned by `test/fence-marker-code-context.test.ts`
("remote privacy boundary" and "remote page replacement").
+<a id="full-backup"></a>
Markdown export is a portable view of pages, **not a full database backup**.
DB-only facts and pages (extract receipts included), revision history, the belief ledger (what the brain
had recorded, and when; `gbrain beliefs`), withdrawal state, jobs, settings,
-and authentication records may not be recoverable from Markdown. Use the engine's
-full backup/restore path and verify a restore into a separate location. Treat
-database backups as sensitive. See the [system-of-record contract](../architecture/system-of-record.md)
-and [isolated local backup guide](in-agent-setup.md#6-back-up-the-complete-local-database).
+and authentication records may not be recoverable from Markdown. On a brain with
+several sources or members, an import of an export puts every page in one source
+with no members, tokens or facts, so a page from a personal source comes back
+readable by everyone in that source. Use the engine's full backup/restore path
+and verify a restore into a separate location:
+
+- **PGLite:** `gbrain backup create --output <absolute path>`, restored with
+ `gbrain backup restore` ([isolated local backup guide](in-agent-setup.md#6-back-up-the-complete-local-database)).
+- **Postgres:** a dump of the brain's database, `pg_dump --format=custom --file <dump> --dbname <database>`,
+ restored into a new, empty database with `pg_restore --no-owner --dbname <new database> <dump>`;
+ `gbrain init --url <new database>` under a separate `GBRAIN_HOME` then opens it with its
+ sources, members, tokens, folder rules and facts. `gbrain backup create` refuses on Postgres.
+ The restored brain's sources still name the original's content folders, so keep
+ only one of the two brains writing to them. See [embedding migrations](../embedding-migrations.md)
+ for a quiesced dump with service files that keep the password off the command line.
+
+Treat database backups as sensitive. See the [system-of-record contract](../architecture/system-of-record.md).
<a id="purge"></a>
## Expire versus purge
diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.md
index 56df819c5d..273bbdf3f6 100644
--- a/docs/guides/multi-source-brains.md
+++ b/docs/guides/multi-source-brains.md
@@ -114,8 +114,10 @@ A new source added without `--federated` or `--no-federated` is federated on
a brain only you use (`access.serves` is one, `brain.audience` reads personal,
and you are not on a thin client). On a shared brain it stays unset, and
`sources add` and `sync --source <id>` print a `source_not_in_default_search`
-notice whose fix is `gbrain sources federate <id>`. Sources you added before
-this change keep their setting.
+notice whose fix is `gbrain sources federate <id>`, marked `ask_user`: it asks
+whether the source should be shared with every connection that reads default
+search, and a source meant to stay private (a member's personal source, say)
+needs nothing. Sources you added before this change keep their setting.
The seeded `default` source is `federated=true` so single-source brains
behave as you'd expect — every page appears in search.
@@ -139,9 +141,11 @@ empty result that reads like a clean miss.
So an unscoped `search`, `query`, `recall` or `list_pages` from such a
connection that comes back empty is refused with `sources_not_readable` when
-the sources it reads hold no page at all (for `recall` and `query`, no active world fact either)
+the sources it reads hold no page that every reader of the source can read (for `recall` and `query`, no active world fact either)
while other sources on the brain hold pages. Quarantined pages count on neither
-side. The check is one yes/no about the whole brain, independent of the query:
+side, and neither do pages kept to named readers (a member's own pages
+included) or private pages, so a member can be refused while its own pages
+sit in `default`. The check is one yes/no about the whole brain, independent of the query:
whether another source holds pages. It never says another source matches the
question, and it never names a source or page the connection cannot read. Its fix is host-side: the
user picks the source these connections should read and the brain host runs
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 0fd17658cc..09a27cd2b3 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -5478,7 +5478,11 @@ whose snapshot was written before snapshots recorded their operation catalog
says "this grant's snapshot excludes N currently eligible operations;
original intent unknown", and only a grant with recorded catalog provenance
says it predates operations. Operations outside the grant's scopes are never
-counted, so a writer is not told about admin-only operations.
+counted, so a writer is not told about admin-only operations. A snapshot the
+owner narrowed on purpose (catalog provenance recorded, and every operation it
+leaves out existed when it was written, as with a guest broker's
+`--operations` list) blocks nothing by mistake, so the notice comes only with a
+refused call, never on a call the grant can make.
It arrives once per session: once per (principal, transport session) on
stdio and HTTP, and for a stateless HTTP call with no session id once per
diff --git a/docs/guides/setup.md b/docs/guides/setup.md
index 52dcf94616..9bd193590e 100644
--- a/docs/guides/setup.md
+++ b/docs/guides/setup.md
@@ -179,6 +179,43 @@ other pages no rule or `readable_by` restricts, which every member's key still r
by folder, with the commands that label them; `--labelled-only` keeps each member to
the pages labelled for it instead (never the owner). See
[pages every member's key can read](access-designations.md#pages-every-members-key-can-read).
+When the brain serves one person and already holds such pages (a journal, DMs, chat,
+mail, the conversation archive), setup asks for that choice before it writes anything:
+it refuses with `setup_history_choice_required`, naming the count, how many are DMs,
+chat or mail and how many are in the conversation archive, until you pass
+`--labelled-only` (keep that history private) or `--open-history` (every member reads
+it). It also refuses when it could not count them, and the `--labelled-only` command it
+suggests leaves the owner out of `--members`, since the owner reads the whole brain. When the brain has the `company` source (`--shape company`), a `--labelled-only` run
+also adds one folder rule, `company/` in source `company`, readable by the owner, the
+run's members and every member who is not labelled-only, so the members still read the
+company pages and imported calls; only keys bound to those members read pages under
+`company/`. A re-run adds new members to that rule and never removes one; because that
+widens it, the new readers wait for `gbrain access apply --source company` (preview, then
+the `--yes --expect` line it prints). A run without `--labelled-only` adds no such rule. A
+new brain, one with no such pages and one that already serves several people are not asked.
+On a brain with no owner, setup also names one: `--owner <id>`, or by default your
+login name as a member id. It adds that member and runs `gbrain access owner set`;
+the preview shows it first, and an owner that is already set is kept. No key is
+rebound: the receipt lists each live token or OAuth client bound to no member with
+the `gbrain auth rescope --token|--client <name> --member <owner>` command that
+binds it, so you bind your own keys on purpose.
+Each key setup mints writes to the run's source and reads a fixed list: that source,
+the `company` source when it exists (`--shape company`), and every source federated
+when the key is minted. The preview names the list and how many pages `company` holds,
+how many of them are imported calls, and that every member reads them all, calls they
+did not attend included. A source federated later reaches these keys only when you run
+setup again: a re-run adds sources to a key setup minted with a list and never removes
+one, but only while the key's list is still the one setup gave it. A key you changed by
+hand (`gbrain auth rescope`) is skipped: the receipt names it, with `action: skipped` on
+its `keys` row under `--json`, and the rescope command that adds the new sources. A
+source archived since the key was minted is dropped from its list; when that source is
+the key's write source, setup blocks the key instead and names the commands that repoint
+or revoke it. Unfederating a source does not take it away from these keys either:
+`gbrain sources unfederate <id>` lists each member key that still reads it, with the
+`gbrain auth rescope --token <name> --sources <ids>` command that drops it.
+Keys minted before this (the default grant) are never changed. When the same run
+adds the `company` source (`--shape company`), setup labels the people first and then
+gives their new keys `company`; `company` itself stays out of default search.
Setup leaves the stdio server unbound: stdio sessions read only pages no rule
restricts, and the harness's instructions keep the one-person scoping lines.
For a Claude Code or Codex install only one person uses, bind that harness alone:
@@ -214,6 +251,25 @@ a brain setup cannot read refuses (`setup_serves_unreadable`).
`gbrain access serves several --members ...` does the labelling alone (preview, then
`--yes`).
+### A member's key into their harness
+
+A member key (`member-keys/<member>.key`) is a plain bearer key for
+`gbrain serve --http`. Hand the file to its member privately; on their machine they
+put it into Claude Code, Codex or opencode with the bearer-token form of
+`gbrain connect`, which reads the key from `GBRAIN_REMOTE_TOKEN` so it never lands in
+shell history:
+
+```bash
+GBRAIN_REMOTE_TOKEN="$(cat alice-example.key)" \
+ gbrain connect https://brain.example.com/mcp --agent claude-code --install
+# --agent codex or --agent opencode for those harnesses
+```
+
+`gbrain whoami` over that connection names the member. `--harness` and
+`--credentials-file` take only the credential handoff that `gbrain mcp grant`
+writes, never a member key; given one, `gbrain connect` refuses and prints the
+command above.
+
On such a brain every remote read must say whom it reads for. A token, OAuth
client or stdio server bound to no member is refused with
[`requester_scope_required`](write-refusals.md#requester_scope_required) before
diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.md
index d7da9bee4f..528ec58b1a 100644
--- a/docs/mcp/ADMIN.md
+++ b/docs/mcp/ADMIN.md
@@ -515,7 +515,8 @@ Fix it by binding first:
The fix is per-person access.
- Per-person access: give each person's agent its own credential bound to
them (`gbrain access member add <id>`, then
- `gbrain auth create <name> --member <id>`) and put `readable_by` on pages
+ `gbrain auth create <name> --member <id>`, which mints read and write only
+ unless you pass `--scopes`) and put `readable_by` on pages
only some people may read. One agent in a shared channel instead uses a
credential made with `gbrain auth create <name> --may-act-for <members>`,
and its harness names each request's audience on every call (see
diff --git a/docs/mcp/CLAUDE_CODE.md b/docs/mcp/CLAUDE_CODE.md
index a7f58fc971..8c424e50c3 100644
--- a/docs/mcp/CLAUDE_CODE.md
+++ b/docs/mcp/CLAUDE_CODE.md
@@ -176,7 +176,8 @@ claude mcp add gbrain -t http \
Replace the host with your MagicDNS name (or your ngrok domain) and
`YOUR_TOKEN` with a token from `gbrain auth create "claude-code"`.
-> A `gbrain auth create` token is a long-lived, full-access secret. Keep it
+> A `gbrain auth create` token is a long-lived secret that carries its grant's
+> scopes (full-access when minted without `--scopes`). Keep it
> private (it lands in `~/.claude.json`), and prefer a scoped/short-lived token
> where your host supports one.
diff --git a/docs/mcp/CODEX.md b/docs/mcp/CODEX.md
index acd3052c56..62161a44e0 100644
--- a/docs/mcp/CODEX.md
+++ b/docs/mcp/CODEX.md
@@ -271,8 +271,10 @@ codex mcp remove gbrain
## Notes
-- The token is a long-lived, full-access secret. Keep `GBRAIN_REMOTE_TOKEN` out of
- version control and prefer a scoped token if your host supports one.
+- The token is a long-lived secret that carries its grant's scopes (a
+ `gbrain auth create` token minted without `--scopes` is full-access). Keep
+ `GBRAIN_REMOTE_TOKEN` out of version control and prefer a scoped token if
+ your host supports one.
- Local stdio also works if you run the brain on the same machine:
`gbrain setup codex` registers `serve --surface starter --advertise verbs` behind
gbrain's launcher, so the session directory's `bunfig.toml` and `.env` never load
diff --git a/docs/mcp/PERPLEXITY.md b/docs/mcp/PERPLEXITY.md
index 37eab2325a..1a874fe7bd 100644
--- a/docs/mcp/PERPLEXITY.md
+++ b/docs/mcp/PERPLEXITY.md
@@ -125,5 +125,6 @@ setup file or a successful server probe does not establish native activation.
version support remote MCP connectors.
- The Mac app can also use a local MCP server (`gbrain serve` stdio) if you'd
rather not expose an HTTP endpoint.
-- A `gbrain auth create` token is a long-lived, full-access secret. Keep it
+- A `gbrain auth create` token is a long-lived secret that carries its grant's
+ scopes (full-access when minted without `--scopes`). Keep it
private and prefer a scoped token where possible.
diff --git a/docs/operations/backup-check.md b/docs/operations/backup-check.md
index 57549de139..6687cd48db 100644
--- a/docs/operations/backup-check.md
+++ b/docs/operations/backup-check.md
@@ -22,7 +22,10 @@ readback can supersede a recorded push failure without erasing that history.
An offline, unavailable, mismatched or not-yet-probed remote is **unknown**, not
green. Git evidence covers committed files only: DB-only pages, facts,
configuration and credentials need a separate backup and restore drill. Managed
-Postgres placement alone is not proof of a remote database backup.
+Postgres placement alone is not proof of a remote database backup. For a source
+that is not a Git repository, doctor's fix is the engine's [full
+backup](../guides/memory-boundaries.md#full-backup): `gbrain backup create` on
+PGLite, a `pg_dump` of the brain's database on Postgres, never a Markdown export.
**Not covered by Git evidence:** the DB file itself (`~/.gbrain` is
deliberately gitignored — only Git-backed content rebuilds via `gbrain sync`);
diff --git a/docs/tutorials/company-brain.md b/docs/tutorials/company-brain.md
index 3a6cad37bc..63d03719f8 100644
--- a/docs/tutorials/company-brain.md
+++ b/docs/tutorials/company-brain.md
@@ -144,7 +144,7 @@ gbrain access rule add --prefix partners/alice-example/ --readers alice-example,
gbrain access rule list --source team-a # store, revisions, applied rules, anything held or pending
```
-A remote read of a page under a rule needs the caller's member to be on every rule covering it and on the page's own `readable_by`; hatches, grants and `--as` never relax it. Narrowing applies at once. Moving a rule's prefix restricts the new folder at once and keeps the old folder under the old readers until approval. A change that widens (removing a rule or a reader, or releasing a moved rule's old folder) is held until `gbrain access apply --source team-a` previews who would gain access and `gbrain access apply --source team-a --yes --expect <plan_hash>` approves it. If an apply stops halfway, its prefixes read as nobody until `gbrain access resume --source team-a`. `gbrain access rule history` and `rule revert --to <revision>` work over the revision log, and `gbrain export` carries the applied rules so `gbrain import` installs them before any page.
+A remote read of a page under a rule needs the caller's member to be on every rule covering it and on the page's own `readable_by`; hatches, grants and `--as` never relax it. Narrowing applies at once. Moving a rule's prefix restricts the new folder at once and keeps the old folder under the old readers until approval. A change that widens (removing a rule or a reader, or releasing a moved rule's old folder) is held until `gbrain access apply --source team-a` previews who would gain access and `gbrain access apply --source team-a --yes --expect <plan_hash>` approves it. If an apply stops halfway, its prefixes read as nobody until `gbrain access resume --source team-a`. `gbrain access rule history` and `rule revert --to <revision>` work over the revision log. `gbrain export` writes the applied rules beside the pages, and `gbrain import --access-policy <source>` installs one source's rules before any page, but an export is not a backup of a brain with several sources or members: the import puts every page in one source and keeps no members, tokens or facts, so a page from a personal source comes back readable by everyone. Back up a company brain with the engine's [full backup](../guides/memory-boundaries.md#full-backup): `gbrain backup create` on PGLite, a `pg_dump` of the database on Postgres.
**Page rules: keep one page to some members.** `gbrain access rule add --slug notes/plan-example --readers alice-example --source team-a` (preview, then `--yes`) covers exactly that slug, never a folder of the same name or a longer slug; in `access.yml` it is `slug: notes/plan-example` in place of `prefix:`. It writes nothing to the page, so it also narrows a page at the source root, or one whose file was removed from git outside gbrain, where a `put_page` with `visibility: private` refuses `source_changed` ([canonical_file_missing](../guides/write-refusals.md#canonical_file_missing)). It binds the owner too, so list the owner's member to keep the owner reading it. Removing the rule is the undo, a widening held until `gbrain access apply`. Upgrade every gbrain host that shares the brain first: an older host keeps the page restricted, but refuses its own `gbrain access rule` commands and stops syncing a git-backed source that holds a page rule until it is upgraded.
diff --git a/llms-full.txt b/llms-full.txt
index b45c67684b..993752fb87 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -5456,6 +5456,30 @@ to connect: it diagnoses the dir from disk, names the repair command, reports
retained repair backups, and escalates when repairs keep recurring (that
means the unclean-shutdown genesis is still active — see the ladder's rung 4).
+<a id="pglite-live-serve"></a>
+### PGLite while `gbrain serve` runs (`pglite_busy` reason `live_serve`)
+
+One gbrain process opens a PGLite brain at a time. While `gbrain serve` (stdio
+or `--http`) holds it, page and fact writes from the CLI (`gbrain put`,
+`gbrain remember`) go through the running server and work. Commands that need
+the database to themselves, which includes the admin commands
+(`gbrain access …`, `gbrain sources …`, `gbrain auth …`) and most reads,
+refuse with `pglite_busy` reason `live_serve`. The refusal names the server's
+PID, and its fix is two steps: stop that server, then run the command again.
+Never remove the lock of a server that is still running.
+
+On a brain that serves one person this is a short pause: quit the agent
+session (a stdio serve) or stop `gbrain serve --http`, run the command, and
+start it again. On a brain that serves several people over
+`gbrain serve --http`, every member's connection drops while the server is
+stopped, for every admin step. Move such a brain to Postgres, where the server
+and the admin commands run side by side: preview with the read-only
+`gbrain migrate --to postgres --url-env GBRAIN_TARGET_URL --plan --json`,
+then follow [Move a PGLite brain to Postgres](guides/move-to-postgres.md). The
+move carries members, tokens, `readable_by` and facts across.
+`gbrain setup <harness> --serves several` on PGLite says this in its
+`engine` line.
+
<a id="legacy-pglite-lock"></a>
### Legacy PGLite lock (`pglite_busy` reason `legacy_owner_unverified`)
diff --git a/plugin-variants/gbrain-coding/skills/mcp-access/SKILL.md b/plugin-variants/gbrain-coding/skills/mcp-access/SKILL.md
index 955e3447da..ac4d00b9f3 100644
--- a/plugin-variants/gbrain-coding/skills/mcp-access/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/mcp-access/SKILL.md
@@ -118,7 +118,7 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- A failed transport after a mutation was sent means the outcome is unknown: re-read the client list before retrying, never re-send blind.
- A list call fails: a failed list is not an empty list; report the error.
- A tool the grant should reach is missing (`unknown_tool`, or a write such as `put_pages` absent): read `grant_diagnosis` from `whoami` or `gbrain://capabilities`. It names the blocker (scope, operation snapshot, client pin or server ceiling) and counts the operations it hides without naming them. Relay its `fix` (`next: tell_user_to_run`) to the brain owner; on the host, `gbrain doctor` check `grant_new_ops_available` shows the exact commands. New memory-profile grants are on the full surface; older ones keep their stored surface until the owner changes it. An "original intent unknown" grant may be restricted on purpose: never widen it unasked, and offer `--operations all` (no snapshot, including operations later upgrades add) only as the user's explicit choice.
-- A `grant_blocked_operations` notice (once per session) is the same diagnosis delivered in band: relay its `fix` to the brain owner (preview, then the `then` command), confirm with `whoami` afterwards, and do not retry the blocked operations meanwhile. It never names operations, and a missing scope is named only when a call was refused.
+- A `grant_blocked_operations` notice (once per session; a grant the owner narrowed on purpose gets it only on a refused call) is the same diagnosis delivered in band: relay its `fix` to the brain owner (preview, then the `then` command), confirm with `whoami` afterwards, and do not retry the blocked operations meanwhile. It never names operations, and a missing scope is named only when a call was refused.
- A `hidden_tool_content` notice means the result left out takes that a tool outside your tool list serves. Follow its `fix` as given: call `takes_list` when it names it, call `request_tools {surface}` when it names that (then `takes_list`), or relay the owner's repair when `next` is `tell_user_to_run`. Do not answer "not found" from that result alone.
## Anti-Patterns
diff --git a/plugin-variants/gbrain-daily/skills/mcp-access/SKILL.md b/plugin-variants/gbrain-daily/skills/mcp-access/SKILL.md
index 955e3447da..ac4d00b9f3 100644
--- a/plugin-variants/gbrain-daily/skills/mcp-access/SKILL.md
+++ b/plugin-variants/gbrain-daily/skills/mcp-access/SKILL.md
@@ -118,7 +118,7 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- A failed transport after a mutation was sent means the outcome is unknown: re-read the client list before retrying, never re-send blind.
- A list call fails: a failed list is not an empty list; report the error.
- A tool the grant should reach is missing (`unknown_tool`, or a write such as `put_pages` absent): read `grant_diagnosis` from `whoami` or `gbrain://capabilities`. It names the blocker (scope, operation snapshot, client pin or server ceiling) and counts the operations it hides without naming them. Relay its `fix` (`next: tell_user_to_run`) to the brain owner; on the host, `gbrain doctor` check `grant_new_ops_available` shows the exact commands. New memory-profile grants are on the full surface; older ones keep their stored surface until the owner changes it. An "original intent unknown" grant may be restricted on purpose: never widen it unasked, and offer `--operations all` (no snapshot, including operations later upgrades add) only as the user's explicit choice.
-- A `grant_blocked_operations` notice (once per session) is the same diagnosis delivered in band: relay its `fix` to the brain owner (preview, then the `then` command), confirm with `whoami` afterwards, and do not retry the blocked operations meanwhile. It never names operations, and a missing scope is named only when a call was refused.
+- A `grant_blocked_operations` notice (once per session; a grant the owner narrowed on purpose gets it only on a refused call) is the same diagnosis delivered in band: relay its `fix` to the brain owner (preview, then the `then` command), confirm with `whoami` afterwards, and do not retry the blocked operations meanwhile. It never names operations, and a missing scope is named only when a call was refused.
- A `hidden_tool_content` notice means the result left out takes that a tool outside your tool list serves. Follow its `fix` as given: call `takes_list` when it names it, call `request_tools {surface}` when it names that (then `takes_list`), or relay the owner's repair when `next` is `tell_user_to_run`. Do not answer "not found" from that result alone.
## Anti-Patterns
diff --git a/plugin/skills/mcp-access/SKILL.md b/plugin/skills/mcp-access/SKILL.md
index 955e3447da..ac4d00b9f3 100644
--- a/plugin/skills/mcp-access/SKILL.md
+++ b/plugin/skills/mcp-access/SKILL.md
@@ -118,7 +118,7 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- A failed transport after a mutation was sent means the outcome is unknown: re-read the client list before retrying, never re-send blind.
- A list call fails: a failed list is not an empty list; report the error.
- A tool the grant should reach is missing (`unknown_tool`, or a write such as `put_pages` absent): read `grant_diagnosis` from `whoami` or `gbrain://capabilities`. It names the blocker (scope, operation snapshot, client pin or server ceiling) and counts the operations it hides without naming them. Relay its `fix` (`next: tell_user_to_run`) to the brain owner; on the host, `gbrain doctor` check `grant_new_ops_available` shows the exact commands. New memory-profile grants are on the full surface; older ones keep their stored surface until the owner changes it. An "original intent unknown" grant may be restricted on purpose: never widen it unasked, and offer `--operations all` (no snapshot, including operations later upgrades add) only as the user's explicit choice.
-- A `grant_blocked_operations` notice (once per session) is the same diagnosis delivered in band: relay its `fix` to the brain owner (preview, then the `then` command), confirm with `whoami` afterwards, and do not retry the blocked operations meanwhile. It never names operations, and a missing scope is named only when a call was refused.
+- A `grant_blocked_operations` notice (once per session; a grant the owner narrowed on purpose gets it only on a refused call) is the same diagnosis delivered in band: relay its `fix` to the brain owner (preview, then the `then` command), confirm with `whoami` afterwards, and do not retry the blocked operations meanwhile. It never names operations, and a missing scope is named only when a call was refused.
- A `hidden_tool_content` notice means the result left out takes that a tool outside your tool list serves. Follow its `fix` as given: call `takes_list` when it names it, call `request_tools {surface}` when it names that (then `takes_list`), or relay the owner's repair when `next` is `tell_user_to_run`. Do not answer "not found" from that result alone.
## Anti-Patterns
diff --git a/plugin/skills/setup/SKILL.md b/plugin/skills/setup/SKILL.md
index 42b72f0ed4..e6fad4f9da 100644
--- a/plugin/skills/setup/SKILL.md
+++ b/plugin/skills/setup/SKILL.md
@@ -40,7 +40,7 @@ Use the user's existing context; do not repeat choices they already made.
| --- | --- |
| Add memory inside Grok Bot | First choice: use the brain on your own computer over MCP — [remote-mcp](../remote-mcp/SKILL.md) publishes it (`--funnel`, the Bot runs in the vendor cloud), then [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md) installs the private handoff in the Bot. No always-on machine: follow [Grok Bot](https://github.com/garrytan/gbrain/blob/master/docs/guides/grok-bot.md) and the isolated [setup helper](https://github.com/garrytan/gbrain/blob/master/docs/guides/in-agent-setup.md). Root: `/workspace/gbrain`, with data under `.gbrain`. |
| Add memory inside Muse | First choice: use the brain on your own computer over MCP — [remote-mcp](../remote-mcp/SKILL.md) publishes it (`--funnel`), then [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md) installs the private handoff in Muse. No always-on machine: follow [Muse](https://github.com/garrytan/gbrain/blob/master/docs/guides/muse.md). Either way, establish its durable user-files location first. Do not invent `MUSE.md`, a persistent path, or a native MCP mechanism. |
-| Memory for a bot that answers several people | `gbrain setup <harness> --serves several --members <id,...>`; ask the user who the people are, never guess. Relay key file paths, never keys, and the `open pages` lines: ask who reads each folder (`--labelled-only` only on their word); keep the owner in every `--readers` list, and pass `--allow-without-owner` only on their word. Fix a `setup_serves_several`, `requester_scope_required` or `credential_scope_required` refusal with its `fix`. Pass `--stdio-member <id>` (claude-code, codex) only for a harness one person uses: it binds that harness's entry alone; refused where OpenClaw or Hermes runs. [Guide](https://github.com/garrytan/gbrain/blob/master/docs/guides/setup.md#a-brain-that-serves-several-people). |
+| Memory for a bot that answers several people | `gbrain setup <harness> --serves several --members <id,...>`; ask the user who the people are, never guess. With no owner set it names one (`--owner <id>`, default the login name); relay its `unbound` lines, and rescope a key only on the user's word. Relay key file paths, never keys, and the `open pages` lines: ask who reads each folder (`--labelled-only` only on their word); keep the owner in every `--readers` list, and pass `--allow-without-owner` only on their word. On `setup_history_choice_required`, ask whether the existing pages stay private (`--labelled-only`) or every member reads them (`--open-history`); never choose for the user. When a re-run's `company/` rule readers wait for `gbrain access apply`, relay it and approve only on the user's word. Fix a `setup_serves_several`, `requester_scope_required` or `credential_scope_required` refusal with its `fix`. Pass `--stdio-member <id>` (claude-code, codex) only for a harness one person uses: it binds that harness's entry alone; refused where OpenClaw or Hermes runs. [Guide](https://github.com/garrytan/gbrain/blob/master/docs/guides/setup.md#a-brain-that-serves-several-people). |
| Add memory to another existing agent | Follow [INSTALL_FOR_AGENTS.md](https://github.com/garrytan/gbrain/blob/master/INSTALL_FOR_AGENTS.md); the [coding-agent tutorial](https://github.com/garrytan/gbrain/blob/master/docs/tutorials/connect-coding-agent.md) covers Claude Code and Codex. |
| Connect an existing hosted brain | Follow [mcp-access](../mcp-access/SKILL.md) and [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md). Select native OAuth/PKCE or a private machine handoff for the intended harness. |
| Use the brain from other devices, apps or cloud agents over MCP | Follow [remote-mcp](../remote-mcp/SKILL.md): `gbrain mcp expose` publishes the local server on the Tailscale tailnet (Funnel only for cloud agents), then [mcp-access](../mcp-access/SKILL.md) / hosted access selects native OAuth or a private machine handoff for each consumer. |
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 75c374b2fa..2c0c0ccf81 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -42,7 +42,7 @@ src/core/persistence/sync-run.ts 1715 ratchet new row: crossed the 1500 unlisted
src/core/persistence/worktree-refresh.ts 1541 ratchet new row: crossed the 1500 unlisted cap in GST-1465/GST-1472/GST-1477 (refresh-recovery ways out: membersPastStart reads partial imports, keepPagesWayOut names a fast-forward, a merge of diverged members or a fetch, underMemberLeases holds every member drain lease for --abandon, adoptsHead shared by recovery and --abandon); these helpers share the module-private withGit, ancestry and refusal seams of the recovery state machine, so they stay beside it; re-measured at the Train A merge of #8930: 1541
src/core/bootstrap/harness.ts 2632 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments); +13 brain-first block lane: --no-instructions flag field + parse, opencodeAgentsPath dep (field + default) and the step-10b / remove call sites (logic lives in harness-brain-first.ts); +7 GBRA-243 per-turn rule hook: consent-block interface field, step-10c call site, turn_hooks JSON field, exit code and the remove arm (writer, host list and consent text live in harness-brain-first.ts); +2 #8428: the harness lane Claude Code and Codex SessionEnd hooks start gbrain through the hook launcher; +16 GBRA-194 skills index lane: --skill-loading flag field + parse, step-10b and remove call sites, skills_index JSON field and exit-code wiring (logic lives in harness-skills-index.ts and setup/skills-block.ts); re-measured at the Train A merge of #8930: 2632
src/core/oauth-provider.ts 1237 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option; +1 GST-1113 transactional token mint
-src/core/ops/pages.ts 744 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (721 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.334.0 merge (727 measured); +1 #7305: capture dry run applies the hyphen-run slug admission (logic in persistence/suffixed-slug.ts); +1 GST-687: get_page include_timeline_entries quotes rows for remote readers (import only; logic in ops/timeline-quote.ts); +2 #8384: the quoted_unverified_origin notice call in get_page and fetch (logic lives in get-page-projection.ts); +1 GBRA-218: put_page checks a remote readable_by before admission (logic in persistence/page-visibility.ts assertSubmittedReaders) (re-summed at the train M merge of master v0.60.539.0: 732 measured); re-summed at the memory train #8481 merge with v0.60.576.0 (739 measured); +4 GBRA-449: an empty list_pages names the page types present when no visible page has the requested type (logic in ops/list-pages-pagination.ts unusedTypeNotice); +1 GST-2462: a static import of the put_page ignored-label notice (a dynamic one yielded on the first put_page, so a queued embedding ran inside it; mode-receipt.serial.test.ts)
+src/core/ops/pages.ts 745 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (721 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.334.0 merge (727 measured); +1 #7305: capture dry run applies the hyphen-run slug admission (logic in persistence/suffixed-slug.ts); +1 GST-687: get_page include_timeline_entries quotes rows for remote readers (import only; logic in ops/timeline-quote.ts); +2 #8384: the quoted_unverified_origin notice call in get_page and fetch (logic lives in get-page-projection.ts); +1 GBRA-218: put_page checks a remote readable_by before admission (logic in persistence/page-visibility.ts assertSubmittedReaders) (re-summed at the train M merge of master v0.60.539.0: 732 measured); re-summed at the memory train #8481 merge with v0.60.576.0 (739 measured); +4 GBRA-449: an empty list_pages names the page types present when no visible page has the requested type (logic in ops/list-pages-pagination.ts unusedTypeNotice); +1 GST-2462: a static import of the put_page ignored-label notice (a dynamic one yielded on the first put_page, so a queued embedding ran inside it; mode-receipt.serial.test.ts); +1 GBRA-585: put_page reports where a sourceless local write landed (static import; logic in access/implicit-placement.ts)
src/core/search/mode.ts 1757 ratchet +12 #7175 (train R): search.keyword_phrase bundle field, config parse and knobsHash part; +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part); +35 GBRA-154: collapse and rank_priors knobs (interface docs, bundles, overrides, pick, config parse, append-only col=/rpr= hash parts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (1704 measured); +5 GBRA-156 #7593: private-pages grant part in the cache key; +7 GBRA-218 A1: append-only xid=/xhp= knobsHash parts (member identity, operator privacy relaxation); +1 GBRA-231: append-only xau= knobsHash part (shared-agent audience identities) (re-summed at the train M .538 merge: 1717 measured); +1 GBRA-283 B2: import of the embedded engine reranker model (engine-gateway.ts); re-summed at the train R merge with v0.60.574.0: 1721 + 9; +1 GST-2490: append-only xol= knobsHash part (owner lineage and the owner opt-in); +1 GBRA-108: append-only xak= knobsHash part (the owner's audience members; member lineage reuses the xol= line as xol=3); +1 GBRA-108 design 1: append-only xlo= knobsHash part (the labelled-only grant); re-measured at the Train A merge of #8943 onto master v0.60.708.0: 1733 + 24 = 1757
src/commands/eval-longmemeval.ts 1545 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter); +1 #7619: parseArgs refuses a value on a switch (--judge=false turned the paid judge on)
src/commands/doctor/checks/extraction-sync.ts 1503 ratchet +7 GBRA-130 A-1: links_extraction_lag held bucket and its retry fix (logic in core/extraction-lag.ts heldExtractionReport); +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge); +1 #7145: content_hash_duplicates reads one group past its list to report a floor ("at least 50"); +3 #7462: atom_provenance_drift resolves a renamed source page through its rename alias (one join; the alias rule lives in core/persistence/atom-origin.ts)
@@ -51,6 +51,6 @@ src/commands/config.ts 1546 ratchet +1 GBRA-216: recall.* config set value refus
src/commands/mcp-expose.ts 1524 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts); +5 GBRA-583: one-click Cursor/Claude link lines in the Next block and verified --status, and install_links in --json (builders live in core/connector-install-links.ts)
src/core/behavior-change-notice.ts 1774 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot) (re-summed at the QM wave merge onto master v0.60.626.0: 1692 + 3); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot); +1 #8477 GST-1158 F2 personal-tools row at the QM wave merge (1695 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 #8483 memory_propose row at the QM wave merge (1696 + 1); +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot); +2 #8479 member-email rows at the QM wave merge (1697 + 2); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +2 access-privacy wave (0.60.649.0): the owner_private_facts_gst2089 and private_labels_write_ahead_gst2092 rows; +1 GBRA-443 private_labels_batch_exit_gbra443 row (rows are data and cannot move), re-summed at the 0.60.650.0 slot on #9038: 1703 + 1; +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.651.0 merge: 1704 + 1; +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (rows are data and cannot move), re-summed at the 0.60.654.0 stack on #9045 6ff5540d: 1705 + 1; +7 QM wave (#9037) rows: attest_scope_read_ops_gst1158, attest_direct_page_writes_deferred_gst1158, personal_sources_gbra284, qm_personal_structured_gst1158, memory_propose_held_writes_gst1158, member_email_link_gst1158, qm_admin_http_gst1094 (re-summed at the 0.60.655.0 stack on #9110 f9b2072e: 1706 + 7); +1 GST-2228 recreated_takes_section_keeps_stored_takes_gst2228 row (since TBD; re-summed at the keep-takes-and-link-dates train merge: 1713 + 1); +1 GST-2228 links_rows_keep_own_dates_gst2228 row (since TBD; re-summed at the same train merge: 1714 + 1); +2 the W1 + memory proposals train (#9133): attest_every_page_write_deferred_gst2249 and memory_proposals_owner_http_gst2407 rows (rows are data and cannot move), re-summed at the #9138 v0.60.661.0 stack merge: 1715 + 2 = 1717 measured; +1 #8903 effect_git_secret_gate_gst1923 row (rows are data and cannot move), re-summed at the 0.60.664.0 stack on #9142 3931adb4: 1717 + 1; +1 GST-2407 PR 3: qm_recall_own_page_contract_v4 row (rows are data and cannot move), re-summed at the 0.60.666.0 stack on #9148 69c12917: 1718 + 1; +2 GST-363 PR 1 and PR 3 (#9135): the serves_several_labels_gst363 and stdio_member_per_harness_gst363 rows; +3 #9134 train rows member_forget_names_host_9101, refresh_fence_retry_id_gst2353 and recorded_read_view_args_gst2214 (rows are data and cannot move), re-summed at the #9134 slot merge onto #8829 dfc24954: 1721 + 3; +3 source-checkouts wave rows (autopilot_git_reconcile_gbra386, unknown_drift_history_rescreen, refresh_abandon_members_gst1465), re-summed at the #9137 stack merge: 1724 + 3; persistence train 13 at 0.60.676.0: its five rows on top of 0.60.675.0; +1 GST-2250 reconcile_publish_opt_out_gst2250 row (since TBD until the merge slot; rows are data and cannot move); +1 #8902 unmanaged_push_history_scan_8902 row (re-summed at the 0.60.678.0 stack on 501742d9: 1733 + 1); +1 GST-2246 maintain_safe_free_phases_gst2246 row (since TBD until the merge slot; rows are data and cannot move), re-summed on the doctor/dream/enrich train at the 0.60.679.0 slot merge onto #9170 82932eda: 1734 + 1; +2 GST-2462 privacy_label_ignored_gst2462 and access_page_rules_gst2462 rows (rows are data and cannot move), re-summed at the #9173 slot merge onto 49a922ef: 1735 + 2; +1 GST-2107 follow-up write_capacity_low_not_refusal_gst2107 row (rows are data and cannot move), re-summed at the 0.60.681.0 slot merge onto #9173 c08d0c8b: 1737 + 1; +1 GST-2490: owner_reads_derived_gst2490 row (rows are data and cannot move); +1 GST-2468: the label_only_operator_repairs_gst2468 row (a BEHAVIOR_CHANGES row cannot move); +1 GST-2446 remember_pageless_reply_gst2446, +1 GST-2492 strict_held_facts_gst2492 and +1 GST-2346 D1 owner_facts_shared_gst2346 rows (rows are data and cannot move), re-summed at the 0.60.685.0 train merge onto #9181 405ea4cf: 1740 + 3; +1 GST-2476: the readers_label_setter_gst2476 row (rows are data and cannot move), re-summed at the #9184 slot merge onto the #9179 train 361d57c6: 1743 + 1; +1 GST-2487: the fence_fact_private_in_place_gst2487 row (rows are data and cannot move), at the same slot merge of #9188 0075f09a: 1744 + 1; +1 GST-2515: the sync_status_commits_waiting_gst2515 row (rows are data and cannot move), at the 0.60.688.0 slot merge onto 599b1234: 1745 + 1; +3 GST-2519: commit_push_untrack_gst2519, db_only_labels_kept_gst2519 and git_ignored_label_repair_gst2519 rows (rows are data and cannot move), re-summed at the 0.60.691.0 slot merge onto #9167 ad4f0aef: 1746 + 3; +3 GST-2492 PR 2: the remember_pageless_ask, strict_fact_writers_held and sync_strict_requires_managed rows (rows are data and cannot move), re-summed at the master v0.60.691.0 merge: 1749 + 3; +3 GST-2346 rows owner_forget_private, owner_forget_readers_page and member_save_withdrawn_scope (rows are data and cannot move), re-summed at the 0.60.693.0 slot merge onto #9202 840858e9: 1752 + 3; +2 GST-2518 page_label_widening_held_gst2518 and GST-2521 owner_labels_guarded_gst2521 rows and +1 GST-2511 fence_fact_widening_held_gst2511 row (rows are data and cannot move), re-summed at the 0.60.694.0 slot merge onto master 2c8320d7: 1755 + 3; +3 the GST-2515/GST-2520 notifier_retry_unwatched_gst2515 and strict_skip_mode_refusal_gst2520 rows and the GST-2456 unmanaged_push_every_site_gst2456 row, re-summed at the 0.60.698.0 slot merge onto #9217 887398f0: 1758 + 3; +2 GST-2407: context_pack scope read and attestRead over the owner route; +9 releases per batch: the generated-table import, the releasedIn helper and its comment, the spread of RELEASED_BEHAVIOR_CHANGES; new rows now live in behavior-changes.d/ and stop growing this file (re-summed at the master v0.60.704.0 merge: 1763 + 9 = 1772 measured); +2 #7646 (GBRA-404 salvage): the disclosure lists releases oldest first whatever the table order
src/core/git/commit-push.ts 1562 ratchet GST-2519: --untrack (#7753 port: untrackTargets, untrackPaths; untrackAdmitted, the managed-worktree storage.db_only admission; previewUntrack) and the staged-removal hint in skippedPathsError grow the commit door past the 1500 default (master 1487 + 140); GST-2456 (#9174): crossed the 1500 unlisted cap at the GST-2456 merge of master v0.60.678.0: pushBase (the scan base and lease read live from every push URL, #5138) and the scan budget and progress options; Ctx and publish internals keep it in this file (1487 + 31), re-summed at the master 0c577834 merge into #9198: 1627 + 31; +47 #8928 salvage rebuild (GBRA-404) #7752: previewPaths (the dry run asks git against a copied index), admitPaths/flaggedEntries/previewRoots split out of commitPaths and shared with it, settlePending exported (re-summed on master v0.60.699.0: 1658 + 47); +1 GBRA-404 /ship round 2: the dry run stages into its temporary index copy for real (staged-rename partner refusal); GST-2767: the git runner (git-run.ts) and the skipped-path checks with their reasons (skipped-paths.ts) moved out, 1600; +14 GST-2767 staged_for_removal refusal and dry-run skipped-path parity; +1 commit_paths_unmerged: admitPaths calls assertNoUnmergedPaths (skipped-paths.ts); GST-2964: the untrack admission (untrackTargets, untrackAdmitted, untrackPageCandidates) moved to untrack-admission.ts, 1561; +1 the relativeEscapesRoot import (path-confine.ts, #9606) so a ..drafts folder is not read as outside the checkout, 1562
-src/commands/auth.ts 1512 ratchet new row: crossed the 1500 unlisted cap at the v0.60.595.0 merge: GST-1113 --attest-sources help lines plus GST-1158 F3 --attest-read help lines (3); CLI help lines cannot move; re-measured at the Train A merge onto master v0.60.708.0: 1503 + 2 (the #8930 shared-token notice) = 1505; re-measured at the Train C merge onto Train B (#9246 onto #9223): 1505 -> 1509, both sides' growth; +3 Wakeshift PR 2 (#8709), one line each: revoke (by name) calls forgetWakePrincipal for every token row its UPDATE returned (RETURNING 1 became RETURNING id, so no line added there), revokeById calls it for the revoked token id, and revokeClient calls it for the revoked OAuth client id; each call ends that principal's open watches and queues its Wakeshift forget (logic in core/wakeshift/forget.ts) after the command's own UPDATE/DELETE; master 1509 + 3 = 1512
+src/commands/auth.ts 1518 ratchet new row: crossed the 1500 unlisted cap at the v0.60.595.0 merge: GST-1113 --attest-sources help lines plus GST-1158 F3 --attest-read help lines (3); CLI help lines cannot move; re-measured at the Train A merge onto master v0.60.708.0: 1503 + 2 (the #8930 shared-token notice) = 1505; re-measured at the Train C merge onto Train B (#9246 onto #9223): 1505 -> 1509, both sides' growth; +3 Wakeshift PR 2 (#8709), one line each: revoke (by name) calls forgetWakePrincipal for every token row its UPDATE returned (RETURNING 1 became RETURNING id, so no line added there), revokeById calls it for the revoked token id, and revokeClient calls it for the revoked OAuth client id; each call ends that principal's open watches and queues its Wakeshift forget (logic in core/wakeshift/forget.ts) after the command's own UPDATE/DELETE; master 1509 + 3 = 1512; +6 GBRA-585 E: auth create --member defaults to read,write (MEMBER_TOKEN_SCOPES, its help lines and the output note) = 1518
src/core/markdown.ts 1501 ratchet new row: crossed the 1500 unlisted cap at the train C merge: #8921 #7052 tag_too_long hold (tagLengthHold import; the limit lives in core/tag-limit.ts) on top of master's 1500
-src/mcp/dispatch.ts 1502 ratchet new row: crossed the 1500 unlisted cap with GBRA-504 guest notes (+4): the guest attribution option threaded into dispatch (parsing and checks live in core/guests/admission.ts); next growth should peel the response-cap block into a sibling module
+src/mcp/dispatch.ts 1505 ratchet new row: crossed the 1500 unlisted cap with GBRA-504 guest notes (+4): the guest attribution option threaded into dispatch (parsing and checks live in core/guests/admission.ts); next growth should peel the response-cap block into a sibling module; +3 GBRA-585: DispatchOpts.localSourceImplicit and its pass-through to the op context (placement logic in core/access/implicit-placement.ts)
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index c62bead269..fee588da52 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -279,6 +279,7 @@ test/persistence-request-indexes.test.ts (file-level) 4 readFileSync
test/persistence-sync-options.serial.test.ts (file-level) 1 readFileSync
test/pg-access-classify.test.ts marker contract (skill↔binary lockstep, the UPGRADE_AVAILABLE pattern) 3 bun-file
test/pglite-engine.test.ts PGLiteEngine: v0.13.1 error-wrap on connect() (#223) 1 source-surface-helper
+test/pglite-live-serve-setup-gbra585.test.ts PGLite with a running serve (GBRA-585 item 10) 2 readFileSync
test/pglite-repair-command.serial.test.ts gbrain pglite-repair — interactive confirm wiring (#4318 residual) 1 readFileSync
test/pglite-wal-repair.serial.test.ts WAL auto-repair — real-brain regression (#223/#1670/#2575) 6 source-surface-helper
test/physical-root-birth-tolerance-6501.test.ts physical root birth drift (${kind}) 5 readFileSync
diff --git a/skills/mcp-access/SKILL.md b/skills/mcp-access/SKILL.md
index 07e73b58cd..a3037446cf 100644
--- a/skills/mcp-access/SKILL.md
+++ b/skills/mcp-access/SKILL.md
@@ -117,7 +117,7 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- A failed transport after a mutation was sent means the outcome is unknown: re-read the client list before retrying, never re-send blind.
- A list call fails: a failed list is not an empty list; report the error.
- A tool the grant should reach is missing (`unknown_tool`, or a write such as `put_pages` absent): read `grant_diagnosis` from `whoami` or `gbrain://capabilities`. It names the blocker (scope, operation snapshot, client pin or server ceiling) and counts the operations it hides without naming them. Relay its `fix` (`next: tell_user_to_run`) to the brain owner; on the host, `gbrain doctor` check `grant_new_ops_available` shows the exact commands. New memory-profile grants are on the full surface; older ones keep their stored surface until the owner changes it. An "original intent unknown" grant may be restricted on purpose: never widen it unasked, and offer `--operations all` (no snapshot, including operations later upgrades add) only as the user's explicit choice.
-- A `grant_blocked_operations` notice (once per session) is the same diagnosis delivered in band: relay its `fix` to the brain owner (preview, then the `then` command), confirm with `whoami` afterwards, and do not retry the blocked operations meanwhile. It never names operations, and a missing scope is named only when a call was refused.
+- A `grant_blocked_operations` notice (once per session; a grant the owner narrowed on purpose gets it only on a refused call) is the same diagnosis delivered in band: relay its `fix` to the brain owner (preview, then the `then` command), confirm with `whoami` afterwards, and do not retry the blocked operations meanwhile. It never names operations, and a missing scope is named only when a call was refused.
- A `hidden_tool_content` notice means the result left out takes that a tool outside your tool list serves. Follow its `fix` as given: call `takes_list` when it names it, call `request_tools {surface}` when it names that (then `takes_list`), or relay the owner's repair when `next` is `tell_user_to_run`. Do not answer "not found" from that result alone.
## Anti-Patterns
diff --git a/skills/setup/SKILL.md b/skills/setup/SKILL.md
index 77dc1dfa6c..7ca6da28b6 100644
--- a/skills/setup/SKILL.md
+++ b/skills/setup/SKILL.md
@@ -39,7 +39,7 @@ Use the user's existing context; do not repeat choices they already made.
| --- | --- |
| Add memory inside Grok Bot | First choice: use the brain on your own computer over MCP — [remote-mcp](../remote-mcp/SKILL.md) publishes it (`--funnel`, the Bot runs in the vendor cloud), then [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md) installs the private handoff in the Bot. No always-on machine: follow [Grok Bot](https://github.com/garrytan/gbrain/blob/master/docs/guides/grok-bot.md) and the isolated [setup helper](https://github.com/garrytan/gbrain/blob/master/docs/guides/in-agent-setup.md). Root: `/workspace/gbrain`, with data under `.gbrain`. |
| Add memory inside Muse | First choice: use the brain on your own computer over MCP — [remote-mcp](../remote-mcp/SKILL.md) publishes it (`--funnel`), then [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md) installs the private handoff in Muse. No always-on machine: follow [Muse](https://github.com/garrytan/gbrain/blob/master/docs/guides/muse.md). Either way, establish its durable user-files location first. Do not invent `MUSE.md`, a persistent path, or a native MCP mechanism. |
-| Memory for a bot that answers several people | `gbrain setup <harness> --serves several --members <id,...>`; ask the user who the people are, never guess. Relay key file paths, never keys, and the `open pages` lines: ask who reads each folder (`--labelled-only` only on their word); keep the owner in every `--readers` list, and pass `--allow-without-owner` only on their word. Fix a `setup_serves_several`, `requester_scope_required` or `credential_scope_required` refusal with its `fix`. Pass `--stdio-member <id>` (claude-code, codex) only for a harness one person uses: it binds that harness's entry alone; refused where OpenClaw or Hermes runs. [Guide](https://github.com/garrytan/gbrain/blob/master/docs/guides/setup.md#a-brain-that-serves-several-people). |
+| Memory for a bot that answers several people | `gbrain setup <harness> --serves several --members <id,...>`; ask the user who the people are, never guess. With no owner set it names one (`--owner <id>`, default the login name); relay its `unbound` lines, and rescope a key only on the user's word. Relay key file paths, never keys, and the `open pages` lines: ask who reads each folder (`--labelled-only` only on their word); keep the owner in every `--readers` list, and pass `--allow-without-owner` only on their word. On `setup_history_choice_required`, ask whether the existing pages stay private (`--labelled-only`) or every member reads them (`--open-history`); never choose for the user. When a re-run's `company/` rule readers wait for `gbrain access apply`, relay it and approve only on the user's word. Fix a `setup_serves_several`, `requester_scope_required` or `credential_scope_required` refusal with its `fix`. Pass `--stdio-member <id>` (claude-code, codex) only for a harness one person uses: it binds that harness's entry alone; refused where OpenClaw or Hermes runs. [Guide](https://github.com/garrytan/gbrain/blob/master/docs/guides/setup.md#a-brain-that-serves-several-people). |
| Add memory to another existing agent | Follow [INSTALL_FOR_AGENTS.md](https://github.com/garrytan/gbrain/blob/master/INSTALL_FOR_AGENTS.md); the [coding-agent tutorial](https://github.com/garrytan/gbrain/blob/master/docs/tutorials/connect-coding-agent.md) covers Claude Code and Codex. |
| Connect an existing hosted brain | Follow [mcp-access](../mcp-access/SKILL.md) and [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md). Select native OAuth/PKCE or a private machine handoff for the intended harness. |
| Use the brain from other devices, apps or cloud agents over MCP | Follow [remote-mcp](../remote-mcp/SKILL.md): `gbrain mcp expose` publishes the local server on the Tailscale tailnet (Funnel only for cloud agents), then [mcp-access](../mcp-access/SKILL.md) / hosted access selects native OAuth or a private machine handoff for each consumer. |
diff --git a/skills/skills.lock.history.json b/skills/skills.lock.history.json
index 613c74d2ca..270e0bed49 100644
--- a/skills/skills.lock.history.json
+++ b/skills/skills.lock.history.json
@@ -612,6 +612,7 @@
"mcp-access/SKILL.md": [
"1bc16338b89f476aa8c24ffec79c989fa60716793998af264d357f7886d2bc96",
"4373e0164981eb7f8cd3794a2eae895d77426cef478c8d9d959de585256d4b50",
+ "49dca25ce5e02a442a8d1c613980726a0f0eba299f70613bab281283368e1ff7",
"77f67fb2c07e891e945a5466ae075a3f9d488ef31e86150a99ed5341a782f73f",
"c2ff223b4461ba5817c6c0e7b50a1006866204b6c1d4bd905e52809350ecd092",
"d308714208f457a9853fec4e83fe035dcd911bc8e506cefec817bd218f3340df",
@@ -1083,6 +1084,7 @@
"setup/SKILL.md": [
"03216a34292ccc44984bca614d5dcf5f2afd1d762a0222c603dd2bc67f047a22",
"1cfb85220ef53a8575a54137ab45296a36e5d00652d1e71e8f569315b425b027",
+ "310b973119a6f3366aa31a34a0d6d3323d37f7ea79b7ff7b39c316cba379d988",
"322faf7099afd71f9add0f6dbe4d2bf9686df54c521a29e018f4ab25608e3dc0",
"427f8703034bf220b87698d0a6b66a74fe767180ba0bd9108d56e781facd679b",
"4a47a5f6ee99ac8a2649a304abb261fd34810cf6185fd7d6a53e1b6c4cbc0764",
@@ -1095,10 +1097,12 @@
"a0c49b3b1f6ff4eaadd64d57bfd54e7c0a090dc33e7b490d95d913441c5821ea",
"a0f9d72565b489c4a60f6546b89218ea9efc307b397ac5ea22f3ed4c737f73f1",
"b73d9f9c93d419d812b39e47160790f8510bcd8564910b9f02aee51e673ad41f",
+ "b8fc92ee7c4e4bfb282331fcfbb45b5c5354c340ecc06ce9a4548c9f5f80c379",
"c82b1e1b97e058991bc52287c24a26628d7d66bed409642023a20457e7f15f05",
"d5250abf65d7fb822646232ed6a27a09ac4443377065b58182292023c6b3606a",
"d6b82f858e60699ff8c5ee82d61c94a98c2fbc7a852b5f74571e7ab3f0921139",
- "f014513080eb81e90f0cc0203ca944698fdff250059be0267f0498c5b69c5416"
+ "f014513080eb81e90f0cc0203ca944698fdff250059be0267f0498c5b69c5416",
+ "f65cbdee8b6153bf2557766de5e9887f2702b8d80ac32e3c875c45442eef249e"
],
"signal-detector/SKILL.md": [
"0ffa92ceee026f8ce1fa6fbea45dc8ebe9689a36d13683ec102c33402a50898a",
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 9328589f45..3cfd2e8578 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -97,7 +97,7 @@
"ingest/SKILL.md": "1acc220ce6e9e65876fa2ccede6ce11f9c75457feb6695ef904955f8debecaae",
"maintain/SKILL.md": "c23b9a91edb5f11306a31a3b00d5262f9f7250eee266a608f2f1bdafecbdde74",
"manifest.json": "f9d16966d26fe9b37ef6ce9609eaa29d06142a409f3b531f1289b1a8c1bc929e",
- "mcp-access/SKILL.md": "4373e0164981eb7f8cd3794a2eae895d77426cef478c8d9d959de585256d4b50",
+ "mcp-access/SKILL.md": "49dca25ce5e02a442a8d1c613980726a0f0eba299f70613bab281283368e1ff7",
"measure-before-you-fix/SKILL.md": "11906da29a1a31976b13d4796b686d9a9981825737846a85f32d88bf431b9b36",
"measure-before-you-fix/routing-eval.jsonl": "0661df9974a9cfe31216d574b1db0ef341945c2eb844ebf4ab6920fcbbc90d6c",
"media-ingest/SKILL.md": "d70374d3df21397380203f541ebdcc90c0bc6bc7207234349594a081e98f2719",
@@ -212,7 +212,7 @@
"resolve-before-asking/routing-eval.jsonl": "bac1bcf30337f5255ef4ce1a2a8a2b38d58ebcd576503c483190c79ec6e69489",
"schema-author/SKILL.md": "38efb8b48399a2dc526d7084579aa265b2ab232882605bc2f86f6ba2869619f5",
"schema-unify/SKILL.md": "36259f1510fd693253535bd203e32db1bfa24aaae7278c7a2e8b7d6859022708",
- "setup/SKILL.md": "a0c49b3b1f6ff4eaadd64d57bfd54e7c0a090dc33e7b490d95d913441c5821ea",
+ "setup/SKILL.md": "f65cbdee8b6153bf2557766de5e9887f2702b8d80ac32e3c875c45442eef249e",
"signal-detector/SKILL.md": "426a8a3b01a007dd25638e61adef510c18c3d9ce6f1c18ba3d77fdfcd3281d60",
"skill-autobench/SKILL.md": "29f5760dcfd823c5f7d4fb50a3cf4e36601b1b8125e57d6bf83645a41f97f613",
"skill-autobench/routing-eval.jsonl": "8d961ed6403b7e2f690948e4c18529d40f26f6f21064befc56d465966b1a9ec0",
@@ -226,7 +226,7 @@
"skillpack-check/SKILL.md": "0d2d2d201ed72e19b47d7e3743b5bbdfb5c2655d1f34d29447c601fca3908f9e",
"skillpack-harvest/SKILL.md": "0f86314b58d25b5511809f567c04aedc3fba6fe35ed642ac52d8216ae365b6eb",
"skillpack-harvest/routing-eval.jsonl": "cb4783288e95af3132b32ecb40a54cffc095f57b36240f96a25c2d2adf5e68c6",
- "skills.lock.history.json": "09610dd63a53ebb252ff98d9f0058d84a5d01c27e2279b971c2c0af2de9c349c",
+ "skills.lock.history.json": "3d73c9db7274e3269ddc81f5823c569488e92796f41319fb2172b19f9a7df4f8",
"smoke-test/SKILL.md": "f5099e1d2ab9dc6827096249e68414f7ae357c29b39fb069a54bb7fb74f414a5",
"soul-audit/SKILL.md": "7a48e180849f7502d332878c443397f90a3756f45caa94f76bcfcc7c997469c8",
"storage-manifest/SKILL.md": "1debbefba61007a17cda1525496875d1edfde90642adf3ec031f25a71724807e",
diff --git a/src/cli/cli-error.ts b/src/cli/cli-error.ts
index c8debbd4d5..76df0dcbb0 100644
--- a/src/cli/cli-error.ts
+++ b/src/cli/cli-error.ts
@@ -178,6 +178,7 @@ export function writeFatalCliError(e: unknown, opts: { argv?: readonly string[];
const err = opError('pglite_busy', String(busy.message ?? 'The brain is busy.'), suggestion, {
...(typeof busy.reason === 'string' ? { reason: busy.reason } : {}),
...(fix ? { fix } : {}),
+ ...(busy.reason === 'live_serve' ? { docs: 'docs/ENGINES.md#pglite-live-serve' } : {}),
});
return writeCliError(err, command, { argv, legacy: { error: 'pglite_busy', retryable: true, reason: busy.reason, next_action: next } });
}
diff --git a/src/commands/access-rules.ts b/src/commands/access-rules.ts
index a042ba04e8..68d9b49106 100644
--- a/src/commands/access-rules.ts
+++ b/src/commands/access-rules.ts
@@ -395,7 +395,8 @@ async function ruleCmd(engine: BrainEngine, sub: string | undefined, args: strin
const preview = await previewRules(engine, sourceId, store, persisted, desired);
if (!yes) {
const stranded = json ? [] : await ruleReadByNobodyLines(engine, sourceId, desired, Object.keys(preview.matched_pages));
- return print(json, { ...preview, applied: false }, () => previewLines(preview, `gbrain access rule ${[sub, ...args.filter(a => a !== '--json')].join(' ')} --yes`).toSpliced(-2, 0, ...stranded));
+ const kept = args.filter((a, i) => a !== '--json' && a !== '--expect' && args[i - 1] !== '--expect');
+ return print(json, { ...preview, applied: false }, () => previewLines(preview, `gbrain access rule ${[sub, ...kept].join(' ')} --yes --expect ${preview.expect}`).toSpliced(-2, 0, ...stranded));
}
const r = await writeRules(engine, sourceId, desired, { expect, operation, message, json });
if (r.state === 'invalid') setCliExitVerdict(1);
diff --git a/src/commands/access-serves.ts b/src/commands/access-serves.ts
index 8f02de459e..968d3a5cb0 100644
--- a/src/commands/access-serves.ts
+++ b/src/commands/access-serves.ts
@@ -2,7 +2,7 @@
* GST-363 (PR 1): `gbrain access serves`, the labelling half of a brain that serves several people.
*
* gbrain access serves [--json] [--no-open-pages] Read-only: one or several, why, owner, stdio member, open pages
- * gbrain access serves several --members a,b [--members-file f] [--source id] [--labelled-only] [--yes] [--json]
+ * gbrain access serves several --members a,b [--members-file f] [--source id] [--labelled-only] [--owner id] [--yes] [--json]
*
* `several` previews, then with --yes: writes config access.serves = several, adds each member (existing ones are
* kept), adds one folder rule per member (people/<member>/ readable by that member) through the folder-rule path
@@ -15,6 +15,15 @@
* GST-2670: the preview, the receipt and the read-only status also count the pages every member's key can still read
* (core/access/open-pages.ts, best effort: a failed count never stops the run), and --labelled-only marks each member
* of the roster labelled-only after the members step (never the owner, refused before anything is written).
+ * GBRA-585 D: --owner <id> names the brain owner when none is configured (the member is added when missing, then
+ * `access owner set`); a configured owner is kept. No credential is rebound: the receipt lists the live credentials
+ * bound to no member, each with the `gbrain auth rescope … --member <owner>` command that binds it on purpose.
+ * GBRA-585 A: a key minted here gets a fixed source list (the federated grant kind): it writes to the run's source and
+ * reads that source, `company` when it exists and every source federated at mint time (memberKeyReadSources). A
+ * re-run adds sources to a key of this name that already holds a list for this source, and never removes one, but only
+ * while that list is still the one setup last gave the key (permissions.setup_reads): a key changed by hand is skipped
+ * and named with the rescope command, a source archived since is dropped from the list, and a key whose write source is
+ * archived is BLOCKED (its write source never moves); any other kept key (today's default or scalar grant) is never changed. The preview names the list and what `company` holds.
*/
import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
import { dirname, join, relative } from 'node:path';
@@ -24,13 +33,15 @@ import { hashToken } from '../core/utils.ts';
import { opError } from '../core/ops/contract.ts';
import { usageError } from '../cli/cli-error.ts';
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
-import { normalizeRule, type FolderRule } from '../core/access/folder-rules.ts';
-import { addMember, getMember, parseIdList } from '../core/access/members.ts';
-import { hintReaders, ownerMemberId } from '../core/access/owner.ts';
+import { normalizeRule, ruleIdForPrefix, type FolderRule } from '../core/access/folder-rules.ts';
+import { addMember, assertAccessId, getMember, listMembers, parseIdList } from '../core/access/members.ts';
+import { hintReaders, ownerMemberId, ownerView, setOwner } from '../core/access/owner.ts';
import { stdioMemberId } from '../core/access/caller.ts';
import { brainServes, SERVES_KEY, unlabeledPeopleFolders, type PeopleFolder, type ServesView } from '../core/access/serves.ts';
import { setMemberLabelledOnly } from '../core/access/labelled-only.ts';
-import { openPagesLines, readOpenPages, type OpenPagesError, type OpenPagesRead } from '../core/access/open-pages.ts';
+import { COMPANY_SOURCE_ID, memberKeyReadSources, openPagesLines, readOpenPages, type OpenPagesError, type OpenPagesRead } from '../core/access/open-pages.ts';
+import { rescopeLegacyToken } from '../core/grants/legacy-token.ts';
+import { coerceLegacyPermissions } from '../core/legacy-token-scope.ts';
import type { OpenPages } from '../core/access/open-pages.ts';
import { addFolderRules, currentFolderRules } from './access-rules.ts';
import { mintToken } from './auth-mint.ts';
@@ -39,18 +50,33 @@ export const MEMBER_KEY_DIR = 'member-keys';
export const memberKeyName = (member: string): string => `member-${member}`;
export const memberKeyDir = (): string => join(configDir(), MEMBER_KEY_DIR);
+type RuleWrite = { store: string; revision: number | null; state: string; git_commit?: string | null };
+
export interface ServesStatus extends ServesView { owner: string | null; stdio_member: string | null; open_pages?: OpenPages | null; open_pages_error?: OpenPagesError }
-type Step = 'members' | 'labelled_only' | 'rules' | 'keys' | 'config';
+type Step = 'members' | 'owner' | 'labelled_only' | 'rules' | 'keys' | 'config';
export interface ServesReceipt {
serves: 'several';
source_id: string;
applied: boolean;
config: { key: string; value: 'several'; action: 'write' | 'keep' };
members: Array<{ id: string; action: 'add' | 'keep' | 'blocked'; detail?: string; labelled_only?: 'set' | 'keep' }>;
+ /** GBRA-585 D (--owner): the owner this run adds and names, names, or keeps (a configured owner always wins). */
+ owner?: { id: string; action: 'add' | 'set' | 'keep' | 'blocked'; detail?: string };
+ /** GBRA-585 D (--owner): live credentials bound to no member, each with the command that binds it to the owner. Never rebound here. */
+ unbound?: Array<{ kind: 'token' | 'client'; name: string; command: string }>;
rules: Array<{ id: string; prefix: string; readers: string[]; action: 'add' | 'keep' | 'blocked'; detail?: string }>;
- rule_write?: { store: string; revision: number | null; state: string; git_commit?: string | null };
- keys: Array<{ member: string; token_name: string; path: string; action: 'mint' | 'keep' | 'blocked'; detail?: string }>;
+ rule_write?: RuleWrite;
+ /**
+ * GBRA-585 C: on a --labelled-only run once the company source exists, one folder rule company/ in source company,
+ * readable by the owner, this run's members and every enabled member who is not labelled-only (who read those pages
+ * today), so labelled-only members still read the company pages. A re-run only adds readers.
+ */
+ company_rule?: { source: string; id: string; prefix: string; readers: string[]; adds?: string[]; action: 'add' | 'keep' | 'blocked'; detail?: string; write?: RuleWrite };
+ /** GBRA-585 A: reads = the source list a minted or list key holds once the run is done; adds = what a re-run adds to a kept list key. */
+ keys: Array<{ member: string; token_name: string; path: string; action: 'mint' | 'keep' | 'skipped' | 'blocked'; detail?: string; reads?: string[]; adds?: string[] }>;
+ /** GBRA-585 A: what the keys this run mints write and read, and what the company source holds when they read it. */
+ reads?: { write: string; sources: string[]; company: { pages: number; calls: number } | null };
key_dir: string;
/** People folders with pages that no rule covers once this run's rules are in place: every member reads them. */
unlabeled: PeopleFolder[];
@@ -92,7 +118,29 @@ export async function servesStatus(engine: BrainEngine, opts: { openPages?: bool
return view.serves === 'several' && opts.openPages !== false ? { ...status, ...await readOpenPages(engine) } : status;
}
-async function plan(engine: BrainEngine, roster: string[], sourceId: string, labelledOnly: boolean): Promise<ServesReceipt> {
+/** The owner for --owner: a configured owner (live or not) is kept; otherwise the requested member, added when missing. */
+async function planOwner(engine: BrainEngine, requested: string): Promise<NonNullable<ServesReceipt['owner']>> {
+ const view = await ownerView(engine);
+ if (view.owner) return { id: view.owner, action: 'keep' };
+ if (view.inactive) return { id: view.inactive.value, action: 'keep', detail: `configured as the owner but not usable (${view.inactive.reason}), so no caller reads as the owner; name an enabled member with gbrain access owner set <member>` };
+ const m = await getMember(engine, requested);
+ if (!m) return { id: requested, action: 'add' };
+ if (m.status !== 'enabled') return { id: requested, action: 'blocked', detail: m.status === 'disabled' ? `member is disabled: enable it with gbrain access member enable ${requested}, or name another owner with --owner` : 'member id was removed and can never be reused; name another owner with --owner' };
+ if (m.labelled_only) return { id: requested, action: 'blocked', detail: `${requested} is labelled-only, and the owner reads the whole brain: clear it (gbrain access member labelled-only ${requested} off) or name another owner with --owner` };
+ return { id: requested, action: 'set' };
+}
+
+/** Live tokens and OAuth clients bound to no member, with the rescope command that binds each to `owner`. */
+async function unboundCredentials(engine: BrainEngine, owner: string): Promise<NonNullable<ServesReceipt['unbound']>> {
+ const tokens = await engine.executeRaw<{ name: string }>('SELECT DISTINCT name FROM access_tokens WHERE revoked_at IS NULL AND member_id IS NULL ORDER BY name');
+ const clients = await engine.executeRaw<{ client_id: string }>('SELECT client_id FROM oauth_clients WHERE deleted_at IS NULL AND member_id IS NULL ORDER BY client_id');
+ return [
+ ...tokens.map(t => ({ kind: 'token' as const, name: t.name, command: `gbrain auth rescope --token ${t.name} --member ${owner}` })),
+ ...clients.map(c => ({ kind: 'client' as const, name: c.client_id, command: `gbrain auth rescope --client ${c.client_id} --member ${owner}` })),
+ ];
+}
+
+async function plan(engine: BrainEngine, roster: string[], sourceId: string, labelledOnly: boolean, requestedOwner?: string): Promise<ServesReceipt> {
const keyDir = memberKeyDir();
const gitRoot = gitRootAbove(keyDir);
if (gitRoot) {
@@ -101,7 +149,8 @@ async function plan(engine: BrainEngine, roster: string[], sourceId: string, lab
{ why: 'Key files hold live credentials and must never sit where a commit could pick them up.' });
}
const explicit = (await engine.getConfig(SERVES_KEY))?.trim();
- const owner = await ownerMemberId(engine);
+ const ownerPlan = requestedOwner ? await planOwner(engine, requestedOwner) : undefined;
+ const owner = ownerPlan && ownerPlan.action !== 'blocked' ? ownerPlan.id : await ownerMemberId(engine);
const members: ServesReceipt['members'] = [];
for (const id of roster) {
const m = await getMember(engine, id);
@@ -128,28 +177,102 @@ async function plan(engine: BrainEngine, roster: string[], sourceId: string, lab
return { id: r.rule.id, prefix: r.rule.prefix, readers: r.rule.readable_by, action: 'blocked',
detail: `rule "${clash.id}" on ${clash.prefix} already exists, readable by ${readers}, not by ${id} alone; change it with gbrain access rule add --id ${clash.id} --prefix ${clash.prefix} --readers ${hinted[i]} --source ${sourceId}` };
});
+ const desired = await memberKeyReadSources(engine, sourceId);
+ const companyRule = labelledOnly && desired.includes(COMPANY_SOURCE_ID) ? await planCompanyRule(engine, members, owner) : undefined;
const keys: ServesReceipt['keys'] = [];
for (const id of roster) {
const name = memberKeyName(id);
const path = join(keyDir, `${id}.key`);
- const [token] = await engine.executeRaw<{ member_id: string | null; token_hash: string }>('SELECT member_id, token_hash FROM access_tokens WHERE name = $1 AND revoked_at IS NULL', [name]);
+ const [token] = await engine.executeRaw<{ member_id: string | null; token_hash: string; source_grant: string | null; source_id: string | null; federated_read: unknown; permissions: unknown }>('SELECT member_id, token_hash, source_grant, source_id, federated_read, permissions FROM access_tokens WHERE name = $1 AND revoked_at IS NULL', [name]);
if (members.find(m => m.id === id)?.action === 'blocked') keys.push({ member: id, token_name: name, path, action: 'blocked', detail: 'the member is not enabled' });
else if (!token && existsSync(path)) keys.push({ member: id, token_name: name, path, action: 'blocked', detail: `a key file is already at ${path} but no live key is named ${name} (another brain's key, or one revoked by hand); move or delete the file, then run this again` });
- else if (!token) keys.push({ member: id, token_name: name, path, action: 'mint' });
+ else if (!token) keys.push({ member: id, token_name: name, path, action: 'mint', reads: desired });
else if (token.member_id !== id) keys.push({ member: id, token_name: name, path, action: 'blocked', detail: `a token named ${name} exists but is not bound to ${id}; revoke it (gbrain auth revoke ${name}) or bind it (gbrain auth rescope --token ${name} --member ${id})` });
else if (!existsSync(path)) keys.push({ member: id, token_name: name, path, action: 'blocked', detail: `the key ${name} exists but its file is gone and a key is shown only once; revoke it (gbrain auth revoke ${name}) and run this again to mint a new one` });
else if (hashToken(readFileSync(path, 'utf8').trim()) !== token.token_hash) keys.push({ member: id, token_name: name, path, action: 'blocked', detail: `the file does not hold the live key ${name} (it was revoked and made again, or another brain wrote it); revoke it (gbrain auth revoke ${name}), delete ${path} and run this again to mint a new one` });
- else keys.push({ member: id, token_name: name, path, action: 'keep' });
+ else if (token.source_grant !== 'federated' || token.source_id !== sourceId) keys.push({ member: id, token_name: name, path, action: 'keep' });
+ else {
+ const held = textList(token.federated_read);
+ const adds = desired.filter(s => !held.includes(s));
+ const active = new Set((await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE id = ANY($1::text[]) AND archived IS NOT TRUE', [held])).map(r => r.id));
+ const reads = [...held.filter(s => active.has(s)), ...adds];
+ const minted = setupReads(token.permissions);
+ if (!active.has(sourceId)) {
+ keys.push({ member: id, token_name: name, path, action: 'blocked', reads: held,
+ detail: `its write source ${sourceId} is archived, so setup leaves the key as it is and never moves where it writes; repoint it with gbrain auth rescope --token ${name} --sources <new write source>${reads.length ? `,${reads.join(',')}` : ''}, or revoke it with gbrain auth revoke ${name}` });
+ } else if (adds.length && !(minted && sameSet(minted, held))) {
+ keys.push({ member: id, token_name: name, path, action: 'skipped', reads: held,
+ detail: `its source list (${held.join(', ')}) is not the one setup gave it${minted ? ` (${minted.join(', ')})` : ''}, so setup leaves it as it is and does not add ${adds.join(', ')}; to add them, run gbrain auth rescope --token ${name} --sources ${reads.join(',')}` });
+ } else keys.push({ member: id, token_name: name, path, action: 'keep', reads: adds.length ? reads : held, ...(adds.length ? { adds } : {}) });
+ }
}
return { serves: 'several', source_id: sourceId, applied: false, config: { key: SERVES_KEY, value: 'several', action: explicit === 'several' ? 'keep' : 'write' },
- members, rules, keys, key_dir: keyDir, unlabeled: await unlabeledOutside(engine, sourceId, rules), ...await openPagesFor(engine, sourceId, members, rules, labelledOnly), completed: [] };
+ members, ...(ownerPlan ? { owner: ownerPlan, unbound: ownerPlan.action === 'blocked' ? [] : await unboundCredentials(engine, ownerPlan.id) } : {}),
+ rules, ...(companyRule ? { company_rule: companyRule } : {}), keys, reads: { write: sourceId, sources: desired, company: desired.includes(COMPANY_SOURCE_ID) ? await companyCounts(engine) : null }, key_dir: keyDir,
+ unlabeled: await unlabeledOutside(engine, sourceId, rules), ...await openPagesFor(engine, sourceId, members, rules, labelledOnly, owner, companyRule), completed: [] };
+}
+
+/** GBRA-585 C: the company/ rule a --labelled-only run adds or widens (ServesReceipt.company_rule); it never removes a reader. */
+async function planCompanyRule(engine: BrainEngine, members: ServesReceipt['members'], owner: string | null): Promise<NonNullable<ServesReceipt['company_rule']>> {
+ const at = { source: COMPANY_SOURCE_ID, id: ruleIdForPrefix(`${COMPANY_SOURCE_ID}/`), prefix: `${COMPANY_SOURCE_ID}/` };
+ if (!owner) return { ...at, readers: [], action: 'blocked', detail: "its readers start with the brain owner and this brain has none; run again with --owner and the owner's member id" };
+ const base = await currentFolderRules(engine, COMPANY_SOURCE_ID);
+ const existing = base.find(b => b.prefix === at.prefix);
+ const clash = existing ? undefined : base.find(b => b.id === at.id);
+ if (clash) return { ...at, readers: [], action: 'blocked', detail: `rule "${clash.id}" in source company already covers ${clash.prefix}; give it another id with gbrain access rule add --id <new id> --prefix ${clash.prefix} --source company, then run this again` };
+ const open = (await listMembers(engine)).filter(m => m.status === 'enabled' && !m.labelled_only).map(m => m.id);
+ const held = existing?.readable_by ?? [];
+ const adds = [...new Set([owner, ...members.filter(m => m.action !== 'blocked').map(m => m.id), ...open].map(m => `member:${m}`))].filter(p => !held.includes(p)).sort();
+ return { ...at, id: existing?.id ?? at.id, readers: [...held, ...adds].sort(), ...(existing && adds.length ? { adds } : {}), action: existing && !adds.length ? 'keep' : 'add' };
+}
+
+/** A text[] column value as a list (Postgres returns an array, PGLite may return the {a,b} literal). */
+const textList = (v: unknown): string[] => Array.isArray(v) ? v.map(String) : String(v ?? '').replace(/^\{|\}$/g, '').split(',').map(s => s.trim().replace(/^"|"$/g, '')).filter(Boolean);
+
+const sameSet = (a: string[], b: string[]): boolean => a.length === b.length && a.every(s => b.includes(s));
+
+/** GBRA-585 A: the source list setup last gave a member key, kept in its permissions JSON, whose unrelated fields every grant write keeps. */
+const setupReads = (permissions: unknown): string[] | undefined => {
+ const v = coerceLegacyPermissions(permissions)?.setup_reads;
+ return Array.isArray(v) && v.every(s => typeof s === 'string') ? v as string[] : undefined;
+};
+
+async function recordSetupReads(engine: BrainEngine, name: string, reads: string[]): Promise<void> {
+ await engine.executeRaw(
+ "UPDATE access_tokens SET permissions = COALESCE(permissions, '{}'::jsonb) || jsonb_build_object('setup_reads', $2::text[]) WHERE name = $1 AND revoked_at IS NULL AND (permissions IS NULL OR jsonb_typeof(permissions) = 'object')",
+ [name, reads]);
+}
+
+/**
+ * GBRA-585 A: live member-bound keys whose fixed read list still holds `sourceId` though it is not their write source,
+ * each with the rescope command that drops it. Unfederating never narrows such a list, so `sources unfederate` names them.
+ */
+export async function keysStillReading(engine: BrainEngine, sourceId: string): Promise<Array<{ token: string; member: string; command: string }>> {
+ const rows = await engine.executeRaw<{ name: string; member_id: string; federated_read: unknown }>(
+ "SELECT name, member_id, federated_read FROM access_tokens WHERE revoked_at IS NULL AND member_id IS NOT NULL AND source_grant = 'federated' AND source_id <> $1 AND $1 = ANY(federated_read) ORDER BY name", [sourceId]);
+ return rows.map(r => ({ token: r.name, member: r.member_id, command: `gbrain auth rescope --token ${r.name} --sources ${textList(r.federated_read).filter(s => s !== sourceId).join(',')}` }));
+}
+
+/** `sources unfederate`: names each key keysStillReading finds, through `say`, and returns them for --json. */
+export async function keysStillReadingNotice(engine: BrainEngine, sourceId: string, say: (text: string) => void): Promise<Awaited<ReturnType<typeof keysStillReading>>> {
+ const keys = await keysStillReading(engine, sourceId);
+ if (keys.length) say([`${keys.length} member key${keys.length === 1 ? '' : 's'} still read source ${sourceId}: a key gbrain setup minted keeps the sources it was given, and unfederating does not narrow it. To take ${sourceId} away from a key:`, ...keys.map(k => ` ${k.command}`)].join('\n'));
+ return keys;
+}
+
+/** The live pages in the company source, and how many are imported calls (company/calls/<date>-<title>). */
+async function companyCounts(engine: BrainEngine): Promise<{ pages: number; calls: number }> {
+ const [row] = await engine.executeRaw<{ pages: number | string; calls: number | string }>(
+ "SELECT count(*)::int AS pages, count(*) FILTER (WHERE slug LIKE 'company/calls/%')::int AS calls FROM pages WHERE source_id = $1 AND deleted_at IS NULL", [COMPANY_SOURCE_ID]);
+ return { pages: Number(row?.pages ?? 0), calls: Number(row?.calls ?? 0) };
}
/** The open pages once this run's members, keys and rules are in place (the preview counts what it is about to add). */
-function openPagesFor(engine: BrainEngine, sourceId: string, members: ServesReceipt['members'], rules: ServesReceipt['rules'], labelledOnly: boolean): Promise<OpenPagesRead> {
+function openPagesFor(engine: BrainEngine, sourceId: string, members: ServesReceipt['members'], rules: ServesReceipt['rules'], labelledOnly: boolean, owner: string | null, companyRule?: ServesReceipt['company_rule']): Promise<OpenPagesRead> {
return readOpenPages(engine, {
- planned: { members: members.filter(m => m.action !== 'blocked').map(m => m.id), source: sourceId, labelledOnly },
- exclude: rules.filter(r => r.action !== 'blocked').map(r => ({ source: sourceId, prefix: r.prefix })),
+ planned: { members: members.filter(m => m.action !== 'blocked').map(m => m.id), source: sourceId, labelledOnly, owner },
+ exclude: [...rules.filter(r => r.action !== 'blocked').map(r => ({ source: sourceId, prefix: r.prefix })),
+ ...(companyRule && companyRule.action !== 'blocked' ? [{ source: companyRule.source, prefix: companyRule.prefix }] : [])],
});
}
@@ -159,7 +282,7 @@ async function unlabeledOutside(engine: BrainEngine, sourceId: string, rules: Se
return (await unlabeledPeopleFolders(engine)).filter(u => !(u.source === sourceId && covered.has(u.prefix)));
}
-const blocked = (r: ServesReceipt): boolean => [...r.members, ...r.rules, ...r.keys].some(x => x.action === 'blocked');
+const blocked = (r: ServesReceipt): boolean => [...r.members, ...(r.owner ? [r.owner] : []), ...r.rules, ...(r.company_rule ? [r.company_rule] : []), ...r.keys].some(x => x.action === 'blocked');
function writeKeyFile(path: string, token: string): void {
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
@@ -175,15 +298,20 @@ function abortAfter(step: string): void {
}
/** Plans, and with `apply` writes, the several-people labelling; a failure is reported in the receipt, never thrown. */
-export async function labelSeveral(engine: BrainEngine, roster: string[], sourceId: string, apply: boolean, json: boolean, opts: { labelledOnly?: boolean } = {}): Promise<ServesReceipt> {
+export async function labelSeveral(engine: BrainEngine, roster: string[], sourceId: string, apply: boolean, json: boolean, opts: { labelledOnly?: boolean; owner?: string } = {}): Promise<ServesReceipt> {
const labelledOnly = opts.labelledOnly === true;
- const receipt = await plan(engine, roster, sourceId, labelledOnly);
+ const receipt = await plan(engine, roster, sourceId, labelledOnly, opts.owner);
if (!apply || blocked(receipt)) return receipt;
receipt.applied = true;
try {
for (const m of receipt.members.filter(x => x.action === 'add')) await addMember(engine, m.id);
receipt.completed.push('members');
abortAfter('serves-members');
+ if (receipt.owner && receipt.owner.action !== 'keep') {
+ if (!(await getMember(engine, receipt.owner.id))) await addMember(engine, receipt.owner.id);
+ await setOwner(engine, receipt.owner.id);
+ receipt.completed.push('owner');
+ }
if (labelledOnly) {
for (const m of receipt.members.filter(x => x.labelled_only === 'set')) await setMemberLabelledOnly(engine, m.id, true, { remote: false });
receipt.completed.push('labelled_only');
@@ -193,11 +321,18 @@ export async function labelSeveral(engine: BrainEngine, roster: string[], source
const { result } = await addFolderRules(engine, sourceId, added, { apply: true, json });
if (result) receipt.rule_write = { store: result.store, revision: result.revision, state: result.state, ...(result.git ? { git_commit: result.git.commit ?? null } : {}) };
}
+ const cr = receipt.company_rule;
+ if (cr?.action === 'add') {
+ const prior = (await currentFolderRules(engine, cr.source)).find(b => b.id === cr.id);
+ const { result } = await addFolderRules(engine, cr.source, [{ ...prior, id: cr.id, prefix: cr.prefix, readable_by: cr.readers }], { apply: true, json });
+ if (result) cr.write = { store: result.store, revision: result.revision, state: result.state, ...(result.git ? { git_commit: result.git.commit ?? null } : {}) };
+ }
receipt.completed.push('rules');
abortAfter('serves-rules');
for (const k of receipt.keys.filter(x => x.action === 'mint')) {
const minted = await mintToken(engine, k.token_name, { scopes: ['read', 'write'], binding: { member: k.member },
- ...(sourceId === 'default' ? {} : { sources: { kind: 'scalar' as const, writeSource: sourceId } }) });
+ sources: { kind: 'federated', writeSource: sourceId, readSources: k.reads! } });
+ await recordSetupReads(engine, k.token_name, k.reads!);
try {
writeKeyFile(k.path, minted.token);
} catch (e) {
@@ -206,11 +341,15 @@ export async function labelSeveral(engine: BrainEngine, roster: string[], source
}
abortAfter('serves-key');
}
+ for (const k of receipt.keys.filter(x => x.action === 'keep' && x.adds?.length)) {
+ await rescopeLegacyToken(engine, { target: { name: k.token_name }, sources: k.reads!, reset: [], refreshOperations: false, allNew: false, dryRun: false, json: true });
+ await recordSetupReads(engine, k.token_name, k.reads!);
+ }
receipt.completed.push('keys');
if (receipt.config.action === 'write') await engine.setConfig(SERVES_KEY, 'several');
receipt.completed.push('config');
receipt.unlabeled = await unlabeledOutside(engine, sourceId, receipt.rules);
- const { open_pages, open_pages_error } = await openPagesFor(engine, sourceId, receipt.members, receipt.rules, labelledOnly);
+ const { open_pages, open_pages_error } = await openPagesFor(engine, sourceId, receipt.members, receipt.rules, labelledOnly, await ownerMemberId(engine), receipt.company_rule);
receipt.open_pages = open_pages;
if (open_pages_error) receipt.open_pages_error = open_pages_error; else delete receipt.open_pages_error;
} catch (e) {
@@ -219,18 +358,26 @@ export async function labelSeveral(engine: BrainEngine, roster: string[], source
return receipt;
}
-const ruleWritePending = (r: ServesReceipt): boolean => !!r.rule_write && r.rule_write.state !== 'applied' && r.rule_write.state !== 'unchanged';
+const writePending = (w: RuleWrite | undefined): boolean => !!w && w.state !== 'applied' && w.state !== 'unchanged';
+const companyHeld = (r: ServesReceipt): boolean => r.company_rule?.write?.state === 'recorded';
+const ruleWritePending = (r: ServesReceipt): boolean => writePending(r.rule_write) || (writePending(r.company_rule?.write) && !companyHeld(r));
+const writeLine = (w: RuleWrite) => ` ${w.store} store, revision ${w.revision ?? '-'} ${w.state}${w.git_commit ? `, committed ${w.git_commit.slice(0, 12)}` : ''}`;
export function receiptLines(r: ServesReceipt): string[] {
- const verb = (a: string) => (r.applied ? { add: 'added', mint: 'minted', write: 'written', keep: 'kept', blocked: 'BLOCKED' } : { add: 'will add', mint: 'will mint', write: 'will write', keep: 'keep', blocked: 'BLOCKED' })[a] ?? a;
+ const verb = (a: string) => (r.applied ? { add: 'added', mint: 'minted', write: 'written', keep: 'kept', skipped: 'skipped', blocked: 'BLOCKED' } : { add: 'will add', mint: 'will mint', write: 'will write', keep: 'keep', skipped: 'will skip', blocked: 'BLOCKED' })[a] ?? a;
return [
`Serves several people (source ${r.source_id}):`,
` config ${r.config.key} = ${r.config.value} (${verb(r.config.action)})`,
...r.members.map(m => ` member ${m.id} (${verb(m.action)}${m.labelled_only ? `; labelled-only ${m.labelled_only === 'keep' ? 'kept' : r.applied ? 'set' : 'will set'}` : ''})${m.detail ? `: ${m.detail}` : ''}`),
+ ...(r.owner ? [` owner ${r.owner.id} (${ownerVerb(r.owner.action, r.applied)})${r.owner.detail ? `: ${r.owner.detail}` : ''}`] : []),
+ ...(r.unbound ?? []).map(u => ` unbound ${u.kind === 'token' ? 'token' : 'OAuth client'} ${u.name} is bound to no member, and setup binds none; if it is the owner's, bind it with ${u.command}`),
...r.rules.map(x => ` rule ${x.prefix} readable by ${x.readers.map(p => p.replace(/^member:/, '')).join(', ')} (${verb(x.action)})${x.detail ? `: ${x.detail}` : ''}`),
- ...(r.rule_write ? [` ${r.rule_write.store} store, revision ${r.rule_write.revision ?? '-'} ${r.rule_write.state}${r.rule_write.git_commit ? `, committed ${r.rule_write.git_commit.slice(0, 12)}` : ''}`] : []),
- ...r.keys.map(k => ` key ${k.member}: ${k.path} (${verb(k.action)}${k.action === 'blocked' ? '' : ', 0600'}; token ${k.token_name})${k.detail ? `: ${k.detail}` : ''}`),
- ...(ruleWritePending(r) ? [` The rules are not enforced yet: finish with gbrain access resume --source ${r.source_id}`] : []),
+ ...(r.rule_write ? [writeLine(r.rule_write)] : []),
+ ...companyRuleLines(r),
+ ...r.keys.map(k => ` key ${k.member}: ${k.path} (${verb(k.action)}${k.action === 'blocked' ? '' : ', 0600'}; token ${k.token_name}${k.adds?.length ? `; ${r.applied ? 'now also reads' : 'will also read'} ${k.adds.join(', ')}` : ''})${k.detail ? `: ${k.detail}` : ''}`),
+ ...readsLines(r),
+ ...(writePending(r.rule_write) ? [` The rules are not enforced yet: finish with gbrain access resume --source ${r.source_id}`] : []),
+ ...(writePending(r.company_rule?.write) && !companyHeld(r) ? [` The company rule is not enforced yet: finish with gbrain access resume --source ${r.company_rule!.source}`] : []),
...r.unlabeled.map(u => ` unlabeled ${u.source}:${u.prefix} (${u.pages} page(s)) has no folder rule, so every member reads it: name its readers with gbrain access rule add --prefix ${u.prefix} --readers <list> --source ${u.source}, or add the person with --members`),
...openPagesLines(r, labelledOnlyCommand(r)),
...(r.error ? [`Stopped: ${r.error.message}`, ` Finished before it stopped: ${r.completed.join(', ') || 'nothing'}. Every step is idempotent: run the same command again to finish.`] : []),
@@ -238,6 +385,40 @@ export function receiptLines(r: ServesReceipt): string[] {
];
}
+/** GBRA-585 C: the company/ rule a --labelled-only run adds, and that only keys bound to its readers read those pages. */
+export function companyRuleLines(r: ServesReceipt): string[] {
+ const c = r.company_rule;
+ if (!c) return [];
+ const names = (ps: string[]) => ps.map(p => p.replace(/^member:/, '')).join(', ');
+ const verb = c.action === 'blocked' ? 'BLOCKED' : c.action === 'keep' ? 'kept' : `${r.applied ? 'added' : 'will add'}${c.adds?.length ? ` ${names(c.adds)} as reader(s)` : ''}`;
+ return [
+ ` rule ${c.source}:${c.prefix} readable by ${names(c.readers)} (${verb})${c.detail ? `: ${c.detail}` : ''}`,
+ ...(c.action === 'blocked' ? [] : [` labelled-only members read the company pages through this rule; only keys bound to these members read pages under ${c.prefix}`]),
+ ...(c.write ? [writeLine(c.write)] : []),
+ ...(companyHeld(r) ? [` the added readers wait for approval, as every widening does: preview with gbrain access apply --source ${c.source}, then approve with the --yes --expect line it prints`] : []),
+ ];
+}
+
+/** GBRA-585 A: what the keys this run mints read, what the company source holds, and that a later-federated source waits for a re-run. */
+export function readsLines(r: ServesReceipt): string[] {
+ if (!r.reads) return [];
+ const { write, sources, company } = r.reads;
+ const lists = r.keys.some(k => k.reads);
+ const kept = r.keys.filter(k => k.action === 'keep' && !k.reads).map(k => k.member);
+ return [
+ ` reads keys this run mints write to ${write} and read ${sources.join(', ')}${lists ? '' : ' (this run mints none)'}. A source federated later does not reach these keys until you run setup again.`,
+ ...(company ? [` source company holds ${company.pages} page(s), ${company.calls} of them imported calls: every member whose key reads company reads all of them, including calls they did not attend, except pages a folder rule or readable_by keeps to others.`] : []),
+ ...(kept.length ? [` kept as they are: the keys of ${kept.join(', ')} keep their earlier grant${company ? ' and do not read company' : ''}; setup never changes a key it did not mint with a source list.`] : []),
+ ];
+}
+
+function ownerVerb(action: NonNullable<ServesReceipt['owner']>['action'], applied: boolean): string {
+ if (action === 'keep') return 'kept: the brain owner already';
+ if (action === 'blocked') return 'BLOCKED';
+ const add = action === 'add';
+ return applied ? `${add ? 'added a member and named' : 'named'} it the brain owner` : `will ${add ? 'add a member and name' : 'name'} it the brain owner`;
+}
+
/** The --labelled-only re-run for the members it would still change: never the owner, a BLOCKED member or one already labelled-only. */
function labelledOnlyCommand(r: ServesReceipt): { labelledOnly?: string } {
const ids = r.members.filter(m => m.action !== 'blocked' && !m.labelled_only && m.id !== r.open_pages?.owner).map(m => m.id);
@@ -259,7 +440,8 @@ export async function runAccessServes(engine: BrainEngine, mode: string | undefi
if (mode !== 'several') throw usageError(`Unknown access serves mode: ${mode}.`, 'gbrain access serves (read-only), or gbrain access serves several --members <id,...>. A one-person brain needs no step.');
const roster = readRoster(flagValue(args, '--members'), flagValue(args, '--members-file'));
if (!roster.length) throw rosterEmpty('gbrain access serves several');
- const r = await labelSeveral(engine, roster, flagValue(args, '--source') ?? 'default', args.includes('--yes'), json, { labelledOnly: args.includes('--labelled-only') });
+ const owner = flagValue(args, '--owner');
+ const r = await labelSeveral(engine, roster, flagValue(args, '--source') ?? 'default', args.includes('--yes'), json, { labelledOnly: args.includes('--labelled-only'), ...(owner !== undefined ? { owner: assertAccessId(owner) } : {}) });
console.log(json ? JSON.stringify(r, null, 2) : receiptLines(r).join('\n'));
if (!receiptOk(r)) setCliExitVerdict(1);
}
diff --git a/src/commands/access.ts b/src/commands/access.ts
index 7364e1b06e..4940048294 100644
--- a/src/commands/access.ts
+++ b/src/commands/access.ts
@@ -91,13 +91,15 @@ Owner (one member who owns this brain; credentials bound to it read every page,
Serves several people (GST-363):
gbrain access serves [--no-open-pages] One or several, and why (config access.serves, else 2+ enabled members);
on several, the pages every member's key reads (--no-open-pages skips the count)
- gbrain access serves several --members a,b [--members-file <file>] [--source <id>] [--labelled-only] [--yes]
+ gbrain access serves several --members a,b [--members-file <file>] [--source <id>] [--labelled-only] [--owner <id>] [--yes]
Preview first; --yes writes access.serves = several, adds each member,
a folder rule people/<member>/ read only by that member, and one key
bound to each member in a 0600 file under <config>/member-keys/.
Both list the pages every member's key can still read (no rule or
readable_by restricts them); --labelled-only keeps each member to the
- pages labelled for it (never the owner)
+ pages labelled for it (never the owner); --owner names the brain owner
+ when none is set (an existing owner is kept) and lists the keys bound to
+ no member with the command that binds each; it rebinds none
Folder rules (one rulebook per source; the database store on a repo-less source, .gbrain/access.yml on a git one):
gbrain access rule add --prefix <folder/> | --slug <page> --readers a,group:b [--raw-only] [--allow-without-owner] [--id <rule>] [--source <id>] [--yes]
@@ -137,7 +139,7 @@ function flagValue(args: string[], name: string): string | undefined {
return v;
}
-const VALUE_FLAGS = new Set(['--name', '--groups', '--bind-token', '--members', '--members-file', '--source', '--token', '--client', '--as', '--qm', '--member', '--email', '--kind']);
+const VALUE_FLAGS = new Set(['--name', '--groups', '--bind-token', '--members', '--members-file', '--source', '--token', '--client', '--as', '--qm', '--member', '--email', '--kind', '--owner']);
function positionals(args: string[]): string[] {
const out: string[] = [];
diff --git a/src/commands/auth.ts b/src/commands/auth.ts
index 28814658c9..ea6af479d7 100644
--- a/src/commands/auth.ts
+++ b/src/commands/auth.ts
@@ -80,6 +80,9 @@ async function withConfiguredSql<T>(
}
}
+/** GBRA-585 E: the scopes a token bound to a member gets when --scopes is not given; an explicit --scopes always wins. */
+export const MEMBER_TOKEN_SCOPES: readonly string[] = ['read', 'write'];
+
async function create(name: string, opts: { takesHolders?: string[]; scopes?: string[]; minTrust?: TrustTier; binding?: BindingPatch | null } = {}) {
if (!name) { console.error('Usage: auth create <name> [--takes-holders world,garry] [--scopes read,write] [--min-trust <tier>] [--member <id>] [--reads-unscoped --yes]'); process.exit(1); }
// #4043 least-privilege: validate scopes at mint time — the verify path
@@ -94,12 +97,16 @@ async function create(name: string, opts: { takesHolders?: string[]; scopes?: st
process.exit(1);
}
}
+ const memberDefault = opts.scopes === undefined && !!opts.binding?.member;
+ if (memberDefault) opts = { ...opts, scopes: [...MEMBER_TOKEN_SCOPES] };
try {
await withConfiguredSql(async (_sql, engine) => {
await assertCredentialScoped(engine, opts.binding ?? null, 'token', name);
const { token, id, takesHolders, bound } = await mintToken(engine, name, opts);
if (bound) auditReadsUnscoped(bound, `token ${name}`, false);
- const scopeLine = opts.scopes !== undefined
+ const scopeLine = memberDefault
+ ? `scopes=${JSON.stringify(opts.scopes)} (the default for a token bound to a member; pass --scopes read,write,admin for admin access)`
+ : opts.scopes !== undefined
? `scopes=${JSON.stringify(opts.scopes)}`
: 'scopes=full access (grandfathered — pass --scopes read,write to narrow)';
console.log(`Token created for "${name}" (takes_holders=${JSON.stringify(takesHolders)}, ${scopeLine}${opts.minTrust ? `, min_trust=${opts.minTrust}` : ''}):\n`);
@@ -1279,8 +1286,8 @@ Usage:
field (default: ["world"]). MCP-bound calls to
takes_list / takes_search / query filter by this.
--scopes narrows the token to the listed op scopes
- (comma or space separated; omit = full access,
- grandfathered).
+ (comma or space separated; omit = read,write with
+ --member, else full access, grandfathered).
--min-trust sets the token's read floor: reads never
return rows below that trust tier (${TRUST_TIERS.join(', ')});
memory_confirm in --scopes lets the token confirm
diff --git a/src/commands/backup.ts b/src/commands/backup.ts
index 55a69395a7..4fd0eebaf0 100644
--- a/src/commands/backup.ts
+++ b/src/commands/backup.ts
@@ -208,6 +208,11 @@ export async function runBackupCli(
writeCliError(error, 'backup', { json, legacy: { ok: false, reason: error.code, message: error.message } });
return { exitCode: 1 };
}
+ if (error instanceof OperationError && error.reason === 'pglite_required') {
+ const { writeCliError } = await import('../cli/cli-error.ts');
+ writeCliError(error, 'backup', { json, legacy: { ok: false, reason: error.reason, message: error.message } });
+ return { exitCode: 1 };
+ }
const detail = (typeof error === 'object' && error !== null ? error : {}) as { code?: unknown; retryable?: unknown };
const reason = typeof detail.code === 'string' && SAFE_ERROR_FIELD.test(detail.code) ? detail.code : 'backup_failed';
const message = backupFailureMessage(error);
diff --git a/src/commands/connect.ts b/src/commands/connect.ts
index dedec75ec3..a13541e3d3 100644
--- a/src/commands/connect.ts
+++ b/src/commands/connect.ts
@@ -137,8 +137,8 @@ export const LEARN_INSTRUCTION =
'full-control writes. Always search the brain before answering or writing.';
const SECRET_NOTE =
- 'Note: that bearer token is a long-lived, full-access secret — keep it private and ' +
- 'prefer a scoped/short-lived token if your host supports one.';
+ 'Note: that bearer token is a long-lived secret that carries whatever its grant allows (whoami shows its scopes) — ' +
+ 'keep it private and prefer a scoped/short-lived token if your host supports one.';
// OAUTH_SECRET_NOTE moved to src/core/mcp-registration.ts (imported +
// re-exported above; text unchanged).
@@ -164,7 +164,8 @@ Prints a copy-paste setup block for your agent, or wires it up directly with
https:// URL.
Auth:
- Bearer token (default) simple, long-lived, full-access — best local/personal
+ Bearer token (default) simple, long-lived; carries its grant's scopes — best local/personal
+ (a member key from setup's member-keys/ folder works here)
--oauth OAuth 2.1 client credentials (perplexity/generic):
least-privilege scopes + short-lived tokens — best for
anything exposed to a third-party cloud
diff --git a/src/commands/doctor/checks/backup-coverage.ts b/src/commands/doctor/checks/backup-coverage.ts
index 99884defda..c610ab9a6e 100644
--- a/src/commands/doctor/checks/backup-coverage.ts
+++ b/src/commands/doctor/checks/backup-coverage.ts
@@ -11,6 +11,7 @@ import type { Check } from '../../doctor.ts';
import { getBackupStatus } from '../../../core/backup/coverage.ts';
import type { Action } from '../../../core/agent-output.ts';
import { checkError, doctorVerify, infoCheck } from '../check-fix.ts';
+import { postgresDumpFix } from '../../../core/backup/preflight.ts';
import {
BACKUP_COACH_MIN_AGE_DAYS,
BACKUP_COACH_MIN_ITEMS,
@@ -59,7 +60,7 @@ function assetCoverageWording(s: BackupStatus): string {
parts.push('A source repo with a pushed git remote restores its Markdown files only, never DB-only pages, facts, config or credentials.');
}
if (kinds.has('db_only') || kinds.has('db_content')) {
- parts.push('DB-only pages and facts live only in the database: an export or database backup is their only copy.');
+ parts.push('DB-only pages and facts live only in the database: a full database backup is their only complete copy.');
}
return parts.length ? parts.join(' ') : 'Git evidence covers committed repository files only, not the full database.';
}
@@ -67,13 +68,23 @@ function assetCoverageWording(s: BackupStatus): string {
/**
* The first blocking asset's fix as an Action. `not_a_git_repo` sources (for
* example gbrain's own content directory) have no git remote to add, so their
- * fix is an export to a directory the user picks; db_only/db_content assets use
- * their own fix argv. `bootstrap repo` and pushes carry {credentials, egress}.
+ * fix is the engine's full backup: `gbrain backup create` on PGLite, a pg_dump
+ * on Postgres. Never `gbrain export`: an import of it drops sources, members,
+ * tokens and facts. db_only/db_content assets use their own fix argv.
+ * `bootstrap repo` and pushes carry {credentials, egress}.
*/
-function backupAssetFix(s: BackupStatus): Action | undefined {
+function backupAssetFix(s: BackupStatus, engineKind: BrainEngine['kind']): Action | undefined {
for (const a of s.assets.filter(assetBlocksRecovery)) {
- const argv = a.fix_argv ?? (a.kind === 'source_repo' && a.detail === 'not_a_git_repo'
- ? ['gbrain', 'export', '--source', a.id, '--dir', `<BACKUP_DIR>/${a.id}`] : null);
+ if (!a.fix_argv && a.kind === 'source_repo' && a.detail === 'not_a_git_repo') {
+ if (engineKind === 'postgres') return postgresDumpFix();
+ return {
+ argv: ['gbrain', 'backup', 'create', '--output', '<BACKUP_FILE>'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Writes a full snapshot of this PGLite brain (every source, page, fact, member, token and rule) to one archive outside the brain.',
+ inputs: [{ name: 'BACKUP_FILE', how: 'Ask the user for an absolute path to a new archive file, in an existing private directory outside the brain (ideally another disk).' }],
+ verify: doctorVerify('backup_coverage'), docs: 'docs/guides/in-agent-setup.md#6-back-up-the-complete-local-database',
+ };
+ }
+ const argv = a.fix_argv;
if (!argv) continue;
const filled = argv.map((x) => x.replace(/^BACKUP_DIR\//, '<BACKUP_DIR>/'));
const egress = argv[1] === 'bootstrap' || (argv[1] === 'sources' && argv[2] === 'push');
@@ -91,7 +102,7 @@ function backupAssetFix(s: BackupStatus): Action | undefined {
return undefined;
}
-function toCheck(s: BackupStatus, now?: number): Check {
+function toCheck(s: BackupStatus, engineKind: BrainEngine['kind'], now?: number): Check {
const details = {
totals: s.totals,
checked_at: s.checked_at,
@@ -105,7 +116,7 @@ function toCheck(s: BackupStatus, now?: number): Check {
const listed = unverified.slice(0, LISTED_ASSET_CAP).map((a) => `${a.id} (${a.reason})`).join(', ');
const more = unverified.length > LISTED_ASSET_CAP ? `, and ${unverified.length - LISTED_ASSET_CAP} more` : '';
const assetClause = unverified.length > 0 ? `${unverified.length} knowledge asset(s) lack verified recovery: ${listed}${more}.` : null;
- const fix = backupAssetFix(s);
+ const fix = backupAssetFix(s, engineKind);
const message =
`${warnLead(assetClause, verdictCaveats(s, now))} ${assetCoverageWording(s)} ` +
'Run `gbrain backup status` for each asset\'s fix command.';
@@ -202,7 +213,7 @@ export async function checkBackupCoverage(
computedBy: 'doctor',
...(opts.now ? { now: opts.now } : {}),
});
- return toCheck(s, opts.now?.getTime());
+ return toCheck(s, engine.kind, opts.now?.getTime());
} catch (e) {
return checkError('backup_coverage', 'read backup coverage', e);
}
diff --git a/src/commands/doctor/checks/transcript-archive.ts b/src/commands/doctor/checks/transcript-archive.ts
index d1e150a8a4..dedad2829f 100644
--- a/src/commands/doctor/checks/transcript-archive.ts
+++ b/src/commands/doctor/checks/transcript-archive.ts
@@ -93,7 +93,7 @@ export async function checkTranscriptArchiveFreshness(
name, { consent: ['persistent_install'] });
}
const details = {
- enabled: true, source_id: status.source_id, stale_days: staleDays, behind, held: status.held,
+ enabled: true, enabled_by: enablement.source, reason: enablement.reason, ...(enablement.serves_several ? { serves_several: true } : {}), source_id: status.source_id, stale_days: staleDays, behind, held: status.held,
harnesses: status.harnesses.map(h => ({ harness: h.harness, reader: h.reader, readable: !h.info, newest_session_day: h.newest_session_day, newest_archived_day: h.newest_archived_day })),
...(record ? { last_maintenance: record } : {}), docs: 'docs/guides/conversation-archive.md#doctor',
};
@@ -105,8 +105,9 @@ export async function checkTranscriptArchiveFreshness(
...(idle.length ? ['no readable sessions for ' + idle.join(', ') + ' (gbrain transcripts archive status names each reader)'] : []),
...(unread.length ? ['not read by an archive run yet: ' + unread.join(', ')] : []),
].join('; ');
- if (!readable.length) return infoCheck(name, 'Conversation archive is on; ' + (idleNote || 'no harness has readable sessions yet') + '.', 'not_applicable', undefined, details);
- return { name, status: 'ok', message: 'Conversation archive is up to date (' + readable.map(h => h.harness + ' ' + h.newest_archived_day).join(', ') + ')' + (idleNote ? '; ' + idleNote : '') + '.', details };
+ const onWhy = enablement.serves_several ? ' (' + enablement.reason + ')' : '';
+ if (!readable.length) return infoCheck(name, 'Conversation archive is on' + onWhy + '; ' + (idleNote || 'no harness has readable sessions yet') + '.', 'not_applicable', undefined, details);
+ return { name, status: 'ok', message: 'Conversation archive is up to date' + onWhy + ' (' + readable.map(h => h.harness + ' ' + h.newest_archived_day).join(', ') + ')' + (idleNote ? '; ' + idleNote : '') + '.', details };
} catch (error) {
return checkError(name, 'read the conversation archive', error);
}
diff --git a/src/commands/guests.ts b/src/commands/guests.ts
index d59f60f541..3e5bce61bc 100644
--- a/src/commands/guests.ts
+++ b/src/commands/guests.ts
@@ -6,7 +6,7 @@
*/
import type { BrainEngine } from '../core/engine.ts';
import { isValidSourceId } from '../core/source-id.ts';
-import { GUEST_TRUST_CEILING, GUEST_WRITER_FORMAT, GuestSourceHoldsPages, initGuestSource, isGuestWriter, planGuestSource } from '../core/guests/sources.ts';
+import { GUEST_TRUST_CEILING, GUEST_WRITER_FORMAT, GuestSourceHoldsPages, initGuestSource, isGuestWriter, planGuestSource, unregisteredClientWriters } from '../core/guests/sources.ts';
import { grantOwnerCredentials, ownerCredentials } from '../core/guests/owner-credentials.ts';
import { exitCliError } from '../cli/cli-error.ts';
import { loadConfig } from '../core/config.ts';
@@ -80,6 +80,8 @@ async function runInit(engine: BrainEngine, rest: string[]): Promise<void> {
console.error(`Not a writer principal: ${malformed.join(', ')}. Name each writer as ${GUEST_WRITER_FORMAT}, for example oauth_client:<client id>.`);
process.exit(2);
}
+ const unregistered = await unregisteredClientWriters(engine, writers);
+ if (unregistered) exitCliError(unregistered, 'guests');
const plan = await planGuestSource(engine, sourceId, writers);
if (plan.localPath) {
diff --git a/src/commands/harness-connect.ts b/src/commands/harness-connect.ts
index fe8ff0e00b..3e66ecae03 100644
--- a/src/commands/harness-connect.ts
+++ b/src/commands/harness-connect.ts
@@ -1,5 +1,6 @@
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
-import { readCredentials, credentialReceipt } from '../core/harness/credentials.ts';
+import { readCredentials, credentialReceipt, PlainBearerKeyFile, type HarnessCredentials } from '../core/harness/credentials.ts';
+import { shellQuote } from '../core/mcp-registration.ts';
import { harnessAdapter } from '../core/harness/registry.ts';
import { installHarnessConnection, type inlineTokenReceipt } from '../core/harness/install.ts';
import { normalizeMcpUrl } from '../core/mcp-registration.ts';
@@ -14,7 +15,15 @@ export async function runHarnessConnect(args: string[]): Promise<void> {
return;
}
const value = (flag: string) => { const i = args.indexOf(flag); return i < 0 ? undefined : args[i + 1]; };
+ // GBRA-585: a bearer key (setup's member-keys/<member>.key) installs through the --agent lane; name it instead of a parse error.
+ const bearerForm = (key: string) => {
+ const agent = value('--harness') ?? value('--agent') ?? 'claude-code';
+ return `gbrain connect ${args[0] && !args[0].startsWith('--') ? args[0] : '<mcp-url>'} --agent ${['claude-code', 'codex', 'opencode', 'perplexity'].includes(agent) ? agent : 'generic'} ${key}--install`;
+ };
try {
+ if (args.includes('--token')) {
+ throw new Error(`--token is the bearer-token form; --harness takes a --credentials-file handoff from gbrain mcp grant. For a bearer key run: ${bearerForm('--token <key> ')} (or set GBRAIN_REMOTE_TOKEN instead of passing --token, which keeps the key out of shell history).`);
+ }
validateHarnessArguments(args[0]?.startsWith('--') ? args : args.slice(1), { values: ['--harness', '--credentials-file', '--root', '--name', '--skill-loading', '--gbrain-bin'], flags: ['--install', '--remove', '--status', '--json', '--fresh-token', '--no-instructions'], aliases: { '--agent': '--harness' }, exclusive: [['--install', '--remove', '--status']] });
if (args.includes('--status')) {
const harness = value('--harness') ?? value('--agent');
@@ -26,7 +35,11 @@ export async function runHarnessConnect(args: string[]): Promise<void> {
if (skillLoading !== undefined && !isSkillLoading(skillLoading)) throw new Error(`Unknown --skill-loading '${skillLoading}'; pass off or spring`);
const path = value('--credentials-file');
if (!path) throw new Error('--credentials-file is required; create the private handoff with gbrain mcp grant on the brain host');
- const c = readCredentials(path);
+ let c: HarnessCredentials;
+ try { c = readCredentials(path); } catch (error) {
+ if (!(error instanceof PlainBearerKeyFile)) throw error;
+ throw new Error(`${path} holds a plain bearer key (like the member keys gbrain setup writes under member-keys/ for a brain that serves several people), not a credential handoff from gbrain mcp grant. Install it with the bearer-token form: GBRAIN_REMOTE_TOKEN="$(cat ${shellQuote(path)})" ${bearerForm('')}`);
+ }
const harness = harnessAdapter(value('--harness') ?? value('--agent') ?? c.harness ?? 'generic');
const endpoint = normalizeMcpUrl(args[0] ?? '');
if (!endpoint.ok || endpoint.url !== c.mcp_url) throw new Error('Endpoint does not match the private credential handoff');
diff --git a/src/commands/migrations/shared-content.ts b/src/commands/migrations/shared-content.ts
index bf58c218cf..f72c90895d 100644
--- a/src/commands/migrations/shared-content.ts
+++ b/src/commands/migrations/shared-content.ts
@@ -7,6 +7,7 @@ import { exportDatabaseContent } from '../../core/shared-skills/migration-export
import { PgliteBusyError } from '../../core/pglite-lock.ts';
import { shellQuote } from '../../core/agent-output.ts';
import { MIGRATION_OPT_OUT_KEYS } from '../../core/migration-ledger.ts';
+import { sharedSkillsHostWork } from '../../core/shared-skills/migration-host-work.ts';
export const SHARED_CONTENT_MIGRATION_VERSION = '0.53.0';
/** #6466: `gbrain config set shared_skills.migration.enabled false` declines this migration (brain-level, every machine). */
@@ -17,12 +18,21 @@ export const SHARED_CONTENT_INSPECT_ARGV = ['gbrain', 'apply-migrations', '--mig
export async function inspectSharedContentMigration(dryRun: boolean, exportOptions?: OrchestratorOpts['dbOnlyExport'],
acceptReviewedInventory?: OrchestratorOpts['acceptReviewedInventory']): Promise<SharedMigrationReport | null> {
+ return (await inspectWithHostWork(dryRun, exportOptions, acceptReviewedInventory))?.report ?? null;
+}
+
+/**
+ * The report plus the sources that owe host work by the ledger's rule (sharedSkillsHostWork, read from the report this
+ * run stored), or null on a dry run, which stores nothing.
+ */
+async function inspectWithHostWork(dryRun: boolean, exportOptions?: OrchestratorOpts['dbOnlyExport'],
+ acceptReviewedInventory?: OrchestratorOpts['acceptReviewedInventory']): Promise<{ report: SharedMigrationReport; owing: string[] | null } | null> {
const config = loadConfig();
if (!config) return null;
- if (isThinClient(config)) return {
+ if (isThinClient(config)) return { owing: null, report: {
version: 1, brain_id: null, dry_run: dryRun, status: 'action_required', sources: [], permission_changes: [],
pending_actions: ['Run content migration on the host brain, then reconnect with an upgraded shared-skills adapter. No client-side host repository was created.'],
- };
+ } };
const { engine, close } = await connectMigrationEngine(config);
try {
const ctx = { engine, config, sourceId: exportOptions?.sourceId ?? 'default', remote: false, dryRun,
@@ -34,7 +44,7 @@ export async function inspectSharedContentMigration(dryRun: boolean, exportOptio
if (exported.status !== 'complete') report.status = exported.status === 'conflict' ? 'conflict' : 'action_required';
report.pending_actions.push(...exported.pending_actions);
}
- return report;
+ return { report, owing: dryRun ? null : (await sharedSkillsHostWork(engine)).sources };
} finally { await close(); }
}
@@ -50,13 +60,22 @@ export const sharedContentMigration: Migration = {
sharesRunEngine: true,
orchestrator: async options => {
try {
- const report = await inspectSharedContentMigration(options.dryRun, options.dbOnlyExport, options.acceptReviewedInventory);
- if (!report) return { version: SHARED_CONTENT_MIGRATION_VERSION, status: 'complete', phases: [{ name: 'inventory', status: 'skipped', detail: 'No brain configured.' }] };
+ const inspected = await inspectWithHostWork(options.dryRun, options.dbOnlyExport, options.acceptReviewedInventory);
+ if (!inspected) return { version: SHARED_CONTENT_MIGRATION_VERSION, status: 'complete', phases: [{ name: 'inventory', status: 'skipped', detail: 'No brain configured.' }] };
+ const { report, owing } = inspected;
const pending = report.status === 'action_required' || report.status === 'conflict';
- console.error(`[shared-skills] ${report.status}. ${report.sources.filter(source => source.status !== 'complete').length} source(s) need host action; no grants or bundle consent changed.`
- + (pending ? ` Inspect each source's next step: ${shellQuote(SHARED_CONTENT_INSPECT_ARGV)}` : ''));
- for (const source of report.sources) for (const phase of source.stages) {
- if (phase.status === 'action_required' || phase.status === 'conflict') console.error(`[shared-skills] ${source.source_id}: ${phase.reason}`);
+ const open = report.sources.filter(source => source.status !== 'complete');
+ // The ledger's rule (#6796): an unverified client enrollment (`members`) or a projection the source's own policy
+ // keeps out is information, not host work, so it never counts as a source that needs host action.
+ const owed = owing === null ? open : open.filter(source => source.status === 'conflict' || owing.includes(source.source_id));
+ const inspect = ` Inspect each source's next step: ${shellQuote(SHARED_CONTENT_INSPECT_ARGV)}`;
+ console.error(pending && owed.length === 0 && report.pending_actions.length === 0
+ ? `[shared-skills] No source needs host action; no grants or bundle consent changed. Not verified here: client enrollment and native activation, and sources whose own policy keeps shared skills out.${inspect}`
+ : `[shared-skills] ${report.status}. ${owed.length} source(s) need host action; no grants or bundle consent changed.${pending ? inspect : ''}`);
+ for (const source of open) for (const phase of source.stages) {
+ if (phase.status === 'action_required' || phase.status === 'conflict') {
+ console.error(`[shared-skills] ${source.source_id}${owed.includes(source) ? '' : ' (no host action owed)'}: ${phase.reason}`);
+ }
}
for (const action of report.pending_actions) console.error(`[shared-skills] ${action}`);
return { version: SHARED_CONTENT_MIGRATION_VERSION, status: report.status === 'conflict' ? 'partial' : 'complete',
diff --git a/src/commands/setup-brain-layout.ts b/src/commands/setup-brain-layout.ts
index ef402a1d9c..4706e4ccb9 100644
--- a/src/commands/setup-brain-layout.ts
+++ b/src/commands/setup-brain-layout.ts
@@ -323,6 +323,12 @@ function importFolder(exec: Run, launcher: string, dir: string, source: string |
}
/** Who can read the call pages, from gbrain access who-can-read on one of them and gbrain access serves; read only. */
+const servesSeveralClause = (enabled: string[]): string => `this brain serves several people: ${enabled.join(', ') || 'none enabled'}`;
+
+/** GBRA-585 A: the call readers once this run's regrant gave the member keys setup minted the company source. */
+export const mintedKeysReadCalls = (enabled: string[]): string =>
+ `every member key gbrain setup minted, and other keys only when their grant names source ${COMPANY_SOURCE} or it is in default search (${servesSeveralClause(enabled)})`;
+
function readersOf(exec: Run, launcher: string, slug: string): NonNullable<TranscriptsOutcome['readers']> {
const unknown = { members: null, serves: null, detail: `unknown; run gbrain access who-can-read ${slug} --source ${COMPANY_SOURCE}` };
let page: { readers: string[] | null; members: 'every_source_reader' | string[] } | undefined;
@@ -330,10 +336,15 @@ function readersOf(exec: Run, launcher: string, slug: string): NonNullable<Trans
try { page = (JSON.parse(exec([launcher, 'access', 'who-can-read', slug, '--source', COMPANY_SOURCE, '--json'], undefined, null).stdout) as { pages?: Array<NonNullable<typeof page>> }).pages?.[0]; } catch { return unknown; }
try { serves = JSON.parse(exec([launcher, 'access', 'serves', '--json', '--no-open-pages'], undefined, null).stdout) as typeof serves; } catch { /* the serves clause is left out */ }
if (!page) return unknown;
- const who = serves.serves === 'several' ? `this brain serves several people: ${(serves.enabled_members ?? []).join(', ') || 'none enabled'}`
- : serves.serves === 'one' ? 'this brain serves one person' : null;
+ const several = serves.serves === 'several';
+ const who = several ? servesSeveralClause(serves.enabled_members ?? []) : serves.serves === 'one' ? 'this brain serves one person' : null;
const members = page.members;
const clauses = [...(members === 'every_source_reader' ? [] : [`access rules on source ${COMPANY_SOURCE} cover ${CALLS_PREFIX}/`]), ...(who ? [who] : [])];
+ if (members === 'every_source_reader' && several) {
+ return { members, serves: 'several', detail: `no member key setup minted reads them yet: source ${COMPANY_SOURCE} is not federated and is not on those keys' source lists. `
+ + `Run gbrain setup again with --serves several to give them ${COMPANY_SOURCE}, or gbrain sources federate ${COMPANY_SOURCE} for keys with no source list; either way every member then reads every page in it, every call included; `
+ + `${CALLS_PREFIX}/ pages carry no readers of their own (gbrain access who-can-read ${slug} --source ${COMPANY_SOURCE}) (${who})` };
+ }
const detail = `${members === 'every_source_reader' ? `everyone who can read source ${COMPANY_SOURCE}` : `${members.join(', ') || 'no member'} only`}${clauses.length ? ` (${clauses.join('; ')})` : ''}`;
return { members, serves: serves.serves ?? null, detail };
}
@@ -382,8 +393,9 @@ function archiveState(exec: Run, launcher: string, calls: TranscriptsOutcome | n
let checks: DoctorChecks = [];
try { checks = (JSON.parse(out.stdout) as { checks?: DoctorChecks }).checks ?? []; } catch { /* unknown below */ }
if (calls) calls.egress = callEgress(checks);
- const details = checks.find(c => c.name === 'transcript_archive_freshness')?.details as { enabled?: boolean; offered?: boolean } | undefined;
+ const details = checks.find(c => c.name === 'transcript_archive_freshness')?.details as { enabled?: boolean; offered?: boolean; serves_several?: boolean; reason?: string } | undefined;
if (!details) return { state: 'unknown', detail: 'could not be read; gbrain transcripts archive status shows it' };
+ if (details.enabled && details.serves_several && details.reason) return { state: 'on', detail: `${details.reason}. Your agent conversations are kept, redacted, under conversations/; call transcripts are separate (gbrain transcripts archive off turns it off)` };
if (details.enabled) return { state: 'on', detail: 'on: your agent conversations are kept, redacted, under conversations/; call transcripts are separate (gbrain transcripts archive off turns it off)' };
if (details.offered) return { state: 'offered', detail: 'offered, not on: this brain may serve more than one person (gbrain transcripts archive on turns it on)' };
return { state: 'off', detail: 'off (gbrain transcripts archive on turns it on)' };
diff --git a/src/commands/setup-serves.ts b/src/commands/setup-serves.ts
index 9ad6edfa8e..b00309afff 100644
--- a/src/commands/setup-serves.ts
+++ b/src/commands/setup-serves.ts
@@ -13,16 +13,41 @@
* - `--serves several --members a,b` runs `gbrain access serves several --yes --json` (members, one folder rule per
* member, one bound key per member in a 0600 file) and proves the labels with one bound read per member
* per other member (`gbrain find people/<other>/ --as <member> --json`): none returns a page.
+ * - GBRA-585 D: on a brain with no owner it also names one: --owner <id>, else the login name as a member id
+ * (loginOwnerId), passed to the child as --owner. An existing owner is kept and no credential is rebound.
+ * - GBRA-585 C: turning a one-person brain shared while it holds open pages refuses (setup_history_choice_required)
+ * until the admin picks --labelled-only (keep that history private) or --open-history (members read it).
*/
import { closeSync, existsSync, openSync, readSync } from 'node:fs';
-import { homedir } from 'node:os';
+import { homedir, userInfo } from 'node:os';
import { join } from 'node:path';
import { openclawStateDir } from '../core/setup/brain-first.ts';
+import { mintedKeysReadCalls, type LayoutOutcome } from './setup-brain-layout.ts';
import { opError, OperationError } from '../core/ops/contract.ts';
+import { ACCESS_ID_RE } from '../core/access/principals.ts';
import { bunSpawnSync } from '../core/spawn.ts';
-import { readRoster, rosterEmpty, type ServesReceipt, type ServesStatus, receiptLines, receiptOk } from './access-serves.ts';
+import { loadConfig } from '../core/config.ts';
+import { companyRuleLines, readRoster, readsLines, rosterEmpty, type ServesReceipt, type ServesStatus, receiptLines, receiptOk } from './access-serves.ts';
-export interface ServesFlags { serves?: 'one' | 'several'; members?: string; membersFile?: string; source?: string; stdioMember?: string; labelledOnly?: boolean; dryRun: boolean }
+export interface ServesFlags { serves?: 'one' | 'several'; members?: string; membersFile?: string; source?: string; stdioMember?: string; labelledOnly?: boolean; openHistory?: boolean; owner?: string; dryRun: boolean }
+
+/** GBRA-585 D: the login name of the person running setup as a member id (lower-cased, other characters as '-'), or null when none fits. */
+export function loginOwnerId(login?: string): string | null {
+ let name = login;
+ if (name === undefined) { try { name = userInfo().username; } catch { name = process.env.USER ?? process.env.LOGNAME ?? ''; } }
+ const id = name.normalize('NFKD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[^a-z0-9]+/, '').slice(0, 64).replace(/[._-]+$/, '');
+ return ACCESS_ID_RE.test(id) ? id : null;
+}
+
+/** The owner --serves several names when the brain has none: --owner, else the login name. */
+function servesOwner(flags: ServesFlags, harness: string, roster: string[]): ServesOwner | OperationError {
+ if (flags.owner) return { id: flags.owner, from: 'flag' };
+ const id = loginOwnerId();
+ return id ? { id, from: 'login' } : opError('invalid_params', `Setup names the brain owner from your login name, and it does not make a member id; nothing was written.`,
+ `Name the owner yourself: run gbrain setup ${harness} --serves several --members ${roster.join(',')} again with --owner followed by the owner's member id.`);
+}
+
+export interface ServesOwner { id: string; from: 'flag' | 'login' }
/** GST-363: the --stdio-member this harness entry will carry (member) and the one it carries now (previous). */
export interface EntryBinding { member: string | null; previous: string | null }
@@ -56,9 +81,20 @@ export interface ServesOutcome {
receipt?: ServesReceipt;
proof?: ProofLine[];
stdio?: { member: string | null; action: 'write' | 'keep' | 'remove' | 'unbound'; detail: string };
+ /** GBRA-585: on PGLite, what serving several people over `gbrain serve --http` costs the admin, and the move to Postgres. */
+ engine?: string;
+ /** GBRA-585 D: where the owner setup asked the child to name came from. */
+ owner_from?: ServesOwner['from'];
+ /** GBRA-585 A: the labelling child run again after the layout step added the company source, so the keys this run minted read it. */
+ regrant?: ServesReceipt;
error?: string;
}
+/** GBRA-585: a PGLite brain is opened by one process at a time, so a running `gbrain serve --http` blocks most admin commands. */
+export const PGLITE_SEVERAL_NOTE = 'PGLite lets one process at a time open this brain, so while gbrain serve --http runs for the members, '
+ + 'admin commands (access, sources, auth) and most reads refuse with pglite_busy until it stops, and every member\'s connection drops while it is down; '
+ + 'page and fact writes (put, remember) still work through it. For a brain several people use, move to Postgres first: gbrain migrate --to postgres (docs/ENGINES.md#pglite-live-serve)';
+
function child(launcher: string, args: string[]): { ok: boolean; stdout: string; stderr: string } {
const r = bunSpawnSync([launcher, ...args], { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', env: process.env });
return { ok: r.exitCode === 0, stdout: r.stdout?.toString() ?? '', stderr: r.stderr?.toString() ?? '' };
@@ -107,12 +143,45 @@ export function servesOneRefusal(status: ServesStatus | null, harness: string, e
verify: { argv: ['gbrain', 'access', 'serves', '--json'] } } });
}
+/**
+ * GBRA-585 C: --serves several on a brain that serves one person and holds pages the members' keys would read (the
+ * labelling preview's open_pages, or a count that could not be read) needs the admin's choice first. A brain this run
+ * creates, a brain with no open pages and a brain already shared are not refused.
+ */
+export function historyRefusal(status: ServesStatus | null, preview: ServesReceipt | null, flags: ServesFlags, harness: string, roster: string[], owner: ServesOwner | undefined, previewError?: string): OperationError | null {
+ if (flags.serves !== 'several' || flags.labelledOnly || flags.openHistory || status?.serves !== 'one') return null;
+ const counted = preview && 'members' in preview ? preview : null;
+ const open = counted?.open_pages;
+ if (open && !open.total) return null;
+ const parts = open ? [open.sensitive ? `${open.sensitive} of them DMs, chat or mail` : '', open.archive ? `${open.archive} in the conversation archive` : ''].filter(Boolean) : [];
+ const holds = open ? `${open.total} page(s) no rule or readable_by restricts${parts.length ? ` (${parts.join(', ')})` : ''}`
+ : `pages setup could not count (${counted ? counted.open_pages_error?.code ?? 'open_pages_failed' : `the preview failed${previewError ? `: ${previewError}` : ''}`})`;
+ const ownerId = status.owner ?? owner?.id;
+ const labelled = roster.filter(m => m !== ownerId);
+ const pin = owner && (owner.from === 'flag' || (owner.id === ownerId && labelled.length < roster.length)) ? ['--owner', owner.id] : [];
+ const argvFor = (members: string[]) => ['gbrain', 'setup', harness, '--serves', 'several', '--members', members.join(','), ...(flags.source ? ['--source', flags.source] : []), ...pin];
+ const keep = [...argvFor(labelled.length ? labelled : roster), '--labelled-only'];
+ const share = [...argvFor(roster), '--open-history'];
+ const ownerOut = ownerId && labelled.length && labelled.length < roster.length ? `; the owner ${ownerId} reads the whole brain, so it is never labelled-only and stays out of that run's --members` : '';
+ return opError('setup_history_choice_required',
+ `This brain serves one person and holds ${holds}; turned shared as asked, every member's key would read them. Nothing was written. Run setup again with --labelled-only to keep that history private, or with --open-history to let every member read it.`,
+ `Pick one: ${keep.join(' ')} keeps that history private (each member reads only pages labelled for them; with the company shape, setup adds one company/ rule so they read the company pages${ownerOut}), or ${share.join(' ')} lets every member read it.`,
+ { fix: { argv: keep, consent: ['credentials'], actor: 'user', ask_user: true, requires_exclusive: false,
+ why: 'Keeps the existing pages from the members; ask the user, who may instead choose --open-history so the members read them.',
+ verify: { argv: ['gbrain', 'access', 'serves', '--json'] } } });
+}
+
/** --serves several: the labelling child (preview on a dry run) and, when applied, one bound read per member. */
-function runServesSeveral(launcher: string, roster: string[], flags: ServesFlags): Omit<ServesOutcome, 'brain_serves'> {
- const r = child(launcher, ['access', 'serves', 'several', '--members', roster.join(','), ...(flags.source ? ['--source', flags.source] : []), ...(flags.labelledOnly ? ['--labelled-only'] : []), ...(flags.dryRun ? [] : ['--yes']), '--json']);
+function servesArgv(roster: string[], flags: ServesFlags, owner: ServesOwner | undefined, apply: boolean): string[] {
+ return ['access', 'serves', 'several', '--members', roster.join(','), ...(flags.source ? ['--source', flags.source] : []), ...(flags.labelledOnly ? ['--labelled-only'] : []), ...(owner ? ['--owner', owner.id] : []), ...(apply ? ['--yes'] : []), '--json'];
+}
+
+function runServesSeveral(launcher: string, roster: string[], flags: ServesFlags, owner: ServesOwner | undefined): Omit<ServesOutcome, 'brain_serves'> {
+ const r = child(launcher, servesArgv(roster, flags, owner, !flags.dryRun));
const receipt = parsed<ServesReceipt>(r.stdout);
- if (!receipt || !('members' in receipt)) return { mode: 'several', error: (r.stderr || r.stdout).trim() || 'gbrain access serves several failed' };
- if (flags.dryRun || receipt.error || !receipt.applied) return { mode: 'several', receipt };
+ const from = owner ? { owner_from: owner.from } : {};
+ if (!receipt || !('members' in receipt)) return { mode: 'several', ...from, error: (r.stderr || r.stdout).trim() || 'gbrain access serves several failed' };
+ if (flags.dryRun || receipt.error || !receipt.applied) return { mode: 'several', ...from, receipt };
const source = flags.source ? ['--source-id', flags.source] : [];
const read = (member: string, prefix: string, limit: number) => {
const found = child(launcher, ['find', prefix, '--as', member, '--limit', String(limit), ...source, '--json']);
@@ -130,10 +199,10 @@ function runServesSeveral(launcher: string, roster: string[], flags: ServesFlags
}
proof.push({ member, own: own.pages.length, leaked });
}
- return { mode: 'several', receipt, proof };
+ return { mode: 'several', ...from, receipt, proof };
}
-export interface ServesPlan { roster: string[]; status: ServesStatus | null }
+export interface ServesPlan { roster: string[]; status: ServesStatus | null; owner?: ServesOwner }
/**
* Before setup writes anything: the roster (an empty one refuses), the brain's serves view (none for a brain setup is
@@ -152,7 +221,15 @@ export function servesPreflight(flags: ServesFlags, launcher: string, harness: s
const read = hasBrain && !liveOurs ? readServesStatus(launcher) : null;
if (read && 'error' in read) return servesUnreadable(read.error, harness);
const status = read?.status ?? null;
- if (flags.serves === 'several') return { roster, status };
+ if (flags.serves === 'several') {
+ const owner = servesOwner(flags, harness, roster);
+ if (owner instanceof OperationError) return owner;
+ const run = status?.serves === 'one' && !flags.labelledOnly && !flags.openHistory ? child(launcher, servesArgv(roster, flags, owner, false)) : null;
+ const preview = run ? parsed<ServesReceipt>(run.stdout) : null;
+ const said = run ? `${run.stdout}\n${run.stderr}` : '';
+ const previewError = said.match(/"code"\s*:\s*"([a-z0-9_]+)"/)?.[1] ?? run?.stderr.trim().split('\n')[0]?.slice(0, 200);
+ return historyRefusal(status, preview, flags, harness, roster, owner, previewError || undefined) ?? { roster, status, owner };
+ }
if (named && !status?.enabled_members.includes(named)) {
return opError('invalid_params', `--stdio-member ${named} is not an enabled member of this brain, so the ${harness} sessions would read as nobody; nothing was written.`,
`Name one of: ${status?.enabled_members.join(', ') || '(none yet; label them with --serves several --members <ids>)'}.`,
@@ -165,15 +242,16 @@ export function servesPreflight(flags: ServesFlags, launcher: string, harness: s
/** The serves part of a setup run (a preview on a dry run), or null when it has nothing to do or say: a one-person brain with no bound entry. */
export function servesApply(flags: ServesFlags, launcher: string, harness: string, plan: ServesPlan, hasBrain: boolean, entry: EntryBinding = { member: null, previous: null }): ServesOutcome | null {
const several = flags.serves === 'several';
- const labelled = !several ? null : hasBrain || !flags.dryRun ? runServesSeveral(launcher, plan.roster, flags)
- : { mode: 'several' as const, note: `the new brain is created first; then ${plan.roster.join(', ')} each get a member, a folder rule and a bound key` };
+ const labelled = !several ? null : hasBrain || !flags.dryRun ? runServesSeveral(launcher, plan.roster, flags, plan.owner)
+ : { mode: 'several' as const, note: `the new brain is created first; then ${plan.roster.join(', ')} each get a member, a folder rule and a bound key${plan.owner ? `, and ${plan.owner.id} is named the brain owner` : ''}` };
const reread = several && !flags.dryRun ? readServesStatus(launcher) : null;
const status = reread ? ('status' in reread ? reread.status : null) : plan.status;
const preview = several && flags.dryRun && status?.serves !== 'several';
const view: ServesStatus | null = preview ? { serves: 'several', from: 'config', enabled_members: plan.roster, since: null, owner: null, stdio_member: status?.stdio_member ?? null } : status;
const stdio = bindStdio(harness, view, entry, flags.dryRun);
if (!labelled && !stdio) return null;
- const outcome: ServesOutcome = { ...(labelled ?? { mode: 'one' as const }), brain_serves: 'one', ...(stdio ? { stdio } : {}),
+ const pglite = several && (loadConfig()?.engine ?? 'pglite') === 'pglite';
+ const outcome: ServesOutcome = { ...(labelled ?? { mode: 'one' as const }), brain_serves: 'one', ...(stdio ? { stdio } : {}), ...(pglite ? { engine: PGLITE_SEVERAL_NOTE } : {}),
...(reread && 'error' in reread ? { error: `reading the brain back failed: ${reread.error}` } : {}) };
const bound = !!stdio?.member && view?.serves === 'several';
return { ...outcome, brain_serves: bound && servesOk(outcome) ? 'several' : 'one' };
@@ -200,7 +278,42 @@ export function bindStdio(harness: string, status: ServesStatus | null, entry: E
}
export function servesOk(o: ServesOutcome | null): boolean {
- return !o || (!o.error && (!o.receipt || receiptOk(o.receipt)) && (o.proof ?? []).every(p => p.leaked.length === 0));
+ return !o || (!o.error && (!o.receipt || receiptOk(o.receipt)) && (!o.regrant || receiptOk(o.regrant)) && (o.proof ?? []).every(p => p.leaked.length === 0));
+}
+
+/**
+ * GBRA-585 A: setup labels the people before the layout step adds the company source, so when this run added it, the
+ * labelling child runs once more and the keys it minted with a source list gain `company` (it adds, never removes).
+ * A dry run says so instead. When the re-run adds the company/ rule (--labelled-only), the layout's call readers become
+ * that rule's readers, since the layout step read them before the rule existed. Otherwise the readers line names the
+ * member keys setup minted only once this run left them reading `company` (callReadersAfterServes).
+ */
+export function servesAfterLayout(o: ServesOutcome | null, flags: ServesFlags, launcher: string, plan: ServesPlan, layout: LayoutOutcome | null | undefined): ServesOutcome | null {
+ if (!o || flags.serves !== 'several') return o;
+ if (layout?.company?.action !== 'created') {
+ callReadersAfterServes(o.receipt, launcher, plan, layout);
+ return o;
+ }
+ if (flags.dryRun) return { ...o, note: [o.note, 'the member keys this run mints also read source company once the layout step adds it: every page in it, including the calls it imports, which every member reads whether or not they attended',
+ ...(flags.labelledOnly ? ['as the members are labelled-only, a folder rule company/ in source company then names them and the owner as its readers'] : [])].filter(Boolean).join('; ') };
+ if (!o.receipt?.applied || o.error) return o;
+ const r = child(launcher, servesArgv(plan.roster, flags, plan.owner, true));
+ const regrant = parsed<ServesReceipt>(r.stdout);
+ if (!regrant || !('members' in regrant)) return { ...o, error: `giving the member keys source company failed: ${(r.stderr || r.stdout).trim() || 'gbrain access serves several printed nothing'}` };
+ const rule = regrant.company_rule;
+ if (rule && rule.action !== 'blocked' && layout.transcripts?.readers) {
+ const names = rule.readers.map(p => p.replace(/^member:/, ''));
+ layout.transcripts.readers = { members: names, serves: 'several', detail: `${names.join(', ')} only (the company/ rule on source company names them, so the labelled-only members read the calls through it)` };
+ } else callReadersAfterServes(regrant, launcher, plan, layout);
+ return { ...o, regrant };
+}
+
+/** GBRA-585 A: the layout read the call readers before the labelling ran; once a member key this run left reads company, they are those keys. */
+function callReadersAfterServes(receipt: ServesReceipt | undefined, launcher: string, plan: ServesPlan, layout: LayoutOutcome | null | undefined): void {
+ const readers = layout?.transcripts?.readers;
+ if (!readers || readers.members !== 'every_source_reader' || readers.serves !== 'several' || !receipt?.applied || !receipt.keys.some(k => k.reads?.includes('company'))) return;
+ const status = parsed<{ enabled_members?: string[] }>(child(launcher, ['access', 'serves', '--json', '--no-open-pages']).stdout);
+ layout!.transcripts!.readers = { members: 'every_source_reader', serves: 'several', detail: mintedKeysReadCalls(status?.enabled_members ?? plan.roster) };
}
/** GST-2670 (F9): the proof covers the people/ folders only, so it names the open pages that member's key still reads. */
@@ -218,7 +331,12 @@ export function servesLines(o: ServesOutcome, dryRun: boolean): string[] {
...(o.proof ?? []).map(p => p.leaked.length
? ` proof ${p.member} reads pages of another member's folder: ${p.leaked.join(', ')}`
: ` proof a read bound to ${p.member} sees its own folder (${p.own} page(s)) and no page of another member's folder${openTail(o.receipt, p.member)}`),
+ ...(o.owner_from === 'login' && o.receipt?.owner && o.receipt.owner.action !== 'keep' && o.receipt.owner.action !== 'blocked'
+ ? [` owner ${o.receipt.owner.id} is named from your login name; to name someone else, ${dryRun ? 'pass --owner <id>' : 'add them (gbrain access member add <id>) and run gbrain access owner set <id>'}`] : []),
+ ...(o.regrant ? [...o.regrant.keys.filter(k => k.adds?.length).map(k => ` key ${k.member}: now also reads ${k.adds!.join(', ')}, which this run added`),
+ ...o.regrant.keys.filter(k => k.action === 'skipped').map(k => ` key ${k.member}: skipped: ${k.detail}`), ...companyRuleLines(o.regrant), ...readsLines(o.regrant)] : []),
...(o.stdio ? [` stdio ${o.stdio.detail}`] : []),
+ ...(o.engine ? [` engine ${o.engine}`] : []),
...(o.note ? [` labels ${o.note}`] : []),
...(o.error ? [` error ${o.error}`] : []),
];
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index b0c69d14eb..7f1d9fcc70 100644
--- a/src/commands/setup.ts
+++ b/src/commands/setup.ts
@@ -53,13 +53,14 @@ import { describeCursorPins, readCursorPinsState, removeCursorSkillPins, syncCur
import { describeResolverSetup, removeSkillResolverSetup, syncSkillResolverSetup, type ResolverSetupResult } from '../core/setup/skill-resolver-setup.ts';
import type { ResolverHarness } from '../core/setup/skill-resolver-hook.ts';
import { isValidSourceId } from '../core/source-id.ts';
+import { ACCESS_ID_RE } from '../core/access/principals.ts';
import { peekLock } from '../core/pglite-lock.ts';
import { claudePluginProvidesName, codexPluginProvidesName } from '../core/bootstrap/plugin-lanes.ts';
import { claudeUserSettingsPath, type ClaudeHookEvent } from '../core/bootstrap/host-specs.ts';
import { readHarnessReceiptState } from '../core/bootstrap/format.ts';
import { smokeStdioRegistration } from './doctor/checks/harness-wiring.ts';
import { finishFreshSetupMigrations } from './setup-migrations.ts';
-import { readServesStatus, sharedStdioHarness, servesApply, servesLines, servesOk, servesPreflight, type EntryBinding, type ServesOutcome } from './setup-serves.ts';
+import { readServesStatus, sharedStdioHarness, servesAfterLayout, servesApply, servesLines, servesOk, servesPreflight, type EntryBinding, type ServesOutcome } from './setup-serves.ts';
import type { McpSurface } from '../mcp/surface.ts';
import {
SETUP_CAPABILITIES,
@@ -170,7 +171,14 @@ Flags:
--members IDS The people of --serves several, comma-separated (e.g. alice-example,bob-example).
--labelled-only With --serves several: each member's key reads only pages labelled for
that member (readable_by or a rule), never the owner's. Opt-in.
+ --open-history With --serves several on a brain that serves one person and already holds
+ pages: let the members read them. Without it or --labelled-only, setup
+ refuses (setup_history_choice_required) and writes nothing.
--members-file PATH The same, one id per line.
+ --owner ID With --serves several: the brain owner, added as a member and named with
+ gbrain access owner set when the brain has none (default: your login name
+ as a member id). An existing owner is kept. No key is rebound: setup lists
+ the keys bound to no member with the auth rescope command for each.
--stdio-member ID claude-code or codex: write serve --stdio-member ID into this harness's
MCP entry, so only its sessions read as ID (an enabled member, or one
of --members). Other harnesses on this host are unchanged. Use it for a
@@ -309,6 +317,10 @@ interface SetupFlags {
membersFile?: string;
/** GST-2670: --labelled-only, passed to access serves several. */
labelledOnly?: boolean;
+ /** GBRA-585 C: --open-history, the members read the pages a one-person brain already holds. */
+ openHistory?: boolean;
+ /** GBRA-585 D: --owner, the brain owner --serves several names when none is set (default: the login name). */
+ owner?: string;
/** GST-363: written into this harness's MCP entry as serve --stdio-member; never into config. */
stdioMember?: string;
noStdioMember: boolean;
@@ -324,7 +336,7 @@ interface SetupFlags {
team?: boolean;
}
-const VALUE_FLAGS = new Set(['--shape', '--notes', '--docs', '--transcripts', '--surface', '--scope', '--name', '--source', '--gbrain-bin', '--workspace', '--skill-loading', '--agent', '--live-fraction', '--pins-route', '--owner-sender', '--serves', '--members', '--members-file', '--stdio-member']);
+const VALUE_FLAGS = new Set(['--shape', '--notes', '--docs', '--transcripts', '--surface', '--scope', '--name', '--source', '--gbrain-bin', '--workspace', '--skill-loading', '--agent', '--live-fraction', '--pins-route', '--owner-sender', '--serves', '--members', '--members-file', '--stdio-member', '--owner']);
function parseFlags(args: string[]): SetupFlags | string {
const value = (flag: string): string | undefined => {
@@ -347,6 +359,11 @@ function parseFlags(args: string[]): SetupFlags | string {
if (serves !== undefined && serves !== 'one' && serves !== 'several') return `unknown --serves '${serves}'; pass one or several`;
if ((args.includes('--members') || args.includes('--members-file')) && serves !== 'several') return '--members and --members-file name the people of --serves several';
if (args.includes('--labelled-only') && serves !== 'several') return '--labelled-only applies to the people of --serves several';
+ if (args.includes('--open-history') && serves !== 'several') return '--open-history applies to the people of --serves several';
+ if (args.includes('--open-history') && args.includes('--labelled-only')) return 'pass --labelled-only (keep the history private) or --open-history (members read it), not both';
+ const owner = value('--owner');
+ if (owner !== undefined && serves !== 'several') return '--owner names the brain owner of --serves several';
+ if (owner !== undefined && !ACCESS_ID_RE.test(owner)) return `invalid --owner '${owner}'; a member id is lower-case letters, digits, '.', '_' and '-' (1-64 characters, starting with a letter or digit)`;
let stdioMember: string | undefined;
try { stdioMember = parseStdioMemberFlag(args); } catch (e) { return `${(e as Error).message}; nothing was written`; }
const noStdioMember = args.includes('--no-stdio-member');
@@ -411,6 +428,8 @@ function parseFlags(args: string[]): SetupFlags | string {
...(value('--members') !== undefined ? { members: value('--members') } : {}),
...(value('--members-file') !== undefined ? { membersFile: value('--members-file') } : {}),
...(args.includes('--labelled-only') ? { labelledOnly: true } : {}),
+ ...(args.includes('--open-history') ? { openHistory: true } : {}),
+ ...(owner !== undefined ? { owner } : {}),
...(stdioMember !== undefined ? { stdioMember } : {}),
noStdioMember,
...layout,
@@ -650,7 +669,8 @@ export async function runSetup(args: string[], deps: { openclaw?: { bin?: string
const skills = skillsFor('claude-code', flags, launcher, { scope, projectDir }, instructions);
const resolver = await resolverFor('claude-code', flags, launcher);
const layout = await layoutFor('claude-code', flags, launcher, instructions, brainCreate);
- return finish(out, { dryRun: true, target, consent, steps, states: [], verify: null, notices: layout.notices([]), notes, instructions, skills, resolver, serves, launcher, layout: layout.outcome });
+ const servesDone = servesAfterLayout(serves, flags, launcher, servesPlan, layout.outcome);
+ return finish(out, { dryRun: true, target, consent, steps, states: [], verify: null, notices: layout.notices([]), notes, instructions, skills, resolver, serves: servesDone, launcher, layout: layout.outcome });
}
let notices: Notice[] = [];
@@ -675,8 +695,9 @@ export async function runSetup(args: string[], deps: { openclaw?: { bin?: string
const states = ['configured', ...(verify.ok ? ['connection-verified', 'native-pending'] : [])];
const turnHook = plan.events.includes('UserPromptSubmit') && instructions?.decision.value === 'accepted' ? verifyTurnHook('claude-code', { projectDir }) : null;
const layout = await layoutFor('claude-code', flags, launcher, instructions, brainCreate);
+ const servesDone = servesAfterLayout(serves, flags, launcher, servesPlan, layout.outcome);
const code = await finish(out, { dryRun: false, target: { ...target, registration_owner: pluginOwner ? 'plugin' : 'setup' }, consent: result.receipt.consent, steps: result.steps, states, verify, notices: layout.notices(notices), notes,
- preserved: Object.keys(result.edited).map((event) => ({ kind: 'hook', event, reason: 'edited' })), instructions, skills, turnHook, resolver, serves, launcher, layout: layout.outcome });
+ preserved: Object.keys(result.edited).map((event) => ({ kind: 'hook', event, reason: 'edited' })), instructions, skills, turnHook, resolver, serves: servesDone, launcher, layout: layout.outcome });
if (turnHook && !turnHook.ok) return out.json ? 1 : refuse(turnHookNotLoaded('claude-code', turnHook, ['gbrain', 'setup', 'claude-code', ...(scope === 'project' ? ['--scope', 'project'] : [])]), out);
return verify.ok || pluginOwner ? code : 1;
} catch (e) {
@@ -851,7 +872,8 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainCon
const skills = skillsFor('codex', flags, launcher, {}, instructions);
const resolver = await resolverFor('codex', flags, launcher);
const layout = await layoutFor('codex', flags, launcher, instructions, brainCreate);
- return finish(out, { harness: 'codex', dryRun: true, target, consent, steps, states: [], verify: null, notices: layout.notices([]), notes, instructions, skills, resolver, serves, layout: layout.outcome });
+ const servesDone = servesAfterLayout(serves, flags, launcher, servesPlan, layout.outcome);
+ return finish(out, { harness: 'codex', dryRun: true, target, consent, steps, states: [], verify: null, notices: layout.notices([]), notes, instructions, skills, resolver, serves: servesDone, layout: layout.outcome });
}
let notices: Notice[] = [];
@@ -878,8 +900,9 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainCon
const states = ['configured', ...(verify.ok ? ['connection-verified', push === 'native-verified' && result.receipt.trust.owned.UserPromptSubmit ? 'native-verified' : 'native-pending'] : [])];
const turnHook = plan.events.includes('UserPromptSubmit') && instructions?.decision.value === 'accepted' ? verifyTurnHook('codex') : null;
const layout = await layoutFor('codex', flags, launcher, instructions, brainCreate);
+ const servesDone = servesAfterLayout(serves, flags, launcher, servesPlan, layout.outcome);
const code = await finish(out, { harness: 'codex', dryRun: false, target: { ...target, registration_owner: pluginOwner ? 'plugin' : 'setup' }, consent: result.receipt.consent,
- steps: result.steps, states, verify, notices: layout.notices(notices), notes: [...notes, ...result.notes], preserved: result.preserved, instructions, skills, turnHook, resolver, serves, layout: layout.outcome });
+ steps: result.steps, states, verify, notices: layout.notices(notices), notes: [...notes, ...result.notes], preserved: result.preserved, instructions, skills, turnHook, resolver, serves: servesDone, layout: layout.outcome });
if (turnHook && !turnHook.ok) return out.json ? 1 : refuse(turnHookNotLoaded('codex', turnHook, ['gbrain', 'setup', 'codex']), out);
return verify.ok || pluginOwner ? code : 1;
} catch (e) {
diff --git a/src/commands/sources-add-next.ts b/src/commands/sources-add-next.ts
index 387edd85c2..d87df0e4d8 100644
--- a/src/commands/sources-add-next.ts
+++ b/src/commands/sources-add-next.ts
@@ -33,7 +33,7 @@ export async function noGrantFloorNext(engine: BrainEngine, id: string): Promise
return {
command: argv.join(' '),
argv,
- why: `Connections with no source grant read only the default source and federated sources, and none of them holds a page, so their reads are refused until "${id}" is federated or they are granted sources.`,
+ why: `Connections with no source grant read only the default source and federated sources, and none of them holds a page every reader of its source can read, so their empty reads are refused until "${id}" is federated or they are granted sources.`,
};
}
@@ -44,7 +44,7 @@ export function notInDefaultSearchNotice(id: string, shared: boolean, ask = shar
kind: 'info',
why: `The source "${id}" is not federated, so it is not in default search: a search, query or recall that names no source leaves its pages out, and a remote token or agent connection with no source grant cannot read them.`
+ (shared ? ' This brain serves several people or is not marked personal, so a new source stays out until someone chooses to add it.' : '')
- + ` Run \`gbrain sources federate ${id}\` to add it, or grant one token with \`gbrain auth rescope --token <name> --sources ${id}\`.`,
+ + ` To share it with every connection that reads default search, run \`gbrain sources federate ${id}\`; to share it with one token, \`gbrain auth rescope --token <name> --sources ${id}\`. A source meant to stay private needs nothing.`,
fix: {
argv: ['gbrain', 'sources', 'federate', id],
consent: [],
@@ -54,6 +54,7 @@ export function notInDefaultSearchNotice(id: string, shared: boolean, ask = shar
why: 'Adds the source to default search and to what connections with no source grant can read.',
verify: { argv: ['gbrain', 'sources', 'list', '--json'] },
},
+ ...(ask ? { user_message: `Should the source "${id}" be shared with every connection that reads this brain's default search? If yes, the command shown adds it. If it is meant for one person or a few connections, leave it as it is.` } : {}),
};
}
diff --git a/src/commands/sources-writers.ts b/src/commands/sources-writers.ts
index be896540e5..2d9b24da56 100644
--- a/src/commands/sources-writers.ts
+++ b/src/commands/sources-writers.ts
@@ -4,7 +4,8 @@
* Refuses a source that is not a guest source. Trusted local CLI only.
*/
import type { BrainEngine } from '../core/engine.ts';
-import { GUEST_WRITER_FORMAT, changeGuestWriters, isGuestWriter, readGuestSource } from '../core/guests/sources.ts';
+import { GUEST_WRITER_FORMAT, changeGuestWriters, isGuestWriter, readGuestSource, unregisteredClientWriters } from '../core/guests/sources.ts';
+import { exitCliError } from '../cli/cli-error.ts';
export const SOURCES_WRITERS_USAGE = `Usage: gbrain sources writers <id> [--add ${GUEST_WRITER_FORMAT}]... [--remove <writer>]... [--clear] [--json]
Lists the writers of a guest source, or changes them. Only a listed writer can
@@ -32,6 +33,8 @@ export async function runSourcesWriters(engine: BrainEngine, args: string[]): Pr
console.error(`Not a writer principal: ${malformed.join(', ')}. Name each writer as ${GUEST_WRITER_FORMAT}.`);
process.exit(2);
}
+ const unregistered = await unregisteredClientWriters(engine, add);
+ if (unregistered) exitCliError(unregistered, 'sources');
const [source] = await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE id = $1', [id]);
if (!source) {
console.error(`Source "${id}" not found. List sources with: gbrain sources list`);
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index df480e877d..007aa439ca 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -1204,8 +1204,8 @@ async function runFederate(engine: BrainEngine, args: string[], value: boolean):
const exposure = await import('../core/access/federation-exposure.ts');
const exposed = await exposure.remotePagesFederationExposesOrWarn(engine, id, value && id !== 'default' && !wasFederated);
if (exposed) console.error(exposure.pagesExposedLines(id, exposed).join('\n'));
- if (json) console.log(JSON.stringify({ id, federated: value, ...(exposed ? { pages_exposed: exposed } : {}) }));
-
+ const keys = value ? [] : await (await import('./access-serves.ts')).keysStillReadingNotice(engine, id, say);
+ if (json) console.log(JSON.stringify({ id, federated: value, ...(exposed ? { pages_exposed: exposed } : {}), ...(keys.length ? { keys_still_reading: keys } : {}) }));
// v0.40 D19: auto-submit embed-backfill when coverage < 100%. Federation
// flip is a moment when the user explicitly opted into seeing this source
// in default search; un-embedded chunks would hide content from the very
diff --git a/src/commands/transcripts-archive.ts b/src/commands/transcripts-archive.ts
index d1462b7b02..41ff8edc8a 100644
--- a/src/commands/transcripts-archive.ts
+++ b/src/commands/transcripts-archive.ts
@@ -56,9 +56,13 @@ export async function runTranscriptsArchive(engine: BrainEngine, args: string[],
if (sub === 'status') {
const status = await archive.archiveStatus(engine, { sourceId });
+ const { resolveArchiveEnabled } = await import('../core/transcripts/archive-default.ts');
+ const { loadConfig } = await import('../core/config.ts');
+ const why = json ? null : await resolveArchiveEnabled(engine, { config: (() => { try { return loadConfig(); } catch { return null; } })() }).then(e => e.reason, () => null);
const upkeepOff = !json && status.enabled && !await (await import('../core/maintenance/run.ts')).upkeepEnabled(engine);
out(status, () => {
console.log('conversation archive: ' + (status.enabled ? 'on' : 'off') + ' (source: ' + status.source_id + ', timezone: ' + (status.timezone ?? status.configured_timezone + ', pinned at the first run') + ')');
+ if (why) console.log(' why: ' + why);
for (const h of status.harnesses) {
const read = h.read_at ? h.conversations + ' conversation(s) read by the last ' + (h.read_mode ?? 'run') + ' (' + h.read_at + '), newest session day ' + (h.newest_session_day ?? '-') : 'not read by an archive run yet';
console.log(' ' + h.reader.padEnd(18) + ' ' + (h.info ?? read + ', newest archived day ' + (h.newest_archived_day ?? '-')));
diff --git a/src/commands/transcripts.ts b/src/commands/transcripts.ts
index 33d1e42326..6bbebe267c 100644
--- a/src/commands/transcripts.ts
+++ b/src/commands/transcripts.ts
@@ -198,7 +198,7 @@ const HELP = `Usage:
gbrain transcripts status # found vs imported gap table
gbrain transcripts recover codex # restore user turns lost to #5163 (preview; --apply)
gbrain transcripts audit-secrets # list imported pages that still carry a credential (read-only)
- gbrain transcripts archive run|backfill|status|adopt-legacy|on|off # day-sliced conversation archive (off unless turned on)
+ gbrain transcripts archive run|backfill|status|adopt-legacy|on|off # day-sliced conversation archive (on by default on a personal brain, offered on a shared one)
gbrain transcripts recent [options]
ingest — import dead session logs and chat exports as conversation pages
diff --git a/src/core/access/implicit-placement.ts b/src/core/access/implicit-placement.ts
new file mode 100644
index 0000000000..e15f20926d
--- /dev/null
+++ b/src/core/access/implicit-placement.ts
@@ -0,0 +1,75 @@
+/**
+ * GBRA-585: where a trusted local `gbrain put` that named no source put its page, on a brain that serves several
+ * people. Source routing is unchanged; the result gains a `placement` object naming the source, the rule that
+ * picked it, who may read the page and how to choose otherwise, so a page never lands in a source its writer did
+ * not pick without a word. A one-person brain, a remote caller and a put that named its source get nothing.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { brainServes } from './serves.ts';
+import { parseSourceConfig } from '../sources-load.ts';
+import { resolveImplicitDefaultSourceId } from '../source-resolver.ts';
+
+export type PlacementRule = 'local_path' | 'brain_default' | 'sole_non_default' | 'seed_default';
+
+export interface Placement {
+ source_id: string;
+ picked_by: PlacementRule;
+ readers: string[] | 'every_source_reader';
+ note: string;
+}
+
+const WHY: Record<PlacementRule, (id: string) => string> = {
+ local_path: id => `the current folder is inside the folder of source '${id}'`,
+ brain_default: () => 'config sources.default names it',
+ sole_non_default: id => `'${id}' is the only source besides 'default' with a folder and 'default' held no pages; once 'default' holds a page, a put that names no source goes to 'default'`,
+ seed_default: () => "it is the brain's default source",
+};
+
+async function pickedBy(engine: BrainEngine, sourceId: string): Promise<PlacementRule> {
+ const [configured, implicit] = await Promise.all([engine.getConfig('sources.default'), resolveImplicitDefaultSourceId(engine)]);
+ if (sourceId === implicit) return implicit === configured ? 'brain_default' : 'sole_non_default';
+ return implicit === null && sourceId === 'default' ? 'seed_default' : 'local_path';
+}
+
+/** The placement of a page a local put wrote with no source named, or null on a brain that serves one person. */
+export async function implicitPlacement(engine: BrainEngine, sourceId: string, slug: string): Promise<Placement | null> {
+ if ((await brainServes(engine)).serves !== 'several') return null;
+ const { whoCanRead } = await import('../../commands/access.ts');
+ const [entry] = await whoCanRead(engine, slug, sourceId);
+ if (!entry) return null;
+ const picked = await pickedBy(engine, sourceId);
+ const [row] = await engine.executeRaw<{ config: unknown }>('SELECT config FROM sources WHERE id = $1', [sourceId]);
+ const noGrantReads = sourceId === 'default' || parseSourceConfig(row?.config).federated === true;
+ const who = entry.members !== 'every_source_reader'
+ ? `Members who may read it: ${entry.members.join(', ') || 'none'}.`
+ : entry.private
+ ? `It names no readers, but it is private: a member key reads it only with private_pages: granted_sources on source '${sourceId}', so a key with no source grant does not.`
+ : noGrantReads
+ ? `It names no readers, so every member whose key reads source '${sourceId}' reads it, and a member key with no source grant does.`
+ : `It names no readers. A member key with no source grant does not read source '${sourceId}' until it is federated (gbrain sources federate ${sourceId}); from then on every member does.`;
+ const qualifications = entry.note.split(/(?<=\.) (?=[A-Z])/)
+ .filter(s => s.startsWith('Labelled-only members') || (entry.members !== 'every_source_reader' && s.startsWith('visibility: private')));
+ return {
+ source_id: sourceId,
+ picked_by: picked,
+ readers: entry.members,
+ note: `No source was named, so ${slug} went to source '${sourceId}': ${WHY[picked](sourceId)}. ${[who, ...qualifications].join(' ')} `
+ + 'To choose the source, pass --source <id> (gbrain sources current shows how one is picked); '
+ + 'to keep the page to some members, give it readable_by: [<member>, ...] in its frontmatter.',
+ };
+}
+
+/** put_page's result with `placement` added for the trusted local CLI's unscoped put on a brain that serves several people. */
+export async function withImplicitPlacement<R>(ctx: { engine: BrainEngine; remote?: boolean; localSourceImplicit?: boolean },
+ sourceId: string, params: Record<string, unknown>, result: R): Promise<R> {
+ if (ctx.remote !== false || ctx.localSourceImplicit !== true || params.source_id !== undefined) return result;
+ const written = (result ?? {}) as Record<string, unknown>;
+ if (written.status !== 'created_or_updated' && written.status !== 'skipped') return result;
+ try {
+ const slug = typeof written.slug === 'string' ? written.slug : String(params.slug);
+ const placement = await implicitPlacement(ctx.engine, sourceId, slug);
+ return placement ? { ...written, placement } as R : result;
+ } catch {
+ return result;
+ }
+}
diff --git a/src/core/access/open-pages.ts b/src/core/access/open-pages.ts
index bb3968062a..c6783cf85c 100644
--- a/src/core/access/open-pages.ts
+++ b/src/core/access/open-pages.ts
@@ -40,6 +40,8 @@ export interface OpenPages {
sensitive: number;
/** Open pages that visibility: private (or a privacy alias) keeps from members; counted in total instead where remote privacy is relaxed or a reading member's grant opens private pages. */
private: number;
+ /** GBRA-585 C: open pages in the conversation archive (conversations/), also counted in total. */
+ archive: number;
folders: OpenFolder[];
other: { folders: number; pages: number; sensitive: number };
top_sensitive: { source: string; type: string; pages: number } | null;
@@ -48,16 +50,24 @@ export interface OpenPagesError { code: string; message: string; retry: string }
export interface OpenPagesRead { open_pages: OpenPages | null; open_pages_error?: OpenPagesError }
export interface OpenPagesOptions {
- /** Members a run is about to add or keep, the source their new keys write (access serves several), and whether it marks them labelled-only. */
- planned?: { members: readonly string[]; source: string; labelledOnly: boolean };
+ /** Members a run is about to add or keep, the source their new keys write (access serves several), whether it marks them labelled-only, and the owner once the run is done. */
+ planned?: { members: readonly string[]; source: string; labelledOnly: boolean; owner?: string | null };
/** Prefixes a rule the run adds will cover, left out of the count. */
exclude?: ReadonlyArray<{ source: string; prefix: string }>;
}
-/** The sources a key minted for `source` reads: that source, or for default the default source and every federated one. */
-async function mintedReadSources(engine: BrainEngine, source: string): Promise<string[]> {
- if (source !== 'default') return [source];
- return await localFederatedSourceIds(engine, 'default', 'seed_default').catch(() => undefined) ?? ['default'];
+/** The source the company shape adds (setup-brain-layout.ts COMPANY_SOURCE). */
+export const COMPANY_SOURCE_ID = 'company';
+
+/**
+ * GBRA-585 A: the sources a member key `gbrain access serves several` mints for `source` reads, as a fixed list (the
+ * federated grant kind, readSources[0] = the write source): that source, the `company` source when it exists, and
+ * every source federated now. A source federated later is added only by a re-run (labelSeveral adds, never removes).
+ */
+export async function memberKeyReadSources(engine: BrainEngine, source: string): Promise<string[]> {
+ const federated = await localFederatedSourceIds(engine, source, 'seed_default').catch(() => undefined) ?? [source];
+ const company = source !== COMPANY_SOURCE_ID && (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE id = $1 AND archived IS NOT TRUE', [COMPANY_SOURCE_ID])).length > 0;
+ return [...new Set([source, ...(company ? [COMPANY_SOURCE_ID] : []), ...federated])];
}
/**
@@ -99,7 +109,7 @@ async function memberReads(engine: BrainEngine, owner: string | null, planned: O
const stdioSet = stdio ? reads.get(stdio) : undefined;
if (stdioSet) for (const s of await stdioReadSources(engine)) stdioSet.add(s);
if (planned) {
- const minted = await mintedReadSources(engine, planned.source);
+ const minted = await memberKeyReadSources(engine, planned.source);
for (const id of planned.members) {
if (id === owner) continue;
const set = reads.get(id) ?? new Set<string>();
@@ -150,7 +160,7 @@ export async function withOpenScope<T>(engine: BrainEngine, opts: OpenPagesOptio
if (state?.unreadable === true) {
throw Object.assign(new Error('the folder-rule state cannot be read, so every page reads as covered and a count would say 0'), { code: 'open_pages_unknown' });
}
- const owner = await ownerMemberId(engine);
+ const owner = opts.planned?.owner !== undefined ? opts.planned.owner : await ownerMemberId(engine);
const { reads, privateSources } = await memberReads(engine, owner, opts.planned);
const reading = [...reads.values()].filter(s => s.size > 0);
const readSources = [...new Set(reading.flatMap(s => [...s]))].sort();
@@ -166,7 +176,7 @@ export async function withOpenScope<T>(engine: BrainEngine, opts: OpenPagesOptio
export async function openPages(engine: BrainEngine, opts: OpenPagesOptions = {}): Promise<OpenPages> {
return withOpenScope(engine, opts, async (scope, boundedRead) => {
const { owner, sources } = scope;
- const result: OpenPages = { owner, members: scope.members, sources, total: 0, sensitive: 0, private: 0,
+ const result: OpenPages = { owner, members: scope.members, sources, total: 0, sensitive: 0, private: 0, archive: 0,
folders: [], other: { folders: 0, pages: 0, sensitive: 0 }, top_sensitive: null };
if (!sources.length) return result;
const params: unknown[] = [sources];
@@ -190,6 +200,7 @@ export async function openPages(engine: BrainEngine, opts: OpenPagesOptions = {}
folders.set(key, f);
f.pages += n;
result.total += n;
+ if (row.folder === 'conversations') result.archive += n;
if (!row.type || !SENSITIVE_PAGE_TYPES.includes(row.type)) continue;
f.sensitive += n;
result.sensitive += n;
diff --git a/src/core/backup/coverage.ts b/src/core/backup/coverage.ts
index c66b56a30e..f6ee74e80b 100644
--- a/src/core/backup/coverage.ts
+++ b/src/core/backup/coverage.ts
@@ -40,6 +40,7 @@ import {
isRemoteTimeout,
isRepoAsset,
assetBlocksRecovery,
+ backupCoachingDue,
BACKUP_VERIFICATION_MAX_AGE_MS,
BACKUP_RECOVERY_SCOPE,
type BackupAssetVerdict,
@@ -370,7 +371,7 @@ export async function computeBackupCoverage(
state: 'info',
detail:
`Postgres contains ${pageCount} pages; database placement and external backups were not verified — ` +
- 'add a source repo (gbrain sources add) or dump with gbrain export',
+ 'add a source repo (gbrain sources add) and back up the database with pg_dump (gbrain export is not a backup)',
fix_argv: ['gbrain', 'bootstrap', 'repo'],
});
} else {
@@ -460,7 +461,15 @@ export async function getBackupStatus(
const remoteDue = opts.localGitProbes === true && opts.verifyRemoteRefs === true
&& (!Number.isFinite(remoteAge) || remoteAge < 0 || remoteAge > BACKUP_VERIFICATION_MAX_AGE_MS
|| (remoteAge >= BACKUP_CONTINUATION_THROTTLE_MS && hasPendingRepoEvidence(cached, nowMs)));
- if (!opts.forceRefresh && cached && !isBackupStatusStale(cached, nowMs) && !remoteDue) return currentBackupEvidence(cached, nowMs);
+ if (!opts.forceRefresh && cached && !isBackupStatusStale(cached, nowMs) && !remoteDue) {
+ const current = currentBackupEvidence(cached, nowMs);
+ // The cache keeps git evidence for its interval, but the page+fact count it
+ // took (often at init, on an empty brain) decides whether coaching is due:
+ // re-read it while the cached count still says "too young to coach".
+ if (!current.maturity || backupCoachingDue(current, nowMs)) return current;
+ const maturity = await brainMaturity(engine);
+ return maturity ? { ...current, maturity } : current;
+ }
try {
const fresh = await computeBackupCoverage(engine, { ...opts, previousStatus: cached ?? undefined });
if (fresh.degraded && cached) return currentBackupEvidence({ ...cached, degraded: true }, nowMs);
diff --git a/src/core/backup/preflight.ts b/src/core/backup/preflight.ts
index 61efc630c0..3111322f5d 100644
--- a/src/core/backup/preflight.ts
+++ b/src/core/backup/preflight.ts
@@ -74,6 +74,36 @@ export function physicalCopyFix(): Action {
};
}
+export const POSTGRES_BACKUP_DOCS = 'docs/guides/memory-boundaries.md#full-backup';
+
+const POSTGRES_DUMP_STEPS = 'This brain lives in Postgres, so back it up with a database dump of its database: ' +
+ '`pg_dump --format custom --file <DUMP_FILE> --dbname <DATABASE_URL>`, kept private (it holds every page, fact, member and token); `pg_restore --list <DUMP_FILE>` reads it back. ' +
+ 'Restore it into a new, empty database with `pg_restore --no-owner --dbname <NEW_DATABASE_URL> <DUMP_FILE>`, then run ' +
+ '`gbrain init --url <NEW_DATABASE_URL>` under a separate GBRAIN_HOME, which opens the restored brain. ' +
+ '`gbrain export` is not a backup: an import of it puts every page in one source and keeps no members, tokens or facts.';
+
+/** The full backup of a Postgres brain: the host admin dumps its database; pg_restore --list reads the dump back. */
+export function postgresDumpFix(): Action {
+ return {
+ argv: ['pg_dump', '--format', 'custom', '--file', '<DUMP_FILE>', '--dbname', '<DATABASE_URL>'],
+ consent: ['credentials'], actor: 'host_admin', requires_exclusive: false, docs: POSTGRES_BACKUP_DOCS,
+ why: 'A database dump keeps every source, page, fact, member, token and folder rule of a Postgres brain; a Markdown export keeps pages only.',
+ user_message: POSTGRES_DUMP_STEPS,
+ inputs: [
+ { name: 'DUMP_FILE', how: 'A new file outside the brain, in a directory only the user can read.' },
+ { name: 'DATABASE_URL', how: 'The brain\'s Postgres connection, preferably service=<name> from a pg_service file so no password lands in the command line.' },
+ ],
+ };
+}
+
+/** `gbrain backup create` on a Postgres brain: the same storage_error code, with the database dump as the fix. */
+export function postgresBackupRefusal(): OperationError {
+ return opError('storage_error',
+ `gbrain backup create snapshots PGLite brains only. ${POSTGRES_DUMP_STEPS}`,
+ 'Tell the user to back up the Postgres database with pg_dump and restore it with pg_restore.',
+ { reason: 'pglite_required', why: 'Full local snapshots copy a PGLite data directory; a Postgres brain\'s data is in its database server.', fix: postgresDumpFix() });
+}
+
/**
* The refusal for a brain this recovery format cannot hold, or null when it can.
* Reads only file metadata; `managedFileBytes` runs only for a managed layout.
diff --git a/src/core/backup/snapshot.ts b/src/core/backup/snapshot.ts
index 1c700f3554..20bc52d70c 100644
--- a/src/core/backup/snapshot.ts
+++ b/src/core/backup/snapshot.ts
@@ -16,7 +16,7 @@ import { quarantineSharedSkillRestore, validateSharedSkillRestoreMode, type Shar
import { isPhysicalRootMetadata } from '../persistence/physical-root-record.ts';
import { protectNewBackupPath } from './private-path.ts';
import { PURGE_MIRROR_FILE, readPurgeMirror, replayPurgesInRestore, type PurgeReplayResult } from '../belief/purge-mirror.ts';
-import { pgliteBackupPreflight } from './preflight.ts';
+import { pgliteBackupPreflight, postgresBackupRefusal } from './preflight.ts';
interface SourceInventory { id: string; local_path: string | null; managed_relative_path: string | null }
interface BackupMetadata {
@@ -136,6 +136,7 @@ export async function createPgliteBackup(options: { output: string; root?: strin
if (!existsSync(dirname(output))) throw new AgentInstallError('output_parent_missing', 'Create a private backup destination directory first.');
const state = readFileConfigState(join(root, '.gbrain', 'config.json'));
if (state.kind !== 'present' || state.config.engine !== 'pglite' || state.config.remote_mcp || state.config.database_url) {
+ if (state.kind === 'present' && !state.config.remote_mcp && (state.config.engine === 'postgres' || state.config.database_url)) throw postgresBackupRefusal();
throw new AgentInstallError('pglite_required', 'Full local snapshots require an existing file-configured PGLite brain.');
}
const dbPath = state.config.database_path;
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index a1e6fb80ac..554b60316e 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -14,7 +14,7 @@
// (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-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'],
+ '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', '--owner', '--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'],
@@ -52,7 +52,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--as', '--background', '--brain', '--break-lock', '--concurrency', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--only', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--room', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--claims', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--card', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--filter', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--only', '--page', '--params', '--patch', '--path', '--phase', '--prefer', '--preview', '--privacy-url', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--surface', '--terms-url', '--to', '--updated-after', '--url', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--agent', '--aggressive', '--alert', '--aliases', '--all', '--all-drifted', '--all-from', '--all-sources', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allow-without-owner', '--allowed-operations', '--anchor', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--assume-unchanged', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--body', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--calls', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--claude-plugins', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--concurrent', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--created-before', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--days', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--drop-field', '--dry-run', '--egress', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--filter', '--finalize', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--from-prefix', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--gbrain-skill-resolver', '--generation', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--heads', '--held', '--help', '--history', '--hold-state', '--holds', '--home', '--http', '--id', '--ids-file', '--if-version', '--ignore-env-override', '--ignore-missing', '--ignore-unmatch', '--images', '--import', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--input-type', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--labelled-only', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extensions', '--no-extract', '--no-federated', '--no-filters', '--no-follow-tags', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-open-pages', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-stdio-member', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preload', '--preset', '--preview', '--principal', '--priority', '--privacy-url', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--push-remote', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--read-sources', '--reader-mode', '--readers', '--reads-unscoped', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--recurse-submodules', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--room', '--root', '--routing', '--rules', '--run', '--runtime', '--safe', '--sample', '--save', '--scan-secrets', '--scan-timeout', '--schedule', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--skip-worktree', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--strict-json', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--synopsis', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--terms-url', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unattended', '--undo', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unschedule', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untrack', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--wakeshift', '--warn-only', '--watch', '--what-if-threshold', '--where', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--agent', '--aggressive', '--alert', '--aliases', '--all', '--all-drifted', '--all-from', '--all-sources', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allow-without-owner', '--allowed-operations', '--anchor', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--assume-unchanged', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--body', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--calls', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--claude-plugins', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--concurrent', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--created-before', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--days', '--db-url', '--dbname', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--drop-field', '--dry-run', '--egress', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--filter', '--finalize', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--from-prefix', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--gbrain-skill-resolver', '--generation', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--heads', '--held', '--help', '--history', '--hold-state', '--holds', '--home', '--http', '--id', '--ids-file', '--if-version', '--ignore-env-override', '--ignore-missing', '--ignore-unmatch', '--images', '--import', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--input-type', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--labelled-only', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extensions', '--no-extract', '--no-federated', '--no-filters', '--no-follow-tags', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-open-pages', '--no-owner', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-stdio-member', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--open-history', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--owner', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preload', '--preset', '--preview', '--principal', '--priority', '--privacy-url', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--push-remote', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--read-sources', '--reader-mode', '--readers', '--reads-unscoped', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--recurse-submodules', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--room', '--root', '--routing', '--rules', '--run', '--runtime', '--safe', '--sample', '--save', '--scan-secrets', '--scan-timeout', '--schedule', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--skip-worktree', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--strict-json', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--synopsis', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--terms-url', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unattended', '--undo', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unschedule', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untrack', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--wakeshift', '--warn-only', '--watch', '--what-if-threshold', '--where', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--card', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--expected-revision', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--patch', '--path', '--phase', '--prefer', '--privacy-url', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--terms-url', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -82,7 +82,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'init': ['--abandon', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--admin-intent', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--allow-without-owner', '--anchor', '--applied', '--apply', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--background', '--base', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--catch-up', '--channel', '--chat-model', '--check', '--check-downgrade', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--decisions', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--file', '--filter', '--first-parent', '--fix', '--force', '--force-retry', '--force-schema', '--format', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-failures', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--list-out', '--local', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-stdio-member', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--of', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--reason', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remote', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--safe', '--save', '--scan-secrets', '--scan-timeout', '--schedule', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--sources', '--squash', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--take', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--uninstall', '--unsettle', '--untrack', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--as', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--room', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],
- 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--agent', '--alert', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--approval-out', '--approved', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--base', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--bundled', '--by-mention', '--cached', '--calls', '--card', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--decisions', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--drop-field', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-catalog', '--expect-local', '--expect-upstream', '--expected-revision', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filter', '--filters', '--finalize', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--format', '--fresh', '--from-index', '--from-json', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-content', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--input-json', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--migrate-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-assume-unchanged', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-skip-worktree', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--out', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--patch', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--prefix', '--preview', '--priority', '--privacy-url', '--probe', '--propose', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--readers', '--reads-unscoped', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--routing', '--row', '--save', '--schedule', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--serves', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skill-loading', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdio-member', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--synopsis', '--target', '--terms-url', '--text', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--unattended', '--uninstall', '--unschedule', '--unshallow', '--untrack', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wakeshift', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
+ 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--agent', '--alert', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--approval-out', '--approved', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--base', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--bundled', '--by-mention', '--cached', '--calls', '--card', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--decisions', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--drop-field', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-catalog', '--expect-local', '--expect-upstream', '--expected-revision', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filter', '--filters', '--finalize', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--format', '--fresh', '--from-index', '--from-json', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-content', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--input-json', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--labelled-only', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--migrate-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-assume-unchanged', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-skip-worktree', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--open-history', '--order', '--others', '--out', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--patch', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--prefix', '--preview', '--priority', '--privacy-url', '--probe', '--propose', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--readers', '--reads-unscoped', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--routing', '--row', '--save', '--schedule', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--serves', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skill-loading', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdio-member', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--synopsis', '--target', '--terms-url', '--text', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--unattended', '--uninstall', '--unschedule', '--unshallow', '--untrack', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wakeshift', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--accept-pending', '--add', '--admin-intent', '--adopt-slug-path', '--as', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--porcelain', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--readers', '--rebase', '--require-clean', '--resolve', '--room', '--scan-secrets', '--scan-timeout', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--stdin', '--timeout', '--timings', '--unset-all', '--untracked-files', '--verify', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
@@ -117,22 +117,22 @@ 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-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'],
+ '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', '--labelled-only', '--lanes', '--limit', '--list-out', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--may-act-for', '--member', '--members', '--members-file', '--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-open-pages', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--owner', '--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'],
'salience': ['--brain', '--days', '--help', '--json', '--kind', '--limit', '--mcp-only', '--request-id', '--slug-prefix', '--source'],
'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--path', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],
'self-upgrade': ['--apply', '--backend', '--brain', '--channel', '--check-only', '--clear-never-installed', '--exit-code', '--ff-only', '--force', '--force-retry', '--help', '--is-ancestor', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-restart', '--non-interactive', '--quiet', '--refresh-cache', '--refs', '--remediation-plan', '--restart-only', '--snooze', '--source', '--stop-mcp', '--swap-only', '--tags', '--version', '--yes'],
- 'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--advertise', '--all-new', '--apply-rewrites', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cli-socket', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--labelled-only', '--limit', '--log-full-params', '--may-act-for', '--member', '--members', '--members-file', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-open-pages', '--no-pull', '--no-stdio-member', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--private-pages', '--profile', '--provenance', '--public-url', '--read-sources', '--reads-unscoped', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--serves', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--stdio-member', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],
- 'setup': ['--accept-capabilities', '--advertise', '--agent', '--all-agents', '--apply', '--arg', '--as', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--calls', '--capture', '--catalog', '--command', '--credentials-file', '--docs', '--dry-run', '--env', '--expect', '--force', '--gbrain-bin', '--gbrain-skill-resolver', '--git-path', '--harness', '--header', '--held', '--help', '--http', '--images', '--input-type', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--labelled-only', '--legacy-lock', '--limit', '--link', '--live-fraction', '--max-cost', '--max-usd', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--name', '--no-capture', '--no-embed', '--no-embedding', '--no-extensions', '--no-hooks', '--no-instructions', '--no-open-pages', '--no-providers', '--no-stdio-member', '--non-interactive', '--notes', '--oauth-client-id', '--oauth-client-secret', '--only', '--owner-sender', '--path', '--pglite', '--pins-route', '--prefix', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--schedule', '--scope', '--serves', '--shape', '--show-toplevel', '--skill-loading', '--skills-index-only', '--solo', '--source', '--source-id', '--source-ids', '--stale', '--stdio-member', '--strict-json', '--surface', '--team', '--token', '--transcripts', '--trust', '--url', '--wakeshift', '--workspace', '--yes'],
+ 'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--advertise', '--all-new', '--apply-rewrites', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cli-socket', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--labelled-only', '--limit', '--log-full-params', '--may-act-for', '--member', '--members', '--members-file', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-open-pages', '--no-pull', '--no-stdio-member', '--oauth-request', '--only', '--open-history', '--operations', '--owner', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--private-pages', '--profile', '--provenance', '--public-url', '--read-sources', '--reads-unscoped', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--serves', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--stdio-member', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--to', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],
+ 'setup': ['--accept-capabilities', '--advertise', '--agent', '--all-agents', '--apply', '--arg', '--as', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--calls', '--capture', '--catalog', '--command', '--credentials-file', '--docs', '--dry-run', '--env', '--expect', '--force', '--gbrain-bin', '--gbrain-skill-resolver', '--git-path', '--harness', '--header', '--held', '--help', '--http', '--images', '--input-type', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--labelled-only', '--legacy-lock', '--limit', '--link', '--live-fraction', '--max-cost', '--max-usd', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--name', '--no-capture', '--no-embed', '--no-embedding', '--no-extensions', '--no-hooks', '--no-instructions', '--no-open-pages', '--no-providers', '--no-stdio-member', '--non-interactive', '--notes', '--oauth-client-id', '--oauth-client-secret', '--only', '--open-history', '--owner', '--owner-sender', '--path', '--pglite', '--pins-route', '--prefix', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--schedule', '--scope', '--serves', '--shape', '--show-toplevel', '--skill-loading', '--skills-index-only', '--solo', '--source', '--source-id', '--source-ids', '--stale', '--stdio-member', '--strict-json', '--surface', '--team', '--to', '--token', '--transcripts', '--trust', '--url', '--wakeshift', '--workspace', '--yes'],
'skill-resolver': ['--accept-capabilities', '--agent', '--brain', '--bundled', '--catalog', '--claude-plugins', '--dir', '--exclude', '--expect-catalog', '--explain-target', '--fail-open', '--force', '--from-json', '--gbrain-bin', '--gbrain-skill-resolver', '--git-path', '--harness', '--help', '--input-json', '--input-type', '--json', '--line', '--link', '--load-hint', '--min-match', '--names-only', '--no-extensions', '--only', '--out', '--previous', '--reset-session', '--routing', '--runtime', '--scope', '--session', '--shadow', '--shadow-log', '--show-toplevel', '--skill-loading', '--source', '--text', '--top-gate', '--top-k'],
'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],
'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--loop', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],
'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-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'],
+ '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', '--labelled-only', '--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', '--members', '--members-file', '--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-open-pages', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--owner', '--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/error-registry.ts b/src/core/error-registry.ts
index 9ef6b6d5a2..ec11b1072e 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -775,6 +775,7 @@ export const CODES = {
setup_hosted_connection: { class: 'caller', summary: "This machine already reaches a hosted brain, so gbrain setup will not create a second, local brain.", why: 'A new local brain would split memory: sessions would read and write the empty local brain while useful memory stays on the hosted one.', docs: 'docs/guides/repair.md#setup-hosted-connection', fix: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows which brain the harness registration reaches.' } },
setup_owner_conflict: { class: 'caller', summary: "Another owner holds what gbrain setup would change: a live server owns this PGLite brain, or the harness configuration holds an entry setup did not write.", why: 'A PGLite brain has one writer, so a second server would fail on its lock; an entry setup did not record by hash is the user\'s or another install\'s and is never overwritten.', reasons: ['live_serve', 'unowned_entry', 'other_install', 'harness_lane'], docs: 'docs/guides/repair.md#setup-owner-conflict', fix: { argv: ['gbrain', 'setup', 'claude-code', '--dry-run', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the resolved target and which owner blocks it, without writing anything.' } },
setup_serves_several: { class: 'caller', summary: 'gbrain setup for one person was run on a brain that serves several people, and neither this harness\'s entry (--stdio-member) nor config mcp.stdio_member binds its stdio connection, so setup wrote nothing.', why: 'On a brain that serves several people an unbound connection reads every page no rule restricts, for whoever is asking; setup never writes one.', suggestion: 'Run gbrain setup <harness> --serves several --members <id,...> to label each person; add --stdio-member <member> only for a harness that one person alone uses.', fix: { argv: ['gbrain', 'access', 'serves', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: shows why the brain counts as several people, its members, its owner and the member the stdio server reads as.' } },
+ setup_history_choice_required: { class: 'caller', summary: 'gbrain setup --serves several would turn a brain that serves one person shared while it holds pages no rule restricts, and nobody chose what happens to them, so setup wrote nothing.', why: 'Each member key setup mints reads every page no rule or readable_by restricts, so the owner\'s journal, DMs, chat, mail and conversation archive would reach every member; only the admin can decide that.', suggestion: 'Run setup again with --labelled-only to keep that history private (each member reads only pages labelled for them) or with --open-history to let the members read it.', fix: { argv: ['gbrain', 'doctor', '--only', 'open_shared_pages', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: counts the pages members\' keys can read, by folder.' } },
setup_serves_unreadable: { class: 'caller', summary: 'gbrain setup could not read whether the existing brain serves several people, so it wrote nothing.', why: 'Setup writes an unbound connection only on a brain it knows serves one person; a brain it cannot read might serve several.', suggestion: 'Run gbrain access serves --json to see why the brain cannot be read, fix that, then run setup again.', fix: { argv: ['gbrain', 'access', 'serves', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: shows whom the brain serves, or the error that stops setup reading it.' } },
hook_session_cwd: { class: 'caller', summary: "A gbrain hook or stdio MCP entry (setup, the turn-rule lane, gbrain bootstrap's lanes) starts gbrain in the session's directory, or the hook launcher it names would not run.", why: 'Script-mode gbrain is a Bun script, and Bun runs the working directory\'s bunfig.toml preload and loads its .env before gbrain starts; harnesses run hooks and stdio MCP servers in the session directory, so a cloned repository could run code on every prompt or session.', reasons: ['session_cwd', 'missing', 'stale', 'foreign'], docs: 'docs/guides/repair.md#hook-session-cwd', fix: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Names the hook and the setup command that rewrites it through the launcher.' } },
turn_hook_not_loaded: { class: 'caller', summary: "The per-turn hook that puts \"check gbrain first\" next to every user turn is missing, untrusted, or does not load in the harness.", why: 'Agents use the brain when that rule reaches them on every turn; registering the MCP server or writing an instruction file alone leaves them answering without it.', reasons: ['missing', 'untrusted', 'hook_failed', 'no_rule', 'not_loaded'], docs: 'docs/guides/repair.md#turn-hook-not-loaded', fix: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows which harness has no working per-turn hook and the command that wires it.' } },
@@ -852,7 +853,7 @@ export const CODES = {
source_root_conflict: { class: 'caller', summary: "Multiple active sources alias this canonical skill root; resolve ownership before publishing." },
source_root_unreadable: { class: 'host_only', retryable: false, reasons: ['missing', 'not_directory', 'permission_denied', 'symlink_loop', 'unreadable'], summary: "The source's registered root on its owner host cannot be read as a directory (gone, unmounted, not a directory, no permission or a symlink loop), so `gbrain sources canonical` planned and wrote nothing.", why: "Converting a source reads its whole checkout; a root that cannot be listed would otherwise surface as a raw filesystem or Git error, or as a missing-checkout refusal whose fix creates an empty repository there.", suggestion: 'Restore or remount the directory on the brain host (or make it readable to the account that runs gbrain), compare it with the root gbrain sources writer status --source <source> --json names, then preview again.' },
source_writeback_required: { class: 'host_only', summary: "Canonical preparation requires a source-content correction; this profile never writes repository files." },
- sources_not_readable: { class: 'host_only', retryable: false, summary: "An unscoped search, query, recall or list_pages came back empty and was refused: every source this connection can read (the default source and federated sources) holds no page search returns (for recall and query, no active world fact either), while other sources on the brain hold such pages it cannot read (not federated, and no source grant).", why: "Answering would return an empty result that reads like a clean miss. The check is one yes/no about the whole brain, independent of the query: whether another source holds pages; it never says another source matches the question. Quarantined pages count on neither side, nor private pages when remote reads exclude them. The refusal names the host command that federates a source or grants this connection the sources it should read; it never names a hidden source and never widens access. A scope that holds pages but matched nothing, a granted token, an OAuth client, a bound connection and a read that names a source are never refused.", docs: 'docs/guides/multi-source-brains.md#an-unscoped-connection-whose-sources-hold-no-pages', suggestion: 'Ask the user which source these connections should read; the brain host runs `gbrain sources federate <source>`, or grants the token its sources with `gbrain auth rescope --token <name> --sources <ids>`.' },
+ sources_not_readable: { class: 'host_only', retryable: false, summary: "An unscoped search, query, recall or list_pages came back empty and was refused: every source this connection can read (the default source and federated sources) holds no page every reader of that source can read (pages kept to named readers or private do not count; for recall and query, no active world fact either), while other sources on the brain hold such pages it cannot read (not federated, and no source grant).", why: "Answering would return an empty result that reads like a clean miss. The check is one yes/no about the whole brain, independent of the query: whether another source holds pages; it never says another source matches the question. Quarantined pages count on neither side, nor private pages when remote reads exclude them. The refusal names the host command that federates a source or grants this connection the sources it should read; it never names a hidden source and never widens access. A scope that holds pages but matched nothing, a granted token, an OAuth client, a bound connection and a read that names a source are never refused.", docs: 'docs/guides/multi-source-brains.md#an-unscoped-connection-whose-sources-hold-no-pages', suggestion: 'Ask the user which source these connections should read; the brain host runs `gbrain sources federate <source>`, or grants the token its sources with `gbrain auth rescope --token <name> --sources <ids>`.' },
split_bad_ratio: { class: 'caller', summary: "Split bad ratio." },
split_unparseable: { class: 'caller', summary: "Split unparseable." },
stable_channel_unresolved: { class: 'unavailable', retired_in: 'TBD', reasons: ['unreadable', 'no_stable', 'no_release_tag'],
diff --git a/src/core/guests/sources.ts b/src/core/guests/sources.ts
index 326aed176c..6dce4a7291 100644
--- a/src/core/guests/sources.ts
+++ b/src/core/guests/sources.ts
@@ -6,6 +6,7 @@
* so owner reads that widen to federated sources include it.
*/
import type { BrainEngine } from '../engine.ts';
+import { opError, type OperationError } from '../ops/contract.ts';
import type { Principal } from '../persistence/model.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
import { addSource } from '../sources-ops.ts';
@@ -23,6 +24,23 @@ export function isGuestWriter(value: string): boolean {
return at > 0 && (PRINCIPAL_KINDS as readonly string[]).includes(value.slice(0, at)) && /^[\x21-\x7e]{1,200}$/.test(value.slice(at + 1));
}
+/**
+ * The oauth_client writers in `writers` that name no live registered OAuth client, refused as client_not_found with
+ * nothing written: a mistyped or deleted client id would sit on the list and let nobody write.
+ */
+export async function unregisteredClientWriters(engine: Pick<BrainEngine, 'executeRaw'>, writers: readonly string[]): Promise<OperationError | null> {
+ const clientId = (w: string) => w.startsWith('oauth_client:') ? w.slice('oauth_client:'.length) : null;
+ const ids = writers.map(clientId).filter((id): id is string => id !== null);
+ if (!ids.length) return null;
+ const live = new Set((await engine.executeRaw<{ client_id: string }>(
+ 'SELECT client_id FROM oauth_clients WHERE client_id = ANY($1::text[]) AND deleted_at IS NULL', [ids])).map(r => r.client_id));
+ const unknown = writers.filter(w => { const id = clientId(w); return id !== null && !live.has(id); });
+ if (!unknown.length) return null;
+ return opError('client_not_found', `No registered OAuth client matches writer ${unknown.join(', ')}; nothing was written.`,
+ 'List the clients with gbrain auth clients --json and name each writer as oauth_client:<client id> from that list (register the broker first with gbrain auth register-client).',
+ { fix: { argv: ['gbrain', 'auth', 'clients', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists the OAuth clients registered on this brain.' } });
+}
+
export interface GuestSource { source_id: string; writers: string[]; trust_ceiling: string }
export const readGuestSource = (engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<GuestSource | null> => lookupGuestSource(engine, sourceId);
diff --git a/src/core/harness/capabilities.ts b/src/core/harness/capabilities.ts
index 287cc25ad7..cbe7a277f7 100644
--- a/src/core/harness/capabilities.ts
+++ b/src/core/harness/capabilities.ts
@@ -283,7 +283,10 @@ export function grantBlockedNotice(d: GrantDiagnosis, opts: { refused: boolean }
const reachable = d.blockers.filter(b => b.blocker !== 'scope');
const scope = d.blockers.find(b => b.blocker === 'scope') as { missing_scopes: string[] } | undefined;
const parts: string[] = [];
- if (reachable.length && d.unreachable_count > 0) {
+ // GBRA-585: a snapshot whose left-out operations all existed when it was written is the owner's narrowing (a guest
+ // broker's --operations), so a call it can make carries no widen nudge; a refused call still says why.
+ const deliberate = d.grant_age.state === 'provenance_recorded' && d.grant_age.predates_count === 0 && reachable.every(b => b.blocker === 'operation_snapshot');
+ if (reachable.length && d.unreachable_count > 0 && (opts.refused || !deliberate)) {
const n = d.unreachable_count;
const age = 'statement' in d.grant_age ? ` ${d.grant_age.statement}` : '';
parts.push(`This connection's grant cannot call ${n} operation${n === 1 ? '' : 's'} its scopes allow, blocked by ${reachable.map(blockerPhrase).join(' and by ')} (counted per blocker; an operation can sit behind more than one).${age}`
diff --git a/src/core/harness/credentials.ts b/src/core/harness/credentials.ts
index 0af9c815b9..23ce2756b0 100644
--- a/src/core/harness/credentials.ts
+++ b/src/core/harness/credentials.ts
@@ -75,6 +75,11 @@ export function readPrivateText(path: string, maximumBytes = 8192): string {
} finally { closeSync(fd); }
}
+/** The file holds one bare bearer token (a member key setup minted), not a credential handoff. */
+export class PlainBearerKeyFile extends Error {
+ constructor() { super('The credential file holds a plain bearer key, not a credential handoff'); }
+}
+
export function readCredentials(path: string): HarnessCredentials {
assertNoSymlinks(resolve(path));
const fd = openSync(resolve(path), constants.O_RDONLY | constants.O_NOFOLLOW);
@@ -82,7 +87,13 @@ export function readCredentials(path: string): HarnessCredentials {
const stat = fstatSync(fd);
if (!stat.isFile() || stat.size > 65_536) throw new Error('Credential handoff must be a small regular file');
if (process.platform !== 'win32' && (stat.mode & 0o077) !== 0) throw new Error('Credential handoff must be private: chmod 600 the file');
- try { return validateCredentials(JSON.parse(readFileSync(fd, 'utf8'))); }
+ const raw = readFileSync(fd, 'utf8');
+ let parsed: unknown;
+ try { parsed = JSON.parse(raw); } catch {
+ if (/^\S+$/.test(raw.trim()) && validateToken(raw.trim()).ok) throw new PlainBearerKeyFile();
+ throw new Error('Invalid credential handoff; re-export it from the brain host');
+ }
+ try { return validateCredentials(parsed); }
catch { throw new Error('Invalid credential handoff; re-export it from the brain host'); }
} finally { closeSync(fd); }
}
diff --git a/src/core/ops/context.ts b/src/core/ops/context.ts
index 5ec1bdea54..2a539da749 100644
--- a/src/core/ops/context.ts
+++ b/src/core/ops/context.ts
@@ -68,10 +68,16 @@ export function withFix(fix: Action | undefined): { fix?: Action } {
* surface-correct prose plus the matching read.
*/
export function pageNotFoundError(
- ctx: Pick<OperationContext, 'remote' | 'transport'>,
+ ctx: Pick<OperationContext, 'remote' | 'transport' | 'auth'>,
slug: string,
opts: { includeDeleted: boolean; sourceIdParam?: string; elsewhereSource?: string },
): OperationError {
+ // GBRA-585: a member's credential misses pages kept to other members too, and it reads the same for both, so it is
+ // sent neither after a deletion nor to the host CLI.
+ if (ctx.remote !== false && ctx.auth?.member) {
+ return opError('page_not_found', `Page not found: ${slug}`,
+ 'This connection reads no page with this slug: it may not exist, or it may not be readable by this connection, since a page can be kept to other members. Do not create it to find out; ask the user whether the page exists and who can read it.');
+ }
const retry = opts.includeDeleted ? `Check the slug or use ${paramUse(ctx, 'fuzzy')}` : `Page may be soft-deleted; pass ${paramUse(ctx, 'include_deleted')} to verify`;
const where = opts.elsewhereSource;
const explicit = opts.sourceIdParam !== ALL_SOURCES ? opts.sourceIdParam : undefined;
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index 9307722951..41681525ed 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -35,6 +35,7 @@ import { resolveExcludePrivatePages, isPrivatePage, findPrivateOnlySlugs, isPriv
import { heldRowsForCaller } from '../eligibility/fence-overlay.ts';
import { unquoteAnyTranscriptText } from '../search/transcript-quote.ts';
import { withIgnoredPrivacyLabelNotice } from '../search/ignored-privacy-labels.ts';
+import { withImplicitPlacement } from '../access/implicit-placement.ts';
import { LIST_PAGES_DESCRIPTION, CAPTURE_DESCRIPTION } from '../operations-descriptions.ts';
import { listPagesPagination, listingTruncatedNotice, unusedTypeNotice } from './list-pages-pagination.ts';
import { OperationError, opError, type Operation, type OperationContext } from './contract.ts';
@@ -380,7 +381,7 @@ const put_page: Operation = {
}
if (ctx.remote !== false && typeof p.slug === 'string') await assertLargePageAdmission(ctx.engine, p.slug, sourceId, p);
(await import('../persistence/page-visibility.ts')).assertSubmittedReaders(ctx.remote, p.slug, p.content);
- return submitPageMutation(ctx, { operation: 'put_page', params: p }).then(funnelPassThrough('save')).catch(error => rethrowNamingRevisionSource(ctx, sourceId, p, error)).then(result => withIgnoredPrivacyLabelNotice(ctx, sourceId, p, result));
+ return submitPageMutation(ctx, { operation: 'put_page', params: p }).then(funnelPassThrough('save')).catch(error => rethrowNamingRevisionSource(ctx, sourceId, p, error)).then(result => withIgnoredPrivacyLabelNotice(ctx, sourceId, p, result)).then(result => withImplicitPlacement(ctx, sourceId, p, result));
},
cliHints: { name: 'put', positional: ['slug'], stdin: 'content' },
};
diff --git a/src/core/persistence/local-client.ts b/src/core/persistence/local-client.ts
index 6f703c5185..17b78df8e6 100644
--- a/src/core/persistence/local-client.ts
+++ b/src/core/persistence/local-client.ts
@@ -166,7 +166,9 @@ export async function maybeDelegateLocalOperation(
// An op that owns `source` (claim or timeline provenance) gets it on the wire, never as routing scope.
const sourceInParams = options.source === undefined && !(await operationOwnsSource(operation));
- const explicit = options.source ?? (sourceInParams && typeof params.source === 'string' ? params.source : null);
+ // GBRA-585: a write's source_id is its target, so the owner builds the write's grant on that source, as the direct path does.
+ const writeTarget = isPersistenceIpcMutation(operation) && typeof params.source_id === 'string' ? params.source_id : null;
+ const explicit = options.source ?? (sourceInParams && typeof params.source === 'string' ? params.source : writeTarget);
const source = resolveSourceIdEngineFree(explicit, cwd);
const wireParams = { ...params };
// These belong to the CLI context/renderer, not the operation schema.
diff --git a/src/core/persistence/provider.ts b/src/core/persistence/provider.ts
index 12d586720c..5cdbc90494 100644
--- a/src/core/persistence/provider.ts
+++ b/src/core/persistence/provider.ts
@@ -88,6 +88,7 @@ export async function createPersistenceIpcProvider(engine: BrainEngine, config:
config, remote: verified.remote, transport: verified.remote || localSkillAdministration || localCliLocalOnly ? 'stdio' : undefined, sourceId, auth,
...(writeWaitMs !== undefined ? { writeWaitMs } : {}),
...(unrestricted ? {} : { localFederatedSourceIds: verified.grant.sourceIds }),
+ ...(request.routing.source === null && !verified.remote ? { localSourceImplicit: true } : {}),
});
const body = JSON.parse(result.content[0].text) as Record<string, unknown>;
// GBRA-498: the trusted local CLI's --room is marked here, where the brain is; any other lane's answer goes back
diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.ts
index 9ec8633ba6..da08a44cd7 100644
--- a/src/core/persistence/verb-errors.ts
+++ b/src/core/persistence/verb-errors.ts
@@ -314,6 +314,14 @@ export async function runMemoryWrite<T>(run: () => Promise<T>): Promise<T> {
Object.assign(guest, { canonical: error.code, docs: error.docs });
throw guest;
}
+ // GBRA-585: an entity page this connection cannot read or write keeps the frozen code; page_not_found is the canonical
+ // code (a caller refusal, not an outage, so no doctor step), and the next step is the save this connection can make.
+ if (error.code === 'page_not_found') {
+ const hidden = verbError('unavailable', error.message, 'The entity page is not readable or writable by this connection: it may not exist for it, or another member may keep that slug. '
+ + 'Nothing was saved. Do not retry with share: true or as a create; remember the fact without share to keep it on your own member page, or ask the user who can read that page.');
+ Object.assign(hidden, { canonical: 'page_not_found', writeError: 'page_not_found' });
+ throw hidden;
+ }
const code = ['permission_denied','scope_denied','source_changed','writer_registration_required'].includes(error.code)
? 'scope_denied' : ['revision_required','revision_conflict','idempotency_conflict','invalid_params','page_identity_changed'].includes(error.code)
? 'invalid_params' : 'unavailable';
diff --git a/src/core/sources-not-readable.ts b/src/core/sources-not-readable.ts
index 77056c0131..71e00f5f05 100644
--- a/src/core/sources-not-readable.ts
+++ b/src/core/sources-not-readable.ts
@@ -2,8 +2,9 @@
* GBRA-156: `sources_not_readable`, the refusal of an unscoped remote read
* that came back empty because its readable sources hold no page it may read
* (and, for recall and query, no active world fact) while other sources hold
- * such pages. Quarantined pages count on neither side, nor private pages when
- * remote reads exclude them. The check is one query-independent yes/no about
+ * such pages. Quarantined pages count on neither side, nor private pages or
+ * pages kept to named readers when remote reads exclude them, so the message
+ * says which pages it counted. The check is one query-independent yes/no about
* the brain; it never says another source matches the question.
*
* A connection with no source grant (a legacy token minted without --sources,
@@ -61,7 +62,7 @@ export async function assertUnscopedReadReachesPages(op: string, params: Record<
}
if (!refuse) return;
throw opError('sources_not_readable',
- `This connection reads only the default source and federated sources, and none of them holds a page, so this ${op} could only come back empty.`,
+ `This connection reads only the default source and federated sources, none of them holds a page every reader of its source can read (pages kept to named readers, or private, do not count), and other sources hold pages, so this ${op} came back empty.`,
'Other sources on this brain hold pages, but they are not federated and this connection has no source grant. Ask the user which source these connections should read; '
+ 'the brain host\'s operator federates it (command in fix) or grants this connection its sources (`gbrain auth rescope --token <name> --sources <ids>`).',
{
diff --git a/src/core/transcripts/archive-default.ts b/src/core/transcripts/archive-default.ts
index 664bd45732..9b91d2ab86 100644
--- a/src/core/transcripts/archive-default.ts
+++ b/src/core/transcripts/archive-default.ts
@@ -9,7 +9,8 @@
import type { BrainEngine } from '../engine.ts';
import { isThinClient, loadConfigFileOnly, type GBrainConfig } from '../config.ts';
-import { classifyBrainAudience, type BrainAudience } from '../facts/writeback-audience.ts';
+import { classifyBrainAudience, SHARED_CLIENT_THRESHOLD, type BrainAudience } from '../facts/writeback-audience.ts';
+import { SERVES_DERIVED_KEY, SERVES_KEY, servesPolicyFrom } from '../search/private-visibility.ts';
export const ARCHIVE_ENABLED_KEY = 'transcripts.archive.enabled';
@@ -20,6 +21,8 @@ export interface ArchiveEnablement {
audience: BrainAudience | null;
/** A shared or unknown brain with the switch unset: offered with gbrain transcripts archive on, never turned on. */
offered: boolean;
+ /** GBRA-585: on by the personal default while the brain serves several people, so it can turn off by itself. */
+ serves_several?: boolean;
reason: string;
}
@@ -45,7 +48,16 @@ export async function resolveArchiveEnabled(
const value = String(raw ?? '').trim().toLowerCase();
if (ON.has(value)) return { enabled: true, source: 'explicit', audience: null, offered: false, reason: ARCHIVE_ENABLED_KEY + ' is on' };
if (OFF.has(value)) return { enabled: false, source: 'explicit', audience: null, offered: false, reason: ARCHIVE_ENABLED_KEY + ' is off' };
- const { audience } = await classifyBrainAudience(engine as BrainEngine, config);
- if (audience === 'personal') return { enabled: true, source: 'default', audience, offered: false, reason: 'on by default on a personal brain' };
+ const { audience, reasons } = await classifyBrainAudience(engine as BrainEngine, config);
+ if (audience === 'personal') {
+ // GBRA-585: a brain that serves several people with brain.audience unset reads personal until its clients say otherwise; say so, so setup, status and doctor agree on why it is on and when it turns off.
+ const several = await Promise.all([engine.getConfig(SERVES_KEY), engine.getConfig(SERVES_DERIVED_KEY)])
+ .then(([explicit, derived]) => servesPolicyFrom({ [SERVES_KEY]: explicit ?? undefined, [SERVES_DERIVED_KEY]: derived ?? undefined }).several, () => false);
+ if (several && reasons[0]?.startsWith('declared:')) return { enabled: true, source: 'default', audience, offered: false, serves_several: true,
+ reason: 'on: this brain serves several people, but brain.audience is set to personal, so it stays on however many people\'s clients connect; turn it off with gbrain config set brain.audience shared (gbrain transcripts archive on|off decides it for good)' };
+ if (several) return { enabled: true, source: 'default', audience, offered: false, serves_several: true,
+ reason: `on for now: this brain serves several people, but brain.audience is unset and fewer than ${SHARED_CLIENT_THRESHOLD} people's clients were active in 30 days, so it reads as personal; it turns off (offered only) once ${SHARED_CLIENT_THRESHOLD} are, or now with gbrain config set brain.audience shared (gbrain transcripts archive on|off decides it for good)` };
+ return { enabled: true, source: 'default', audience, offered: false, reason: 'on by default on a personal brain' };
+ }
return { enabled: false, source: 'default', audience, offered: true, reason: 'off by default on a ' + audience + ' brain; offered with gbrain transcripts archive on' };
}
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index efc957c357..c01dc04940 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -245,6 +245,8 @@ export interface DispatchOpts {
* caller params. See OperationContext.localFederatedSourceIds.
*/
localFederatedSourceIds?: string[];
+ /** GBRA-585: the trusted local CLI named no source (OperationContext.localSourceImplicit); ignored unless remote is false. */
+ localSourceImplicit?: boolean;
/**
* #5081: explicit-read admission for a stdio connection bound by
* GBRAIN_SOURCE or a .gbrain-source pin. Stdio transport only; see
@@ -979,6 +981,7 @@ export function buildOperationContext(
sourceId: opts.sourceId ?? 'default',
...(sessionId ? { sessionId } : {}),
...(opts.localFederatedSourceIds ? { localFederatedSourceIds: opts.localFederatedSourceIds } : {}),
+ ...(opts.localSourceImplicit && opts.remote === false ? { localSourceImplicit: true } : {}),
...(opts.explicitReadBinding ? { explicitReadBinding: opts.explicitReadBinding } : {}),
...(opts.surfaceCeiling ? { surfaceCeiling: opts.surfaceCeiling } : {}),
...(opts.stdioSurface ? { stdioSurface: opts.stdioSurface } : {}),
diff --git a/test/access-rule-preview-expect-gbra585.test.ts b/test/access-rule-preview-expect-gbra585.test.ts
new file mode 100644
index 0000000000..9ce05239ba
--- /dev/null
+++ b/test/access-rule-preview-expect-gbra585.test.ts
@@ -0,0 +1,41 @@
+/**
+ * GBRA-585: the folder-rule preview asks for --yes --expect <revision>, so the command it prints carries both.
+ *
+ * 1. Protects: the human preview of gbrain access rule add prints a rerun command that ends in --yes --expect <n>,
+ * with the revision the preview asked for, and running that exact command applies the rule.
+ * 2. Fails when: the printed command drops --expect (the walk's "To approve, add --yes --expect 0 (gbrain access rule
+ * add … --yes)"), or names another revision.
+ * 3. Real seams: the gbrain access rule CLI module on a repo-less PGLite brain.
+ */
+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runAccessRules } from '../src/commands/access-rules.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ for (const id of ['alice-example', 'bob-example']) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1) ON CONFLICT DO NOTHING', [id]);
+});
+afterAll(async () => { await engine.disconnect(); });
+
+async function printed(args: string[]): Promise<string> {
+ const lines: string[] = [];
+ const spy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { lines.push(a.map(String).join(' ')); });
+ try { await runAccessRules(engine, args[0]!, args.slice(1), false); } finally { spy.mockRestore(); }
+ return lines.join('\n');
+}
+
+describe('access rule preview (GBRA-585)', () => {
+ test('the printed approve command carries the --expect the preview asks for, and running it applies', async () => {
+ const preview = await printed(['rule', 'add', '--prefix', 'team/', '--readers', 'alice-example,bob-example']);
+ const line = preview.split('\n').find(l => l.startsWith('Nothing written. To approve'))!;
+ const expectN = /add --yes --expect (\d+)/.exec(line)?.[1];
+ expect(expectN).toBe('0');
+ const command = /\((gbrain access rule .*)\)\.$/.exec(line)?.[1];
+ expect(command).toBe(`gbrain access rule add --prefix team/ --readers alice-example,bob-example --yes --expect ${expectN}`);
+ const applied = await printed(command!.split(' ').slice(2));
+ expect(applied).toContain('applied');
+ });
+});
diff --git a/test/auth-create-member-scopes.test.ts b/test/auth-create-member-scopes.test.ts
new file mode 100644
index 0000000000..283f7d96d4
--- /dev/null
+++ b/test/auth-create-member-scopes.test.ts
@@ -0,0 +1,125 @@
+/**
+ * GBRA-585 E: `gbrain auth create <name> --member <id>` without --scopes mints read and write only.
+ *
+ * 1. Protects: the documented way to give a person a key (access-designations.md, ADMIN.md) no longer mints an admin
+ * key; an explicit --scopes still wins (admin included), and a token without --member keeps today's grant.
+ * 2. Fails when: a --member token without --scopes can call an admin operation (get_stats), cannot search or write, or
+ * --scopes / the no-member default change.
+ * 3. Existing coverage: auth-create-args.test.ts (argument parsing), the scope checks of each operation.
+ * 4. Real seams: `bun src/cli.ts auth create` spawned against PGLite and Postgres, the key verified by the
+ * serve --http verifier, held to the serve --http scope gate (operationScopesAllowed) and dispatched remote=true.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { AuthInfo } from '../src/core/ops/contract.ts';
+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { openBrainFile } from './helpers/setup-serves-box.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { operationScopesAllowed } from '../src/core/scope.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { runCli } from './helpers/cli-spawn.ts';
+
+const roots: string[] = [];
+afterAll(() => { for (const r of roots.splice(0)) rmSync(r, { recursive: true, force: true }); });
+
+interface Brain { env: Record<string, string | undefined>; engine: () => Promise<BrainEngine>; close: () => Promise<void> }
+
+async function brain(kind: string): Promise<Brain> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-auth-member-'));
+ roots.push(home);
+ const base = { HOME: home, GBRAIN_HOME: home, GBRAIN_SOURCE: undefined };
+ if (kind === 'postgres') {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ return { env: { ...base, GBRAIN_DATABASE_URL: pg.databaseUrl, DATABASE_URL: pg.databaseUrl }, engine: async () => pg.engine, close: pg.close };
+ }
+ const init = await runCli(['init', '--pglite', '--no-embedding', '--json'], { env: base, timeoutMs: 120_000 });
+ expect(init.exitCode).toBe(0);
+ let engine: PGLiteEngine | null = null;
+ return {
+ env: base,
+ engine: async () => {
+ engine = await openBrainFile(home);
+ return engine;
+ },
+ close: async () => { await engine?.disconnect(); },
+ };
+}
+
+const tokenOf = (stdout: string) => stdout.match(/gbrain_[0-9a-f]{16,}/)![0];
+
+async function call(engine: BrainEngine, token: string, tool: string, params: Record<string, unknown>): Promise<{ isError: boolean; text: string }> {
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const auth = await provider.verifyAccessToken(token) as unknown as AuthInfo;
+ if (!operationScopesAllowed(auth.scopes, operationsByName[tool]!)) return { isError: true, text: 'insufficient_scope (the serve --http scope gate)' };
+ const out = await dispatchToolCall(engine, tool, params, { remote: true, transport: 'http', auth, sourceId: auth.sourceId ?? 'default', takesHoldersAllowList: auth.takesHoldersAllowList ?? ['world'] });
+ return { isError: out.isError === true, text: out.content.map(c => c.text).join('\n') };
+}
+
+for (const kind of testBackends()) {
+ describe(`E: auth create --member mints read and write (${kind})`, () => {
+ test('--member without --scopes: read,write; get_stats is refused while search and put_page work; --scopes and no --member are unchanged', async () => {
+ const b = await brain(kind);
+ try {
+ const cli = (args: string[]) => runCli(args, { env: b.env, timeoutMs: 120_000 });
+ expect((await cli(['access', 'member', 'add', 'dave-example'])).exitCode).toBe(0);
+ const laptop = await cli(['auth', 'create', 'dave-laptop', '--member', 'dave-example']);
+ expect(laptop.exitCode).toBe(0);
+ expect(laptop.stdout).toContain('scopes=["read","write"]');
+ expect(laptop.stdout).toContain('--scopes read,write,admin');
+ const admin = await cli(['auth', 'create', 'dave-admin', '--member', 'dave-example', '--scopes', 'read,write,admin']);
+ expect(admin.exitCode).toBe(0);
+ const bot = await cli(['auth', 'create', 'house-bot']);
+ expect(bot.exitCode).toBe(0);
+ expect(bot.stdout).toContain('full access (grandfathered');
+ const engine = await b.engine();
+ const rows = await engine.executeRaw<{ name: string; scopes: string[] | null }>("SELECT name, scopes FROM access_tokens WHERE revoked_at IS NULL ORDER BY name");
+ expect(rows.map(r => [r.name, r.scopes])).toEqual([['dave-admin', ['read', 'write', 'admin']], ['dave-laptop', ['read', 'write']], ['house-bot', null]]);
+ const key = tokenOf(laptop.stdout);
+ const stats = await call(engine, key, 'get_stats', {});
+ expect(stats.isError).toBe(true);
+ expect(stats.text).toMatch(/scope/i);
+ const put = await call(engine, key, 'put_page', { slug: 'notes/dave-plan', content: '---\ntitle: Dave plan\n---\n# Dave plan\n\nHarbor ledger notes davecanary.\n' });
+ expect(put.isError === false || put.text.includes('"code": "write_pending"')).toBe(true);
+ expect(put.text).not.toMatch(/insufficient_scope|permission_denied/);
+ const found = await call(engine, key, 'search', { query: 'harbor ledger notes', match: 'keyword', limit: 5 });
+ expect(found.isError).toBe(false);
+ expect((await call(engine, tokenOf(admin.stdout), 'get_stats', {})).isError).toBe(false);
+ } finally {
+ await b.close();
+ }
+ }, 300_000);
+
+ test("an owner's key made with --member reads the same pages as one made with the old full-access default", async () => {
+ const b = await brain(kind);
+ try {
+ const cli = (args: string[]) => runCli(args, { env: b.env, timeoutMs: 120_000 });
+ expect((await cli(['access', 'member', 'add', 'owner-example'])).exitCode).toBe(0);
+ expect((await cli(['access', 'owner', 'set', 'owner-example'])).exitCode).toBe(0);
+ for (const [slug, canary] of [['notes/world-topic', 'worldcanary'], ['journal/owner-day', 'journalcanary']]) {
+ expect((await cli(['put', slug, '--content', `---\ntitle: ${slug}\n---\n# ${slug}\n\nHarbor ledger notes ${canary}.\n`])).exitCode).toBe(0);
+ }
+ const before = await cli(['auth', 'create', 'owner-old', '--member', 'owner-example', '--scopes', 'read,write,admin']);
+ const after = await cli(['auth', 'create', 'owner-new', '--member', 'owner-example']);
+ expect(before.exitCode).toBe(0);
+ expect(after.exitCode).toBe(0);
+ const engine = await b.engine();
+ const reads = async (token: string) => {
+ const r = await call(engine, token, 'search', { query: 'harbor ledger notes', match: 'keyword', limit: 20 });
+ expect(r.isError).toBe(false);
+ return ['worldcanary', 'journalcanary'].filter(c => r.text.includes(c)).sort();
+ };
+ expect(await reads(tokenOf(before.stdout))).toEqual(['journalcanary', 'worldcanary']);
+ expect(await reads(tokenOf(after.stdout))).toEqual(await reads(tokenOf(before.stdout)));
+ } finally {
+ await b.close();
+ }
+ }, 300_000);
+ });
+}
diff --git a/test/backup-cli.serial.test.ts b/test/backup-cli.serial.test.ts
index 269b50131e..96b0bcd24b 100644
--- a/test/backup-cli.serial.test.ts
+++ b/test/backup-cli.serial.test.ts
@@ -472,9 +472,12 @@ describe('runBackupCli — nag impression', () => {
// ── create/restore failure diagnostic (#5312) ────────────────────────────────
+const REAL_CREATE = Symbol('real createPgliteBackup');
+
describe('runBackupCli create — failure diagnostic for message-less errors (#5312)', () => {
+ /** `thrown === REAL_CREATE` runs the real createPgliteBackup against the test home's config. */
async function failCreate(thrown: unknown, json: boolean) {
- const spy = spyOn(snapshot, 'createPgliteBackup').mockImplementation(async () => { throw thrown; });
+ const spy = thrown === REAL_CREATE ? null : spyOn(snapshot, 'createPgliteBackup').mockImplementation(async () => { throw thrown; });
const fd1: string[] = [];
const realWriteSync = fs.writeSync;
const fdSpy = spyOn(fs, 'writeSync').mockImplementation(((fd: number, buf: Buffer, off = 0, len?: number) => {
@@ -493,7 +496,7 @@ describe('runBackupCli create — failure diagnostic for message-less errors (#5
} finally {
(process.stderr as { write: unknown }).write = origStderr;
fdSpy.mockRestore();
- spy.mockRestore();
+ spy?.mockRestore();
}
}
@@ -548,6 +551,30 @@ describe('runBackupCli create — failure diagnostic for message-less errors (#5
} finally { rmSync(dir, { recursive: true, force: true }); }
});
+ test('GBRA-585: on a Postgres brain the refusal names a pg_dump/pg_restore database dump, not doctor', async () => {
+ fs.mkdirSync(home(), { recursive: true });
+ fs.writeFileSync(join(home(), 'config.json'), JSON.stringify({ engine: 'postgres', database_url: ['postgresql://alice-example', '[email protected]/brain'].join(':') }));
+ for (const json of [true, false]) {
+ const r = await failCreate(REAL_CREATE, json);
+ expect(r.exitCode).toBe(1);
+ const out = `${r.stdout}${r.log}${r.stderr}`;
+ expect(out).not.toContain('hunter2-secret');
+ if (json) {
+ const doc = JSON.parse(r.stdout.trim());
+ expect(doc).toMatchObject({ ok: false, reason: 'pglite_required', code: 'storage_error' });
+ expect(doc.message).toContain('pg_dump');
+ expect(doc.message).toContain('pg_restore');
+ expect(doc.fix).toMatchObject({ next: 'tell_user_to_run', actor: 'host_admin' });
+ expect(doc.fix.argv[0]).toBe('pg_dump');
+ expect(doc.fix.verify).toBeUndefined();
+ expect(doc.message).toContain('`pg_restore --list <DUMP_FILE>` reads it back');
+ } else {
+ expect(r.stderr).toContain('pg_dump');
+ expect(r.stderr).not.toContain('gbrain doctor --json');
+ }
+ }
+ });
+
test('an error message keeps its text with URL credentials redacted; retryable is preserved', async () => {
const err = Object.assign(new Error('dump failed for postgres://alice-example:[email protected]/brain'), { code: 'writers_active', retryable: true });
const r = await failCreate(err, true);
diff --git a/test/connect-member-key-gbra585.test.ts b/test/connect-member-key-gbra585.test.ts
new file mode 100644
index 0000000000..d7d20b9b43
--- /dev/null
+++ b/test/connect-member-key-gbra585.test.ts
@@ -0,0 +1,65 @@
+/**
+ * GBRA-585 item 12: a member key that setup minted (member-keys/<member>.key, a plain bearer token) reaches a harness.
+ *
+ * 1. Protects: `connect --credentials-file` given a plain bearer key file says it is a plain key, not a handoff, and
+ * prints the --agent form that installs it; `connect --token` with `--harness` names the --agent form instead of
+ * "Unknown setup argument"; the paste block calls the token a long-lived secret without claiming it is full-access.
+ * 2. Fails when: those refusals go back to "Invalid credential handoff" or "Unknown setup argument", the key value is
+ * echoed into the output, or the block labels a read/write member key full-access.
+ * 3. Real seams: the connect command's harness lane (runConnect) with a real 0600 key file; no network call is made.
+ */
+import { afterAll, describe, expect, spyOn, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runConnect, buildConnectBlock } from '../src/commands/connect.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
+
+const dir = mkdtempSync(join(tmpdir(), 'gbrain-member-key-'));
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+const KEY = 'gbrain_' + 'a1b2c3d4'.repeat(8);
+const keyFile = join(dir, 'alice-example.key');
+writeFileSync(keyFile, KEY + '\n', { mode: 0o600 });
+
+async function connect(args: string[]): Promise<Record<string, any>> {
+ const lines: string[] = [];
+ const log = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { lines.push(a.map(String).join(' ')); });
+ const err = spyOn(console, 'error').mockImplementation(() => {});
+ const priorExitCode = process.exitCode;
+ let exit: number;
+ try { await runConnect(args); } finally {
+ exit = currentExitCode();
+ _resetCliExitVerdictForTests();
+ process.exitCode = priorExitCode ?? 0;
+ log.mockRestore(); err.mockRestore();
+ }
+ expect(exit).toBe(1);
+ const text = lines.join('\n');
+ expect(text).not.toContain(KEY);
+ return JSON.parse(text);
+}
+
+describe('a setup-minted member key into a harness (GBRA-585)', () => {
+ test('--credentials-file with a plain bearer key says so and prints the --agent form', async () => {
+ const out = await connect(['http://127.0.0.1:3131/mcp', '--harness', 'claude-code', '--credentials-file', keyFile, '--install']);
+ expect(out.status).toBe('error');
+ expect(out.message).not.toContain('Invalid credential handoff');
+ expect(out.message).toContain('plain bearer key');
+ expect(out.message).toContain(`GBRAIN_REMOTE_TOKEN="$(cat ${keyFile})" gbrain connect http://127.0.0.1:3131/mcp --agent claude-code --install`);
+ });
+
+ test('--token with --harness names the --agent form instead of an unknown argument', async () => {
+ const out = await connect(['http://127.0.0.1:3131/mcp', '--token', KEY, '--harness', 'codex', '--install']);
+ expect(out.status).toBe('error');
+ expect(out.message).not.toContain('Unknown setup argument');
+ expect(out.message).toContain('gbrain connect http://127.0.0.1:3131/mcp --agent codex --token <key> --install');
+ });
+
+ test('the paste block calls the bearer token a long-lived secret, not full-access', () => {
+ for (const agent of ['claude-code', 'codex', 'opencode'] as const) {
+ const block = buildConnectBlock({ agent, name: 'gbrain', url: 'https://brain.example.com/mcp', token: 'TOK' });
+ expect(block).not.toContain('full-access');
+ expect(block).toContain('long-lived secret');
+ }
+ });
+});
diff --git a/test/connect.test.ts b/test/connect.test.ts
index 48713e2a7d..0c6b0356f0 100644
--- a/test/connect.test.ts
+++ b/test/connect.test.ts
@@ -237,7 +237,7 @@ describe('buildConnectBlock', () => {
expect(block).toContain("claude mcp add gbrain -t http https://h/mcp -H 'Authorization: Bearer TOK'");
expect(block).toContain(LEARN_INSTRUCTION);
expect(block).not.toContain(PLACEHOLDER_TOKEN);
- expect(block).toMatch(/long-lived, full-access secret/);
+ expect(block).toMatch(/long-lived secret that carries whatever its grant allows/);
});
test('claude-code without a token emits a placeholder + replace hint', () => {
const block = buildConnectBlock({ agent: 'claude-code', name: 'gbrain', url: 'https://h/mcp', token: null });
diff --git a/test/doctor-backup-coverage.serial.test.ts b/test/doctor-backup-coverage.serial.test.ts
index 61cd24ab82..4697daae80 100644
--- a/test/doctor-backup-coverage.serial.test.ts
+++ b/test/doctor-backup-coverage.serial.test.ts
@@ -400,3 +400,66 @@ describe('checkBackupCoverage — localOnly catch branch', () => {
expect(check.message).not.toBe('backup coverage unreadable');
});
});
+
+// ── GBRA-585 item 7: the young-brain count and the full-backup fix per engine ─
+
+/** Engine stub answering the maturity count before the sources/pages listings (its SQL names both tables). */
+function makeCountingEngine(kind: 'pglite' | 'postgres', sources: Array<{ id: string; local_path: string }>, pages: number, facts: number): BrainEngine {
+ const listing = makeEngine(sources, pages);
+ return {
+ kind,
+ executeRaw: async (sql: string) => {
+ if (/AS pages/i.test(sql)) return [{ pages, facts, since: new Date(Date.now() - 60_000).toISOString() }];
+ return listing.executeRaw(sql);
+ },
+ } as unknown as BrainEngine;
+}
+
+/** A verdict cached when the brain was empty (init), with remote evidence fresh enough to be reused. */
+function cacheFromEmptyBrain(assetId: string): BackupStatus {
+ const now = new Date().toISOString();
+ return {
+ ...makeWarnCache(assetId),
+ checked_at: now,
+ remote_check_at: now,
+ totals: { assets: 1, no_remote: 0, unpushed: 0, failing: 0, recoverable_repos: 0, pages_at_risk: 0 },
+ assets: [{ kind: 'source_repo', id: assetId, state: 'unknown', detail: 'not_a_git_repo', fix_argv: null }],
+ maturity: { items: 0, since: new Date(Date.now() - 60_000).toISOString() },
+ };
+}
+
+describe('checkBackupCoverage — GBRA-585 item 7', () => {
+ test('a cached verdict from the empty brain reports the current page+fact count, not 0', async () => {
+ const plain = join(tmp, 'default');
+ mkdirSync(plain, { recursive: true });
+ saveBackupStatus(cacheFromEmptyBrain('default'));
+
+ const young = await checkBackupCoverage(makeCountingEngine('pglite', [{ id: 'default', local_path: plain }], 20, 3), { localOnly: true });
+ expect(young.message).toContain('the brain holds 23 page(s)+fact(s)');
+
+ const full = await checkBackupCoverage(makeCountingEngine('pglite', [{ id: 'default', local_path: plain }], 27, 7), { localOnly: true });
+ expect(full.status).toBe('warn');
+ expect(full.message).not.toContain('holds 0 page(s)');
+ });
+
+ test('PGLite: a content directory with no git repo is fixed by gbrain backup create, never gbrain export', async () => {
+ const plain = join(tmp, 'default');
+ mkdirSync(plain, { recursive: true });
+ const check = await checkBackupCoverage(makeCountingEngine('pglite', [{ id: 'default', local_path: plain }], 27, 7), { localOnly: true });
+ expect(check.status).toBe('warn');
+ expect(check.fix?.argv).toEqual(['gbrain', 'backup', 'create', '--output', '<BACKUP_FILE>']);
+ });
+
+ test('Postgres: the same asset is fixed by a pg_dump of the brain database, never gbrain export', async () => {
+ const plain = join(tmp, 'default');
+ mkdirSync(plain, { recursive: true });
+ const check = await checkBackupCoverage(makeCountingEngine('postgres', [{ id: 'default', local_path: plain }], 27, 7), { localOnly: true });
+ expect(check.status).toBe('warn');
+ expect(check.fix?.argv?.[0]).toBe('pg_dump');
+ expect(check.fix?.actor).toBe('host_admin');
+ expect(check.fix?.user_message).toContain('pg_restore');
+ expect(check.fix?.user_message).toContain('`gbrain export` is not a backup');
+ expect(check.fix?.argv).not.toContain('export');
+ });
+});
+
diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.json
index 6b33a8eb3a..68d4165e73 100644
--- a/test/fixtures/goldens/doctor/content-pglite-json.json
+++ b/test/fixtures/goldens/doctor/content-pglite-json.json
@@ -2670,6 +2670,7 @@
"behind": [],
"docs": "docs/guides/conversation-archive.md#doctor",
"enabled": true,
+ "enabled_by": "default",
"harnesses": [
{
"harness": "claude-code",
@@ -2715,6 +2716,7 @@
}
],
"held": [],
+ "reason": "on by default on a personal brain",
"source_id": "conversations",
"stale_days": 2
},
@@ -2974,21 +2976,20 @@
"actor": "agent",
"argv": [
"gbrain",
- "export",
- "--source",
- "default",
- "--dir",
- "<BACKUP_DIR>/default",
+ "backup",
+ "create",
+ "--output",
+ "<BACKUP_FILE>",
"--brain",
"host"
],
- "command": "gbrain export --source default --dir '<BACKUP_DIR>/default' --brain host",
+ "command": "gbrain backup create --output '<BACKUP_FILE>' --brain host",
"consent": [],
- "docs": "https://github.com/garrytan/gbrain/blob/master/docs/operations/backup-check.md",
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/in-agent-setup.md#6-back-up-the-complete-local-database",
"inputs": [
{
- "how": "Ask the user where backups should live (a directory outside the brain, ideally synced or on another disk).",
- "name": "BACKUP_DIR"
+ "how": "Ask the user for an absolute path to a new archive file, in an existing private directory outside the brain (ideally another disk).",
+ "name": "BACKUP_FILE"
}
],
"next": "run",
@@ -3004,7 +3005,7 @@
"host"
]
},
- "why": "Writes a Markdown copy of 'default' (pages and facts) to a directory outside the brain so it survives losing the database."
+ "why": "Writes a full snapshot of this PGLite brain (every source, page, fact, member, token and rule) to one archive outside the brain."
},
"message": "Not urgent yet: the brain holds 5 page(s)+fact(s) and is under 7 days old (backup coaching starts at 25 items or 7 days). 2 knowledge asset(s) lack verified recovery: default (not_a_git_repo), notes (no git remote). A source repo with a pushed git remote restores its Markdown files only, never DB-only pages, facts, config or credentials. Run `gbrain backup status` for each asset's fix command.",
"name": "backup_coverage",
diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
index 1d8b501eef..c3b3179c6c 100644
--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
@@ -2852,6 +2852,7 @@
"behind": [],
"docs": "docs/guides/conversation-archive.md#doctor",
"enabled": true,
+ "enabled_by": "default",
"harnesses": [
{
"harness": "claude-code",
@@ -2897,6 +2898,7 @@
}
],
"held": [],
+ "reason": "on by default on a personal brain",
"source_id": "conversations",
"stale_days": 2
},
@@ -3156,21 +3158,20 @@
"actor": "agent",
"argv": [
"gbrain",
- "export",
- "--source",
- "default",
- "--dir",
- "<BACKUP_DIR>/default",
+ "backup",
+ "create",
+ "--output",
+ "<BACKUP_FILE>",
"--brain",
"host"
],
- "command": "gbrain export --source default --dir '<BACKUP_DIR>/default' --brain host",
+ "command": "gbrain backup create --output '<BACKUP_FILE>' --brain host",
"consent": [],
- "docs": "https://github.com/garrytan/gbrain/blob/master/docs/operations/backup-check.md",
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/in-agent-setup.md#6-back-up-the-complete-local-database",
"inputs": [
{
- "how": "Ask the user where backups should live (a directory outside the brain, ideally synced or on another disk).",
- "name": "BACKUP_DIR"
+ "how": "Ask the user for an absolute path to a new archive file, in an existing private directory outside the brain (ideally another disk).",
+ "name": "BACKUP_FILE"
}
],
"next": "run",
@@ -3186,7 +3187,7 @@
"host"
]
},
- "why": "Writes a Markdown copy of 'default' (pages and facts) to a directory outside the brain so it survives losing the database."
+ "why": "Writes a full snapshot of this PGLite brain (every source, page, fact, member, token and rule) to one archive outside the brain."
},
"message": "Not urgent yet: the brain holds 23 page(s)+fact(s) and is under 7 days old (backup coaching starts at 25 items or 7 days). 3 knowledge asset(s) lack verified recovery: default (not_a_git_repo), plain (not_a_git_repo), notes (no git remote). A source repo with a pushed git remote restores its Markdown files only, never DB-only pages, facts, config or credentials. Run `gbrain backup status` for each asset's fix command.",
"name": "backup_coverage",
@@ -8324,6 +8325,7 @@
"behind": [],
"docs": "docs/guides/conversation-archive.md#doctor",
"enabled": true,
+ "enabled_by": "default",
"harnesses": [
{
"harness": "claude-code",
@@ -8369,6 +8371,7 @@
}
],
"held": [],
+ "reason": "on by default on a personal brain",
"source_id": "conversations",
"stale_days": 2
},
@@ -8628,21 +8631,20 @@
"actor": "agent",
"argv": [
"gbrain",
- "export",
- "--source",
- "default",
- "--dir",
- "<BACKUP_DIR>/default",
+ "backup",
+ "create",
+ "--output",
+ "<BACKUP_FILE>",
"--brain",
"host"
],
- "command": "gbrain export --source default --dir '<BACKUP_DIR>/default' --brain host",
+ "command": "gbrain backup create --output '<BACKUP_FILE>' --brain host",
"consent": [],
- "docs": "https://github.com/garrytan/gbrain/blob/master/docs/operations/backup-check.md",
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/in-agent-setup.md#6-back-up-the-complete-local-database",
"inputs": [
{
- "how": "Ask the user where backups should live (a directory outside the brain, ideally synced or on another disk).",
- "name": "BACKUP_DIR"
+ "how": "Ask the user for an absolute path to a new archive file, in an existing private directory outside the brain (ideally another disk).",
+ "name": "BACKUP_FILE"
}
],
"next": "run",
@@ -8658,7 +8660,7 @@
"host"
]
},
- "why": "Writes a Markdown copy of 'default' (pages and facts) to a directory outside the brain so it survives losing the database."
+ "why": "Writes a full snapshot of this PGLite brain (every source, page, fact, member, token and rule) to one archive outside the brain."
},
"message": "Not urgent yet: the brain holds 23 page(s)+fact(s) and is under 7 days old (backup coaching starts at 25 items or 7 days). 3 knowledge asset(s) lack verified recovery: default (not_a_git_repo), plain (not_a_git_repo), notes (no git remote). A source repo with a pushed git remote restores its Markdown files only, never DB-only pages, facts, config or credentials. Run `gbrain backup status` for each asset's fix command.",
"name": "backup_coverage",
diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
index 340228b3b2..64aa02aa65 100644
--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
@@ -2863,6 +2863,7 @@
"behind": [],
"docs": "docs/guides/conversation-archive.md#doctor",
"enabled": true,
+ "enabled_by": "default",
"harnesses": [
{
"harness": "claude-code",
@@ -2908,6 +2909,7 @@
}
],
"held": [],
+ "reason": "on by default on a personal brain",
"source_id": "conversations",
"stale_days": 2
},
@@ -3164,40 +3166,35 @@
},
"elapsed_ms": "<volatile>",
"fix": {
- "actor": "agent",
+ "actor": "host_admin",
"argv": [
- "gbrain",
- "export",
- "--source",
- "default",
- "--dir",
- "<BACKUP_DIR>/default",
- "--brain",
- "host"
+ "pg_dump",
+ "--format",
+ "custom",
+ "--file",
+ "<DUMP_FILE>",
+ "--dbname",
+ "<DATABASE_URL>"
+ ],
+ "command": "pg_dump --format custom --file '<DUMP_FILE>' --dbname '<DATABASE_URL>'",
+ "consent": [
+ "credentials"
],
- "command": "gbrain export --source default --dir '<BACKUP_DIR>/default' --brain host",
- "consent": [],
- "docs": "https://github.com/garrytan/gbrain/blob/master/docs/operations/backup-check.md",
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/memory-boundaries.md#full-backup",
"inputs": [
{
- "how": "Ask the user where backups should live (a directory outside the brain, ideally synced or on another disk).",
- "name": "BACKUP_DIR"
+ "how": "A new file outside the brain, in a directory only the user can read.",
+ "name": "DUMP_FILE"
+ },
+ {
+ "how": "The brain's Postgres connection, preferably service=<name> from a pg_service file so no password lands in the command line.",
+ "name": "DATABASE_URL"
}
],
- "next": "run",
+ "next": "tell_user_to_run",
"requires_exclusive": false,
- "verify": {
- "argv": [
- "gbrain",
- "doctor",
- "--only",
- "backup_coverage",
- "--json",
- "--brain",
- "host"
- ]
- },
- "why": "Writes a Markdown copy of 'default' (pages and facts) to a directory outside the brain so it survives losing the database."
+ "user_message": "This brain lives in Postgres, so back it up with a database dump of its database: `pg_dump --format custom --file <DUMP_FILE> --dbname <DATABASE_URL>`, kept private (it holds every page, fact, member and token); `pg_restore --list <DUMP_FILE>` reads it back. Restore it into a new, empty database with `pg_restore --no-owner --dbname <NEW_DATABASE_URL> <DUMP_FILE>`, then run `gbrain init --url <NEW_DATABASE_URL>` under a separate GBRAIN_HOME, which opens the restored brain. `gbrain export` is not a backup: an import of it puts every page in one source and keeps no members, tokens or facts.",
+ "why": "A database dump keeps every source, page, fact, member, token and folder rule of a Postgres brain; a Markdown export keeps pages only."
},
"message": "Not urgent yet: the brain holds 23 page(s)+fact(s) and is under 7 days old (backup coaching starts at 25 items or 7 days). 3 knowledge asset(s) lack verified recovery: default (not_a_git_repo), plain (not_a_git_repo), notes (no git remote). A source repo with a pushed git remote restores its Markdown files only, never DB-only pages, facts, config or credentials. Run `gbrain backup status` for each asset's fix command.",
"name": "backup_coverage",
@@ -8339,6 +8336,7 @@
"behind": [],
"docs": "docs/guides/conversation-archive.md#doctor",
"enabled": true,
+ "enabled_by": "default",
"harnesses": [
{
"harness": "claude-code",
@@ -8384,6 +8382,7 @@
}
],
"held": [],
+ "reason": "on by default on a personal brain",
"source_id": "conversations",
"stale_days": 2
},
@@ -8640,40 +8639,35 @@
},
"elapsed_ms": "<volatile>",
"fix": {
- "actor": "agent",
+ "actor": "host_admin",
"argv": [
- "gbrain",
- "export",
- "--source",
- "default",
- "--dir",
- "<BACKUP_DIR>/default",
- "--brain",
- "host"
+ "pg_dump",
+ "--format",
+ "custom",
+ "--file",
+ "<DUMP_FILE>",
+ "--dbname",
+ "<DATABASE_URL>"
+ ],
+ "command": "pg_dump --format custom --file '<DUMP_FILE>' --dbname '<DATABASE_URL>'",
+ "consent": [
+ "credentials"
],
- "command": "gbrain export --source default --dir '<BACKUP_DIR>/default' --brain host",
- "consent": [],
- "docs": "https://github.com/garrytan/gbrain/blob/master/docs/operations/backup-check.md",
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/memory-boundaries.md#full-backup",
"inputs": [
{
- "how": "Ask the user where backups should live (a directory outside the brain, ideally synced or on another disk).",
- "name": "BACKUP_DIR"
+ "how": "A new file outside the brain, in a directory only the user can read.",
+ "name": "DUMP_FILE"
+ },
+ {
+ "how": "The brain's Postgres connection, preferably service=<name> from a pg_service file so no password lands in the command line.",
+ "name": "DATABASE_URL"
}
],
- "next": "run",
+ "next": "tell_user_to_run",
"requires_exclusive": false,
- "verify": {
- "argv": [
- "gbrain",
- "doctor",
- "--only",
- "backup_coverage",
- "--json",
- "--brain",
- "host"
- ]
- },
- "why": "Writes a Markdown copy of 'default' (pages and facts) to a directory outside the brain so it survives losing the database."
+ "user_message": "This brain lives in Postgres, so back it up with a database dump of its database: `pg_dump --format custom --file <DUMP_FILE> --dbname <DATABASE_URL>`, kept private (it holds every page, fact, member and token); `pg_restore --list <DUMP_FILE>` reads it back. Restore it into a new, empty database with `pg_restore --no-owner --dbname <NEW_DATABASE_URL> <DUMP_FILE>`, then run `gbrain init --url <NEW_DATABASE_URL>` under a separate GBRAIN_HOME, which opens the restored brain. `gbrain export` is not a backup: an import of it puts every page in one source and keeps no members, tokens or facts.",
+ "why": "A database dump keeps every source, page, fact, member, token and folder rule of a Postgres brain; a Markdown export keeps pages only."
},
"message": "Not urgent yet: the brain holds 23 page(s)+fact(s) and is under 7 days old (backup coaching starts at 25 items or 7 days). 3 knowledge asset(s) lack verified recovery: default (not_a_git_repo), plain (not_a_git_repo), notes (no git remote). A source repo with a pushed git remote restores its Markdown files only, never DB-only pages, facts, config or credentials. Run `gbrain backup status` for each asset's fix command.",
"name": "backup_coverage",
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index d367613d53..ed0c9b3fe3 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -2422,6 +2422,7 @@
"behind": [],
"docs": "docs/guides/conversation-archive.md#doctor",
"enabled": true,
+ "enabled_by": "default",
"harnesses": [
{
"harness": "claude-code",
@@ -2467,6 +2468,7 @@
}
],
"held": [],
+ "reason": "on by default on a personal brain",
"source_id": "conversations",
"stale_days": 2
},
@@ -2662,21 +2664,20 @@
"actor": "agent",
"argv": [
"gbrain",
- "export",
- "--source",
- "default",
- "--dir",
- "<BACKUP_DIR>/default",
+ "backup",
+ "create",
+ "--output",
+ "<BACKUP_FILE>",
"--brain",
"host"
],
- "command": "gbrain export --source default --dir '<BACKUP_DIR>/default' --brain host",
+ "command": "gbrain backup create --output '<BACKUP_FILE>' --brain host",
"consent": [],
- "docs": "https://github.com/garrytan/gbrain/blob/master/docs/operations/backup-check.md",
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/in-agent-setup.md#6-back-up-the-complete-local-database",
"inputs": [
{
- "how": "Ask the user where backups should live (a directory outside the brain, ideally synced or on another disk).",
- "name": "BACKUP_DIR"
+ "how": "Ask the user for an absolute path to a new archive file, in an existing private directory outside the brain (ideally another disk).",
+ "name": "BACKUP_FILE"
}
],
"next": "run",
@@ -2692,7 +2693,7 @@
"host"
]
},
- "why": "Writes a Markdown copy of 'default' (pages and facts) to a directory outside the brain so it survives losing the database."
+ "why": "Writes a full snapshot of this PGLite brain (every source, page, fact, member, token and rule) to one archive outside the brain."
},
"message": "Not urgent yet: the brain holds 0 page(s)+fact(s) and is under 7 days old (backup coaching starts at 25 items or 7 days). 1 knowledge asset(s) lack verified recovery: default (not_a_git_repo). A source repo with a pushed git remote restores its Markdown files only, never DB-only pages, facts, config or credentials. Run `gbrain backup status` for each asset's fix command.",
"name": "backup_coverage",
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 76dc505294..440cb7a6fc 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -2478,6 +2478,7 @@
"behind": [],
"docs": "docs/guides/conversation-archive.md#doctor",
"enabled": true,
+ "enabled_by": "default",
"harnesses": [
{
"harness": "claude-code",
@@ -2523,6 +2524,7 @@
}
],
"held": [],
+ "reason": "on by default on a personal brain",
"source_id": "conversations",
"stale_days": 2
},
@@ -2718,21 +2720,20 @@
"actor": "agent",
"argv": [
"gbrain",
- "export",
- "--source",
- "default",
- "--dir",
- "<BACKUP_DIR>/default",
+ "backup",
+ "create",
+ "--output",
+ "<BACKUP_FILE>",
"--brain",
"host"
],
- "command": "gbrain export --source default --dir '<BACKUP_DIR>/default' --brain host",
+ "command": "gbrain backup create --output '<BACKUP_FILE>' --brain host",
"consent": [],
- "docs": "https://github.com/garrytan/gbrain/blob/master/docs/operations/backup-check.md",
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/in-agent-setup.md#6-back-up-the-complete-local-database",
"inputs": [
{
- "how": "Ask the user where backups should live (a directory outside the brain, ideally synced or on another disk).",
- "name": "BACKUP_DIR"
+ "how": "Ask the user for an absolute path to a new archive file, in an existing private directory outside the brain (ideally another disk).",
+ "name": "BACKUP_FILE"
}
],
"next": "run",
@@ -2748,7 +2749,7 @@
"host"
]
},
- "why": "Writes a Markdown copy of 'default' (pages and facts) to a directory outside the brain so it survives losing the database."
+ "why": "Writes a full snapshot of this PGLite brain (every source, page, fact, member, token and rule) to one archive outside the brain."
},
"message": "Not urgent yet: the brain holds 0 page(s)+fact(s) and is under 7 days old (backup coaching starts at 25 items or 7 days). 1 knowledge asset(s) lack verified recovery: default (not_a_git_repo). A source repo with a pushed git remote restores its Markdown files only, never DB-only pages, facts, config or credentials. Run `gbrain backup status` for each asset's fix command.",
"name": "backup_coverage",
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 968846061f..867093c68e 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -2489,6 +2489,7 @@
"behind": [],
"docs": "docs/guides/conversation-archive.md#doctor",
"enabled": true,
+ "enabled_by": "default",
"harnesses": [
{
"harness": "claude-code",
@@ -2534,6 +2535,7 @@
}
],
"held": [],
+ "reason": "on by default on a personal brain",
"source_id": "conversations",
"stale_days": 2
},
@@ -2726,40 +2728,35 @@
},
"elapsed_ms": "<volatile>",
"fix": {
- "actor": "agent",
+ "actor": "host_admin",
"argv": [
- "gbrain",
- "export",
- "--source",
- "default",
- "--dir",
- "<BACKUP_DIR>/default",
- "--brain",
- "host"
+ "pg_dump",
+ "--format",
+ "custom",
+ "--file",
+ "<DUMP_FILE>",
+ "--dbname",
+ "<DATABASE_URL>"
],
- "command": "gbrain export --source default --dir '<BACKUP_DIR>/default' --brain host",
- "consent": [],
- "docs": "https://github.com/garrytan/gbrain/blob/master/docs/operations/backup-check.md",
+ "command": "pg_dump --format custom --file '<DUMP_FILE>' --dbname '<DATABASE_URL>'",
+ "consent": [
+ "credentials"
+ ],
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/memory-boundaries.md#full-backup",
"inputs": [
{
- "how": "Ask the user where backups should live (a directory outside the brain, ideally synced or on another disk).",
- "name": "BACKUP_DIR"
+ "how": "A new file outside the brain, in a directory only the user can read.",
+ "name": "DUMP_FILE"
+ },
+ {
+ "how": "The brain's Postgres connection, preferably service=<name> from a pg_service file so no password lands in the command line.",
+ "name": "DATABASE_URL"
}
],
- "next": "run",
+ "next": "tell_user_to_run",
"requires_exclusive": false,
- "verify": {
- "argv": [
- "gbrain",
- "doctor",
- "--only",
- "backup_coverage",
- "--json",
- "--brain",
- "host"
- ]
- },
- "why": "Writes a Markdown copy of 'default' (pages and facts) to a directory outside the brain so it survives losing the database."
+ "user_message": "This brain lives in Postgres, so back it up with a database dump of its database: `pg_dump --format custom --file <DUMP_FILE> --dbname <DATABASE_URL>`, kept private (it holds every page, fact, member and token); `pg_restore --list <DUMP_FILE>` reads it back. Restore it into a new, empty database with `pg_restore --no-owner --dbname <NEW_DATABASE_URL> <DUMP_FILE>`, then run `gbrain init --url <NEW_DATABASE_URL>` under a separate GBRAIN_HOME, which opens the restored brain. `gbrain export` is not a backup: an import of it puts every page in one source and keeps no members, tokens or facts.",
+ "why": "A database dump keeps every source, page, fact, member, token and folder rule of a Postgres brain; a Markdown export keeps pages only."
},
"message": "Not urgent yet: the brain holds 0 page(s)+fact(s) and is under 7 days old (backup coaching starts at 25 items or 7 days). 1 knowledge asset(s) lack verified recovery: default (not_a_git_repo). A source repo with a pushed git remote restores its Markdown files only, never DB-only pages, facts, config or credentials. Run `gbrain backup status` for each asset's fix command.",
"name": "backup_coverage",
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index abfda30e28..67c1997457 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6879,7 +6879,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"page_body_rows_unreadable\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_identity_unavailable\" | \"access_member_disabled\" | \"archive_audience_unproven\" | \"archive_gateway_unreachable\" | \"archive_gateway_auth\" | \"archive_gateway_failed\" | \"archive_owner_unset\" | \"archive_redaction_failed\" | \"archive_run_busy\" | \"autopilot_no_repo\" | \"autopilot_pglite_daemon\" | \"cycle_already_running\" | \"engine_degraded\" | \"maintenance_disabled\" | \"maintenance_owned_by_serve\" | \"schedule_unsupported\" | \"schedule_install_failed\" | \"maintenance_owned_by_autopilot\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_history_unreadable\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"requester_scope_required\" | \"requester_scope_unknown\" | \"credential_scope_required\" | \"access_serves_roster_empty\" | \"access_serves_key_dir_in_git\" | \"repair_propose_dir_in_git\" | \"access_member_id_retired\" | \"access_labelled_only_owner\" | \"access_labelled_only_unnamed\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"append_links_fence\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_behind\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_base_moved\" | \"commit_paths_unmerged\" | \"commit_paths_invalid\" | \"commit_paths_skipped\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_filter_owned\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_alert_act\" | \"doctor_alert_unknown\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"enforced_member_refused\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"foreign_table\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"moved_pages_mass_fold_refused\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_command_stopped\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_delta\" | \"conversion_file_in_source_root\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"link_dates_unattributed\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migration_host_work_owed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_projection_stale\" | \"label_edit_refused\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"publish_secret_found\" | \"publish_scan_unreadable\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"postgres_tls_required\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"proposal_closed\" | \"proposal_expired\" | \"proposals_pending_limit\" | \"provider_response_unparseable\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"purge_replay_incomplete\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"repair_preview_timeout\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_backfill_pending\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"openclaw_not_found\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"setup_serves_several\" | \"setup_serves_unreadable\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unmanifested\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_catalog_mismatch\" | \"skill_catalog_too_large\" | \"skill_catalog_unknown\" | \"skill_index_incompatible\" | \"skill_index_locked\" | \"skill_index_missing\" | \"skill_index_removed\" | \"skill_resolve_invalid_input\" | \"skill_resolve_no_input\" | \"skill_resolve_timeout\" | \"skill_resolver_config_invalid\" | \"skill_resolver_config_unreadable\" | \"skill_resolver_setup_incomplete\" | \"skill_resolver_plugin_not_installed\" | \"skill_resolver_host_not_local\" | \"skill_resolver_selftest_failed\" | \"skill_resolver_pin_unknown\" | \"skill_resolver_library_missing\" | \"skill_resolver_library_mismatch\" | \"skill_resolver_library_skew\" | \"skill_resolver_worker_crash\" | \"skill_resolver_worker_stuck\" | \"skill_resolver_worker_unavailable\" | \"skill_resolver_state_missing\" | \"skill_resolver_host_load_cut\" | \"skill_resolver_internal\" | \"skill_source_invalid\" | \"skill_source_unreadable\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"skillpack_backup_corrupt\" | \"skillpack_journal_not_found\" | \"skillpack_restore_conflict\" | \"skillpack_state_locked\" | \"skillpack_update_incomplete\" | \"skillpack_workspace_locked\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_pages_remain\" | \"source_referenced\" | \"source_retire_superseded\" | \"source_root_conflict\" | \"source_root_unreadable\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"storage_adopt_field_refused\" | \"storage_adopt_unverified\" | \"storage_card_exists\" | \"storage_manifest_missing\" | \"storage_record_invalid\" | \"storage_record_secret\" | \"storage_revision_conflict\" | \"storage_source_managed\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"tag_too_long\" | \"target_escape\" | \"timeline_comment_markup\" | \"source_writer_restricted\" | \"guest_page_immutable\" | \"guest_page_promoted\" | \"guest_attribution_missing\" | \"guest_frontmatter_refused\" | \"guest_readers_invalid\" | \"guest_promotion_owner_only\" | \"guest_mark_immutable\" | \"guest_source_database_only\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"untrack_not_db_only\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"wakeshift_key_invalid\" | \"wakeshift_needs_conversation\" | \"wakeshift_not_enabled\" | \"wakeshift_refused\" | \"wakeshift_shared_brain\" | \"wakeshift_unavailable\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
+ "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"page_body_rows_unreadable\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_identity_unavailable\" | \"access_member_disabled\" | \"archive_audience_unproven\" | \"archive_gateway_unreachable\" | \"archive_gateway_auth\" | \"archive_gateway_failed\" | \"archive_owner_unset\" | \"archive_redaction_failed\" | \"archive_run_busy\" | \"autopilot_no_repo\" | \"autopilot_pglite_daemon\" | \"cycle_already_running\" | \"engine_degraded\" | \"maintenance_disabled\" | \"maintenance_owned_by_serve\" | \"schedule_unsupported\" | \"schedule_install_failed\" | \"maintenance_owned_by_autopilot\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_history_unreadable\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"requester_scope_required\" | \"requester_scope_unknown\" | \"credential_scope_required\" | \"access_serves_roster_empty\" | \"access_serves_key_dir_in_git\" | \"repair_propose_dir_in_git\" | \"access_member_id_retired\" | \"access_labelled_only_owner\" | \"access_labelled_only_unnamed\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"append_links_fence\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_behind\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_base_moved\" | \"commit_paths_unmerged\" | \"commit_paths_invalid\" | \"commit_paths_skipped\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_filter_owned\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_alert_act\" | \"doctor_alert_unknown\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"enforced_member_refused\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"foreign_table\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"moved_pages_mass_fold_refused\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_command_stopped\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_delta\" | \"conversion_file_in_source_root\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"link_dates_unattributed\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migration_host_work_owed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_projection_stale\" | \"label_edit_refused\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"publish_secret_found\" | \"publish_scan_unreadable\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"postgres_tls_required\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"proposal_closed\" | \"proposal_expired\" | \"proposals_pending_limit\" | \"provider_response_unparseable\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"purge_replay_incomplete\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"repair_preview_timeout\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_backfill_pending\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"openclaw_not_found\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"setup_serves_several\" | \"setup_history_choice_required\" | \"setup_serves_unreadable\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unmanifested\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_catalog_mismatch\" | \"skill_catalog_too_large\" | \"skill_catalog_unknown\" | \"skill_index_incompatible\" | \"skill_index_locked\" | \"skill_index_missing\" | \"skill_index_removed\" | \"skill_resolve_invalid_input\" | \"skill_resolve_no_input\" | \"skill_resolve_timeout\" | \"skill_resolver_config_invalid\" | \"skill_resolver_config_unreadable\" | \"skill_resolver_setup_incomplete\" | \"skill_resolver_plugin_not_installed\" | \"skill_resolver_host_not_local\" | \"skill_resolver_selftest_failed\" | \"skill_resolver_pin_unknown\" | \"skill_resolver_library_missing\" | \"skill_resolver_library_mismatch\" | \"skill_resolver_library_skew\" | \"skill_resolver_worker_crash\" | \"skill_resolver_worker_stuck\" | \"skill_resolver_worker_unavailable\" | \"skill_resolver_state_missing\" | \"skill_resolver_host_load_cut\" | \"skill_resolver_internal\" | \"skill_source_invalid\" | \"skill_source_unreadable\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"skillpack_backup_corrupt\" | \"skillpack_journal_not_found\" | \"skillpack_restore_conflict\" | \"skillpack_state_locked\" | \"skillpack_update_incomplete\" | \"skillpack_workspace_locked\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_pages_remain\" | \"source_referenced\" | \"source_retire_superseded\" | \"source_root_conflict\" | \"source_root_unreadable\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"storage_adopt_field_refused\" | \"storage_adopt_unverified\" | \"storage_card_exists\" | \"storage_manifest_missing\" | \"storage_record_invalid\" | \"storage_record_secret\" | \"storage_revision_conflict\" | \"storage_source_managed\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"tag_too_long\" | \"target_escape\" | \"timeline_comment_markup\" | \"source_writer_restricted\" | \"guest_page_immutable\" | \"guest_page_promoted\" | \"guest_attribution_missing\" | \"guest_frontmatter_refused\" | \"guest_readers_invalid\" | \"guest_promotion_owner_only\" | \"guest_mark_immutable\" | \"guest_source_database_only\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"untrack_not_db_only\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"wakeshift_key_invalid\" | \"wakeshift_needs_conversation\" | \"wakeshift_not_enabled\" | \"wakeshift_refused\" | \"wakeshift_shared_brain\" | \"wakeshift_unavailable\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
diff --git a/test/grant-blocked-notice.test.ts b/test/grant-blocked-notice.test.ts
index 587d433f34..23a575f491 100644
--- a/test/grant-blocked-notice.test.ts
+++ b/test/grant-blocked-notice.test.ts
@@ -117,6 +117,18 @@ describe('grant_blocked_operations', () => {
expect((await readClientGrant(engine, created.clientId)).allowedOperations).not.toContain('put_pages');
});
+ // GBRA-585: the guest broker narrowed with --operations, as docs/guides/guest-notes.md says, got the widen nudge on every session.
+ test('a client the owner narrowed on purpose gets no notice on a call it can make, and a refused call still says why', async () => {
+ const created = await client('narrowed-example', 'memory-writer', { allowedOperations: ['get_page', 'put_page', 'get_write_request', 'get_brain_identity'] });
+ const opts = await connect(created);
+ expect(grantNotice(await read(opts('narrowed-session')))).toEqual([]);
+ const refused = await dispatchToolCall(engine, 'put_pages', { pages: [] }, opts('narrowed-session'));
+ expect(refused.isError).toBe(true);
+ const [n] = grantNotice(refused);
+ expect(n.why).toContain('all existed when the snapshot was written');
+ expect([...(await readClientGrant(engine, created.clientId)).allowedOperations!].sort()).toEqual(['get_brain_identity', 'get_page', 'get_write_request', 'put_page']);
+ });
+
test('a memory-reader stays unable to call put_pages; the refusal names the missing write scope, a plain read says nothing', async () => {
const opts = await connect(await client('reader-example', 'memory-reader'));
expect(grantNotice(await read(opts('reader-session-a')))).toEqual([]);
diff --git a/test/guests-cli.test.ts b/test/guests-cli.test.ts
index 976ebc5ba6..d8748e730e 100644
--- a/test/guests-cli.test.ts
+++ b/test/guests-cli.test.ts
@@ -39,6 +39,7 @@ afterAll(async () => {
beforeEach(async () => {
await resetPgliteState(engine);
+ for (const id of ['client-a', 'client-b']) await engine.executeRaw('INSERT INTO oauth_clients (client_id, client_name) VALUES ($1, $1)', [id]);
exitCode = null; out = []; err = [];
origExit = process.exit;
(process as unknown as { exit: (n: number) => never }).exit = ((n: number) => {
@@ -48,6 +49,7 @@ beforeEach(async () => {
spies = [
spyOn(console, 'log').mockImplementation((...a: unknown[]) => { out.push(a.join(' ')); }),
spyOn(console, 'error').mockImplementation((...a: unknown[]) => { err.push(a.join(' ')); }),
+ spyOn(process.stderr, 'write').mockImplementation(((chunk: unknown) => { err.push(String(chunk)); return true; }) as never),
];
});
@@ -139,6 +141,21 @@ describe('gbrain guests init', () => {
expect(exitCode).toBe(2);
expect(await sourceRow('guests')).toBeUndefined();
});
+
+ test('GBRA-585: refuses an oauth_client writer that names no registered client, or a deleted one, in the preview and with --yes, and writes nothing', async () => {
+ await engine.executeRaw("INSERT INTO oauth_clients (client_id, client_name, deleted_at) VALUES ('client-gone', 'client-gone', now())");
+ for (const id of ['client-missing', 'client-gone']) {
+ for (const yes of [[], ['--yes']]) {
+ exitCode = null; err = []; out = [];
+ await run(() => runGuests(engine, ['init', '--writer', 'oauth_client:client-a', '--writer', `oauth_client:${id}`, ...yes]));
+ expect({ id, yes, exitCode: exitCode as number | null }).toEqual({ id, yes, exitCode: 1 });
+ expect(err.join('\n')).toContain('client_not_found');
+ expect(err.join('\n')).toContain(`oauth_client:${id}`);
+ expect(await sourceRow('guests')).toBeUndefined();
+ expect(await engine.executeRaw('SELECT 1 FROM guest_sources')).toEqual([]);
+ }
+ }
+ });
});
describe('gbrain sources writers', () => {
@@ -156,6 +173,19 @@ describe('gbrain sources writers', () => {
expect(exitCode).toBeNull();
});
+ test('GBRA-585: --add refuses an oauth_client writer that names no registered client and leaves the list unchanged; --remove still takes one', async () => {
+ await run(() => runGuests(engine, ['init', '--writer', 'oauth_client:client-a', '--yes']));
+ await run(() => runSources(engine, ['writers', 'guests', '--add', 'oauth_client:client-missing']));
+ expect(exitCode as number | null).toBe(1);
+ expect(err.join('\n')).toContain('client_not_found');
+ expect((await guestRow('guests'))?.writers).toEqual(['oauth_client:client-a']);
+ exitCode = null;
+ await engine.executeRaw("UPDATE oauth_clients SET deleted_at = now() WHERE client_id = 'client-a'");
+ await run(() => runSources(engine, ['writers', 'guests', '--remove', 'oauth_client:client-a']));
+ expect(exitCode).toBeNull();
+ expect((await guestRow('guests'))?.writers).toEqual([]);
+ });
+
test('refuses a source that is not a guest source, and an unknown one', async () => {
await run(() => runSources(engine, ['writers', 'default', '--add', 'oauth_client:client-a']));
expect(exitCode).toBe(2);
diff --git a/test/helpers/setup-serves-box.ts b/test/helpers/setup-serves-box.ts
index 4fdc463627..be672e122f 100644
--- a/test/helpers/setup-serves-box.ts
+++ b/test/helpers/setup-serves-box.ts
@@ -9,6 +9,7 @@ import { chmodSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, w
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { ownedEntryFingerprint } from '../../src/core/bootstrap/adopted-connections.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { runCli, type CliResult } from './cli-spawn.ts';
export const ROSTER = ['alice-example', 'bob-example'];
@@ -28,6 +29,20 @@ export const CLI = resolve(import.meta.dir, '..', '..', 'src', 'cli.ts');
export const CLEAN = { CLAUDE_CONFIG_DIR: undefined, CODEX_HOME: undefined, GBRAIN_SOURCE: undefined, GBRAIN_SURFACE: undefined, GBRAIN_HOOKS: undefined, GBRAIN_SETUP_ABORT_AFTER: undefined };
export interface Box { root: string; home: string; bin: string }
+/** The PGLite brain under a box's (or any) HOME, opened after the spawned CLI is done with it; the caller disconnects it. */
+export async function openBrainFile(home: string): Promise<PGLiteEngine> {
+ const engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite', database_path: join(home, '.gbrain', 'brain.pglite') } as never);
+ return engine;
+}
+/** An in-memory PGLite brain with the schema, for a beforeAll; the caller disconnects it in afterAll. */
+export async function memoryBrain(): Promise<PGLiteEngine> {
+ const engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite' } as never);
+ await engine.initSchema();
+ return engine;
+}
+
export function box(): Box {
const root = tempDir('gbrain-setup-serves-');
const home = join(root, 'home');
diff --git a/test/member-agent-messages-gbra585.test.ts b/test/member-agent-messages-gbra585.test.ts
new file mode 100644
index 0000000000..a23e945e29
--- /dev/null
+++ b/test/member-agent-messages-gbra585.test.ts
@@ -0,0 +1,102 @@
+/**
+ * GBRA-585 item 13: refusals a member's agent gets point the right way, and say nothing about pages it cannot read.
+ *
+ * 1. Protects: (a) a member-bound remote caller's page_not_found reads the same for a missing page and a page kept to
+ * another member, says it may not exist or may not be readable by this connection, and carries no soft-delete chase
+ * and no host CLI command; an unbound stdio caller keeps the soft-delete check. (b) sources_not_readable says what it
+ * checked: pages every reader of the source can read, so a member whose own pages sit in default is not told that
+ * default holds no page. (c) a blocked remember share:true onto an entity page this connection cannot read keeps its
+ * frozen code (unavailable) with page_not_found as its canonical code, and points at saving without share instead of
+ * gbrain doctor.
+ * 2. Fails when: a member is sent to include_deleted or a host command, the restricted and missing replies differ, the
+ * sources_not_readable message claims the readable sources hold no page, or the share refusal points at doctor.
+ * 3. Real seams: member-bound legacy tokens (as setup --serves several mints), MCP dispatch as a remote HTTP caller,
+ * a repo-less PGLite brain with a non-federated second source.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import { addMember, bindCredential } from '../src/core/access/members.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import type { AuthInfo } from '../src/core/ops/contract.ts';
+
+let engine: BrainEngine;
+const tokens: Record<string, string> = {};
+const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+
+async function call(who: string, op: string, params: Record<string, unknown>) {
+ const auth = await provider().verifyAccessToken(tokens[who]!) as unknown as AuthInfo;
+ const out = await dispatchToolCall(engine, op, { ...params }, { remote: true, transport: 'http', auth, sourceId: 'default', takesHoldersAllowList: ['world'] });
+ const text = out.content.map(c => c.text).join('\n');
+ let json: Record<string, any> = {};
+ try { json = JSON.parse(out.content[0]!.text); } catch { /* prose */ }
+ return { isError: out.isError === true, text, json };
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite' } as never);
+ await engine.initSchema();
+ __resetPrivateVisibilityCacheForTests();
+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('company', 'company') ON CONFLICT (id) DO NOTHING");
+ for (const id of ['alice-example', 'bob-example']) await addMember(engine, id);
+ await importFromContent(engine, 'companies/initech-example', '---\ntype: company\ntitle: Initech Example\nreadable_by: [bob-example]\n---\n# Initech Example\n\nKept to bob-example.', { sourceId: 'default', noEmbed: true });
+ await importFromContent(engine, 'notes/alice-pricing-idea', '---\ntitle: Pricing idea\nreadable_by: [alice-example]\n---\n# Pricing idea\n\nalice-example walrusword.', { sourceId: 'default', noEmbed: true });
+ await importFromContent(engine, 'notes/team-roadmap', '# Team roadmap\n\nThe team otterword roadmap.', { sourceId: 'company', noEmbed: true });
+ for (const m of ['alice', 'bob']) {
+ const minted = await mintLegacyToken(engine, { name: `member-${m}-example`, scopes: ['read', 'write'], takesHolders: ['world'] });
+ await bindCredential(engine, { kind: 'token', id: minted.id }, { member: `${m}-example` });
+ tokens[m] = minted.token;
+ }
+}, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+
+describe('member-facing refusals (GBRA-585 item 13)', () => {
+ test('(a) a member reads the same not-found for a missing page and a page kept to another member, with no deletion chase or host command', async () => {
+ expect((await call('bob', 'get_page', { slug: 'companies/initech-example' })).isError).toBe(false);
+ const restricted = await call('alice', 'get_page', { slug: 'companies/initech-example' });
+ const missing = await call('alice', 'get_page', { slug: 'companies/initrode-example' });
+ for (const r of [restricted, missing]) {
+ expect(r.isError).toBe(true);
+ expect(r.json.code).toBe('page_not_found');
+ expect(r.text).not.toContain('soft-deleted');
+ expect(r.text).not.toContain('include_deleted');
+ expect(r.json.fix?.argv).toBeUndefined();
+ expect(r.json.suggestion).toContain('may not exist');
+ expect(r.json.suggestion).toContain('not be readable by this connection');
+ }
+ const strip = (r: typeof restricted) => JSON.stringify({ ...r.json, message: undefined }).replaceAll('initech', 'X').replaceAll('initrode', 'X');
+ expect(strip(restricted)).toBe(strip(missing));
+ const stdio = await dispatchToolCall(engine, 'get_page', { slug: 'companies/initrode-example' }, { remote: true, transport: 'stdio', sourceId: 'default', takesHoldersAllowList: ['world'] });
+ expect(JSON.parse(stdio.content[0]!.text).suggestion).toContain('include_deleted');
+ });
+
+ test('(b) sources_not_readable says it counted pages every reader of the source can read, not that the source holds none', async () => {
+ expect((await call('alice', 'search', { query: 'walrusword' })).text).toContain('notes/alice-pricing-idea');
+ const out = await call('alice', 'search', { query: 'otterword' });
+ expect(out.isError).toBe(true);
+ expect(out.json.code).toBe('sources_not_readable');
+ expect(out.json.message).not.toMatch(/none of them holds a page,|could only come back empty/);
+ expect(out.json.message).toContain('every reader');
+ expect(out.text).not.toContain('company');
+ });
+
+ test('(c) a share onto an entity page this connection cannot read keeps code unavailable, names page_not_found and never points at doctor', async () => {
+ const out = await call('alice', 'remember', { fact: 'Initech example CFO is unhappy', entity: 'companies/initech-example', provenance: 'heard from bob-example', share: true });
+ expect(out.isError).toBe(true);
+ expect(out.json.error).toBe('unavailable');
+ expect(out.json.code).toBe('page_not_found');
+ expect(out.json.write_error).toBe('page_not_found');
+ expect(out.text).not.toContain('doctor');
+ expect(out.json.suggestion).toContain('without share');
+ const kept = await call('alice', 'remember', { fact: 'Initech example CFO is unhappy', entity: 'companies/initech-example', provenance: 'heard from bob-example' });
+ expect([kept.isError, kept.json.status]).toEqual([false, 'inserted']);
+ expect((await engine.executeRaw<Record<string, unknown>>('SELECT visibility, source_markdown_slug FROM facts WHERE id = $1', [Number(kept.json.id)]))[0])
+ .toEqual({ visibility: 'private', source_markdown_slug: 'memory/members/alice-example' });
+ });
+});
diff --git a/test/pglite-live-serve-setup-gbra585.test.ts b/test/pglite-live-serve-setup-gbra585.test.ts
new file mode 100644
index 0000000000..dd3615b6d6
--- /dev/null
+++ b/test/pglite-live-serve-setup-gbra585.test.ts
@@ -0,0 +1,39 @@
+/**
+ * GBRA-585 (company brains, item 10): on PGLite every admin command refuses while `gbrain serve --http` runs, and
+ * the refusal linked the legacy stale-lock section. Setup for several people on PGLite now says so up front and
+ * points at the move to Postgres, and the live-serve refusal links the section about a running serve.
+ * 1. Protects: servesLines on a several-person PGLite setup carries the engine line naming pglite_busy and
+ * `gbrain migrate --to postgres`; Postgres and one-person setups carry none; the fatal seam's live-serve
+ * refusal links docs/ENGINES.md#pglite-live-serve, and the anchor exists; the legacy-owner refusal keeps its link.
+ * 2. Fails when: the line or the link is missing, or the anchor it names does not exist.
+ */
+import { afterEach, describe, expect, spyOn, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { writeFatalCliError } from '../src/cli/cli-error.ts';
+import { LiveServeLockError } from '../src/core/pglite-lock.ts';
+import { PGLITE_SEVERAL_NOTE, servesLines, type ServesOutcome } from '../src/commands/setup-serves.ts';
+
+function stderrOf(run: () => number): string {
+ const chunks: string[] = [];
+ const spy = spyOn(process.stderr, 'write').mockImplementation(((chunk: string | Uint8Array) => { chunks.push(String(chunk)); return true; }) as typeof process.stderr.write);
+ try { run(); return chunks.join(''); } finally { spy.mockRestore(); }
+}
+
+describe('PGLite with a running serve (GBRA-585 item 10)', () => {
+ test('the live-serve refusal links the running-serve section, which exists', () => {
+ const text = stderrOf(() => writeFatalCliError(new LiveServeLockError('GBrain\'s local database is already open through `gbrain serve` (MCP, PID 4242).', { pid: 4242, transport: 'http' }), { argv: ['access', 'member', 'list'] }));
+ expect(text).toContain('Error [pglite_busy]');
+ expect(text).toContain('docs/ENGINES.md#pglite-live-serve');
+ expect(text).not.toContain('#legacy-pglite-lock');
+ expect(readFileSync(new URL('../docs/ENGINES.md', import.meta.url), 'utf8')).toContain('<a id="pglite-live-serve"></a>');
+ });
+
+ test('setup --serves several on PGLite says admin commands refuse while serve runs and names the move to Postgres', () => {
+ const outcome: ServesOutcome = { mode: 'several', brain_serves: 'one', engine: PGLITE_SEVERAL_NOTE };
+ const lines = servesLines(outcome, false).join('\n');
+ expect(lines).toContain(' engine PGLite');
+ expect(lines).toContain('pglite_busy');
+ expect(lines).toContain('gbrain migrate --to postgres');
+ expect(servesLines({ mode: 'several', brain_serves: 'one' }, false).join('\n')).not.toContain('engine');
+ });
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 5549c6d357..88f73bc48f 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -47,6 +47,7 @@ test/adopt-local-edit.test.ts
test/alias-source-cascade-5094.test.ts
test/atom-retirement-keeps-trust-9456.test.ts
test/attribution-backfill-history.test.ts
+test/auth-create-member-scopes.test.ts
test/backlinks-type-exists-gbra449.test.ts
test/backstop-same-page-shadow-managed-6333.test.ts
test/behavior-change-notice.test.ts
@@ -663,6 +664,7 @@ test/segmented-untiled-hold-gst1209.test.ts
test/serve-head-watcher-managed.serial.test.ts
test/serve-http-access.test.ts
test/serve-http-memory-proposals.test.ts
+test/setup-company-access.test.ts
test/setup-serves-several.test.ts
test/shared-content-freshness.test.ts
test/shared-skills-catalog.test.ts
diff --git a/test/put-implicit-placement-gbra585.test.ts b/test/put-implicit-placement-gbra585.test.ts
new file mode 100644
index 0000000000..edd49aaebf
--- /dev/null
+++ b/test/put-implicit-placement-gbra585.test.ts
@@ -0,0 +1,133 @@
+/**
+ * GBRA-585 (company brains, item 2): after `gbrain setup --serves several --shape company`, the owner's first local
+ * `gbrain put` with no source landed in the `company` source with no word (the sole-non-default rule while 'default'
+ * is empty), and later puts went to 'default'. Routing stays as it is; the result now says where the page went.
+ * 1. Protects: a trusted local put that named no source, on a brain that serves several people, returns
+ * `placement` naming the source, the rule that picked it and who may read the page; a put that named its source,
+ * a remote caller and a one-person brain get no placement and route exactly as before.
+ * 2. Fails when: the placement is missing on the company brain, names the wrong rule or readers, or appears on a
+ * one-person brain, a remote call or an explicit source.
+ * 3. Real seams: MCP dispatch with remote=false (the path the CLI and the live owner socket use), the durable write
+ * path, the real source resolver and access tables.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { resolveSourceWithTier } from '../src/core/source-resolver.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import { withImplicitPlacement } from '../src/core/access/implicit-placement.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { bindCredential } from '../src/core/access/members.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import type { AuthInfo } from '../src/core/ops/contract.ts';
+
+const note = (title: string) => ['---', 'type: note', 'title: ' + title, '---', '# ' + title, '', 'Board prep ' + randomUUID()].join('\n');
+
+describe('a local put that names no source says where its page went (company brain, PGLite)', () => {
+ let engine: BrainEngine;
+ let dir: string;
+ const quiet = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE: '1' }, fn);
+
+ async function put(slug: string, opts: { sourceId: string; implicit?: boolean }) {
+ const out = await dispatchToolCall(engine, 'put_page', { slug, content: note(slug), request_id: randomUUID() },
+ { remote: false, sourceId: opts.sourceId, ...(opts.implicit ? { localSourceImplicit: true } : {}), takesHoldersAllowList: ['world'] });
+ if (out.isError) throw new Error(out.content.map(c => c.text).join('\n'));
+ return JSON.parse(out.content.map(c => c.text).join('\n')) as { source_id: string; placement?: { source_id: string; picked_by: string; readers: unknown; note: string } };
+ }
+
+ beforeAll(async () => {
+ dir = mkdtempSync(join(tmpdir(), 'gbra585-placement-'));
+ mkdirSync(join(dir, 'company'));
+ engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite' } as never);
+ await engine.initSchema();
+ __resetPrivateVisibilityCacheForTests();
+ for (const id of ['alice-example', 'bob-example']) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1)', [id]);
+ await engine.setConfig('access.serves', 'several');
+ await engine.executeRaw("INSERT INTO sources (id, name, local_path, config) VALUES ('company', 'company', $1, '{}'::jsonb)", [join(dir, 'company')]);
+ }, 240_000);
+ afterAll(async () => {
+ await engine?.disconnect();
+ rmSync(dir, { recursive: true, force: true });
+ }, 60_000);
+
+ test('the first unsourced put routes to company as before, and says so and who reads it', () => quiet(async () => {
+ const routed = await resolveSourceWithTier(engine, null, dir);
+ expect(routed).toMatchObject({ source_id: 'company', tier: 'sole_non_default' });
+ const out = await put('notes/owner-board-prep', { sourceId: routed.source_id, implicit: true });
+ expect(out.source_id).toBe('company');
+ expect(out.placement).toMatchObject({ source_id: 'company', picked_by: 'sole_non_default', readers: 'every_source_reader' });
+ expect(out.placement!.note).toContain("went to source 'company'");
+ expect(out.placement!.note).toContain('gbrain sources federate company');
+ expect(out.placement!.note).toContain('--source <id>');
+ expect(out.placement!.note).toContain('readable_by');
+ }), 120_000);
+
+ test('a put that named its source, and a remote put, carry no placement', () => quiet(async () => {
+ expect((await put('notes/named-source', { sourceId: 'company' })).placement).toBeUndefined();
+ const written = { status: 'created_or_updated', slug: 'notes/named-source', source_id: 'company' };
+ expect(await withImplicitPlacement({ engine, remote: true, localSourceImplicit: true }, 'company', { slug: 'notes/named-source' }, written)).toBe(written);
+ }), 120_000);
+
+ test("once 'default' holds a page, an unsourced put goes to default and says every member reads it", () => quiet(async () => {
+ await put('notes/team-roadmap', { sourceId: 'default' });
+ const routed = await resolveSourceWithTier(engine, null, dir);
+ expect(routed).toMatchObject({ source_id: 'default', tier: 'seed_default' });
+ const out = await put('notes/owner-later', { sourceId: routed.source_id, implicit: true });
+ expect(out.placement).toMatchObject({ source_id: 'default', picked_by: 'seed_default', readers: 'every_source_reader' });
+ expect(out.placement!.note).toContain('a member key with no source grant does');
+ }), 120_000);
+
+ test('a page that names its readers lists them', () => quiet(async () => {
+ const out = await dispatchToolCall(engine, 'put_page', { slug: 'notes/for-alice', request_id: randomUUID(),
+ content: ['---', 'type: note', 'title: For alice', 'readable_by: [alice-example]', '---', '# For alice'].join('\n') },
+ { remote: false, sourceId: 'default', localSourceImplicit: true, takesHoldersAllowList: ['world'] });
+ const doc = JSON.parse(out.content.map(c => c.text).join('\n')) as { placement?: { readers: unknown; note: string } };
+ expect(doc.placement?.readers).toEqual(['alice-example']);
+ expect(doc.placement?.note).toContain('Members who may read it: alice-example.');
+ }), 120_000);
+
+ test('a private page in default does not claim a member key reads it, and the member really gets page_not_found', () => quiet(async () => {
+ const out = await dispatchToolCall(engine, 'put_page', { slug: 'notes/owner-private', request_id: randomUUID(),
+ content: ['---', 'type: note', 'title: Owner private', 'visibility: private', '---', '# Owner private'].join('\n') },
+ { remote: false, sourceId: 'default', localSourceImplicit: true, takesHoldersAllowList: ['world'] });
+ const doc = JSON.parse(out.content.map(c => c.text).join('\n')) as { placement?: { readers: unknown; note: string } };
+ expect(doc.placement?.readers).toBe('every_source_reader');
+ expect(doc.placement?.note).not.toContain('a member key with no source grant does');
+ expect(doc.placement?.note).toContain('private_pages: granted_sources');
+ const minted = await mintLegacyToken(engine, { name: 'member-alice-placement', scopes: ['read', 'write'], takesHolders: ['world'] });
+ await bindCredential(engine, { kind: 'token', id: minted.id }, { member: 'alice-example' });
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const auth = await provider.verifyAccessToken(minted.token) as unknown as AuthInfo;
+ const read = await dispatchToolCall(engine, 'get_page', { slug: 'notes/owner-private' }, { remote: true, transport: 'http', auth, sourceId: 'default', takesHoldersAllowList: ['world'] });
+ expect(read.isError).toBe(true);
+ expect(JSON.parse(read.content[0]!.text).code).toBe('page_not_found');
+ }), 120_000);
+
+ test('a labelled-only member is named as not reading a page that names nobody', () => quiet(async () => {
+ await engine.executeRaw('UPDATE access_members SET labelled_only = true WHERE id = $1', ['bob-example']);
+ try {
+ const out = await put('notes/owner-labelled', { sourceId: 'default', implicit: true });
+ expect(out.placement!.note).toContain('Labelled-only members (bob-example) read it only when it names them');
+ expect(out.placement!.note).toContain('so none of them reads it');
+ } finally {
+ await engine.executeRaw('UPDATE access_members SET labelled_only = false WHERE id = $1', ['bob-example']);
+ }
+ }), 120_000);
+
+ test('a brain that serves one person gets no placement', () => quiet(async () => {
+ await engine.setConfig('access.serves', 'one');
+ try {
+ expect((await put('notes/personal', { sourceId: 'default', implicit: true })).placement).toBeUndefined();
+ } finally {
+ await engine.setConfig('access.serves', 'several');
+ }
+ }), 120_000);
+});
diff --git a/test/put-source-id-delegated-gbra585.test.ts b/test/put-source-id-delegated-gbra585.test.ts
new file mode 100644
index 0000000000..b20fc81950
--- /dev/null
+++ b/test/put-source-id-delegated-gbra585.test.ts
@@ -0,0 +1,57 @@
+/**
+ * GBRA-585: `gbrain put <slug> --source-id <id>` on a PGLite brain whose `gbrain serve` is running.
+ *
+ * 1. Protects: the CLI delegates the write to the resident serve with the routing source set to the --source-id it was
+ * given, so the owner builds the write's grant on that source, as the direct (no serve) path writes there.
+ * 2. Fails when: the delegated write is routed to the ambient source while its source_id names another, which the owner
+ * refused with "permission_denied: The source is outside this writer grant" (walk step 12), or a read's source_id
+ * starts redirecting its routing.
+ * 3. Real seams: maybeDelegateLocalOperation against a real persistence IPC socket and a serve lock holder.
+ */
+import { describe, expect, test } from 'bun:test';
+import { once } from 'node:events';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { acquireLock, releaseLock } from '../src/core/pglite-lock.ts';
+import { maybeDelegateLocalOperation } from '../src/core/persistence/local-client.ts';
+import { startPersistenceIpcServer, persistenceSocketPathForConfig, type PersistenceIpcRequest } from '../src/core/persistence/ipc.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const BRAIN = '10000000-0000-4000-8000-000000000585';
+
+describe('put --source-id delegated to a resident serve (GBRA-585)', () => {
+ test('a write routes to its source_id; a read keeps the ambient routing', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-put-source-id-'));
+ const config = { engine: 'pglite' as const, database_path: join(dir, 'db') };
+ mkdirSync(join(dir, '.gbrain', 'persistence'), { recursive: true });
+ mkdirSync(config.database_path, { recursive: true });
+ const lock = await acquireLock(config.database_path);
+ const metadataPath = lock.lockPath ?? join(config.database_path, '.gbrain-lock', 'lock');
+ writeFileSync(metadataPath, JSON.stringify({ ...JSON.parse(readFileSync(metadataPath, 'utf8')), subcommand: 'serve' }));
+ writeFileSync(join(dir, '.gbrain', 'config.json'), JSON.stringify(config));
+ writeFileSync(join(dir, '.gbrain', 'persistence', `${BRAIN}.cli.json`), JSON.stringify({ id: BRAIN, credential: 'a'.repeat(64), lane: 'cli' }), { mode: 0o600 });
+ const calls: PersistenceIpcRequest[] = [];
+ const binding = await startPersistenceIpcServer(persistenceSocketPathForConfig(config)!, {
+ brainId: BRAIN,
+ dispatch: async request => {
+ calls.push(request);
+ return { slug: request.params.slug, status: 'ok', write_request: { request_id: request.params.request_id, state: 'committed', retry_after_ms: null } };
+ },
+ });
+ try {
+ await withEnv({ GBRAIN_HOME: dir, GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: undefined, GBRAIN_DATABASE_URL: undefined, DATABASE_URL: undefined }, async () => {
+ const put = await maybeDelegateLocalOperation('put_page', { slug: 'notes/board-prep', content: '# Board prep\n', source_id: 'source-a' }, config, { brain: 'host', cwd: dir });
+ expect(put.handled).toBe(true);
+ expect([calls.at(-1)!.params.source_id, calls.at(-1)!.routing.source]).toEqual(['source-a', 'source-a']);
+ const get = await maybeDelegateLocalOperation('get_page', { slug: 'notes/board-prep', source_id: 'source-a' }, config, { brain: 'host', cwd: dir });
+ expect(get.handled).toBe(true);
+ expect([calls.at(-1)!.params.source_id, calls.at(-1)!.routing.source]).toEqual(['source-a', null]);
+ });
+ } finally {
+ if (binding) { const closed = once(binding.server, 'close'); binding.close(); await closed; }
+ await releaseLock(lock);
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }, 60_000);
+});
diff --git a/test/setup-brain-layout.test.ts b/test/setup-brain-layout.test.ts
index f55bb721f5..ec36c96de0 100644
--- a/test/setup-brain-layout.test.ts
+++ b/test/setup-brain-layout.test.ts
@@ -446,6 +446,51 @@ describe('setup --transcripts', () => {
expect(who.members).toEqual(['alice-example']);
}
}, 300_000);
+
+ test('GBRA-585: a company setup whose member keys do not read company says no member key setup minted reads the calls yet', async () => {
+ const b = box();
+ expect((await setup(b, ['claude-code', '--serves', 'several', '--members', 'alice-example,bob-example', '--shape', 'company'])).exitCode).toBe(0);
+ for (const m of ['alice-example', 'bob-example']) expect((await gbrain(b, ['auth', 'rescope', '--token', `member-${m}`, '--sources', 'default'])).exitCode).toBe(0);
+ const r = await setup(b, ['claude-code', '--serves', 'several', '--members', 'alice-example,bob-example', '--shape', 'company', '--transcripts', callsDir(b, plantedToken())]);
+ expect(r.exitCode).toBe(0);
+ expect(r.doc.brain_layout.company).toMatchObject({ action: 'kept', federated: false });
+ expect(r.doc.serves.regrant).toBeUndefined();
+ const t = r.doc.brain_layout.transcripts;
+ expect(t.imported).toBe(3);
+ expect(t.readers).toMatchObject({ members: 'every_source_reader', serves: 'several' });
+ expect(t.readers.detail).toStartWith('no member key setup minted reads them yet: source company is not federated');
+ expect(t.readers.detail).toContain('gbrain sources federate company');
+ expect(t.readers.detail).toContain('this brain serves several people: alice-example, bob-example');
+ expect(t.readers.detail).not.toContain('every member key gbrain setup minted');
+ }, 300_000);
+
+ test('GBRA-585: setup for several people says the member keys it minted read the imported calls, and why the archive is on', async () => {
+ const b = box();
+ const r = await setup(b, ['claude-code', '--serves', 'several', '--members', 'alice-example,bob-example', '--shape', 'company', '--transcripts', callsDir(b, plantedToken())]);
+ expect(r.exitCode).toBe(0);
+ expect(r.doc.brain_layout.company).toMatchObject({ action: 'created', federated: false });
+ expect(r.doc.serves.engine).toContain('gbrain migrate --to postgres');
+ const t = r.doc.brain_layout.transcripts;
+ expect(t.imported).toBe(3);
+ expect(t.readers.members).toBe('every_source_reader');
+ expect(t.readers.serves).toBe('several');
+ expect(t.readers.detail).toStartWith('every member key gbrain setup minted, and other keys only when their grant names source company or it is in default search');
+ expect(t.readers.detail).toContain('this brain serves several people: alice-example, bob-example');
+ expect(r.doc.serves.regrant.keys.map((k: any) => [k.member, k.adds])).toEqual([['alice-example', ['company']], ['bob-example', ['company']]]);
+ const archive = r.doc.brain_layout.archive;
+ expect(archive.state).toBe('on');
+ expect(archive.detail).toStartWith('on for now: this brain serves several people');
+ expect(archive.detail).toContain('gbrain config set brain.audience shared');
+ const status = await gbrain(b, ['transcripts', 'archive', 'status']);
+ expect(status.stdout).toContain('conversation archive: on');
+ expect(status.stdout).toContain(' why: on for now: this brain serves several people');
+ const doctor = JSON.parse((await gbrain(b, ['doctor', '--only', 'transcript_archive_freshness', '--json'])).stdout);
+ const check = doctor.checks.find((c: any) => c.name === 'transcript_archive_freshness');
+ expect(check.message).toContain('Conversation archive is on (on for now: this brain serves several people');
+ expect(check.details).toMatchObject({ enabled: true, enabled_by: 'default', serves_several: true });
+ const help = await gbrain(b, ['transcripts', '--help']);
+ expect(help.stdout).not.toContain('off unless turned on');
+ }, 300_000);
});
describe('transcripts units', () => {
diff --git a/test/setup-company-access.test.ts b/test/setup-company-access.test.ts
new file mode 100644
index 0000000000..6650b509bc
--- /dev/null
+++ b/test/setup-company-access.test.ts
@@ -0,0 +1,503 @@
+/**
+ * GBRA-585 PR 1: company-brain setup decisions D (setup names the owner), A (setup's member keys read the company
+ * source) and C (setup refuses to turn a brain with history shared until the admin picks).
+ *
+ * 1. Protects: `gbrain access serves several --owner <id>` (what `gbrain setup <harness> --serves several` runs) names
+ * the brain owner when none is set, keeps an existing one, rebinds no credential and lists the live credentials
+ * bound to no member with the command that binds each; nothing it does narrows what an owner-bound credential reads.
+ * 2. Fails when: setup leaves the brain with no owner, replaces an owner, binds a credential on its own, or an
+ * owner-bound credential reads a different set of pages after setup.
+ * 3. Existing coverage: setup-serves-several.test.ts (members, rules, keys), access-owner tests (access owner set).
+ * 4. Real seams: labelSeveral on PGLite and Postgres (repo-less), the key verified by the serve --http verifier and
+ * dispatched remote=true; `bun src/cli.ts setup` spawned against a temp HOME / GBRAIN_HOME.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { userInfo } from 'node:os';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { AuthInfo } from '../src/core/ops/contract.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { noGrantFederatedScope } from '../src/core/source-resolver.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { labelSeveral, receiptLines, receiptOk } from '../src/commands/access-serves.ts';
+import { applyApproved, previewApply } from '../src/core/access/policy.ts';
+import { historyRefusal } from '../src/commands/setup-serves.ts';
+import { currentFolderRules } from '../src/commands/access-rules.ts';
+import { mintToken } from '../src/commands/auth-mint.ts';
+import { addMember } from '../src/core/access/members.ts';
+import { ownerMemberId, setOwner } from '../src/core/access/owner.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { box, gbrain, memoryBrain, openBrainFile, pageText, removeTempDirs, setup, tempDir } from './helpers/setup-serves-box.ts';
+
+afterAll(removeTempDirs);
+
+const ROSTER = ['alice-example', 'bob-example'];
+/** Pages outside the roster's people/ folders, so labelling the roster changes nothing an owner-bound key reads. */
+const PAGES: Record<string, string> = {
+ 'notes/world-topic': 'worldcanary',
+ 'journal/owner-day': 'journalcanary',
+ 'people/carol-public': 'carolcanary',
+};
+
+async function openEngine(kind: string): Promise<{ engine: BrainEngine; close: () => Promise<void> }> {
+ if (kind === 'postgres') return isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ const engine = await memoryBrain();
+ return { engine, close: () => engine.disconnect() };
+}
+
+/** The canaries a keyword search through `token` returns, read remotely as the serve --http verifier does. */
+async function tokenReads(engine: BrainEngine, token: string, canaries: string[], sourceIds?: string[]): Promise<string[]> {
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const auth = await provider.verifyAccessToken(token) as unknown as AuthInfo;
+ const sourceId = auth.sourceId ?? 'default';
+ const localFederated = await noGrantFederatedScope(engine, auth.hasSourceGrant, sourceId);
+ const out = await dispatchToolCall(engine, 'search', { query: 'harbor ledger notes', match: 'keyword', fields: 'full', limit: 50, ...(sourceIds ? { source_ids: sourceIds } : {}) }, {
+ remote: true, transport: 'http', auth, sourceId, takesHoldersAllowList: auth.takesHoldersAllowList ?? ['world'], ...(localFederated ? { localFederatedSourceIds: localFederated } : {}) });
+ const text = out.content.map(c => c.text).join('\n');
+ return canaries.filter(c => text.includes(c)).sort();
+}
+
+for (const kind of testBackends()) {
+ describe(`D: access serves several names the owner (${kind}, repo-less)`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let home: string;
+ const label = (roster: string[], owner?: string) => withEnv({ GBRAIN_HOME: home, GBRAIN_SETUP_ABORT_AFTER: undefined },
+ () => labelSeveral(engine, roster, 'default', true, true, { ...(owner ? { owner } : {}) } as never));
+
+ beforeAll(async () => {
+ ({ engine, close } = await openEngine(kind));
+ home = tempDir('gbrain-owner-');
+ for (const [slug, canary] of Object.entries(PAGES)) await importFromContent(engine, slug, pageText(slug, canary), { sourceId: 'default', noEmbed: true });
+ }, 120_000);
+ afterAll(async () => { await close?.(); }, 60_000);
+
+ test('no owner: --owner adds the member, names it the owner, binds nothing and lists each unbound credential with its rescope command', async () => {
+ const unbound = await mintToken(engine, 'claude-desktop', { scopes: ['read', 'write'] });
+ expect(await ownerMemberId(engine)).toBeNull();
+ const r = await label(ROSTER, 'owner-example') as any;
+ expect(r.error).toBeUndefined();
+ expect(r.owner).toEqual({ id: 'owner-example', action: 'add' });
+ expect(r.completed).toContain('owner');
+ expect(await ownerMemberId(engine)).toBe('owner-example');
+ expect(r.unbound).toEqual([{ kind: 'token', name: 'claude-desktop', command: 'gbrain auth rescope --token claude-desktop --member owner-example' }]);
+ const [row] = await engine.executeRaw<{ member_id: string | null }>('SELECT member_id FROM access_tokens WHERE id = $1', [unbound.id]);
+ expect(row!.member_id).toBeNull();
+ const again = await label(ROSTER, 'owner-example') as any;
+ expect(again.owner).toEqual({ id: 'owner-example', action: 'keep' });
+ }, 120_000);
+ });
+
+ describe(`D: an existing owner is kept and its credential reads the same pages (${kind}, repo-less)`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let home: string;
+ beforeAll(async () => {
+ ({ engine, close } = await openEngine(kind));
+ home = tempDir('gbrain-owner-kept-');
+ for (const [slug, canary] of Object.entries(PAGES)) await importFromContent(engine, slug, pageText(slug, canary), { sourceId: 'default', noEmbed: true });
+ }, 120_000);
+ afterAll(async () => { await close?.(); }, 60_000);
+
+ test("an owner set by hand stays the owner, and the owner's bound key reads the same pages before and after", async () => {
+ await addMember(engine, 'owner-example');
+ await setOwner(engine, 'owner-example');
+ const ownerKey = await mintToken(engine, 'owner-laptop', { scopes: ['read', 'write'], binding: { member: 'owner-example' } });
+ const canaries = Object.values(PAGES);
+ const before = await tokenReads(engine, ownerKey.token, canaries);
+ expect(before).toEqual([...canaries].sort());
+ const r = await withEnv({ GBRAIN_HOME: home, GBRAIN_SETUP_ABORT_AFTER: undefined }, () => labelSeveral(engine, ROSTER, 'default', true, true, { owner: 'login-example' } as never)) as any;
+ expect(r.error).toBeUndefined();
+ expect(r.owner).toMatchObject({ id: 'owner-example', action: 'keep' });
+ expect(await ownerMemberId(engine)).toBe('owner-example');
+ expect((await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM access_members WHERE id = 'login-example'"))[0]!.n).toBe(0);
+ expect(await tokenReads(engine, ownerKey.token, canaries)).toEqual(before);
+ }, 120_000);
+ });
+}
+
+describe('D: gbrain setup --serves several names the owner (spawned, PGLite)', () => {
+ const login = (() => { try { return userInfo().username; } catch { return ''; } })().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[^a-z0-9]+/, '').slice(0, 64).replace(/[._-]+$/, '');
+
+ test('--owner: the preview shows it and writes nothing; the run sets it, binds no credential and prints each unbound one with its rescope command', async () => {
+ const b = box();
+ expect((await gbrain(b, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);
+ expect((await gbrain(b, ['auth', 'create', 'claude-desktop', '--scopes', 'read,write'])).exitCode).toBe(0);
+ const preview = await setup(b, ['claude-code', '--serves', 'several', '--members', ROSTER.join(','), '--owner', 'owner-example', '--dry-run']);
+ expect(preview.exitCode).toBe(0);
+ expect(preview.stdout).toContain('owner owner-example (will add a member and name it the brain owner)');
+ expect(preview.stdout).toContain('gbrain auth rescope --token claude-desktop --member owner-example');
+ expect(JSON.parse((await gbrain(b, ['access', 'owner', '--json'])).stdout).owner).toBeNull();
+ expect(existsSync(join(b.home, '.claude.json'))).toBe(false);
+ const run = await setup(b, ['claude-code', '--serves', 'several', '--members', ROSTER.join(','), '--owner', 'owner-example']);
+ expect(run.exitCode).toBe(0);
+ expect(run.stdout).toContain('owner owner-example (added a member and named it the brain owner)');
+ const owner = JSON.parse((await gbrain(b, ['access', 'owner', '--json'])).stdout);
+ expect(owner.owner).toBe('owner-example');
+ expect(owner.bound_credentials).toEqual([]);
+ const kept = await setup(b, ['claude-code', '--serves', 'several', '--members', ROSTER.join(','), '--owner', 'other-example', '--json']);
+ expect(kept.exitCode).toBe(0);
+ expect(kept.doc.serves.receipt.owner).toMatchObject({ id: 'owner-example', action: 'keep' });
+ expect(JSON.parse((await gbrain(b, ['access', 'owner', '--json'])).stdout).owner).toBe('owner-example');
+ }, 480_000);
+
+ test('without --owner the owner is the login name as a member id, and setup says how to name someone else', async () => {
+ const b = box();
+ expect((await gbrain(b, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);
+ const preview = await setup(b, ['claude-code', '--serves', 'several', '--members', ROSTER.join(','), '--dry-run']);
+ expect(preview.exitCode).toBe(0);
+ expect(preview.stdout).toContain(`owner ${login} is named from your login name; to name someone else, pass --owner <id>`);
+ const run = await setup(b, ['claude-code', '--serves', 'several', '--members', ROSTER.join(','), '--json']);
+ expect(run.exitCode).toBe(0);
+ expect(run.doc.serves).toMatchObject({ owner_from: 'login', receipt: { owner: { id: login, action: 'add' } } });
+ expect(JSON.parse((await gbrain(b, ['access', 'owner', '--json'])).stdout).owner).toBe(login);
+ }, 480_000);
+});
+
+const COMPANY: Record<string, string> = {
+ 'company/facts': 'factscanary',
+ 'company/calls/2026-11-01-hiring-debrief': 'callcanary',
+ 'company/board/owner-only': 'boardcanary',
+};
+const companyText = (slug: string, canary: string) => slug === 'company/board/owner-only'
+ ? `---\ntype: note\ntitle: ${slug}\nreadable_by: [owner-example]\n---\n# ${slug}\n\nHarbor ledger notes ${canary}.\n`
+ : pageText(slug, canary);
+const keyFile = (home: string, member: string) => join(home, '.gbrain', 'member-keys', `${member}.key`);
+const tokenRow = async (engine: BrainEngine, name: string) => (await engine.executeRaw<{ source_grant: string; source_id: string | null; federated_read: unknown }>(
+ 'SELECT source_grant, source_id, federated_read FROM access_tokens WHERE name = $1 AND revoked_at IS NULL', [name]))[0]!;
+const list = (v: unknown) => Array.isArray(v) ? v : String(v ?? '').replace(/^\{|\}$/g, '').split(',').filter(Boolean);
+
+for (const kind of testBackends()) {
+ describe(`A: setup's member keys read the company source (${kind}, repo-less)`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let home: string;
+ let ownerKey: string;
+ const ALL = [...Object.values(PAGES), ...Object.values(COMPANY), 'alicecanary', 'bobcanary'];
+ const label = (roster: string[], apply = true) => withEnv({ GBRAIN_HOME: home, GBRAIN_SETUP_ABORT_AFTER: undefined }, () => labelSeveral(engine, roster, 'default', apply, true, { owner: 'owner-example' }));
+
+ beforeAll(async () => {
+ ({ engine, close } = await openEngine(kind));
+ home = tempDir('gbrain-company-');
+ for (const [slug, canary] of Object.entries(PAGES)) await importFromContent(engine, slug, pageText(slug, canary), { sourceId: 'default', noEmbed: true });
+ for (const m of ['alice-example', 'bob-example']) await importFromContent(engine, `people/${m}/plan`, pageText(`people/${m}/plan`, `${m.split('-')[0]}canary`), { sourceId: 'default', noEmbed: true });
+ await engine.executeRaw("INSERT INTO sources (id, name, config) VALUES ('company', 'company', '{}'::jsonb) ON CONFLICT (id) DO NOTHING");
+ for (const [slug, canary] of Object.entries(COMPANY)) await importFromContent(engine, slug, companyText(slug, canary), { sourceId: 'company', noEmbed: true });
+ await addMember(engine, 'owner-example');
+ await setOwner(engine, 'owner-example');
+ ownerKey = (await mintToken(engine, 'owner-laptop', { scopes: ['read', 'write'], binding: { member: 'owner-example' } })).token;
+ await addMember(engine, 'carol-example');
+ const carol = await mintToken(engine, 'member-carol-example', { scopes: ['read', 'write'], binding: { member: 'carol-example' } });
+ mkdirSync(join(home, '.gbrain', 'member-keys'), { recursive: true, mode: 0o700 });
+ writeFileSync(keyFile(home, 'carol-example'), `${carol.token}\n`, { mode: 0o600 });
+ }, 120_000);
+ afterAll(async () => { await close?.(); }, 60_000);
+
+ test('the preview names the read set, the company pages and calls, and says a later-federated source waits for a re-run', async () => {
+ const preview = await label(['alice-example', 'bob-example', 'carol-example'], false) as any;
+ expect(preview.reads).toEqual({ write: 'default', sources: ['default', 'company'], company: { pages: 3, calls: 1 } });
+ const text = receiptLines(preview).join('\n');
+ expect(text).toContain('reads keys this run mints write to default and read default, company');
+ expect(text).toContain('source company holds 3 page(s), 1 of them imported calls');
+ expect(text).toContain("including calls they did not attend");
+ expect(text).toContain('A source federated later does not reach these keys until you run setup again');
+ expect((await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM access_members WHERE id = 'alice-example'"))[0]!.n).toBe(0);
+ }, 120_000);
+
+ test("new keys get a source list with company; a key minted before is kept as it is; the owner's key reads the same pages", async () => {
+ // The roster's own people/<member>/ folders are closed to the owner by the folder rules access serves several already
+ // wrote on master; this PR does not change them, so the owner's reads are compared on every other page.
+ const OWNER_SEES = ALL.filter(c => c !== 'alicecanary' && c !== 'bobcanary');
+ const ownerBefore = await tokenReads(engine, ownerKey, OWNER_SEES);
+ expect(ownerBefore).toEqual(['carolcanary', 'journalcanary', 'worldcanary']);
+ const r = await label(['alice-example', 'bob-example', 'carol-example']);
+ expect(r.error).toBeUndefined();
+ for (const m of ['alice-example', 'bob-example']) {
+ const row = await tokenRow(engine, `member-${m}`);
+ expect([row.source_grant, row.source_id, list(row.federated_read)]).toEqual(['federated', 'default', ['default', 'company']]);
+ }
+ expect((await tokenRow(engine, 'member-carol-example')).source_grant).toBe('default');
+ const alice = await tokenReads(engine, readFileSync(keyFile(home, 'alice-example'), 'utf8').trim(), ALL);
+ expect(alice).toContain('callcanary');
+ expect(alice).toContain('factscanary');
+ expect(alice).toContain('alicecanary');
+ expect(alice).not.toContain('bobcanary');
+ expect(alice).not.toContain('boardcanary');
+ expect(await tokenReads(engine, readFileSync(keyFile(home, 'carol-example'), 'utf8').trim(), ALL)).not.toContain('callcanary');
+ const [company] = await engine.executeRaw<{ config: unknown }>("SELECT config FROM sources WHERE id = 'company'");
+ expect(JSON.stringify(company!.config)).not.toContain('"federated":true');
+ expect(await tokenReads(engine, ownerKey, OWNER_SEES)).toEqual(ownerBefore);
+ }, 120_000);
+
+ test('a re-run adds a newly federated source to the list keys and never removes one; default-grant keys stay as they are', async () => {
+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ('guests', 'guests', '{"federated":true}'::jsonb) ON CONFLICT (id) DO NOTHING`);
+ const r = await label(['alice-example', 'bob-example', 'carol-example']) as any;
+ expect(r.error).toBeUndefined();
+ expect(r.keys.map((k: any) => [k.member, k.action, k.adds ?? []])).toEqual([['alice-example', 'keep', ['guests']], ['bob-example', 'keep', ['guests']], ['carol-example', 'keep', []]]);
+ expect(list((await tokenRow(engine, 'member-alice-example')).federated_read)).toEqual(['default', 'company', 'guests']);
+ expect((await tokenRow(engine, 'member-carol-example')).source_grant).toBe('default');
+ await engine.executeRaw("UPDATE sources SET config = '{}'::jsonb WHERE id = 'guests'");
+ const again = await label(['alice-example', 'bob-example', 'carol-example']) as any;
+ expect(again.keys.every((k: any) => !k.adds?.length)).toBe(true);
+ expect(list((await tokenRow(engine, 'member-alice-example')).federated_read)).toEqual(['default', 'company', 'guests']);
+ }, 120_000);
+ });
+}
+
+describe('A: gbrain setup --shape company --transcripts gives the members the calls (spawned, PGLite)', () => {
+ test("on a new brain each member's key reads an imported call, and the readers line says who reads them", async () => {
+ const b = box();
+ const dir = join(b.root, 'calls');
+ mkdirSync(dir);
+ writeFileSync(join(dir, '2026-03-04 acme-example renewal.txt'), 'Alice: harbor ledger notes callcanary, we agreed to move acme-example to annual billing.\n');
+ const r = await setup(b, ['claude-code', '--serves', 'several', '--members', ROSTER.join(','), '--owner', 'owner-example', '--shape', 'company', '--transcripts', dir, '--json']);
+ expect(r.exitCode).toBe(0);
+ expect(r.doc.serves.regrant.keys.map((k: any) => [k.member, k.adds])).toEqual([['alice-example', ['company']], ['bob-example', ['company']]]);
+ expect(r.doc.brain_layout.transcripts.readers.detail).toMatch(/^every member key gbrain setup minted, and other keys only when their grant names source company/);
+ expect(r.doc.brain_layout.transcripts.readers.detail).not.toContain('everyone who can read source company');
+ const engine = await openBrainFile(b.home);
+ try {
+ for (const m of ROSTER) expect(await tokenReads(engine, readFileSync(keyFile(b.home, m), 'utf8').trim(), ['callcanary'])).toEqual(['callcanary']);
+ } finally {
+ await engine.disconnect();
+ }
+ }, 480_000);
+});
+
+
+const HISTORY: Record<string, string> = {
+ 'journal/owner-day': 'journalcanary',
+ 'conversations/claude-code/2026-11-01/plan-abc12345': 'archivecanary',
+};
+const historyText = (slug: string, canary: string) => `---\ntype: ${slug.startsWith('conversations/') ? 'conversation' : 'note'}\ntitle: ${slug}\n---\n# ${slug}\n\nHarbor ledger notes ${canary}.\n`;
+
+for (const kind of testBackends()) {
+ describe(`C: turning a brain with history shared needs a choice (${kind}, repo-less)`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let home: string;
+ beforeAll(async () => {
+ ({ engine, close } = await openEngine(kind));
+ home = tempDir('gbrain-history-');
+ for (const [slug, canary] of Object.entries(HISTORY)) await importFromContent(engine, slug, historyText(slug, canary), { sourceId: 'default', noEmbed: true });
+ }, 120_000);
+ afterAll(async () => { await close?.(); }, 60_000);
+
+ test('the refusal names the count, the DMs/chat/mail and archive share and both choices; --labelled-only keeps the history from members, not from the owner', async () => {
+ await addMember(engine, 'owner-example');
+ await setOwner(engine, 'owner-example');
+ const ownerKey = (await mintToken(engine, 'owner-laptop', { scopes: ['read', 'write'], binding: { member: 'owner-example' } })).token;
+ const canaries = Object.values(HISTORY);
+ const ownerBefore = await tokenReads(engine, ownerKey, canaries);
+ expect(ownerBefore).toEqual([...canaries].sort());
+ const flags = { serves: 'several' as const, dryRun: false };
+ const status = { serves: 'one' as const, from: 'derived' as const, enabled_members: ['owner-example'], since: null, owner: 'owner-example', stdio_member: null } as never;
+ const preview = await withEnv({ GBRAIN_HOME: home }, () => labelSeveral(engine, ROSTER, 'default', false, true, { owner: 'owner-example' }));
+ const refusal = historyRefusal(status, preview, flags, 'claude-code', ROSTER, { id: 'owner-example', from: 'flag' });
+ expect(refusal).toMatchObject({ code: 'setup_history_choice_required' });
+ expect(refusal!.message).toContain('2 page(s)');
+ expect(refusal!.message).toContain('1 of them DMs, chat or mail');
+ expect(refusal!.message).toContain('1 in the conversation archive');
+ expect(refusal!.suggestion).toContain('--labelled-only');
+ expect(refusal!.suggestion).toContain('--open-history');
+ expect(historyRefusal(status, preview, { ...flags, openHistory: true }, 'claude-code', ROSTER, undefined)).toBeNull();
+ expect(historyRefusal(status, preview, { ...flags, labelledOnly: true }, 'claude-code', ROSTER, undefined)).toBeNull();
+ expect(historyRefusal({ ...(status as object), serves: 'several' } as never, preview, flags, 'claude-code', ROSTER, undefined)).toBeNull();
+ expect(historyRefusal(status, { ...preview, open_pages: { ...preview.open_pages!, total: 0 } }, flags, 'claude-code', ROSTER, undefined)).toBeNull();
+ const r = await withEnv({ GBRAIN_HOME: home }, () => labelSeveral(engine, ROSTER, 'default', true, true, { owner: 'owner-example', labelledOnly: true }));
+ expect(r.error).toBeUndefined();
+ const alice = readFileSync(keyFile(home, 'alice-example'), 'utf8').trim();
+ expect(await tokenReads(engine, alice, canaries)).toEqual([]);
+ expect(await tokenReads(engine, ownerKey, canaries)).toEqual(ownerBefore);
+ }, 120_000);
+ });
+}
+
+describe('C: gbrain setup --serves several on a brain with history (spawned, PGLite)', () => {
+ async function historyBox() {
+ const b = box();
+ expect((await gbrain(b, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);
+ for (const [slug, canary] of Object.entries(HISTORY)) expect((await gbrain(b, ['put', slug, '--content', historyText(slug, canary)])).exitCode).toBe(0);
+ return b;
+ }
+ const memberReads = async (b: ReturnType<typeof box>, member: string) => {
+ const engine = await openBrainFile(b.home);
+ try { return await tokenReads(engine, readFileSync(keyFile(b.home, member), 'utf8').trim(), Object.values(HISTORY)); } finally { await engine.disconnect(); }
+ };
+ const args = ['claude-code', '--serves', 'several', '--members', ROSTER.join(','), '--owner', 'owner-example'];
+
+ test('without a choice setup refuses and writes nothing; --labelled-only keeps the history private; a brain already shared is not refused', async () => {
+ const b = await historyBox();
+ const refused = await setup(b, [...args, '--json']);
+ expect(refused.exitCode).not.toBe(0);
+ expect(refused.stdout + refused.stderr).toContain('setup_history_choice_required');
+ expect(existsSync(join(b.home, '.claude.json'))).toBe(false);
+ const status = JSON.parse((await gbrain(b, ['access', 'serves', '--json', '--no-open-pages'])).stdout);
+ expect(status).toMatchObject({ serves: 'one', enabled_members: [] });
+ const run = await setup(b, [...args, '--labelled-only']);
+ expect(run.exitCode).toBe(0);
+ expect(await memberReads(b, 'alice-example')).toEqual([]);
+ const again = await setup(b, args);
+ expect(again.exitCode).toBe(0);
+ }, 480_000);
+
+ test('--open-history lets the members read it', async () => {
+ const b = await historyBox();
+ const run = await setup(b, [...args, '--open-history']);
+ expect(run.exitCode).toBe(0);
+ expect(await memberReads(b, 'alice-example')).toEqual(['archivecanary', 'journalcanary']);
+ }, 480_000);
+
+ test('a new brain is not asked: one this run creates, and one with no pages yet', async () => {
+ const fresh = box();
+ expect((await setup(fresh, args)).exitCode).toBe(0);
+ const empty = box();
+ expect((await gbrain(empty, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);
+ expect((await setup(empty, args)).exitCode).toBe(0);
+ }, 480_000);
+});
+
+
+
+const COMPANY_CANARIES = ['factscanary', 'callcanary', 'boardcanary'];
+const companyRules = (engine: BrainEngine) => currentFolderRules(engine, 'company');
+
+for (const kind of testBackends()) {
+ describe(`C: labelled-only members read the company pages through one company/ rule (${kind}, repo-less)`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let home: string;
+ let ownerKey: string;
+ const label = (roster: string[], labelledOnly: boolean, apply = true) => withEnv({ GBRAIN_HOME: home, GBRAIN_SETUP_ABORT_AFTER: undefined },
+ () => labelSeveral(engine, roster, 'default', apply, true, { owner: 'owner-example', labelledOnly }));
+ const memberReads = (member: string) => tokenReads(engine, readFileSync(keyFile(home, member), 'utf8').trim(), COMPANY_CANARIES);
+
+ beforeAll(async () => {
+ ({ engine, close } = await openEngine(kind));
+ home = tempDir('gbrain-company-rule-');
+ await engine.executeRaw("INSERT INTO sources (id, name, config) VALUES ('company', 'company', '{}'::jsonb) ON CONFLICT (id) DO NOTHING");
+ for (const [slug, canary] of Object.entries(COMPANY)) await importFromContent(engine, slug, companyText(slug, canary), { sourceId: 'company', noEmbed: true });
+ await addMember(engine, 'owner-example');
+ await setOwner(engine, 'owner-example');
+ ownerKey = (await mintToken(engine, 'owner-laptop', { scopes: ['read', 'write'], binding: { member: 'owner-example' },
+ sources: { kind: 'federated', writeSource: 'default', readSources: ['default', 'company'] } })).token;
+ }, 120_000);
+ afterAll(async () => { await close?.(); }, 60_000);
+
+ test('a run that is not labelled-only adds no company rule', async () => {
+ const r = await label(['dave-example'], false) as any;
+ expect(r.error).toBeUndefined();
+ expect(r.company_rule).toBeUndefined();
+ expect(await companyRules(engine)).toEqual([]);
+ expect(await memberReads('dave-example')).toEqual(['callcanary', 'factscanary']);
+ }, 120_000);
+
+ test("the preview shows the rule and writes nothing; the run adds company/ for the owner and every member; members read company/facts and a call; the owner's key reads the same", async () => {
+ const ownerBefore = await tokenReads(engine, ownerKey, COMPANY_CANARIES);
+ expect(ownerBefore).toEqual(['boardcanary', 'callcanary', 'factscanary']);
+ const preview = await label(['alice-example', 'bob-example'], true, false) as any;
+ expect(preview.company_rule).toMatchObject({ source: 'company', id: 'company', prefix: 'company/', action: 'add',
+ readers: ['member:alice-example', 'member:bob-example', 'member:dave-example', 'member:owner-example'] });
+ expect(receiptLines(preview).join('\n')).toContain('rule company:company/ readable by alice-example, bob-example, dave-example, owner-example (will add)');
+ expect(await companyRules(engine)).toEqual([]);
+ const r = await label(['alice-example', 'bob-example'], true) as any;
+ expect(r.error).toBeUndefined();
+ expect((await companyRules(engine)).map(x => [x.id, x.prefix, x.readable_by])).toEqual([['company', 'company/', ['member:alice-example', 'member:bob-example', 'member:dave-example', 'member:owner-example']]]);
+ for (const m of ['alice-example', 'bob-example', 'dave-example']) expect(await memberReads(m)).toEqual(['callcanary', 'factscanary']);
+ expect(await tokenReads(engine, ownerKey, COMPANY_CANARIES)).toEqual(ownerBefore);
+ }, 120_000);
+
+ test('a re-run with one more member adds that member and keeps every reader', async () => {
+ const r = await label(['alice-example', 'bob-example', 'carol-example'], true) as any;
+ expect(r.error).toBeUndefined();
+ expect(r.company_rule).toMatchObject({ action: 'add', adds: ['member:carol-example'], write: { state: 'recorded' } });
+ expect(receiptOk(r)).toBe(true);
+ expect(receiptLines(r).join('\n')).toContain('the added readers wait for approval, as every widening does: preview with gbrain access apply --source company');
+ expect((await companyRules(engine))[0]!.readable_by).toEqual(['member:alice-example', 'member:bob-example', 'member:carol-example', 'member:dave-example', 'member:owner-example']);
+ expect(await memberReads('carol-example')).toEqual([]);
+ const plan = await previewApply(engine, 'company');
+ await applyApproved(engine, 'company', { expect: plan.plan_hash! });
+ expect(await memberReads('carol-example')).toEqual(['callcanary', 'factscanary']);
+ for (const m of ['alice-example', 'bob-example', 'dave-example']) expect(await memberReads(m)).toEqual(['callcanary', 'factscanary']);
+ const again = await label(['alice-example'], true) as any;
+ expect(again.company_rule).toMatchObject({ action: 'keep' });
+ expect((await companyRules(engine))[0]!.readable_by).toHaveLength(5);
+ }, 120_000);
+ });
+}
+
+describe('C: gbrain setup --shape company --labelled-only gives labelled-only members the calls (spawned, PGLite)', () => {
+ test('each labelled-only member reads an imported call through the company/ rule', async () => {
+ const b = box();
+ const dir = join(b.root, 'calls');
+ mkdirSync(dir);
+ writeFileSync(join(dir, '2026-03-04 acme-example renewal.txt'), 'Alice: harbor ledger notes callcanary, we agreed to move acme-example to annual billing.\n');
+ const r = await setup(b, ['claude-code', '--serves', 'several', '--members', ROSTER.join(','), '--owner', 'owner-example', '--shape', 'company', '--transcripts', dir, '--labelled-only', '--json']);
+ expect(r.exitCode).toBe(0);
+ expect(r.doc.serves.regrant.company_rule).toMatchObject({ prefix: 'company/', action: 'add', readers: ['member:alice-example', 'member:bob-example', 'member:owner-example'] });
+ expect(r.doc.brain_layout.transcripts.readers).toMatchObject({ members: ['alice-example', 'bob-example', 'owner-example'], serves: 'several' });
+ expect(r.doc.brain_layout.transcripts.readers.detail).toMatch(/^alice-example, bob-example, owner-example only \(the company\/ rule on source company names them/);
+ const engine = await openBrainFile(b.home);
+ try {
+ for (const m of ROSTER) expect(await tokenReads(engine, readFileSync(keyFile(b.home, m), 'utf8').trim(), ['callcanary'])).toEqual(['callcanary']);
+ } finally {
+ await engine.disconnect();
+ }
+ }, 480_000);
+});
+
+
+test('C: a preview that failed or could not count the pages still refuses (fail closed)', () => {
+ const status = { serves: 'one', from: 'derived', enabled_members: [], since: null, owner: null, stdio_member: null } as never;
+ const flags = { serves: 'several' as const, dryRun: false };
+ const failed = historyRefusal(status, null, flags, 'claude-code', ROSTER, undefined);
+ expect(failed).toMatchObject({ code: 'setup_history_choice_required' });
+ expect(failed!.message).toContain('pages setup could not count (the preview failed)');
+ const uncounted = historyRefusal(status, { members: [], open_pages: null, open_pages_error: { code: 'open_pages_timeout', message: 'x', retry: 'y' } } as never, flags, 'claude-code', ROSTER, undefined);
+ expect(uncounted!.message).toContain('pages setup could not count (open_pages_timeout)');
+ expect(historyRefusal(status, null, { ...flags, labelledOnly: true }, 'claude-code', ROSTER, undefined)).toBeNull();
+});
+
+test('C: the --labelled-only choice leaves the owner out of --members, so following it is not blocked', () => {
+ const status = { serves: 'one', from: 'derived', enabled_members: [], since: null, owner: null, stdio_member: null } as never;
+ const preview = { members: [], open_pages: { total: 3, sensitive: 0, archive: 0 } } as never;
+ const flags = { serves: 'several' as const, dryRun: false };
+ for (const owner of [{ id: 'alice-example', from: 'login' as const }, { id: 'alice-example', from: 'flag' as const }]) {
+ const refusal = historyRefusal(status, preview, flags, 'claude-code', ROSTER, owner)!;
+ const argv = (refusal.fix as { argv: string[] }).argv;
+ expect(argv.slice(argv.indexOf('--members'), argv.indexOf('--members') + 2)).toEqual(['--members', 'bob-example']);
+ expect(argv).toContain('--labelled-only');
+ expect(refusal.message + refusal.suggestion).toContain('--members alice-example,bob-example');
+ }
+});
+
+describe('C: the history refusal names the effective owner and the preview error (review fix-check)', () => {
+ const one = { serves: 'one', from: 'derived', enabled_members: [], since: null, owner: null, stdio_member: null };
+ const preview = { members: [], open_pages: { total: 3, sensitive: 0, archive: 0 } } as never;
+ const flags = { serves: 'several' as const, dryRun: false };
+ const argvOf = (e: unknown) => (e as { fix: { argv: string[] } }).fix.argv;
+ const membersOf = (argv: string[]) => argv[argv.indexOf('--members') + 1];
+
+ test('a configured owner wins over the login owner: it is the one left out of --members and named', () => {
+ const refusal = historyRefusal({ ...one, owner: 'alice-example' } as never, preview, flags, 'claude-code', ROSTER, { id: 'login-example', from: 'login' })!;
+ expect(membersOf(argvOf(refusal))).toBe('bob-example');
+ expect(refusal.suggestion).toContain('the owner alice-example reads the whole brain');
+ expect(refusal.suggestion).not.toContain('login-example');
+ });
+
+ test('a login owner left out of --members is pinned with --owner', () => {
+ const argv = argvOf(historyRefusal(one as never, preview, flags, 'claude-code', ROSTER, { id: 'alice-example', from: 'login' }));
+ expect(membersOf(argv)).toBe('bob-example');
+ expect(argv.slice(argv.indexOf('--owner'), argv.indexOf('--owner') + 2)).toEqual(['--owner', 'alice-example']);
+ });
+
+ test('a failed preview names the error the preview reported', () => {
+ const refusal = historyRefusal(one as never, null, flags, 'claude-code', ROSTER, undefined, 'access_serves_key_dir_in_git')!;
+ expect(refusal.message).toContain('the preview failed: access_serves_key_dir_in_git');
+ });
+});
diff --git a/test/setup-member-key-regrant-gbra585.test.ts b/test/setup-member-key-regrant-gbra585.test.ts
new file mode 100644
index 0000000000..92db3042db
--- /dev/null
+++ b/test/setup-member-key-regrant-gbra585.test.ts
@@ -0,0 +1,121 @@
+/**
+ * GBRA-585 A: what a setup re-run does to the member keys an earlier run minted with a source list.
+ *
+ * 1. Protects: a re-run re-grants a member key only while the key's source list is still the one setup last gave it
+ * (recorded on the key as permissions.setup_reads), so a key an admin narrowed by hand keeps its list, and the
+ * receipt names it as skipped with the rescope command that adds the sources; and a source archived since the key
+ * was minted is dropped from the list instead of failing every later re-run with invalid_grant.
+ * 2. Fails when: a re-run gives back a source an admin took off a key, names no skipped key, fails on an archived
+ * source, or stops adding new sources to a key it left as it minted it.
+ * 3. Existing coverage: setup-company-access.test.ts covers the first mint and the company regrant, not a hand rescope
+ * or an archived source.
+ * 4. No production seam: the real labelling and rescope on PGLite.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { labelSeveral, receiptLines } from '../src/commands/access-serves.ts';
+import { rescopeLegacyToken } from '../src/core/grants/legacy-token.ts';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { mintToken } from '../src/commands/auth-mint.ts';
+import { addMember } from '../src/core/access/members.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { memoryBrain, removeTempDirs, tempDir } from './helpers/setup-serves-box.ts';
+
+afterAll(removeTempDirs);
+
+const reads = async (e: PGLiteEngine, name: string) => [...((await e.executeRaw<{ f: string[] }>('SELECT federated_read AS f FROM access_tokens WHERE name = $1 AND revoked_at IS NULL', [name]))[0]?.f ?? [])];
+const addSource = (e: PGLiteEngine, id: string, federated = false) => e.executeRaw(`INSERT INTO sources (id, name, config) VALUES ($1, $1, $2::jsonb)`, [id, JSON.stringify(federated ? { federated: true } : {})]);
+async function brain() {
+ const e = await memoryBrain();
+ const home = tempDir('gbrain-regrant-');
+ const label = (roster: string[]) => withEnv({ GBRAIN_HOME: home, GBRAIN_SETUP_ABORT_AFTER: undefined }, () => labelSeveral(e, roster, 'default', true, true));
+ return { e, label, home };
+}
+
+describe('setup re-run and the member keys it minted', () => {
+ test('a key an admin changed by hand is skipped and named, and keeps its list', async () => {
+ const { e, label } = await brain();
+ await addSource(e, 'company');
+ await addSource(e, 'team-b', true);
+ await label(['alice-example']);
+ expect(await reads(e, 'member-alice-example')).toEqual(['default', 'company', 'team-b']);
+ await rescopeLegacyToken(e, { target: { name: 'member-alice-example' }, sources: ['default', 'team-b'], reset: [], refreshOperations: false, allNew: false, dryRun: false, json: true });
+ const r = await label(['alice-example', 'bob-example']);
+ expect(r.error).toBeUndefined();
+ expect(await reads(e, 'member-alice-example')).toEqual(['default', 'team-b']);
+ expect(await reads(e, 'member-bob-example')).toEqual(['default', 'company', 'team-b']);
+ const alice = r.keys.find(k => k.member === 'alice-example')!;
+ expect(alice.action).toBe('skipped');
+ expect(alice.adds).toBeUndefined();
+ expect(alice.detail).toContain('gbrain auth rescope --token member-alice-example --sources default,team-b,company');
+ expect(receiptLines(r).join('\n')).toContain('key alice-example: ');
+ expect(receiptLines(r).find(l => l.includes('alice-example:'))).toContain('skipped');
+ await e.disconnect();
+ }, 120_000);
+
+ test('a source archived since the key was minted is dropped, not a re-run failure', async () => {
+ const { e, label } = await brain();
+ await addSource(e, 'team-b', true);
+ await label(['alice-example']);
+ expect(await reads(e, 'member-alice-example')).toEqual(['default', 'team-b']);
+ await e.executeRaw("UPDATE sources SET archived = true WHERE id = 'team-b'");
+ await addSource(e, 'company');
+ const r = await label(['alice-example']);
+ expect(r.error).toBeUndefined();
+ expect(r.keys[0]).toMatchObject({ action: 'keep', adds: ['company'], reads: ['default', 'company'] });
+ expect(await reads(e, 'member-alice-example')).toEqual(['default', 'company']);
+ await e.disconnect();
+ }, 120_000);
+
+ test('a key whose write source is archived is blocked and keeps its write source', async () => {
+ const e = await memoryBrain();
+ const home = tempDir('gbrain-regrant-');
+ const label = () => withEnv({ GBRAIN_HOME: home, GBRAIN_SETUP_ABORT_AFTER: undefined }, () => labelSeveral(e, ['alice-example'], 'team-a', true, true));
+ const row = async () => (await e.executeRaw<{ source_id: string; f: string[] }>("SELECT source_id, federated_read AS f FROM access_tokens WHERE name = 'member-alice-example' AND revoked_at IS NULL"))[0]!;
+ await addSource(e, 'team-a');
+ await label();
+ const before = await row();
+ expect(before.source_id).toBe('team-a');
+ await e.executeRaw("UPDATE sources SET archived = true WHERE id = 'team-a'");
+ await addSource(e, 'company');
+ const r = await label();
+ const after = await row();
+ expect(after.source_id).toBe('team-a');
+ expect([...after.f]).toEqual([...before.f]);
+ expect(r.applied).toBe(false);
+ expect(r.keys[0]).toMatchObject({ action: 'blocked' });
+ expect(r.keys[0]!.detail).toContain('write source team-a is archived');
+ expect(r.keys[0]!.detail).toContain('gbrain auth rescope --token member-alice-example --sources <new write source>');
+ expect(r.keys[0]!.detail).toContain('gbrain auth revoke member-alice-example');
+ expect(receiptLines(r).find(l => l.includes('alice-example:'))).toContain('BLOCKED');
+ await e.disconnect();
+ }, 120_000);
+
+ test('a key a released gbrain minted (default grant, no setup_reads) is kept unchanged, never skipped', async () => {
+ const { e, label, home } = await brain();
+ await addMember(e, 'alice-example');
+ const minted = await mintToken(e, 'member-alice-example', { scopes: ['read', 'write'], binding: { member: 'alice-example' } });
+ mkdirSync(join(home, '.gbrain', 'member-keys'), { recursive: true, mode: 0o700 });
+ writeFileSync(join(home, '.gbrain', 'member-keys', 'alice-example.key'), `${minted.token}\n`, { mode: 0o600 });
+ await addSource(e, 'company');
+ const r = await label(['alice-example']);
+ expect(r.error).toBeUndefined();
+ expect(r.keys[0]).toMatchObject({ action: 'keep' });
+ expect(r.keys[0]!.adds).toBeUndefined();
+ expect((await e.executeRaw<{ g: string }>("SELECT source_grant AS g FROM access_tokens WHERE name = 'member-alice-example' AND revoked_at IS NULL"))[0]!.g).toBe('default');
+ await e.disconnect();
+ }, 120_000);
+
+ test('a key left as setup minted it still gains new sources on each re-run', async () => {
+ const { e, label } = await brain();
+ await label(['alice-example']);
+ expect(await reads(e, 'member-alice-example')).toEqual(['default']);
+ await addSource(e, 'company');
+ expect((await label(['alice-example'])).keys[0]).toMatchObject({ action: 'keep', adds: ['company'] });
+ await addSource(e, 'team-c', true);
+ expect((await label(['alice-example'])).keys[0]).toMatchObject({ action: 'keep', adds: ['team-c'] });
+ expect(await reads(e, 'member-alice-example')).toEqual(['default', 'company', 'team-c']);
+ await e.disconnect();
+ }, 120_000);
+});
diff --git a/test/setup-serves-several.test.ts b/test/setup-serves-several.test.ts
index 91f33ff075..353805720b 100644
--- a/test/setup-serves-several.test.ts
+++ b/test/setup-serves-several.test.ts
@@ -242,11 +242,14 @@ describe('labelling refuses or reports what it cannot make safe (pglite, repo-le
expect(again.keys[0]!.action).toBe('mint');
}, 60_000);
- test('keys minted for a named source are granted that source', async () => {
+ test('keys minted for a named source write to it and read it first (GBRA-585 A: a fixed source list)', async () => {
await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', ['team']);
const r = await label(['pat-example'], undefined, 'team');
expect(r.error).toBeUndefined();
- expect(await liveToken('member-pat-example')).toMatchObject({ source_grant: 'scalar' });
+ expect(await liveToken('member-pat-example')).toMatchObject({ source_grant: 'federated' });
+ const [row] = await engine.executeRaw<{ source_id: string; federated_read: unknown }>("SELECT source_id, federated_read FROM access_tokens WHERE name = 'member-pat-example' AND revoked_at IS NULL");
+ expect(row!.source_id).toBe('team');
+ expect(String(row!.federated_read).replace(/[{}]/g, '').split(',')[0]).toBe('team');
}, 60_000);
test('people folders no rule covers are reported, and the run is not ok', async () => {
@@ -268,13 +271,13 @@ describe('gbrain setup --serves (spawned, PGLite)', () => {
test('--serves several labels each person, proves it with bound reads, prints key paths never values; a re-run keeps it all', async () => {
const b = box();
await brainWithPages(b);
- const preview = await setup(b, ['claude-code', '--serves', 'several', '--members', 'alice-example,bob-example', '--stdio-member', 'alice-example', '--dry-run']);
+ const preview = await setup(b, ['claude-code', '--serves', 'several', '--members', 'alice-example,bob-example', '--stdio-member', 'alice-example', '--open-history', '--dry-run']);
expect(preview.exitCode).toBe(0);
expect(preview.stdout).toContain('stdio this claude-code entry would start serve --stdio-member alice-example: only its sessions read as alice-example');
expect(preview.stdout).toContain('serve --surface starter --advertise verbs --stdio-member alice-example');
expect(existsSync(join(b.home, '.claude.json'))).toBe(false);
expect(await stdioKey(b)).toBe('');
- const first = await setup(b, ['claude-code', '--serves', 'several', '--members', 'alice-example,bob-example']);
+ const first = await setup(b, ['claude-code', '--serves', 'several', '--members', 'alice-example,bob-example', '--open-history']);
expect(first.exitCode).toBe(0);
for (const m of ROSTER) {
const key = readFileSync(join(b.home, '.gbrain', 'member-keys', `${m}.key`), 'utf8').trim();
diff --git a/test/setup-serves-upgrade.test.ts b/test/setup-serves-upgrade.test.ts
index 7867035032..bd4118d278 100644
--- a/test/setup-serves-upgrade.test.ts
+++ b/test/setup-serves-upgrade.test.ts
@@ -25,7 +25,7 @@ describe('gbrain setup --serves (spawned, PGLite)', () => {
test('upgrade paths carry an entry\'s --stdio-member forward and never add one: post-upgrade rewrites, setup re-runs from the receipt, --no-stdio-member removes it', async () => {
const b = box();
await brainWithPages(b);
- expect((await setup(b, ['claude-code', '--serves', 'several', '--members', ROSTER.join(','), '--stdio-member', 'alice-example'])).exitCode).toBe(0);
+ expect((await setup(b, ['claude-code', '--serves', 'several', '--members', ROSTER.join(','), '--stdio-member', 'alice-example', '--open-history'])).exitCode).toBe(0);
const refresh = async () => { const lines: string[] = []; await withEnv({ ...CLEAN, HOME: b.home, GBRAIN_HOME: b.home }, () => refreshHookLaunchers((l) => lines.push(l))); return lines; };
staleEntry(b);
expect((await refresh()).join('\n')).toContain('now start gbrain from its own directory');
diff --git a/test/shared-skills-notice-fresh-brain.test.ts b/test/shared-skills-notice-fresh-brain.test.ts
new file mode 100644
index 0000000000..090211eb59
--- /dev/null
+++ b/test/shared-skills-notice-fresh-brain.test.ts
@@ -0,0 +1,51 @@
+/**
+ * GBRA-585: the v0.53.0 shared-skills orchestrator's console summary counts
+ * host work by the same rule as the migration ledger and doctor
+ * (sharedSkillsHostWork, #6796): a source whose only open stage is
+ * `members` (no client installation enrolled, which is never verified) owes
+ * no host work, so a fresh brain is not told on every apply-migrations and
+ * post-upgrade that it "need[s] host action". The per-source reason stays
+ * visible as information, with the read-only inspect command.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { sharedContentMigration } from '../src/commands/migrations/shared-content.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-shared-notice-'));
+
+beforeAll(() => {
+ const init = Bun.spawnSync(['bun', 'run', join(import.meta.dir, '..', 'src', 'cli.ts'), 'init', '--pglite', '--no-embedding', '--non-interactive'], {
+ env: { ...process.env, GBRAIN_HOME: home, GBRAIN_NO_AUTOPILOT_INSTALL: '1' }, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',
+ });
+ if (init.exitCode !== 0) throw new Error(`gbrain init failed: ${init.stderr.toString()}`);
+}, 180_000);
+
+afterAll(() => {
+ rmSync(home, { recursive: true, force: true });
+});
+
+async function runOrchestrator(): Promise<{ lines: string[]; result: Awaited<ReturnType<typeof sharedContentMigration.orchestrator>> }> {
+ const lines: string[] = [];
+ const original = console.error;
+ console.error = (...args: unknown[]) => { lines.push(args.map(String).join(' ')); };
+ try {
+ const result = await withEnv({ GBRAIN_HOME: home }, () => sharedContentMigration.orchestrator({ yes: true, dryRun: false, noAutopilotInstall: true }));
+ return { lines: lines.filter(line => line.startsWith('[shared-skills]')), result };
+ } finally { console.error = original; }
+}
+
+describe('GBRA-585 shared-skills notice on a fresh brain', () => {
+ test('a source with only an unenrolled client installation is not counted as needing host action', async () => {
+ const { lines, result } = await runOrchestrator();
+ const summary = lines[0] ?? '';
+ expect(summary).not.toContain('action_required');
+ expect(summary).not.toContain('need host action');
+ expect(summary).toContain('No source needs host action');
+ expect(lines.join('\n')).toContain('No installation has enrolled');
+ expect(lines.join('\n')).toContain('gbrain apply-migrations --migration 0.53.0 --dry-run --json');
+ expect(result.status).toBe('complete');
+ }, 120_000);
+});
diff --git a/test/sources-add-federation-warning.test.ts b/test/sources-add-federation-warning.test.ts
index debccabcd7..de661b6b3f 100644
--- a/test/sources-add-federation-warning.test.ts
+++ b/test/sources-add-federation-warning.test.ts
@@ -85,6 +85,17 @@ describe('sources add federation warning', () => {
expect(out.notices[0]).toMatchObject({ code: 'source_not_in_default_search', kind: 'info', fix: { argv: ['gbrain', 'sources', 'federate', 'source-n'] } });
});
+ // GBRA-585: a personal source (private-<member>) on a team brain was met with "next: ask_user: gbrain sources federate".
+ test('the notice asks whether the source should be shared, and says a private source needs nothing', async () => {
+ const { stdout, stderr } = await add(['private-alice-example', '--json']);
+ const notice = JSON.parse(stdout).notices[0];
+ expect(notice.fix.next).toBe('ask_user');
+ expect(notice.user_message).toContain('Should the source "private-alice-example" be shared');
+ expect(notice.user_message).toContain('leave it as it is');
+ expect(notice.why).toContain('A source meant to stay private needs nothing');
+ expect(stderr).not.toContain('Run `gbrain sources federate private-alice-example` to add it');
+ });
+
test('--federated adds without the warning', async () => {
const { stderr } = await add(['source-b', '--federated']);
expect(stderr).not.toContain('is not federated');
diff --git a/test/sources-unfederate-member-keys-gbra585.test.ts b/test/sources-unfederate-member-keys-gbra585.test.ts
new file mode 100644
index 0000000000..37355d6c95
--- /dev/null
+++ b/test/sources-unfederate-member-keys-gbra585.test.ts
@@ -0,0 +1,71 @@
+/**
+ * GBRA-585 A: `gbrain sources unfederate <id>` names the member keys that still read the source.
+ *
+ * 1. Protects: a member key setup mints holds a fixed read list (its write source, `company` and every source federated
+ * at mint time), so unfederating a source no longer takes it away from that key the way it did for an unscoped
+ * key. The unfederate output names each live member-bound key whose list still holds the source, with the
+ * `gbrain auth rescope` command that drops it, on stdout and under --json as keys_still_reading.
+ * 2. Fails when: unfederate stays silent about those keys, names a key that no longer holds the source, or prints a
+ * command that keeps the source or loses the key's write source.
+ * 3. Existing coverage: setup-company-access.test.ts covers what the minted lists hold, never unfederate.
+ * 4. No production seam: the real labelling and sources commands on PGLite, console spies only.
+ */
+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { labelSeveral } from '../src/commands/access-serves.ts';
+import { runSources } from '../src/commands/sources.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { memoryBrain, removeTempDirs, tempDir } from './helpers/setup-serves-box.ts';
+
+let engine: PGLiteEngine;
+let home: string;
+
+async function sources(args: string[]): Promise<{ stdout: string; stderr: string }> {
+ const out: string[] = [];
+ const err: string[] = [];
+ const log = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { out.push(a.join(' ')); });
+ const warn = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { err.push(a.join(' ')); });
+ try {
+ await runSources(engine, args);
+ } finally {
+ log.mockRestore();
+ warn.mockRestore();
+ }
+ return { stdout: out.join('\n'), stderr: err.join('\n') };
+}
+
+beforeAll(async () => {
+ engine = await memoryBrain();
+ home = tempDir('gbrain-unfederate-keys-');
+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ('team-b', 'team-b', '{"federated": true}'::jsonb) ON CONFLICT (id) DO NOTHING`);
+ await withEnv({ GBRAIN_HOME: home, GBRAIN_SETUP_ABORT_AFTER: undefined }, () => labelSeveral(engine, ['alice-example', 'bob-example'], 'default', true, true));
+}, 120_000);
+
+afterAll(async () => {
+ await engine?.disconnect();
+ removeTempDirs();
+});
+
+describe('sources unfederate and the member keys setup minted', () => {
+ test('the minted keys hold team-b, and unfederate names each with the rescope command that drops it', async () => {
+ const rows = await engine.executeRaw<{ name: string; federated_read: string[] }>("SELECT name, federated_read FROM access_tokens WHERE name LIKE 'member-%' AND revoked_at IS NULL ORDER BY name");
+ expect(rows.map(r => [r.name, [...r.federated_read]])).toEqual([['member-alice-example', ['default', 'team-b']], ['member-bob-example', ['default', 'team-b']]]);
+ const { stdout } = await sources(['unfederate', 'team-b']);
+ expect(stdout).toContain('isolated');
+ expect(stdout).toContain('2 member keys still read source team-b');
+ expect(stdout).toContain('gbrain auth rescope --token member-alice-example --sources default');
+ expect(stdout).toContain('gbrain auth rescope --token member-bob-example --sources default');
+ });
+
+ test('--json carries keys_still_reading, and a key rescoped off the source drops out', async () => {
+ await engine.executeRaw("UPDATE access_tokens SET federated_read = ARRAY['default']::text[] WHERE name = 'member-bob-example'");
+ const { stdout } = await sources(['unfederate', 'team-b', '--json']);
+ const doc = JSON.parse(stdout.split('\n').filter(Boolean).pop()!);
+ expect(doc.keys_still_reading).toEqual([{ token: 'member-alice-example', member: 'alice-example', command: 'gbrain auth rescope --token member-alice-example --sources default' }]);
+ });
+
+ test('federating prints no key list', async () => {
+ const { stdout } = await sources(['federate', 'team-b', '--json']);
+ expect(JSON.parse(stdout.split('\n').filter(Boolean).pop()!).keys_still_reading).toBeUndefined();
+ });
+});
diff --git a/test/transcripts-archive-default.test.ts b/test/transcripts-archive-default.test.ts
index eb5f4770d0..957c3a82bc 100644
--- a/test/transcripts-archive-default.test.ts
+++ b/test/transcripts-archive-default.test.ts
@@ -73,6 +73,23 @@ describe('archive default resolution', () => {
expect(await archiveEnabled(broken)).toBe(false);
});
+ test('GBRA-585: on a brain that serves several people, an explicit personal audience is not reported as unset or as switching itself off', async () => {
+ await engine.setConfig('access.serves', 'several');
+ const heuristic = await resolveArchiveEnabled(engine, { config: null });
+ expect(heuristic).toMatchObject({ enabled: true, source: 'default', audience: 'personal', serves_several: true });
+ expect(heuristic.reason).toContain('brain.audience is unset');
+ expect(heuristic.reason).toContain('turns off');
+ expect(heuristic.reason).toContain('gbrain config set brain.audience shared');
+
+ await engine.setConfig('brain.audience', 'personal');
+ const declared = await resolveArchiveEnabled(engine, { config: null });
+ expect(declared).toMatchObject({ enabled: true, source: 'default', audience: 'personal', serves_several: true });
+ expect(declared.reason).toContain('brain.audience is set to personal');
+ expect(declared.reason).not.toContain('unset');
+ expect(declared.reason).not.toContain('turns off');
+ expect(declared.reason).toContain('gbrain config set brain.audience shared');
+ });
+
test('a thin client and a remote caller resolve off, even with the switch on', async () => {
await engine.setConfig('brain.audience', 'personal');
await engine.setConfig(ARCHIVE_ENABLED_KEY, 'true');